Skip to content

Commit

Permalink
Feat(postgres): add support for ALTER TABLE ONLY ... (#2179)
Browse files Browse the repository at this point in the history
  • Loading branch information
georgesittas authored Sep 7, 2023
1 parent 93b7ba2 commit cd301cc
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 4 deletions.
2 changes: 1 addition & 1 deletion sqlglot/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3710,7 +3710,7 @@ class Rollback(Expression):


class AlterTable(Expression):
arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {"this": True, "actions": True, "exists": False, "only": False}


class AddConstraint(Expression):
Expand Down
3 changes: 2 additions & 1 deletion sqlglot/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2289,7 +2289,8 @@ def altertable_sql(self, expression: exp.AlterTable) -> str:
actions = self.expressions(expression, key="actions")

exists = " IF EXISTS" if expression.args.get("exists") else ""
return f"ALTER TABLE{exists} {self.sql(expression, 'this')} {actions}"
only = " ONLY" if expression.args.get("only") else ""
return f"ALTER TABLE{exists}{only} {self.sql(expression, 'this')} {actions}"

def droppartition_sql(self, expression: exp.DropPartition) -> str:
expressions = self.expressions(expression)
Expand Down
3 changes: 3 additions & 0 deletions sqlglot/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -4785,6 +4785,7 @@ def _parse_alter(self) -> exp.AlterTable | exp.Command:
return self._parse_as_command(start)

exists = self._parse_exists()
only = self._match_text_seq("ONLY")
this = self._parse_table(schema=True)

if self._next:
Expand All @@ -4800,7 +4801,9 @@ def _parse_alter(self) -> exp.AlterTable | exp.Command:
this=this,
exists=exists,
actions=actions,
only=only,
)

return self._parse_as_command(start)

def _parse_merge(self) -> exp.Merge:
Expand Down
9 changes: 7 additions & 2 deletions tests/dialects/test_postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,12 +126,17 @@ def test_array_offset(self, logger):
)

def test_postgres(self):
self.validate_identity("x @@ y")

expr = parse_one("SELECT * FROM r CROSS JOIN LATERAL UNNEST(ARRAY[1]) AS s(location)")
unnest = expr.args["joins"][0].this.this
unnest.assert_is(exp.Unnest)

alter_table_only = """ALTER TABLE ONLY "Album" ADD CONSTRAINT "FK_AlbumArtistId" FOREIGN KEY ("ArtistId") REFERENCES "Artist" ("ArtistId") ON DELETE NO ACTION ON UPDATE NO ACTION"""
expr = parse_one(alter_table_only)

self.assertIsInstance(expr, exp.AlterTable)
self.assertEqual(expr.sql(dialect="postgres"), alter_table_only)

self.validate_identity("x @@ y")
self.validate_identity("CAST(x AS MONEY)")
self.validate_identity("CAST(x AS INT4RANGE)")
self.validate_identity("CAST(x AS INT4MULTIRANGE)")
Expand Down

0 comments on commit cd301cc

Please sign in to comment.