How to get DDL string from metadata?

253 views
Skip to first unread message

Stefan Urbanek

unread,
Apr 24, 2012, 3:33:00 AM4/24/12
to sqlal...@googlegroups.com
Hi,

How can I get a string that is going to be executed without executing it?

Example code:

from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String

engine = create_engine("sqlite://")
metadata = MetaData(engine)

table = Table("foo", metadata)
table.append_column(Column("id", Integer))
table.append_column(Column("name", String))


Now I would like to get the "CREATE TABLE ..." string that I would like to store/use somewhere else.

How can I do that?

Thanks for any hints,

Stefan

Robert Forkel

unread,
Apr 24, 2012, 3:50:21 AM4/24/12
to sqlal...@googlegroups.com
what I do is using a custom engine like this:


out = StringIO()
def dump(sql, *multiparams, **params):
# make sure the mock engine appends ';' to the end of DDL statements
# so they can be pasted and run in sql developer!
out.write(('%s' %
sql.compile(dialect=engine.dialect)).strip()+';\n/\n')
engine = create_engine('oracle://', strategy='mock', executor=dump)

regards
robert
> --
> You received this message because you are subscribed to the Google Groups
> "sqlalchemy" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/sqlalchemy/-/jJTcbg44Yx8J.
> To post to this group, send email to sqlal...@googlegroups.com.
> To unsubscribe from this group, send email to
> sqlalchemy+...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/sqlalchemy?hl=en.

Stefan Urbanek

unread,
Apr 24, 2012, 4:00:13 AM4/24/12
to sqlal...@googlegroups.com
Thank you very much, seems to work as I wanted.

By the way, you are using executor=function in create_engine. I do not see it in the documentation [1]. Is it just missing in the docs or it is a private parameter?

Regards,

Stefan

[1] http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine
Stefan Urbanek
data analyst and data brewmaster

Twitter: @Stiivi
Home: http://stiivi.com
Brewery: http://databrewery.org
Github: https://github.com/Stiivi



Robert Forkel

unread,
Apr 24, 2012, 4:10:18 AM4/24/12
to sqlal...@googlegroups.com
As far as i can see, the 'mock' strategy isn't in the docs either, but
I found a thread [1] where it is mentioned as if it is supposed to be
public.

[1] http://groups.google.com/group/sqlalchemy/browse_thread/thread/dd2596febeff1728


On Tue, Apr 24, 2012 at 10:00 AM, Stefan Urbanek

Michael Bayer

unread,
Apr 24, 2012, 9:24:40 AM4/24/12
to sqlal...@googlegroups.com
the FAQ has the full details on the several ways you might go about this:



Reply all
Reply to author
Forward
0 new messages