Skip to content

Commit fc050bd

Browse files
authored
fix(sqlite): Fix transpilation of GENERATED AS IDENTITY (#3634)
* fix(postgres, sqlite): Fix transpilation of IDENTITY <-> AUTOINCREMENT columns * PR Feedback 1
1 parent 1afe6ac commit fc050bd

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

sqlglot/dialects/sqlite.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,26 @@ def _transform_create(expression: exp.Expression) -> exp.Expression:
7575
return expression
7676

7777

78+
def _generated_to_auto_increment(expression: exp.Expression) -> exp.Expression:
79+
if not isinstance(expression, exp.ColumnDef):
80+
return expression
81+
82+
generated = expression.find(exp.GeneratedAsIdentityColumnConstraint)
83+
84+
if generated:
85+
t.cast(exp.ColumnConstraint, generated.parent).pop()
86+
87+
not_null = expression.find(exp.NotNullColumnConstraint)
88+
if not_null:
89+
t.cast(exp.ColumnConstraint, not_null.parent).pop()
90+
91+
expression.append(
92+
"constraints", exp.ColumnConstraint(kind=exp.AutoIncrementColumnConstraint())
93+
)
94+
95+
return expression
96+
97+
7898
class SQLite(Dialect):
7999
# https://sqlite.org/forum/forumpost/5e575586ac5c711b?raw
80100
NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE
@@ -141,6 +161,7 @@ class Generator(generator.Generator):
141161
exp.CurrentDate: lambda *_: "CURRENT_DATE",
142162
exp.CurrentTime: lambda *_: "CURRENT_TIME",
143163
exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
164+
exp.ColumnDef: transforms.preprocess([_generated_to_auto_increment]),
144165
exp.DateAdd: _date_add_sql,
145166
exp.DateStrToDate: lambda self, e: self.sql(e, "this"),
146167
exp.If: rename_func("IIF"),

tests/dialects/test_sqlite.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@ def test_ddl(self):
202202
"CREATE TABLE z (a INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT)",
203203
read={
204204
"mysql": "CREATE TABLE z (a INT UNIQUE PRIMARY KEY AUTO_INCREMENT)",
205+
"postgres": "CREATE TABLE z (a INT GENERATED BY DEFAULT AS IDENTITY NOT NULL UNIQUE PRIMARY KEY)",
205206
},
206207
write={
207208
"sqlite": "CREATE TABLE z (a INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT)",

0 commit comments

Comments
 (0)