Skip to content

Commit 006b384

Browse files
authored
Fix(postgres): add support for WHERE clause in INSERT DML (#4550)
1 parent cead7c3 commit 006b384

File tree

4 files changed

+9
-1
lines changed

4 files changed

+9
-1
lines changed

sqlglot/expressions.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2291,6 +2291,7 @@ class OnConflict(Expression):
22912291
"action": False,
22922292
"conflict_keys": False,
22932293
"constraint": False,
2294+
"where": False,
22942295
}
22952296

22962297

sqlglot/generator.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1861,7 +1861,8 @@ def onconflict_sql(self, expression: exp.OnConflict) -> str:
18611861
set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
18621862
expressions = f" {set_keyword}{expressions}"
18631863

1864-
return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"
1864+
where = self.sql(expression, "where")
1865+
return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
18651866

18661867
def returning_sql(self, expression: exp.Returning) -> str:
18671868
return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"

sqlglot/parser.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2732,6 +2732,8 @@ def _parse_insert(self) -> t.Union[exp.Insert, exp.MultitableInserts]:
27322732
if not is_function
27332733
else self._parse_function()
27342734
)
2735+
if isinstance(this, exp.Table) and self._match(TokenType.ALIAS, advance=False):
2736+
this.set("alias", self._parse_table_alias())
27352737

27362738
returning = self._parse_returning()
27372739

@@ -2796,6 +2798,7 @@ def _parse_on_conflict(self) -> t.Optional[exp.OnConflict]:
27962798
action=action,
27972799
conflict_keys=conflict_keys,
27982800
constraint=constraint,
2801+
where=self._parse_where(),
27992802
)
28002803

28012804
def _parse_returning(self) -> t.Optional[exp.Returning]:

tests/dialects/test_postgres.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -874,6 +874,9 @@ def test_ddl(self):
874874
self.validate_identity("ALTER TABLE t1 SET ACCESS METHOD method")
875875
self.validate_identity("ALTER TABLE t1 SET TABLESPACE tablespace")
876876
self.validate_identity("ALTER TABLE t1 SET (fillfactor = 5, autovacuum_enabled = TRUE)")
877+
self.validate_identity(
878+
"INSERT INTO newtable AS t(a, b, c) VALUES (1, 2, 3) ON CONFLICT(c) DO UPDATE SET a = t.a + 1 WHERE t.a < 1"
879+
)
877880
self.validate_identity(
878881
"ALTER TABLE tested_table ADD CONSTRAINT unique_example UNIQUE (column_name) NOT VALID"
879882
)

0 commit comments

Comments
 (0)