Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(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.

like image 874
rmweiss Avatar asked Mar 08 '11 21:03

rmweiss


People also ask

How do I run a raw SQL query in SQLAlchemy?

Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() function as shown below, create a table called books with columns book_id and book_price. Insert record into the tables using insert() and values() function as shown.

Is SQL injection possible with SQLAlchemy?

SQLAlchemy through 1.2. 17 and 1.3. x through 1.3. 0b2 allows SQL Injection via the order_by parameter.

Does SQLAlchemy use SQL?

SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.


2 Answers

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.)

like image 171
Amber Avatar answered Sep 20 '22 11:09

Amber


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(..)
like image 31
Mark Hildreth Avatar answered Sep 21 '22 11:09

Mark Hildreth