Obtaining the db information from a table expression #379
-
Hello 👋 This library is really great, thanks for all your hard work! Hopefully this isn't a silly question, I have a script where I am extracting the tables from a query, when I print an individual table I get the perfect output of I would ideally love to store the clean Thanks again for the awesome library and for taking a look at my question. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
First, I think there is some confusion about fundamental Python behavior. From the python docs for print:
So when you do However, when converting a dict object to a str, Python will call repr on it's entries. So when you do So a good way to dig into this behavior is to check the For sqlglot, import sqlglot
from sqlglot import expressions as exp
table = sqlglot.parse_one("SELECT a FROM db.x").find(exp.Table)
print(table.to_s())
# (TABLE this:
# (IDENTIFIER this: x, quoted: False), db:
# (IDENTIFIER this: db, quoted: False))
print(repr(table))
# (TABLE this:
# (IDENTIFIER this: x, quoted: False), db:
# (IDENTIFIER this: db, quoted: False))
print(table.sql())
# db.x
print(str(table))
# db.x Now, keep in mind that the string that repr returns is NOT what's getting stored in your dictionary - the sqlglot Table object is. You're just seeing the result of calling str on the dictionary. tldr:{"a": table.sql()} |
Beta Was this translation helpful? Give feedback.
First, I think there is some confusion about fundamental Python behavior.
From the python docs for print:
So when you do
print(obj)
,str(obj)
gets called.However, when converting a dict object to a str, Python will call repr on it's entries.
So when you do
print({"a": obj})
,repr(obj)
gets called.So a good way to dig into this behavior is to check the
__str__
and__repr__
methods of the object.For sqlglot,
__repr__
calls theto_s
method, and__str__
calls thesql
method: