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 1 commit
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
Prev Previous commit
Next Next commit
extended returning support
  • Loading branch information
marlon-sousa committed Oct 5, 2021
commit 31a68ea9aef8a91557909dd3e7fc99da1d30a72e
12 changes: 11 additions & 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 Expand Up @@ -92,6 +92,16 @@ jobs:
command: test
args: --all-features

- uses: actions-rs/cargo@v1
with:
command: test
args: --no-default-features --features="backend-mysql" --test test-mysql

- uses: actions-rs/cargo@v1
with:
command: test
args: --no-default-features --features="backend-sqlite" --test test-sqlite

derive-test:
name: Derive Tests
runs-on: ubuntu-20.04
Expand Down
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ uuid = { version = "^0", optional = true }

[features]
backend-mysql = []
backend-postgres = []
backend-postgres = ["with-returning"]
backend-sqlite = []
default = ["derive", "backend-mysql", "backend-postgres", "backend-sqlite"]
derive = ["sea-query-derive"]
Expand All @@ -67,6 +67,7 @@ with-json = ["serde_json"]
with-rust_decimal = ["rust_decimal"]
with-bigdecimal = ["bigdecimal"]
with-uuid = ["uuid"]
with-returning = []

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

fn prepare_returning(
&self,
returning: &Returning,
sql: &mut SqlWriter,
collector: &mut dyn FnMut(Value),
) {
match returning {
Returning::All => write!(sql, " RETURNING *").unwrap(),
Returning::Collumns(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::PrimaryKey => write!(sql, " RETURNING *").unwrap(),
Returning::Nothing => return,
}
}

fn if_null_function(&self) -> &str {
"COALESCE"
}
Expand Down
31 changes: 31 additions & 0 deletions src/backend/query_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -734,6 +734,7 @@ pub trait QueryBuilder: QuotedBuilder {

#[doc(hidden)]
/// Hook to insert "RETURNING" statements.
#[cfg(not(feature = "with-returning"))]
fn prepare_returning(
&self,
returning: &Returning,
Expand All @@ -742,6 +743,36 @@ pub trait QueryBuilder: QuotedBuilder {
) {
}

#[cfg(feature = "with-returning")]
fn prepare_returning(
&self,
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)]
/// Translate a condition to a "WHERE" clause.
fn prepare_condition(
Expand Down
18 changes: 8 additions & 10 deletions src/query/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,36 +100,36 @@ impl DeleteStatement {
self
}

/// RETURNING expressions. Postgres only.
/// RETURNING expressions. Enabled by default for postgres and under the feature with-returning for the remaining back ends.
///
/// ```
/// use sea_query::{tests_cfg::*, *};
///
/// let query = Query::delete()
/// .from_table(Glyph::Table)
/// .and_where(Expr::col(Glyph::Id).eq(1))
/// .returning(Returning::Collumns(vec![Glyph::Id.into_column_ref()]))
/// .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, returning_cols: Returning) -> &mut Self {
self.returning = returning_cols;
self
}

/// RETURNING a column after delete. Postgres only.
/// RETURNING a column after delete. Enabled by default for postgres and under the feature with-returning for the remaining back ends.
/// Wrapper over [`DeleteStatement::returning()`].
///
/// ```
Expand All @@ -143,24 +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(Returning::Collumns(vec![ColumnRef::Column(
col.into_iden(),
)]))
self.returning(Returning::Columns(vec![ColumnRef::Column(col.into_iden())]))
}
}

Expand Down
18 changes: 8 additions & 10 deletions src/query/insert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ impl InsertStatement {
self.exprs(values).unwrap()
}

/// RETURNING expressions. Postgres only.
/// RETURNING expressions. Enabled by default for postgres and under the feature with-returning for the remaining back ends.
///
/// ```
/// 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(Returning::Collumns(vec![Glyph::Id.into_column_ref()]))
/// .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, 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. Enabled by default for postgres and under the feature with-returning for the remaining back ends.
/// Wrapper over [`InsertStatement::returning()`].
///
/// ```
Expand All @@ -224,24 +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(Returning::Collumns(vec![ColumnRef::Column(
col.into_iden(),
)]))
self.returning(Returning::Columns(vec![ColumnRef::Column(col.into_iden())]))
}
}

Expand Down
16 changes: 13 additions & 3 deletions src/query/returning.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
use std::default::Default;

use crate::ColumnRef;
use crate::{ColumnRef, IntoColumnRef};

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

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 {
Expand Down
18 changes: 8 additions & 10 deletions src/query/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ impl UpdateStatement {
self
}

/// RETURNING expressions. Postgres only.
/// RETURNING expressions. Enabled by default for postgres and under the feature with-returning for the remaining back ends.
///
/// ```
/// use sea_query::{tests_cfg::*, *};
Expand All @@ -233,28 +233,28 @@ impl UpdateStatement {
/// .value(Glyph::Aspect, 2.1345.into())
/// .value(Glyph::Image, "235m".into())
/// .and_where(Expr::col(Glyph::Id).eq(1))
/// .returning(Returning::Collumns(vec![Glyph::Id.into_column_ref()]))
/// .returning(Returning::Columns(vec![Glyph::Id.into_column_ref()]))
/// .to_owned();
///
/// assert_eq!(
/// query.to_string(MysqlQueryBuilder),
/// r#"UPDATE `glyph` SET `aspect` = 2.1345, `image` = '235m' WHERE `id` = 1"#
/// r#"UPDATE `glyph` SET `aspect` = 2.1345, `image` = '235m' WHERE `id` = 1 RETURNING `id`"#
/// );
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
/// r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m' WHERE "id" = 1 RETURNING "id""#
/// );
/// assert_eq!(
/// query.to_string(SqliteQueryBuilder),
/// r#"UPDATE `glyph` SET `aspect` = 2.1345, `image` = '235m' WHERE `id` = 1"#
/// r#"UPDATE `glyph` SET `aspect` = 2.1345, `image` = '235m' WHERE `id` = 1 RETURNING `id`"#
/// );
/// ```
pub fn returning(&mut self, returning_cols: Returning) -> &mut Self {
self.returning = returning_cols;
self
}

/// RETURNING a column after update. Postgres only.
/// RETURNING a column after update. Enabled by default for postgres and under the feature with-returning for the remaining back ends.
/// Wrapper over [`UpdateStatement::returning()`].
///
/// ```
Expand All @@ -271,24 +271,22 @@ impl UpdateStatement {
///
/// assert_eq!(
/// query.to_string(MysqlQueryBuilder),
/// r#"UPDATE `glyph` SET `aspect` = 2.1345, `image` = '235m' WHERE `id` = 1"#
/// r#"UPDATE `glyph` SET `aspect` = 2.1345, `image` = '235m' WHERE `id` = 1 RETURNING `id`"#
/// );
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
/// r#"UPDATE "glyph" SET "aspect" = 2.1345, "image" = '235m' WHERE "id" = 1 RETURNING "id""#
/// );
/// assert_eq!(
/// query.to_string(SqliteQueryBuilder),
/// r#"UPDATE `glyph` SET `aspect` = 2.1345, `image` = '235m' WHERE `id` = 1"#
/// r#"UPDATE `glyph` SET `aspect` = 2.1345, `image` = '235m' WHERE `id` = 1 RETURNING `id`"#
/// );
/// ```
pub fn returning_col<C>(&mut self, col: C) -> &mut Self
where
C: IntoIden,
{
self.returning(Returning::Collumns(vec![ColumnRef::Column(
col.into_iden(),
)]))
self.returning(Returning::Columns(vec![ColumnRef::Column(col.into_iden())]))
}
}

Expand Down
Loading