I am using sqlalchemy's core features to write some abstraction layer. The layer itself needs to be able to create tables from select statements.
Sample code:
metadata = MetaData(bind=engine)
table = Table(table_name, metadata, autoload=True, autoload_with=engine)
s = select(table).where(table.c.column_1 > 10)
Now what I want to be able to do is create a new table from the select statement above. How can I do it?
note: This question has also been asked by me at https://groups.google.com/forum/#!topic/sqlalchemy/lKDkX68fOqI. Sorry for cross-posting
Only way I can think of is to compile the above select statement with parameters bound to it. The construct SQL manually and then do the create table
For example:
sql = str(s.compile(dialect=postgresql.dialect(),
compile_kwargs={"literal_binds": True}
)
)
create_tbl_sql = "CREATE TABLE {0} AS {2}".format(new_table_name, sql)
connection.execute(create_tbl_sql)
Also the literal bind compile is a pain when datetime objects are involved in the where condition. Pretty much whenever something that can not be serialised exists in the query. I will have to work around that.
It does not seem clean to take this approach. So I am asking the community at large if they know something better.