Skip to content

Commit

Permalink
Feat: add the ability to set meta in sql comments (#2351)
Browse files Browse the repository at this point in the history
  • Loading branch information
tobymao authored Oct 2, 2023
1 parent e4da5d7 commit 8dc2a9c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
12 changes: 11 additions & 1 deletion sqlglot/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ def __new__(cls, clsname, bases, attrs):
return klass


SQLGLOT_META = "sqlglot.meta"


class Expression(metaclass=_Expression):
"""
The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
Expand Down Expand Up @@ -266,7 +269,14 @@ def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
if self.comments is None:
self.comments = []
if comments:
self.comments.extend(comments)
for comment in comments:
_, *meta = comment.split(SQLGLOT_META)
if meta:
for kv in "".join(meta).split(","):
k, *v = kv.split("=")
value = v[0].strip() if v else True
self.meta[k.strip()] = value
self.comments.append(comment)

def append(self, arg_key: str, value: t.Any) -> None:
"""
Expand Down
5 changes: 5 additions & 0 deletions tests/test_expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -951,3 +951,8 @@ def test_is_type(self):

with self.assertRaises(ParseError):
exp.DataType.build("foo")

def test_set_meta(self):
query = parse_one("SELECT * FROM foo /* sqlglot.meta x = 1, y = a, z */")
self.assertEqual(query.find(exp.Table).meta, {"x": "1", "y": "a", "z": True})
self.assertEqual(query.sql(), "SELECT * FROM foo /* sqlglot.meta x = 1, y = a, z */")

0 comments on commit 8dc2a9c

Please sign in to comment.