English 中文(简体)
Textual SQL
  • 时间:2024-11-03

SQLAlchemy ORM - Textual SQL


Previous Page Next Page  

Earper, textual SQL using text() function has been explained from the perspective of core expression language of SQLAlchemy. Now we shall discuss it from ORM point of view.

Literal strings can be used flexibly with Query object by specifying their use with the text() construct. Most apppcable methods accept it. For example, filter() and order_by().

In the example given below, the filter() method translates the string “id<3” to the WHERE id<3

from sqlalchemy import text
for cust in session.query(Customers).filter(text("id<3")):
   print(cust.name)

The raw SQL expression generated shows conversion of filter to WHERE clause with the code illustrated below −

SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email
FROM customers
WHERE id<3

From our sample data in Customers table, two rows will be selected and name column will be printed as follows −

Ravi Kumar
Komal Pande

To specify bind parameters with string-based SQL, use a colon,and to specify the values, use the params() method.

cust = session.query(Customers).filter(text("id = :value")).params(value = 1).one()

The effective SQL displayed on Python console will be as given below −

SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email
FROM customers
WHERE id = ?

To use an entirely string-based statement, a text() construct representing a complete statement can be passed to from_statement().

session.query(Customers).from_statement(text("SELECT * FROM customers")).all()

The result of above code will be a basic SELECT statement as given below −

SELECT * FROM customers

Obviously, all records in customers table will be selected.

The text() construct allows us to pnk its textual SQL to Core or ORM-mapped column expressions positionally. We can achieve this by passing column expressions as positional arguments to the TextClause.columns() method.

stmt = text("SELECT name, id, name, address, email FROM customers")
stmt = stmt.columns(Customers.id, Customers.name)
session.query(Customers.id, Customers.name).from_statement(stmt).all()

The id and name columns of all rows will be selected even though the SQLite engine executes following expression generated by above code shows all columns in text() method −

SELECT name, id, name, address, email FROM customers
Advertisements