Skip to content
Draft
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
10 changes: 5 additions & 5 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ConflictTarget>,
/// Action to take when a conflict occurs.
pub action: OnConflictAction,
Expand All @@ -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 <https://www.postgresql.org/docs/current/sql-insert.html>
/// and <https://www.sqlite.org/lang_upsert.html>
Columns {
/// The columns of the conflict target.
columns: Vec<Ident>,
/// The `WHERE index_predicate` after the columns, if any.
/// The index inference terms of the conflict target.
columns: Vec<IndexColumn>,
/// The `WHERE index_predicate` after the list, if any.
predicate: Option<Expr>,
},
/// Target specified as a named constraint.
Expand Down
66 changes: 42 additions & 24 deletions src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
Expand All @@ -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))
}
}

Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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]
Expand Down
4 changes: 4 additions & 0 deletions src/dialect/generic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
5 changes: 5 additions & 0 deletions src/dialect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions src/dialect/postgresql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
28 changes: 25 additions & 3 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15424,6 +15424,30 @@ impl<'a> Parser<'a> {
})
}

fn parse_conflict_target_columns(&mut self) -> Result<Vec<IndexColumn>, 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(
Expand Down Expand Up @@ -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 {
Expand Down
160 changes: 157 additions & 3 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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![
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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"
);
}
Loading
Loading