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

Writing rows

Insert, Update and Delete are statements on rows, built like a query and run by a Db. They are Django’s Model.objects.create(), QuerySet.update() and QuerySet.delete().

They are writes of rows, not of objects: they run none of the model’s behaviours or hooks. To write one object with them, use its own methods instead (train.insert(&db), train.save(&db), see Writing objects).

Inserting: Insert

#![allow(unused)]
fn main() {
let train: Train = db
    .insert(
        &Insert::<Train>::new()
            .value(Train::number(), "TGV1")
            .value(Train::name(), "Le Mistral")
            .value(Train::kind(), "passenger")
            .value(Train::depot_id(), 1),
    )
    .await?;
}
INSERT INTO "fleet_train" ("number", "name", "kind", "depot_id")
VALUES ($1, $2, $3, $4)
RETURNING "id", "number", "name", "kind", "status", "depot_id"
-- params: [Text("TGV1"), Text("Le Mistral"), Text("passenger"), Int(1)]
Train { id: 101, number: "TGV1", name: "Le Mistral", kind: "passenger", status: "active", depot_id: 1 }
  • Each value(path, value) gives a column. The value has the column’s type, checked when the code compiles.
  • The columns you do not give take their SQL default: status is 'active' here, and the key comes from the identity.
  • insert answers the row as the database stored it, with its key and its defaults (RETURNING).
  • A column without a default that you do not give is a database error (null value in column … violates not-null constraint).

insert_keyed answers the new key beside the row, for a model whose key is not id, or when you only need the key:

#![allow(unused)]
fn main() {
let (key, train): (i64, Train) = db.insert_keyed(&insert).await?;
}

A value can be None for a nullable column (NULL), or an expression.

There is no insert of several rows in one statement (Django’s bulk_create): loop over insert, in a transaction so that it is fast and all or nothing, or write it in raw SQL.

Updating: Update

#![allow(unused)]
fn main() {
let changed: u64 = db
    .execute(
        &Update::<Train>::new()
            .set(Train::status(), "retired")
            .filter(Train::id().eq(train.id)),
    )
    .await?;
}
UPDATE "fleet_train" AS "t0"
SET "status" = $1
WHERE "t0"."id" = $2
-- params: [Text("retired"), Int(101)]
-- → 1

set(path, value) gives a column its new value; several set calls set several columns. filter chooses the rows, with the same conditions as a query. execute answers the number of rows changed.

A None writes NULL:

#![allow(unused)]
fn main() {
Update::<Station>::new()
    .set(Station::opened(), None::<NaiveDate>)
    .filter(Station::id().eq(6))
// SET "opened" = NULL
}

Values computed by the database

The new value can be computed from the row, with an expression. This is Django’s update(platforms=F("platforms") + 1):

#![allow(unused)]
fn main() {
db.execute(
    &Update::<Station>::new()
        .set(Station::platforms(), Station::platforms() + 1)
        .filter(Station::city().eq("Paris")),
)
.await?;
}
UPDATE "network_station" AS "t0"
SET "platforms" = ("t0"."platforms" + $1)
WHERE "t0"."city" = $2

The database reads and writes the value in one step. Two such updates at the same moment are both counted, where reading the value, adding one in Rust and writing it back would lose one of them.

Through a relation

A filter of an update cannot follow a relation (an UPDATE has no joins):

#![allow(unused)]
fn main() {
Update::<Station>::new()
    .set(Station::status(), "open")
    .filter(Station::region().name().eq("Finistère"))
// refused: update of `network_station` filtered through the relation `region`: write the filter with `any(..)`
}

Write the relation as a sub-query:

#![allow(unused)]
fn main() {
Update::<Station>::new()
    .set(Station::status(), "open")
    .filter(Station::region_id().in_sub(
        Query::<Region>::new().filter(Region::name().eq("Finistère")).select(Region::id()),
    ))
}
UPDATE "network_station" AS "t0"
SET "status" = $1
WHERE "t0"."region_id" IN (SELECT "t1"."id" FROM "network_region" AS "t1" WHERE "t1"."name" = $2)
-- → 2 rows

An update of every row must say so

An update without a filter is refused before anything is sent, so that a forgotten filter does not change a whole table:

query rejected: update of `fleet_train` has no filter; an update of every row must say so with `.filter(Cond::Const(true))`

When you mean it, say it:

#![allow(unused)]
fn main() {
Update::<Train>::new().set(Train::status(), "active").filter(Cond::Const(true))
// UPDATE "fleet_train" AS "t0" SET "status" = $1 WHERE TRUE
}

Deleting: Delete

#![allow(unused)]
fn main() {
let gone: u64 = db
    .delete(&Delete::<Train>::new().filter(Train::number().in_(["TGV1", "TGV2"])))
    .await?;
}
DELETE FROM "fleet_train" AS "t0"
WHERE "t0"."number" IN ($1, $2)
-- → 2

delete answers the number of rows deleted. As for an update, a delete without a filter is refused, and Cond::Const(true) says “every row”; a filter cannot follow a relation, and in_sub can.

The database’s foreign keys decide what goes with the rows: a cascade key deletes the rows that point to them, a restrict key refuses:

database: ERROR: update or delete on table "fleet_train" violates RESTRICT setting of foreign key
constraint "timetable_journey_train_id_fkey" on table "timetable_journey"
DETAIL: Key (id)=(1) is referenced from table "timetable_journey".

Unlike Django’s QuerySet.delete(), a Delete does not collect and delete the related rows itself: the database does, by its rules. For a database whose keys have no rules (made by Django), use an object’s delete_cascade.

Errors of the database

A write the database refuses is an Error::Database, with PostgreSQL’s message:

database: ERROR: duplicate key value violates unique constraint "fleet_train_number_key"
DETAIL: Key (number)=(FRET42) already exists.

In a resource’s write, rind turns these into a 400 for the client. In your own code, they are errors to handle.

There is no INSERT … ON CONFLICT yet (Django’s get_or_create, update_or_create): read first, then write, in a transaction with a lock, or write it in raw SQL.

#![allow(unused)]
fn main() {
db.link(&USER_GROUPS, 5, 1).await?;     // true: the link was added
db.link(&USER_GROUPS, 5, 1).await?;     // false: it was there already
db.unlink(&USER_GROUPS, 5, 1).await?;   // true: it was removed
db.unlink(&USER_GROUPS, 5, 1).await?;   // false: there was none
}

link(&hop, from, to) adds a row to the link table (Django’s user.groups.add(group)), and does nothing when the link is there. unlink removes it (Django’s .remove(group)). Both answer whether they changed something. USER_GROUPS is the relation’s hop (Loading related rows).

Summary

StatementRun withAnswers
Insert::<M>::new().value(p, v)…db.insert(&i)M, as stored
db.insert_keyed(&i)(i64, M)
Update::<M>::new().set(p, v)….filter(c)db.execute(&u)u64, rows changed
Delete::<M>::new().filter(c)db.delete(&d)u64, rows deleted
a linkdb.link(&hop, from, to), db.unlink(…)bool

Each also has to_sql(), to see its SQL without running it.

Next: Trees.