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

On conflict do nothing for MySql #684

Closed
wants to merge 9 commits into from
Closed
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
57 changes: 55 additions & 2 deletions src/backend/mysql/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,61 @@ impl QueryBuilder for MysqlQueryBuilder {
sql.push_param(value.clone(), self as _);
}

#[doc(hidden)]
/// Write ON CONFLICT expression
fn prepare_on_conflict(&self, on_conflict: &Option<OnConflict>, sql: &mut dyn SqlWriter) {
if let Some(on_conflict) = on_conflict {
self.prepare_on_conflict_keywords(sql);
self.prepare_on_conflict_target(&on_conflict.target, sql);
self.prepare_on_conflict_condition(&on_conflict.target_where, sql);
self.prepare_on_conflict_action(&on_conflict.action, sql);
self.prepare_on_conflict_condition(&on_conflict.action_where, sql);
}
}

fn prepare_on_conflict_action(
&self,
on_conflict_action: &Option<OnConflictAction>,
sql: &mut dyn SqlWriter,
) {
if let Some(action) = on_conflict_action {
self.prepare_on_conflict_do_update_keywords(sql);
match action {
OnConflictAction::DoNothing(pk_cols) => {
pk_cols.iter().fold(true, |first, pk_col| {
if !first {
write!(sql, ", ").unwrap()
}
pk_col.prepare(sql.as_writer(), self.quote());
write!(sql, " = ").unwrap();
self.prepare_on_conflict_excluded_table(pk_col, sql);
false
});
}
OnConflictAction::Update(update_strats) => {
update_strats.iter().fold(true, |first, update_strat| {
if !first {
write!(sql, ", ").unwrap()
}
match update_strat {
OnConflictUpdate::Column(col) => {
col.prepare(sql.as_writer(), self.quote());
write!(sql, " = ").unwrap();
self.prepare_on_conflict_excluded_table(col, sql);
}
OnConflictUpdate::Expr(col, expr) => {
col.prepare(sql.as_writer(), self.quote());
write!(sql, " = ").unwrap();
self.prepare_simple_expr(expr, sql);
}
}
false
});
}
}
}
}

fn prepare_on_conflict_target(&self, _: &Option<OnConflictTarget>, _: &mut dyn SqlWriter) {
// MySQL doesn't support declaring ON CONFLICT target.
}
Expand All @@ -72,9 +127,7 @@ impl QueryBuilder for MysqlQueryBuilder {
}

fn prepare_on_conflict_excluded_table(&self, col: &DynIden, sql: &mut dyn SqlWriter) {
write!(sql, "VALUES(").unwrap();
col.prepare(sql.as_writer(), self.quote());
write!(sql, ")").unwrap();
}

