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

Add support for MySQL's INSERT INTO ... SET syntax #1641

Merged
merged 1 commit into from
Jan 6, 2025
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
14 changes: 9 additions & 5 deletions src/ast/dml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ use sqlparser_derive::{Visit, VisitMut};
pub use super::ddl::{ColumnDef, TableConstraint};

use super::{
display_comma_separated, display_separated, ClusteredBy, CommentDef, Expr, FileFormat,
FromTable, HiveDistributionStyle, HiveFormat, HiveIOFormat, HiveRowFormat, Ident,
display_comma_separated, display_separated, Assignment, ClusteredBy, CommentDef, Expr,
FileFormat, FromTable, HiveDistributionStyle, HiveFormat, HiveIOFormat, HiveRowFormat, Ident,
InsertAliases, MysqlInsertPriority, ObjectName, OnCommit, OnInsert, OneOrManyWithParens,
OrderByExpr, Query, RowAccessPolicy, SelectItem, SqlOption, SqliteOnConflict, TableEngine,
TableWithJoins, Tag, WrappedCollection,
Expand Down Expand Up @@ -480,6 +480,9 @@ pub struct Insert {
pub overwrite: bool,
/// A SQL query that specifies what to insert
pub source: Option<Box<Query>>,
/// MySQL `INSERT INTO ... SET`
/// See: <https://dev.mysql.com/doc/refman/8.4/en/insert.html>
pub assignments: Vec<Assignment>,
/// partitioned insert (Hive)
pub partitioned: Option<Vec<Expr>>,
/// Columns defined after PARTITION
Expand Down Expand Up @@ -545,9 +548,10 @@ impl Display for Insert {

if let Some(source) = &self.source {
write!(f, "{source}")?;
}

if self.source.is_none() && self.columns.is_empty() {
} else if !self.assignments.is_empty() {
write!(f, "SET ")?;
write!(f, "{}", display_comma_separated(&self.assignments))?;
} else if self.source.is_none() && self.columns.is_empty() {
write!(f, "DEFAULT VALUES")?;
}

Expand Down
2 changes: 2 additions & 0 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1152,13 +1152,15 @@ impl Spanned for Insert {
replace_into: _, // bool
priority: _, // todo, mysql specific
insert_alias: _, // todo, mysql specific
assignments,
} = self;

union_spans(
core::iter::once(table_name.span())
.chain(table_alias.as_ref().map(|i| i.span))
.chain(columns.iter().map(|i| i.span))
.chain(source.as_ref().map(|q| q.span()))
.chain(assignments.iter().map(|i| i.span()))
.chain(partitioned.iter().flat_map(|i| i.iter().map(|k| k.span())))
.chain(after_columns.iter().map(|i| i.span))
.chain(on.as_ref().map(|i| i.span()))
Expand Down
7 changes: 7 additions & 0 deletions src/dialect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,13 @@ pub trait Dialect: Debug + Any {
fn supports_table_sample_before_alias(&self) -> bool {
false
}

/// Returns true if this dialect supports the `INSERT INTO ... SET col1 = 1, ...` syntax.
///
/// MySQL: <https://dev.mysql.com/doc/refman/8.4/en/insert.html>
fn supports_insert_set(&self) -> bool {
false
}
}

/// This represents the operators for which precedence must be defined
Expand Down
7 changes: 6 additions & 1 deletion src/dialect/mysql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,15 @@ impl Dialect for MySqlDialect {
true
}

/// see <https://dev.mysql.com/doc/refman/8.4/en/create-table-select.html>
/// See: <https://dev.mysql.com/doc/refman/8.4/en/create-table-select.html>
fn supports_create_table_select(&self) -> bool {
true
}

/// See: <https://dev.mysql.com/doc/refman/8.4/en/insert.html>
fn supports_insert_set(&self) -> bool {
true
}
}

/// `LOCK TABLES`
Expand Down
24 changes: 10 additions & 14 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11842,9 +11842,9 @@ impl<'a> Parser<'a> {

let is_mysql = dialect_of!(self is MySqlDialect);

let (columns, partitioned, after_columns, source) =
let (columns, partitioned, after_columns, source, assignments) =
if self.parse_keywords(&[Keyword::DEFAULT, Keyword::VALUES]) {
(vec![], None, vec![], None)
(vec![], None, vec![], None, vec![])
} else {
let (columns, partitioned, after_columns) = if !self.peek_subquery_start() {
let columns = self.parse_parenthesized_column_list(Optional, is_mysql)?;
Expand All @@ -11861,9 +11861,14 @@ impl<'a> Parser<'a> {
Default::default()
};

let source = Some(self.parse_query()?);
let (source, assignments) =
if self.dialect.supports_insert_set() && self.parse_keyword(Keyword::SET) {
(None, self.parse_comma_separated(Parser::parse_assignment)?)
} else {
(Some(self.parse_query()?), vec![])
};

(columns, partitioned, after_columns, source)
(columns, partitioned, after_columns, source, assignments)
};

let insert_alias = if dialect_of!(self is MySqlDialect | GenericDialect)
Expand Down Expand Up @@ -11943,6 +11948,7 @@ impl<'a> Parser<'a> {
columns,
after_columns,
source,
assignments,
table,
on,
returning,
Expand Down Expand Up @@ -14171,16 +14177,6 @@ mod tests {
assert!(Parser::parse_sql(&GenericDialect {}, sql).is_err());
}

#[test]
fn test_replace_into_set() {
// NOTE: This is actually valid MySQL syntax, REPLACE and INSERT,
// but the parser does not yet support it.
// https://dev.mysql.com/doc/refman/8.3/en/insert.html
let sql = "REPLACE INTO t SET a='1'";

assert!(Parser::parse_sql(&MySqlDialect {}, sql).is_err());
}

#[test]
fn test_replace_into_set_placeholder() {
let sql = "REPLACE INTO t SET ?";
Expand Down
6 changes: 6 additions & 0 deletions tests/sqlparser_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,12 @@ fn parse_insert_values() {
verified_stmt("INSERT INTO customer WITH foo AS (SELECT 1) SELECT * FROM foo UNION VALUES (1)");
}

#[test]
fn parse_insert_set() {
let dialects = all_dialects_where(|d| d.supports_insert_set());
dialects.verified_stmt("INSERT INTO tbl1 SET col1 = 1, col2 = 'abc', col3 = current_date()");
}

#[test]
fn parse_replace_into() {
let dialect = PostgreSqlDialect {};
Expand Down
3 changes: 3 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4423,6 +4423,7 @@ fn test_simple_postgres_insert_with_alias() {
settings: None,
format_clause: None,
})),
assignments: vec![],
partitioned: None,
after_columns: vec![],
table: false,
Expand Down Expand Up @@ -4493,6 +4494,7 @@ fn test_simple_postgres_insert_with_alias() {
settings: None,
format_clause: None,
})),
assignments: vec![],
partitioned: None,
after_columns: vec![],
table: false,
Expand Down Expand Up @@ -4559,6 +4561,7 @@ fn test_simple_insert_with_quoted_alias() {
settings: None,
format_clause: None,
})),
assignments: vec![],
partitioned: None,
after_columns: vec![],
table: false,
Expand Down
Loading