rmweiss
rmweiss

Reputation: 716

(Only) generate SQL-Code with SqlAlchemy

Can i use the SqlAlchemy ORM-Mapper to only generate the SQL-Code?

With simple tables i can use code like

print users_table.select()
print users_table.insert()
print users_table.update()
print users_table.delete()

But with the ORM i have only found a way for SELECT-Statements:

TestUser = User("John", "Doe")
print session.query(User)

How can i generate the SQL for INSERT/UPDATE/DELETE (without realy manipulating the database)?

Thanks.

Upvotes: 14

Views: 12919

Answers (3)

Fang-Pen Lin
Fang-Pen Lin

Reputation: 14436

It's simple. Just like what you do, you can convert the query as string

TestUser = User("John", "Doe")
# convert querying object to string
query_stat = str(session.query(User))
print query_stat 

And here, the query_stat should be SQL querying statement.

Upvotes: 3

Mark Hildreth
Mark Hildreth

Reputation: 43091

You can access the table objects for a mapped class through the sqlalchemy.orm.class_mapper function:


users_table = class_mapper(User).mapped_table 
users_table.insert(..)

If you're using declarative syntax, you can do this:


users_table = User.__table__
users_table.insert(..)

Upvotes: 3

Amber
Amber

Reputation: 527063

Perhaps you want the SQLAlchemy core expression language, instead of the ORM?

http://www.sqlalchemy.org/docs/core/index.html

The ORM is designed to be very tightly data-bound, and thus to not really be decoupled from its DB sessions. The expression language, on the other hand, can be directly translated to SQL. (Just take any of the resulting objects and pass them to str() and you'll get the equivalent SQL.)

Upvotes: 10

Related Questions