fn prepare_on_conflict_condition(&self, _: &ConditionHolder, _: &mut dyn SqlWriter) {}
Expand Down
6 changes: 3 additions & 3 deletions src/backend/query_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub trait QueryBuilder: QuotedBuilder + EscapeBuilder + TableRefBuilder {

/// Translate [`InsertStatement`] into SQL statement.
fn prepare_insert_statement(&self, insert: &InsertStatement, sql: &mut dyn SqlWriter) {
self.prepare_insert(insert.replace, sql);
self.prepare_insert(insert.replace, &insert.on_conflict, sql);

if let Some(table) = &insert.table {
write!(sql, " INTO ").unwrap();
Expand Down Expand Up @@ -825,7 +825,7 @@ pub trait QueryBuilder: QuotedBuilder + EscapeBuilder + TableRefBuilder {
}
}

fn prepare_insert(&self, replace: bool, sql: &mut dyn SqlWriter) {
fn prepare_insert(&self, replace: bool, _: &Option<OnConflict>, sql: &mut dyn SqlWriter) {
if replace {
write!(sql, "REPLACE").unwrap();
} else {
Expand Down Expand Up @@ -1142,7 +1142,7 @@ pub trait QueryBuilder: QuotedBuilder + EscapeBuilder + TableRefBuilder {
) {
if let Some(action) = on_conflict_action {
match action {
OnConflictAction::DoNothing => {
OnConflictAction::DoNothing(_) => {
write!(sql, " DO NOTHING").unwrap();
}
OnConflictAction::Update(update_strats) => {
Expand Down
90 changes: 84 additions & 6 deletions src/query/on_conflict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub enum OnConflictTarget {
#[derive(Debug, Clone, PartialEq)]
pub enum OnConflictAction {
/// Do nothing
DoNothing,
DoNothing(Vec<DynIden>),
/// Update column value of existing row
Update(Vec<OnConflictUpdate>),
}
Expand Down Expand Up @@ -64,8 +64,86 @@ impl OnConflict {
}
}

/// Set ON CONFLICT do nothing.
/// Please use do_nothing_on() and provide primary keys if you are using MySql.
///
/// # Examples
///
/// ```
/// use sea_query::{tests_cfg::*, *};
///
/// let query = Query::insert()
/// .into_table(Glyph::Table)
/// .columns([Glyph::Aspect, Glyph::Image])
/// .values_panic(["abcd".into(), 3.1415.into()])
/// .on_conflict(
/// OnConflict::columns([Glyph::Id, Glyph::Aspect])
/// .do_nothing()
/// .to_owned(),
/// )
/// .to_owned();
///
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
/// [
/// r#"INSERT INTO "glyph" ("aspect", "image")"#,
/// r#"VALUES ('abcd', 3.1415)"#,
/// r#"ON CONFLICT ("id", "aspect") DO NOTHING"#,
/// ]
/// .join(" ")
/// );
/// assert_eq!(
/// query.to_string(SqliteQueryBuilder),
/// [
/// r#"INSERT INTO "glyph" ("aspect", "image")"#,
/// r#"VALUES ('abcd', 3.1415)"#,
/// r#"ON CONFLICT ("id", "aspect") DO NOTHING"#,
/// ]
/// .join(" ")
/// );
/// ```
pub fn do_nothing(&mut self) -> &mut Self {
self.action = Some(OnConflictAction::DoNothing);
self.action = Some(OnConflictAction::DoNothing(vec![]));
self
}

/// Set ON CONFLICT do nothing.
/// MySql only.
///
/// # Examples
///
/// ```
/// use sea_query::{tests_cfg::*, *};
///
/// let query = Query::insert()
/// .into_table(Glyph::Table)
/// .columns([Glyph::Aspect, Glyph::Image])
/// .values_panic(["abcd".into(), 3.1415.into()])
/// .on_conflict(
/// OnConflict::columns([Glyph::Id, Glyph::Aspect])
/// .do_nothing_on(vec![Glyph::Id])
/// .to_owned(),
/// )
/// .to_owned();
///
/// assert_eq!(
/// query.to_string(MysqlQueryBuilder),
/// [
/// r#"INSERT INTO `glyph` (`aspect`, `image`)"#,
/// r#"VALUES ('abcd', 3.1415)"#,
/// r#"ON DUPLICATE KEY UPDATE `id` = `id`"#,
/// ]
/// .join(" ")
/// );
#[cfg(feature = "backend-mysql")]
pub fn do_nothing_on<C, I>(&mut self, pk_cols: I) -> &mut Self
where
C: IntoIden,
I: IntoIterator<Item = C>,
{
self.action = Some(OnConflictAction::DoNothing(
pk_cols.into_iter().map(IntoIden::into_iden).collect(),
));
self
}

Expand Down Expand Up @@ -96,7 +174,7 @@ impl OnConflict {
/// [
/// r#"INSERT INTO `glyph` (`aspect`, `image`)"#,
/// r#"VALUES ('abcd', 3.1415)"#,
/// r#"ON DUPLICATE KEY UPDATE `aspect` = VALUES(`aspect`), `image` = 1 + 2"#,
/// r#"ON DUPLICATE KEY UPDATE `aspect` = `aspect`, `image` = 1 + 2"#,
/// ]
/// .join(" ")
/// );
Expand Down Expand Up @@ -149,7 +227,7 @@ impl OnConflict {
///
/// assert_eq!(
/// query.to_string(MysqlQueryBuilder),
/// r#"INSERT INTO `glyph` (`aspect`, `image`) VALUES (2, 3) ON DUPLICATE KEY UPDATE `aspect` = VALUES(`aspect`), `image` = VALUES(`image`)"#
/// r#"INSERT INTO `glyph` (`aspect`, `image`) VALUES (2, 3) ON DUPLICATE KEY UPDATE `aspect` = `aspect`, `image` = `image`"#
/// );
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
Expand All @@ -174,7 +252,7 @@ impl OnConflict {
Some(OnConflictAction::Update(v)) => {
v.append(&mut update_strats);
}
Some(OnConflictAction::DoNothing) | None => {
Some(OnConflictAction::DoNothing(_)) | None => {
self.action = Some(OnConflictAction::Update(update_strats));
}
};
Expand Down Expand Up @@ -229,7 +307,7 @@ impl OnConflict {
Some(OnConflictAction::Update(v)) => {
v.append(&mut update_exprs);
}
Some(OnConflictAction::DoNothing) | None => {
Some(OnConflictAction::DoNothing(_)) | None => {
self.action = Some(OnConflictAction::Update(update_exprs));
}
};
Expand Down
32 changes: 27 additions & 5 deletions tests/mysql/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1141,6 +1141,28 @@ fn insert_from_select() {
);
}

#[test]
#[allow(clippy::approx_constant)]
fn insert_on_conflict_do_nothing() {
assert_eq!(
Query::insert()
.into_table(Glyph::Table)
.columns([Glyph::Aspect, Glyph::Image])
.values_panic([
"04108048005887010020060000204E0180400400".into(),
3.1415.into(),
])
.on_conflict(OnConflict::new().do_nothing_on(vec![Glyph::Id]).to_owned())
.to_string(MysqlQueryBuilder),
[
r#"INSERT INTO `glyph` (`aspect`, `image`)"#,
r#"VALUES ('04108048005887010020060000204E0180400400', 3.1415)"#,
r#"ON DUPLICATE KEY UPDATE `id` = `id`"#,
]
.join(" ")
);
}

#[test]
#[allow(clippy::approx_constant)]
fn insert_on_conflict_0() {
Expand All @@ -1161,7 +1183,7 @@ fn insert_on_conflict_0() {
[
r#"INSERT INTO `glyph` (`aspect`, `image`)"#,
r#"VALUES ('04108048005887010020060000204E0180400400', 3.1415)"#,
r#"ON DUPLICATE KEY UPDATE `aspect` = VALUES(`aspect`), `image` = VALUES(`image`)"#,
r#"ON DUPLICATE KEY UPDATE `aspect` = `aspect`, `image` = `image`"#,
Copy link
Member

Choose a reason for hiding this comment

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

Oh sad, this is wrong. ON DUPLICATE KEY UPDATE id = id should only applies to do_nothing_on.
While the behaviour of update_columns() should not be changed.
The two expressions have different semantics.

]
.join(" ")
);
Expand All @@ -1187,7 +1209,7 @@ fn insert_on_conflict_1() {
[
r#"INSERT INTO `glyph` (`aspect`, `image`)"#,
r#"VALUES ('04108048005887010020060000204E0180400400', 3.1415)"#,
r#"ON DUPLICATE KEY UPDATE `aspect` = VALUES(`aspect`)"#,
r#"ON DUPLICATE KEY UPDATE `aspect` = `aspect`"#,
]
.join(" ")
);
Expand All @@ -1213,7 +1235,7 @@ fn insert_on_conflict_2() {
[
r#"INSERT INTO `glyph` (`aspect`, `image`)"#,
r#"VALUES ('04108048005887010020060000204E0180400400', 3.1415)"#,
r#"ON DUPLICATE KEY UPDATE `aspect` = VALUES(`aspect`), `image` = VALUES(`image`)"#,
r#"ON DUPLICATE KEY UPDATE `aspect` = `aspect`, `image` = `image`"#,
]
.join(" ")
);
Expand Down Expand Up @@ -1295,7 +1317,7 @@ fn insert_on_conflict_5() {
[
r#"INSERT INTO `glyph` (`aspect`, `image`)"#,
r#"VALUES ('04108048005887010020060000204E0180400400', 3.1415)"#,
r#"ON DUPLICATE KEY UPDATE `aspect` = '04108048005887010020060000204E0180400400', `image` = VALUES(`image`)"#,
r#"ON DUPLICATE KEY UPDATE `aspect` = '04108048005887010020060000204E0180400400', `image` = `image`"#,
]
.join(" ")
);
Expand All @@ -1322,7 +1344,7 @@ fn insert_on_conflict_6() {
[
r#"INSERT INTO `glyph` (`aspect`, `image`)"#,
r#"VALUES ('04108048005887010020060000204E0180400400', 3.1415)"#,
r#"ON DUPLICATE KEY UPDATE `aspect` = VALUES(`aspect`), `image` = 1 + 2"#,
r#"ON DUPLICATE KEY UPDATE `aspect` = `aspect`, `image` = 1 + 2"#,
]
.join(" ")
);
Expand Down
22 changes: 22 additions & 0 deletions tests/postgres/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1278,6 +1278,28 @@ fn insert_10() {
);
}

#[test]
#[allow(clippy::approx_constant)]
fn insert_on_conflict_do_nothing() {
assert_eq!(
Query::insert()
.into_table(Glyph::Table)
.columns([Glyph::Aspect, Glyph::Image])
.values_panic([
"04108048005887010020060000204E0180400400".into(),
3.1415.into(),
])
.on_conflict(OnConflict::column(Glyph::Id).do_nothing().to_owned())
.to_string(PostgresQueryBuilder),
[
r#"INSERT INTO "glyph" ("aspect", "image")"#,
r#"VALUES ('04108048005887010020060000204E0180400400', 3.1415)"#,
r#"ON CONFLICT ("id") DO NOTHING"#,
]
.join(" ")
);
}

#[test]
#[allow(clippy::approx_constant)]
fn insert_on_conflict_1() {
Expand Down
22 changes: 22 additions & 0 deletions tests/sqlite/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1209,6 +1209,28 @@ fn insert_7() {
);
}

#[test]
#[allow(clippy::approx_constant)]
fn insert_on_conflict_do_nothing() {
assert_eq!(
Query::insert()
.into_table(Glyph::Table)
.columns([Glyph::Aspect, Glyph::Image])
.values_panic([
"04108048005887010020060000204E0180400400".into(),
3.1415.into(),
])
.on_conflict(OnConflict::column(Glyph::Id).do_nothing().to_owned())
.to_string(SqliteQueryBuilder),
[
r#"INSERT INTO "glyph" ("aspect", "image")"#,
r#"VALUES ('04108048005887010020060000204E0180400400', 3.1415)"#,
r#"ON CONFLICT ("id") DO NOTHING"#,
]
.join(" ")
);
}

#[test]
#[allow(clippy::approx_constant)]
fn insert_on_conflict_1() {
Expand Down