Writing objects
The Model derive gives each object its own writes: insert, save,
update, refresh, delete. They are Django’s obj.save(),
obj.save(update_fields=[…]), obj.refresh_from_db() and
obj.delete().
They are for code that runs outside a request: an operation of an
ops crate, a job, a command, a test, an import. Writes
through the API go through a resource and its
input, which validate and check permissions; these do
neither.
There is a second way to write: statements on rows, Insert, Update
and Delete, run by the database (Writing rows).
The difference is explained at the end of this page.
A first example
#![allow(unused)]
fn main() {
// sample/tests/model_writes.rs
let mut station = brest.clone();
station.code = "BRE2".into();
let mut station = station.insert(&db).await?; // the row back, with its new id
station.name = "Brest Saint-Marc".into();
station.save(&db).await?; // every column, by the key
station.city = "Plouzané".into();
station.update(&db, &[StationColumn::City]).await?; // only this column
station.refresh(&db).await?; // read it again
station.delete(&db).await?; // one DELETE
}
Each method takes a &Db: the pool’s, or a transaction’s.
insert: a new row
#![allow(unused)]
fn main() {
let tag = Tag { id: 0, name: "rust".into() }.insert(&db).await?;
// Tag { id: 1, name: "rust" }
}
insert writes every column of the object, except:
- an identity key (the usual
id), which the database gives; - generated columns and columns read through SQL.
It answers the row as the database stored it: with its new key, and the values the database computed. The object you called it on is consumed; use the one it answers.
A key of a manual_key
model is written: Country { code: "FR".into(), .. }.insert(&db).
Since every column is written, the columns’ SQL defaults are not used.
To let the database fill a default, insert with Insert and leave the
column out (column defaults).
save: every column, by the key
#![allow(unused)]
fn main() {
tag.name = "Rust".into();
tag.save(&db).await?;
}
save writes every column (except the key, generated and read ones) to
the row that has the object’s key, then reads the row again into the
object. A row that is not there is Error::NotFound: save never
inserts. (Django’s save() inserts or updates depending on the key; in
rind you say which one you mean.)
Watch out:
savewrites every column. An object read partially (the serializers read only the columns their fields need) holds default values in the fields that were not read, andsavewould write those defaults over the real values. When you did not read the whole row, useupdatewith the columns you changed.
update: some columns
#![allow(unused)]
fn main() {
tag.name = "RUST".into();
tag.update(&db, &[TagColumn::Name]).await?;
}
update writes only the columns named, then reads the row again. This is
Django’s save(update_fields=["name"]).
The columns are the variants of an enum the derive writes for each
model, <Model>Column, with one variant per column, in CamelCase:
TagColumn::Name, StationColumn::City. A wrong name does not compile.
Prefer update to save when two programs may change the same row at
the same time: each writes only what it changed.
refresh: read the row again
#![allow(unused)]
fn main() {
tag.refresh(&db).await?;
}
Reads the row again into the object: Django’s refresh_from_db(). A row
that is gone is Error::NotFound.
delete: remove the row
#![allow(unused)]
fn main() {
let gone: u64 = tag.delete(&db).await?; // 1, or 0 if it was not there
}
One DELETE by the key. The database’s foreign keys decide what goes
with it: a cascade key deletes the rows that point to it, a restrict
key refuses the deletion with an error.
Deleting what depends on an object
A database that Django made has foreign keys that do nothing (Django
applies on_delete in Python). On such a database, delete alone fails,
or leaves rows that point nowhere. delete_cascade does what Django’s
delete() does:
#![allow(unused)]
fn main() {
let gone = journey.delete_cascade(&db, &app.schema()).await?;
}
It deletes the object and, table by table, what the models say depends on
it, following each relation’s on_delete as a
deletion through the API does. A relation with
on_delete = restrict refuses the whole deletion. It answers what went,
table by table.
The second argument is the list of the application’s tables, which it
needs to find the keys that point to the object: app.schema(), or
ctx.tables() inside a request. delete_cascade exists only for a model
whose key is an i64.
In a transaction
Each method runs in what its Db is. Several writes that must succeed
or fail together go in a transaction:
#![allow(unused)]
fn main() {
let tx = db.begin().await?;
let train = train.insert(tx.db()).await?;
for wagon in wagons {
Wagon { train_id: train.id, ..wagon }.insert(tx.db()).await?;
}
tx.commit().await?; // without it, nothing is kept
}
A transaction that is dropped without commit is rolled back. Inside a
request’s write (a resource’s hook), ctx.db is
already the write’s transaction: write with it, and do not begin another
one (rind has no nested transactions).
Writes that skip the model’s behaviours
insert, save and update run the model’s
behaviours and hooks: they set updated,
render a text, move a journey’s stops. The _raw variants do the same
writes without them, and do not read the row again:
| Method | Runs behaviours and hooks | Reads the row again |
|---|---|---|
insert(&db) | yes | yes (it answers it) |
insert_raw(&db) | no | yes (it answers it) |
save(&db) | yes | yes |
save_raw(&db) | no | no |
update(&db, &[…]) | yes | yes |
update_raw(&db, &[…]) | no | no |
Use them for an import that keeps its own times, or to repair data without triggering what a normal write does.
Objects or rows?
The same change can be written on an object, or as a statement on rows:
#![allow(unused)]
fn main() {
// an object
tag.name = "Rust".into();
tag.update(&db, &[TagColumn::Name]).await?;
// rows
db.execute(&Update::<Tag>::new()
.set(Tag::name(), "Rust".to_owned())
.filter(Tag::id().eq(tag.id)))
.await?;
}
| Object writes | Row statements (Insert, Update, Delete) | |
|---|---|---|
| How many rows | one, by its key | any number, by a filter |
| Behaviours and hooks | run | never run |
| Reading back | the object is up to date | insert answers the row; execute the count |
| A value computed by the database | no | yes: .set(Station::platforms(), Station::platforms() + 1) |
| In Django | obj.save() | QuerySet.update(), .delete() |
Use objects for “this train”, rows for “every train of this depot”. As in
Django, where QuerySet.update() sends no signal, a statement on rows
runs none of the model’s hooks.
Every method
| Method | What it does |
|---|---|
insert(&db) | every column but an identity key (a manual_key one is written), generated columns and columns read through SQL; runs behaviours and hooks; answers the row as the database has it |
insert_raw(&db) | the same, without behaviours or hooks |
save(&db) | every column but the key, generated and read ones; runs behaviours and hooks; reads the row again. A row that is not there is Error::NotFound |
save_raw(&db) | the same, without behaviours or hooks, and without reading the row again |
update(&db, &[columns]) | these columns, and what the behaviours add (updated); runs hooks; reads the row again |
update_raw(&db, &[columns]) | the same, without behaviours or hooks, and without reading the row again |
refresh(&db) | reads the row again; Error::NotFound when it is gone |
delete(&db) | one DELETE by the key; runs the deleting hooks before; answers 0 or 1 |
delete_cascade(&db, tables) | the object and what the models say depends on it, table by table; refused by a restrict relation; answers what went. Only for a model whose key is an i64 |
Next: Behaviours and hooks.