From bbca0a8e7525d871eb04d452dc064af833b4314f Mon Sep 17 00:00:00 2001 From: Andi Albrecht Date: Sun, 12 Jul 2009 12:33:56 +0200 Subject: Query token ancestry. --- sqlparse/sql.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'sqlparse/sql.py') diff --git a/sqlparse/sql.py b/sqlparse/sql.py index b5ba902..484b0f0 100644 --- a/sqlparse/sql.py +++ b/sqlparse/sql.py @@ -93,6 +93,32 @@ class Token(object): """Return ``True`` if this token is a whitespace token.""" return self.ttype and self.ttype in T.Whitespace + def within(self, group_cls): + """Returns ``True`` if this token is within *group_cls*. + + Use this method for example to check if an identifier is within + a function: ``t.within(sql.Function)``. + """ + parent = self.parent + while parent: + if isinstance(parent, group_cls): + return True + parent = parent.parent + return False + + def is_child_of(self, other): + """Returns ``True`` if this token is a direct child of *other*.""" + return self.parent == other + + def has_ancestor(self, other): + """Returns ``True`` if *other* is in this tokens ancestry.""" + parent = self.parent + while parent: + if parent == other: + return True + parent = parent.parent + return False + class TokenList(Token): """A group of tokens. -- cgit v1.2.1