Skip to content

Commit a9dca8d

Browse files
feat(postgres): Support generated columns (#4472)
* feat(postgres): Support STORED computed columns * Update sqlglot/dialects/postgres.py Co-authored-by: Jo <[email protected]> --------- Co-authored-by: Jo <[email protected]>
1 parent 3945acc commit a9dca8d

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

sqlglot/dialects/postgres.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,20 @@ def _parse_jsonb_exists(self) -> exp.JSONBExists:
476476
and self.dialect.to_json_path(self._parse_bitwise()),
477477
)
478478

479+
def _parse_generated_as_identity(
480+
self,
481+
) -> (
482+
exp.GeneratedAsIdentityColumnConstraint
483+
| exp.ComputedColumnConstraint
484+
| exp.GeneratedAsRowColumnConstraint
485+
):
486+
this = super()._parse_generated_as_identity()
487+
488+
if self._match_text_seq("STORED"):
489+
this = self.expression(exp.ComputedColumnConstraint, this=this.expression)
490+
491+
return this
492+
479493
class Generator(generator.Generator):
480494
SINGLE_STRING_INTERVAL = True
481495
RENAME_TABLE_WITH_DB = False
@@ -691,3 +705,6 @@ def array_sql(self, expression: exp.Array) -> str:
691705
if isinstance(seq_get(exprs, 0), exp.Select)
692706
else f"{self.normalize_func('ARRAY')}[{self.expressions(expression, flat=True)}]"
693707
)
708+
709+
def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
710+
return f"GENERATED ALWAYS AS ({self.sql(expression, 'this')}) STORED"

tests/dialects/test_postgres.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1047,6 +1047,7 @@ def test_ddl(self):
10471047
self.validate_identity("CREATE TABLE tbl (col INT UNIQUE NULLS NOT DISTINCT DEFAULT 9.99)")
10481048
self.validate_identity("CREATE TABLE tbl (col UUID UNIQUE DEFAULT GEN_RANDOM_UUID())")
10491049
self.validate_identity("CREATE TABLE tbl (col UUID, UNIQUE NULLS NOT DISTINCT (col))")
1050+
self.validate_identity("CREATE TABLE tbl (col_a INT GENERATED ALWAYS AS (1 + 2) STORED)")
10501051

10511052
self.validate_identity("CREATE INDEX CONCURRENTLY ix_table_id ON tbl USING btree(id)")
10521053
self.validate_identity(

0 commit comments

Comments
 (0)