From 4a8b69ba04b01972280b12d215fc13dc454fffec Mon Sep 17 00:00:00 2001 From: icefery Date: Tue, 1 Dec 2026 21:08:30 +0800 Subject: [PATCH] PostgreSQL: Parse index expressions in ON CONFLICT targets Reuse the CREATE INDEX column parser for PostgreSQL and Generic conflict inference. Preserve the index predicate and the update condition as distinct expressions. --- src/ast/mod.rs | 10 +-- src/ast/spans.rs | 66 +++++++++------ src/dialect/generic.rs | 4 + src/dialect/mod.rs | 5 ++ src/dialect/postgresql.rs | 4 + src/parser/mod.rs | 28 ++++++- tests/sqlparser_postgres.rs | 160 +++++++++++++++++++++++++++++++++++- tests/sqlparser_sqlite.rs | 18 +++- 8 files changed, 259 insertions(+), 36 deletions(-) diff --git a/src/ast/mod.rs b/src/ast/mod.rs index c61c32cf32..f2ef4b08db 100644 --- a/src/ast/mod.rs +++ b/src/ast/mod.rs @@ -7083,7 +7083,7 @@ pub struct TableAliasWithoutColumns { #[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] /// `ON CONFLICT` clause representation. pub struct OnConflict { - /// Optional conflict target specifying columns or constraint. + /// Optional conflict target for index inference or a named constraint. pub conflict_target: Option, /// Action to take when a conflict occurs. pub action: OnConflictAction, @@ -7093,16 +7093,16 @@ pub struct OnConflict { #[cfg_attr(feature = "visitor", derive(Visit, VisitMut))] /// Target specification for an `ON CONFLICT` clause. pub enum ConflictTarget { - /// Target specified as a list of columns, optionally followed by + /// Target specified as a list of index columns or expressions, optionally followed by /// `WHERE index_predicate`, which lets a partial unique index be inferred as the arbiter: /// `ON CONFLICT (a) WHERE b > 0 DO ...`. PostgreSQL and SQLite both accept the predicate. /// /// See /// and Columns { - /// The columns of the conflict target. - columns: Vec, - /// The `WHERE index_predicate` after the columns, if any. + /// The index inference terms of the conflict target. + columns: Vec, + /// The `WHERE index_predicate` after the list, if any. predicate: Option, }, /// Target specified as a named constraint. diff --git a/src/ast/spans.rs b/src/ast/spans.rs index 4baf106c9a..ece0862d5c 100644 --- a/src/ast/spans.rs +++ b/src/ast/spans.rs @@ -772,7 +772,7 @@ impl Spanned for CreateIndex { name.iter() .map(|i| i.span()) .chain(core::iter::once(table_name.span())) - .chain(columns.iter().map(|i| i.column.span())) + .chain(columns.iter().map(Spanned::span)) .chain(include.iter().map(|i| i.span)) .chain(with.iter().map(|i| i.span())) .chain(predicate.iter().map(|i| i.span())) @@ -783,7 +783,9 @@ impl Spanned for CreateIndex { impl Spanned for IndexColumn { fn span(&self) -> Span { - self.column.span() + self.column + .span() + .union_opt(&self.operator_class.as_ref().map(Spanned::span)) } } @@ -1580,7 +1582,7 @@ impl Spanned for ConflictTarget { ConflictTarget::Columns { columns, predicate } => union_spans( columns .iter() - .map(|i| i.span) + .map(Spanned::span) .chain(predicate.iter().map(|p| p.span())), ), ConflictTarget::OnConstraint(object_name) => object_name.span(), @@ -3132,27 +3134,43 @@ ALTER TABLE users #[test] fn test_on_conflict_target_predicate_span() { - let dialect = crate::dialect::PostgreSqlDialect {}; - let conflict_span = |sql: &str| -> Span { - let stmts = Parser::parse_sql(&dialect, sql).unwrap(); - let Statement::Insert(Insert { - on: Some(OnInsert::OnConflict(on_conflict)), - .. - }) = &stmts[0] - else { - panic!("not an INSERT ... ON CONFLICT statement"); - }; - on_conflict.span() - }; - - // The target's predicate extends the clause's span past the column list. - let sql = "INSERT INTO t (a, b) VALUES (1, 2) ON CONFLICT (a) WHERE b > 0 DO NOTHING"; - let test = SpanTest::new(&dialect, sql); - assert_eq!(test.get_source(conflict_span(sql)), "a) WHERE b > 0"); - - let sql = "INSERT INTO t (a, b) VALUES (1, 2) ON CONFLICT (a) DO NOTHING"; - let test = SpanTest::new(&dialect, sql); - assert_eq!(test.get_source(conflict_span(sql)), "a"); + let dialects: [&dyn Dialect; 2] = [&crate::dialect::PostgreSqlDialect {}, &GenericDialect]; + for (sql, expected_target, expected_conflict) in [ + ( + "INSERT INTO t (a, b) VALUES (1, 2) ON CONFLICT (a) WHERE b > 0 DO NOTHING", + "a) WHERE b > 0", + "a) WHERE b > 0", + ), + ( + "INSERT INTO t (a, b) VALUES (1, 2) ON CONFLICT (a) DO NOTHING", + "a", + "a", + ), + ( + r#"INSERT INTO t VALUES ('x') ON CONFLICT (lower(a) COLLATE "C" pg_catalog.text_pattern_ops) DO NOTHING"#, + r#"lower(a) COLLATE "C" pg_catalog.text_pattern_ops"#, + r#"lower(a) COLLATE "C" pg_catalog.text_pattern_ops"#, + ), + ( + "INSERT INTO t VALUES (1, 2) ON CONFLICT ((a + 1)) WHERE b > 0 DO UPDATE SET b = EXCLUDED.b WHERE t.b < 10", + "a + 1)) WHERE b > 0", + "a + 1)) WHERE b > 0 DO UPDATE SET b = EXCLUDED.b WHERE t.b < 10", + ), + ] { + for dialect in dialects { + let mut test = SpanTest::new(dialect, sql); + let Statement::Insert(Insert { + on: Some(OnInsert::OnConflict(on_conflict)), + .. + }) = test.0.parse_statement().unwrap() + else { + panic!("not an INSERT ... ON CONFLICT statement"); + }; + let target = on_conflict.conflict_target.as_ref().unwrap(); + assert_eq!(test.get_source(target.span()), expected_target, "{sql}"); + assert_eq!(test.get_source(on_conflict.span()), expected_conflict, "{sql}"); + } + } } #[test] diff --git a/src/dialect/generic.rs b/src/dialect/generic.rs index fdf3529054..dc89c82677 100644 --- a/src/dialect/generic.rs +++ b/src/dialect/generic.rs @@ -141,6 +141,10 @@ impl Dialect for GenericDialect { true } + fn supports_on_conflict_index_expressions(&self) -> bool { + true + } + fn supports_sql_option_without_value(&self) -> bool { true } diff --git a/src/dialect/mod.rs b/src/dialect/mod.rs index b975805b5f..24e2a416aa 100644 --- a/src/dialect/mod.rs +++ b/src/dialect/mod.rs @@ -1726,6 +1726,11 @@ pub trait Dialect: Debug + Any { false } + /// Does the dialect support index expressions in `ON CONFLICT (...)` targets? + fn supports_on_conflict_index_expressions(&self) -> bool { + false + } + /// Returns true if the dialect accepts `VALUE` as a synonym of `VALUES`. /// /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/insert.html) diff --git a/src/dialect/postgresql.rs b/src/dialect/postgresql.rs index 4e7265cb02..33a2b5d5d0 100644 --- a/src/dialect/postgresql.rs +++ b/src/dialect/postgresql.rs @@ -583,6 +583,10 @@ impl Dialect for PostgreSqlDialect { true } + fn supports_on_conflict_index_expressions(&self) -> bool { + true + } + fn supports_create_table_like_parenthesized(&self) -> bool { true } diff --git a/src/parser/mod.rs b/src/parser/mod.rs index 2e653c7983..f5517ff6e5 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -15424,6 +15424,30 @@ impl<'a> Parser<'a> { }) } + fn parse_conflict_target_columns(&mut self) -> Result, ParserError> { + if !self.dialect.supports_on_conflict_index_expressions() { + return self.parse_parenthesized_column_list_inner(Mandatory, false, |p| { + p.parse_identifier().map(IndexColumn::from) + }); + } + + self.parse_parenthesized_column_list_inner(Mandatory, false, |p| { + let column = p.parse_create_index_expr()?; + let order = &column.column; + // PostgreSQL's shared grammar accepts ordering, but index inference rejects it. + if order.options.sort.is_some() + || order.options.nulls_first.is_some() + || order.with_fill.is_some() + { + return parser_err!( + "Ordering options are not allowed in an ON CONFLICT target", + p.get_current_token().span.start + ); + } + Ok(column) + }) + } + /// Parses a parenthesized comma-separated list of qualified, possibly quoted identifiers. /// For example: `(db1.sc1.tbl1.col1, db1.sc1.tbl1."col 2", ...)` pub fn parse_parenthesized_qualified_column_list( @@ -20274,9 +20298,7 @@ impl<'a> Parser<'a> { if self.parse_keywords(&[Keyword::ON, Keyword::CONSTRAINT]) { Some(ConflictTarget::OnConstraint(self.parse_object_name(false)?)) } else if self.peek_token_ref().token == Token::LParen { - let columns = - self.parse_parenthesized_column_list(IsOptional::Mandatory, false)?; - // PostgreSQL: `( column [, ...] ) [ WHERE index_predicate ]`. + let columns = self.parse_conflict_target_columns()?; let predicate = if self.parse_keyword(Keyword::WHERE) { Some(self.parse_expr()?) } else { diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs index 9c59720aa8..7b9ddabde2 100644 --- a/tests/sqlparser_postgres.rs +++ b/tests/sqlparser_postgres.rs @@ -2687,7 +2687,7 @@ fn parse_pg_on_conflict() { })), .. }) => { - assert_eq!(vec![Ident::from("did")], cols); + assert_eq!(vec![IndexColumn::from("did")], cols); assert_eq!( OnConflictAction::DoUpdate(DoUpdate { assignments: vec![Assignment { @@ -2723,7 +2723,10 @@ fn parse_pg_on_conflict() { })), .. }) => { - assert_eq!(vec![Ident::from("did"), Ident::from("area"),], cols); + assert_eq!( + vec![IndexColumn::from("did"), IndexColumn::from("area")], + cols + ); assert_eq!( OnConflictAction::DoUpdate(DoUpdate { assignments: vec![ @@ -2789,7 +2792,7 @@ fn parse_pg_on_conflict() { })), .. }) => { - assert_eq!(vec![Ident::from("did")], cols); + assert_eq!(vec![IndexColumn::from("did")], cols); assert_eq!( OnConflictAction::DoUpdate(DoUpdate { assignments: vec![Assignment { @@ -14874,3 +14877,154 @@ fn parse_create_function_transform() { ); } } + +#[test] +fn parse_pg_on_conflict_index_expressions() { + let stmt = pg_and_generic().one_statement_parses_to( + "INSERT INTO tbl_a (val1, val2) SELECT val1, val2 FROM tbl_2 \ + ON CONFLICT (val1, COALESCE(val2, '')) DO NOTHING", + "INSERT INTO tbl_a (val1, val2) SELECT val1, val2 FROM tbl_2 \ + ON CONFLICT(val1, COALESCE(val2, '')) DO NOTHING", + ); + let Statement::Insert(Insert { + on: + Some(OnInsert::OnConflict(OnConflict { + conflict_target: + Some(ConflictTarget::Columns { + columns, + predicate: None, + }), + action: OnConflictAction::DoNothing, + })), + .. + }) = stmt + else { + panic!("expected an INSERT with a conflict target, got {stmt:?}"); + }; + let [name, expression] = columns.as_slice() else { + panic!("expected a name and an expression, got {columns:?}"); + }; + assert_eq!(name, &IndexColumn::from("val1")); + let Expr::Function(Function { + name, + args: FunctionArguments::List(FunctionArgumentList { args, .. }), + .. + }) = &expression.column.expr + else { + panic!("expected a function call, got {:?}", expression.column.expr); + }; + assert_eq!(*name, ObjectName::from(vec![Ident::new("COALESCE")])); + assert_eq!( + args.as_slice(), + &[ + FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Identifier("val2".into()))), + FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::value(single_quoted_string("")))), + ] + ); +} + +#[test] +fn parse_pg_on_conflict_index_options() { + let dialects = pg_and_generic(); + let stmt = dialects.verified_stmt( + "INSERT INTO t VALUES ('x', 1) ON CONFLICT(lower(a) COLLATE \"C\" pg_catalog.text_pattern_ops, \ + (b + 1)) WHERE b > 0 DO UPDATE SET a = EXCLUDED.a WHERE t.b < 10", + ); + let Statement::Insert(Insert { + on: + Some(OnInsert::OnConflict(OnConflict { + conflict_target: + Some(ConflictTarget::Columns { + columns, + predicate: Some(predicate), + }), + action: + OnConflictAction::DoUpdate(DoUpdate { + selection: Some(selection), + .. + }), + })), + .. + }) = stmt + else { + panic!("expected an INSERT with a conflict target and an update condition, got {stmt:?}"); + }; + assert_eq!( + columns, + vec![ + IndexColumn { + column: OrderByExpr { + expr: Expr::Collate { + expr: Box::new(dialects.verified_expr("lower(a)")), + collation: ObjectName::from(vec![Ident::with_quote('"', "C")]), + }, + options: OrderByOptions::default(), + with_fill: None, + }, + operator_class: Some(ObjectName::from(vec![ + "pg_catalog".into(), + "text_pattern_ops".into(), + ])), + }, + IndexColumn { + column: OrderByExpr { + expr: Expr::Nested(Box::new(dialects.verified_expr("b + 1"))), + options: OrderByOptions::default(), + with_fill: None, + }, + operator_class: None, + }, + ] + ); + assert_eq!(predicate, dialects.verified_expr("b > 0")); + assert_eq!(selection, dialects.verified_expr("t.b < 10")); +} + +#[test] +fn parse_pg_on_conflict_index_target_errors() { + let dialects = pg_and_generic(); + let ordering_error = "Ordering options are not allowed in an ON CONFLICT target"; + for (target, error) in [ + ("()", "Expected: an expression, found: )"), + ("((a + ))", "Expected: an expression, found: )"), + ("(a,)", "Expected: an expression, found: )"), + ("(a ops (x = 1))", "Expected: ), found: ("), + ("(a DESC)", ordering_error), + ("(a NULLS LAST)", ordering_error), + ] { + let sql = format!("INSERT INTO t VALUES (1) ON CONFLICT {target} DO NOTHING"); + assert_eq!( + dialects.parse_sql_statements(&sql).unwrap_err(), + ParserError::ParserError(error.to_string()), + "{sql}" + ); + } + + let generic = TestedDialects::new(vec![Box::new(GenericDialect {})]); + assert_eq!( + generic + .parse_sql_statements("INSERT INTO t VALUES (1) ON CONFLICT (a WITH FILL) DO NOTHING") + .unwrap_err(), + ParserError::ParserError(ordering_error.to_string()), + ); +} + +#[cfg(feature = "visitor")] +#[test] +fn parse_pg_on_conflict_index_expressions_are_visitable() { + let mut stmt = pg_and_generic().verified_stmt( + "INSERT INTO t VALUES ('x') ON CONFLICT(lower(a)) WHERE b > 0 \ + DO UPDATE SET a = EXCLUDED.a WHERE c < 10", + ); + let _ = visit_expressions_mut(&mut stmt, |expr| { + if let Expr::Identifier(ident) = expr { + ident.value.push_str("_new"); + } + core::ops::ControlFlow::<()>::Continue(()) + }); + assert_eq!( + stmt.to_string(), + "INSERT INTO t VALUES ('x') ON CONFLICT(lower(a_new)) WHERE b_new > 0 \ + DO UPDATE SET a = EXCLUDED.a WHERE c_new < 10" + ); +} diff --git a/tests/sqlparser_sqlite.rs b/tests/sqlparser_sqlite.rs index e947ffb7c2..671af62b57 100644 --- a/tests/sqlparser_sqlite.rs +++ b/tests/sqlparser_sqlite.rs @@ -1703,7 +1703,7 @@ fn parse_on_conflict_target_predicate() { })), .. }) => { - assert_eq!(columns, vec![Ident::new("a")]); + assert_eq!(columns, vec![IndexColumn::from("a")]); assert_eq!(predicate.to_string(), "b > 0"); } other => panic!("unexpected statement: {other:?}"), @@ -2228,3 +2228,19 @@ fn parse_is_null_test_precedence() { let without_is_operator = all_dialects_where(|d| !d.supports_is_operator()); assert_eq!(top_operator(&without_is_operator, "a IS NULL + 1"), Plus); } + +#[test] +fn parse_on_conflict_target_rejects_index_expressions() { + let dialect = sqlite(); + for (target, error) in [ + ("(lower(a))", "Expected: ), found: ("), + (r#"(a COLLATE "C")"#, "Expected: ), found: COLLATE"), + ] { + let sql = format!("INSERT INTO t VALUES (1) ON CONFLICT {target} DO NOTHING"); + assert_eq!( + dialect.parse_sql_statements(&sql).unwrap_err(), + ParserError::ParserError(error.to_string()), + "{sql}" + ); + } +}