Skip to content

Commit

Permalink
feat: Introduce meta comment to parse known functions as exp.Anonymous (
Browse files Browse the repository at this point in the history
#4532)

* feat: Introduce meta comment to parse known functions as exp.Anonymous

* PR Feedback 1

* Make flag case sensitive

* Change to sqlglot.anonymous
  • Loading branch information
VaggelisD authored Dec 19, 2024
1 parent e56d6a9 commit 7a517d7
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
1 change: 1 addition & 0 deletions sqlglot/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ def __new__(cls, clsname, bases, attrs):


SQLGLOT_META = "sqlglot.meta"
SQLGLOT_ANONYMOUS = "sqlglot.anonymous"
TABLE_PARTS = ("this", "db", "catalog")
COLUMN_PARTS = ("this", "table", "db", "catalog")

Expand Down
10 changes: 10 additions & 0 deletions sqlglot/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -5361,6 +5361,16 @@ def _parse_function_call(
alias = not known_function or upper in self.FUNCTIONS_WITH_ALIASED_ARGS
args = self._parse_csv(lambda: self._parse_lambda(alias=alias))

post_func_comments = self._curr and self._curr.comments
if known_function and post_func_comments:
# If the user-inputted comment "/* sqlglot.anonymous */" is following the function
# call we'll construct it as exp.Anonymous, even if it's "known"
if any(
comment.lstrip().startswith(exp.SQLGLOT_ANONYMOUS)
for comment in post_func_comments
):
known_function = False

if alias and known_function:
args = self._kv_to_prop_eq(args)

Expand Down
12 changes: 12 additions & 0 deletions tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -888,3 +888,15 @@ def test_drop_column(self):
ast = parse_one("ALTER TABLE tbl DROP COLUMN col")
self.assertEqual(len(list(ast.find_all(exp.Table))), 1)
self.assertEqual(len(list(ast.find_all(exp.Column))), 1)

def test_udf_meta(self):
ast = parse_one("YEAR(a) /* sqlglot.anonymous */")
self.assertIsInstance(ast, exp.Anonymous)

# Meta flag is case sensitive
ast = parse_one("YEAR(a) /* sqlglot.anONymous */")
self.assertIsInstance(ast, exp.Year)

# Incomplete or incorrect anonymous meta comments are not registered
ast = parse_one("YEAR(a) /* sqlglot.anon */")
self.assertIsInstance(ast, exp.Year)

0 comments on commit 7a517d7

Please sign in to comment.