Skip to content

Commit

Permalink
Feat: add iter for expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
tobymao committed Sep 22, 2023
1 parent 79fc4d1 commit f1b6546
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
6 changes: 4 additions & 2 deletions sqlglot/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -752,12 +752,14 @@ def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
return klass(this=other, expression=this)
return klass(this=this, expression=other)

def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]) -> Bracket:
return Bracket(
this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
)

def __iter__(self):
def __iter__(self) -> t.Iterator:
if "expressions" in self.arg_types:
return iter(self.args.get("expressions") or [])
# We define this because __getitem__ converts Expression into an iterable, which is
# problematic because one can hit infinite loops if they do "for x in some_expr: ..."
# See: https://peps.python.org/pep-0234/
Expand Down
4 changes: 3 additions & 1 deletion tests/test_expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ def test_depth(self):
self.assertEqual(parse_one("x(1)").find(exp.Literal).depth, 1)

def test_iter(self):
self.assertEqual([exp.Literal.number(1), exp.Literal.number(2)], list(parse_one("[1, 2]")))

with self.assertRaises(TypeError):
for x in parse_one("SELECT 1"):
for x in parse_one("1"):
pass

def test_eq(self):
Expand Down

0 comments on commit f1b6546

Please sign in to comment.