Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Raw SQL

The query layer does not try to say everything SQL can say. What it does not say is written in SQL, with parameters. This is Django’s Model.objects.raw() and connection.cursor().execute().

Reading: query_sql

#![allow(unused)]
fn main() {
let rows: Vec<(i64, String)> = db
    .query_sql("SELECT id, name FROM network_station WHERE code = $1", &[Value::Text("BRE".into())])
    .await?;
// [(3, "Brest")]
}

query_sql(sql, &params) runs the SQL and reads each row as any type that can be read from a row: a tuple (up to six columns), or a model. The same type rules apply: an integer is read as an i32.

A model is read by the order of its columns, so select them all, in the struct’s order (SELECT * works on a table whose columns are in that order, which is the case of a table rind created):

#![allow(unused)]
fn main() {
let stations: Vec<Station> = db
    .query_sql("SELECT * FROM network_station WHERE id = $1", &[Value::Int(3)])
    .await?;
}

Writing: execute_sql

#![allow(unused)]
fn main() {
let changed: u64 = db
    .execute_sql(
        "UPDATE network_station SET platforms = platforms + $1 WHERE id = ANY($2)",
        &[Value::Int(1), Value::IntArray(vec![3, 4])],
    )
    .await?;
// 2
}

execute_sql answers the number of rows changed. It is what the sample’s model hook uses to move a journey’s stops.

Several statements: batch_execute

#![allow(unused)]
fn main() {
db.batch_execute(
    "INSERT INTO catalog_author (id, name) VALUES (1, 'Frank Herbert');
     INSERT INTO catalog_book (id, title, year, author_id) VALUES (1, 'Dune', 1965, 1);",
)
.await?;
}

batch_execute runs several statements separated by ;, without parameters: for seed data and test fixtures, never for values that come from outside.

Parameters

Parameters are $1, $2… in the SQL, and Values in the list, in the same order:

ValuePostgreSQL
Value::NullNULL
Value::Bool(b)boolean
Value::Int(i)an integer (an i64)
Value::Float(f)double precision
Value::Text(s)text
Value::IntArray(v), Value::TextArray(v)an array of integers, of texts
Value::Date(d)date
Value::Timestamp(t)timestamp with time zone
Value::LocalTimestamp(t)timestamp without time zone
Value::Json(j)jsonb
Value::Binary(b)a value in PostgreSQL’s binary form (bytes, PostGIS, enums)
Value::Array(v)an array of any of these
Value::Decimal(d)numeric (feature decimal)

Never build SQL with format! from a value. A value goes in a parameter; only names you control (a table, a column) may go in the text.

A parameter’s SQL type is guessed by PostgreSQL from where it is used. When it cannot guess, or guesses wrong, cast it: $1::float8, $2::bigint[].

When to use it

  • a statement the query layer cannot say: CASE … WHEN, window functions (ROW_NUMBER() OVER (…)), INSERT … ON CONFLICT, an insert of several rows, SKIP LOCKED, a function of several columns;
  • a report whose SQL is clearer than its translation;
  • a table no model describes.

Keep raw SQL in functions of an ops crate, with a test, and the rest of the code calls the function. A typo in the SQL is found when the test runs, not when the code compiles.

Next: Reference.