Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extended returning support #155

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jobs:
toolchain: stable
components: clippy
override: true

- uses: actions-rs/clippy-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
Expand Down
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ with-rust_decimal = ["rust_decimal"]
with-bigdecimal = ["bigdecimal"]
with-uuid = ["uuid"]


[[test]]
name = "test-derive"
path = "tests/derive/mod.rs"
Expand Down
18 changes: 0 additions & 18 deletions src/backend/postgres/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,6 @@ impl QueryBuilder for PostgresQueryBuilder {
("$", true)
}

fn prepare_returning(
&self,
returning: &[SelectExpr],
sql: &mut SqlWriter,
collector: &mut dyn FnMut(Value),
) {
if !returning.is_empty() {
write!(sql, " RETURNING ").unwrap();
returning.iter().fold(true, |first, expr| {
if !first {
write!(sql, ", ").unwrap()
}
self.prepare_select_expr(expr, sql, collector);
false
});
}
}

fn if_null_function(&self) -> &str {
"COALESCE"
}
Expand Down
25 changes: 23 additions & 2 deletions src/backend/query_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -756,10 +756,31 @@ pub trait QueryBuilder: QuotedBuilder {
/// Hook to insert "RETURNING" statements.
fn prepare_returning(
&self,
_returning: &[SelectExpr],
_sql: &mut SqlWriter,
returning: &Returning,
sql: &mut SqlWriter,
_collector: &mut dyn FnMut(Value),
) {
match returning {
Returning::All => write!(sql, " RETURNING *").unwrap(),
Returning::Columns(cols) => {
write!(sql, " RETURNING ").unwrap();
cols.into_iter().fold(true, |first, column_ref| {
if !first {
write!(sql, ", ").unwrap()
}
match column_ref {
ColumnRef::Column(column) => column.prepare(sql, self.quote()),
ColumnRef::TableColumn(table, column) => {
table.prepare(sql, self.quote());
write!(sql, ".").unwrap();
column.prepare(sql, self.quote());
}
};
false
});
}
Returning::Nothing => return,
}
}

#[doc(hidden)]
Expand Down
26 changes: 13 additions & 13 deletions src/query/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::{
query::{condition::*, OrderedStatement},
types::*,
value::*,
Query, QueryStatementBuilder, SelectExpr, SelectStatement,
ColumnRef, QueryStatementBuilder, Returning,
};

/// Delete existing rows from the table
Expand Down Expand Up @@ -39,7 +39,7 @@ pub struct DeleteStatement {
pub(crate) wherei: ConditionHolder,
pub(crate) orders: Vec<OrderExpr>,
pub(crate) limit: Option<Value>,
pub(crate) returning: Vec<SelectExpr>,
pub(crate) returning: Returning,
}

impl Default for DeleteStatement {
Expand All @@ -56,7 +56,7 @@ impl DeleteStatement {
wherei: ConditionHolder::new(),
orders: Vec::new(),
limit: None,
returning: Vec::new(),
returning: Returning::default(),
}
}

Expand Down Expand Up @@ -100,36 +100,36 @@ impl DeleteStatement {
self
}

/// RETURNING expressions. Postgres only.
/// RETURNING expressions. Supported fully by postgres, version deppendant on other databases
///
/// ```
/// use sea_query::{tests_cfg::*, *};
///
/// let query = Query::delete()
/// .from_table(Glyph::Table)
/// .and_where(Expr::col(Glyph::Id).eq(1))
/// .returning(Query::select().column(Glyph::Id).take())
/// .returning(Returning::Columns(vec![Glyph::Id.into_column_ref()]))
/// .to_owned();
///
/// assert_eq!(
/// query.to_string(MysqlQueryBuilder),
/// r#"DELETE FROM `glyph` WHERE `id` = 1"#
/// r#"DELETE FROM `glyph` WHERE `id` = 1 RETURNING `id`"#
/// );
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
/// r#"DELETE FROM "glyph" WHERE "id" = 1 RETURNING "id""#
/// );
/// assert_eq!(
/// query.to_string(SqliteQueryBuilder),
/// r#"DELETE FROM `glyph` WHERE `id` = 1"#
/// r#"DELETE FROM `glyph` WHERE `id` = 1 RETURNING `id`"#
/// );
/// ```
pub fn returning(&mut self, select: SelectStatement) -> &mut Self {
self.returning = select.selects;
pub fn returning(&mut self, returning_cols: Returning) -> &mut Self {
self.returning = returning_cols;
self
}

/// RETURNING a column after delete. Postgres only.
/// RETURNING a column after delete. Supported fully by postgres, version deppendant on other databases
/// Wrapper over [`DeleteStatement::returning()`].
///
/// ```
Expand All @@ -143,22 +143,22 @@ impl DeleteStatement {
///
/// assert_eq!(
/// query.to_string(MysqlQueryBuilder),
/// r#"DELETE FROM `glyph` WHERE `id` = 1"#
/// r#"DELETE FROM `glyph` WHERE `id` = 1 RETURNING `id`"#
/// );
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
/// r#"DELETE FROM "glyph" WHERE "id" = 1 RETURNING "id""#
/// );
/// assert_eq!(
/// query.to_string(SqliteQueryBuilder),
/// r#"DELETE FROM `glyph` WHERE `id` = 1"#
/// r#"DELETE FROM `glyph` WHERE `id` = 1 RETURNING `id`"#
/// );
/// ```
pub fn returning_col<C>(&mut self, col: C) -> &mut Self
where
C: IntoIden,
{
self.returning(Query::select().column(col.into_iden()).take())
self.returning(Returning::Columns(vec![ColumnRef::Column(col.into_iden())]))
}
}

Expand Down
26 changes: 13 additions & 13 deletions src/query/insert.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
backend::QueryBuilder, error::*, prepare::*, types::*, value::*, Expr, Query,
QueryStatementBuilder, SelectExpr, SelectStatement, SimpleExpr,
backend::QueryBuilder, error::*, prepare::*, types::*, value::*, Expr, QueryStatementBuilder,
Returning, SimpleExpr,
};

/// Insert any new rows into an existing table
Expand Down Expand Up @@ -35,7 +35,7 @@ pub struct InsertStatement {
pub(crate) table: Option<Box<TableRef>>,
pub(crate) columns: Vec<DynIden>,
pub(crate) values: Vec<Vec<SimpleExpr>>,
pub(crate) returning: Vec<SelectExpr>,
pub(crate) returning: Returning,
}

impl InsertStatement {
Expand Down Expand Up @@ -179,7 +179,7 @@ impl InsertStatement {
self.exprs(values).unwrap()
}

/// RETURNING expressions. Postgres only.
/// RETURNING expressions. Supported fully by postgres, version deppendant on other databases
///
/// ```
/// use sea_query::{tests_cfg::*, *};
Expand All @@ -188,28 +188,28 @@ impl InsertStatement {
/// .into_table(Glyph::Table)
/// .columns(vec![Glyph::Image])
/// .values_panic(vec!["12A".into()])
/// .returning(Query::select().column(Glyph::Id).take())
/// .returning(Returning::Columns(vec![Glyph::Id.into_column_ref()]))
/// .to_owned();
///
/// assert_eq!(
/// query.to_string(MysqlQueryBuilder),
/// "INSERT INTO `glyph` (`image`) VALUES ('12A')"
/// "INSERT INTO `glyph` (`image`) VALUES ('12A') RETURNING `id`"
/// );
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
/// r#"INSERT INTO "glyph" ("image") VALUES ('12A') RETURNING "id""#
/// );
/// assert_eq!(
/// query.to_string(SqliteQueryBuilder),
/// "INSERT INTO `glyph` (`image`) VALUES ('12A')"
/// "INSERT INTO `glyph` (`image`) VALUES ('12A') RETURNING `id`"
/// );
/// ```
pub fn returning(&mut self, select: SelectStatement) -> &mut Self {
self.returning = select.selects;
pub fn returning(&mut self, returning: Returning) -> &mut Self {
self.returning = returning;
self
}

/// RETURNING a column after insertion. Postgres only. This is equivalent to MySQL's LAST_INSERT_ID.
/// RETURNING a column after insertion. Supported fully by postgres, version deppendant on other databases
/// Wrapper over [`InsertStatement::returning()`].
///
/// ```
Expand All @@ -224,22 +224,22 @@ impl InsertStatement {
///
/// assert_eq!(
/// query.to_string(MysqlQueryBuilder),
/// "INSERT INTO `glyph` (`image`) VALUES ('12A')"
/// "INSERT INTO `glyph` (`image`) VALUES ('12A') RETURNING `id`"
/// );
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
/// r#"INSERT INTO "glyph" ("image") VALUES ('12A') RETURNING "id""#
/// );
/// assert_eq!(
/// query.to_string(SqliteQueryBuilder),
/// "INSERT INTO `glyph` (`image`) VALUES ('12A')"
/// "INSERT INTO `glyph` (`image`) VALUES ('12A') RETURNING `id`"
/// );
/// ```
pub fn returning_col<C>(&mut self, col: C) -> &mut Self
where
C: IntoIden,
{
self.returning(Query::select().column(col.into_iden()).take())
self.returning(Returning::Columns(vec![ColumnRef::Column(col.into_iden())]))
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ mod condition;
mod delete;
mod insert;
mod ordered;
mod returning;
mod select;
mod shim;
mod traits;
Expand All @@ -20,6 +21,7 @@ pub use condition::*;
pub use delete::*;
pub use insert::*;
pub use ordered::*;
pub use returning::*;
pub use select::*;
pub use traits::*;
pub use update::*;
Expand Down
27 changes: 27 additions & 0 deletions src/query/returning.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use std::default::Default;

use crate::{ColumnRef, IntoColumnRef};

#[derive(Clone, Debug)]
pub enum Returning {
All,
Columns(Vec<ColumnRef>),
Nothing,
}

impl Returning {
pub fn cols<T, I>(cols: I) -> Self
where
T: IntoColumnRef,
I: IntoIterator<Item = T>,
{
let cols: Vec<_> = cols.into_iter().map(|c| c.into_column_ref()).collect();
Self::Columns(cols)
}
}

impl Default for Returning {
fn default() -> Self {
Self::Nothing
}
}
Loading