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

feat: support UPDATE ... FROM ... syntax #833

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
12 changes: 12 additions & 0 deletions src/backend/query_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,18 @@ pub trait QueryBuilder:
false
});

if !update.from.is_empty() {
write!(sql, " FROM ").unwrap();

update.from.iter().fold(true, |first, table_ref| {
if !first {
write!(sql, ", ").unwrap()
}
self.prepare_table_ref(table_ref, sql);
false
});
}

self.prepare_output(&update.returning, sql);

self.prepare_condition(&update.r#where, "WHERE", sql);
Expand Down
57 changes: 57 additions & 0 deletions src/query/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ use inherent::inherent;
#[derive(Default, Debug, Clone, PartialEq)]
pub struct UpdateStatement {
pub(crate) table: Option<Box<TableRef>>,
pub(crate) from: Vec<TableRef>,
pub(crate) values: Vec<(DynIden, Box<SimpleExpr>)>,
pub(crate) r#where: ConditionHolder,
pub(crate) orders: Vec<OrderExpr>,
Expand Down Expand Up @@ -66,6 +67,62 @@ impl UpdateStatement {
self
}

/// From table.
///
/// # Examples
///
/// ```
/// use sea_query::{tests_cfg::*, *};
///
/// let query = Query::update()
/// .table(Glyph::Table)
/// .value(
/// Glyph::Tokens,
/// SimpleExpr::Column(ColumnRef::TableColumn(
/// SeaRc::new(Char::Table),
/// SeaRc::new(Char::Character),
/// )),
/// )
/// .from(Char::Table)
/// .cond_where(
/// SimpleExpr::Column(ColumnRef::TableColumn(
/// SeaRc::new(Glyph::Table),
/// SeaRc::new(Glyph::Image),
/// ))
/// .eq(SimpleExpr::Column(ColumnRef::TableColumn(
/// SeaRc::new(Char::Table),
/// SeaRc::new(Char::UserData),
/// ))),
/// )
/// .to_owned();
///
///
/// assert_eq!(
/// query.to_string(MysqlQueryBuilder),
/// "UPDATE `glyph` SET `tokens` = `character`.`character` FROM `character` WHERE `glyph`.`image` = `character`.`user_data`"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The syntax of MySQL appears similar, but not identical. Here a MySQL UPDATE JOIN could be used to achieve the same:

UPDATE `glyph`
JOIN `character`
  ON `glyph`.`image` = `character`.`user_data`
SET `glyph`.`tokens` = `character`.`character`;

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gronke Took a wild swing at at least getting started here, and extracted the specific behavior into a discrete method (prepare_update_from_table_refs) so it can be overridden as needed by whichever dialect. I've got the MySQL-specific handling as a unimplemented! call at the moment though, cause I've got a case of end-of-year-holidays-brain.

If you have a second, would you take a look at the changes and let me know if there's a better / more preferable way of doing this please let me know? Otherwise I'll carry on as time allows 😁

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gronke ^bump

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gronke ^bump 🙂

/// );
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
/// r#"UPDATE "glyph" SET "tokens" = "character"."character" FROM "character" WHERE "glyph"."image" = "character"."user_data""#
/// );
/// assert_eq!(
/// query.to_string(SqliteQueryBuilder),
/// r#"UPDATE "glyph" SET "tokens" = "character"."character" FROM "character" WHERE "glyph"."image" = "character"."user_data""#
/// );
/// ```
pub fn from<R>(&mut self, tbl_ref: R) -> &mut Self
where
R: IntoTableRef,
{
self.from_from(tbl_ref.into_table_ref())
}

#[allow(clippy::wrong_self_convention)]
fn from_from(&mut self, select: TableRef) -> &mut Self {
self.from.push(select);
self
}

/// Update column values. To set multiple column-value pairs at once.
///
/// # Examples
Expand Down