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

Models

A model describes one table of the database: its columns, its keys, its relations to other tables, its indexes and its constraints. It is what a Django model class is: class Train(models.Model), its fields and its Meta. In rind, a model is a plain Rust struct with #[derive(Model)].

Everything else is built on the models. Queries are written with their columns, migrations are computed from them, and resources serve them over HTTP.

This chapter is long, so it is cut into sections. This first page shows a complete model and what the derive gives you. The next pages take each part of a model in turn, list every option, and show the SQL each one produces.

PageWhat it coversIn Django
Fields and column typeswhich Rust type gives which SQL type, NULL, every type rind knowsthe field classes: CharField, IntegerField, JSONField…
Column optionslengths, defaults, unique columns, indexed columns, generated columnsmax_length, default, unique, db_index
Types of your ownstoring an enum or any type of yours in a columncustom fields, choices
Primary keysid, another key, keys the application givesprimary_key=True, AutoField
Foreign keyspointing to another model, what a deletion doesForeignKey, on_delete
Reverse and many-to-many relationswalking a key backwards, link tablesrelated_name, ManyToManyField
Treesrows that have a parent among themselvesdjango-mptt, django-treebeard
Indexes and constraintsindexes on several columns, unique together, checksMeta.indexes, Meta.constraints
Scopes and scoped modelsnamed queries on a model; models with no default querymanagers, objects.published()
Sharing fieldsfields written once, used by several modelsabstract models, mixins
Writing objectsinsert, save, update, delete on an objectobj.save(), obj.delete()
Behaviours and hookswhat every write of a model doesauto_now, save() overrides, signals
Referenceevery attribute and every key, in tables

A first model

Here is the train of the sample application, the railway:

#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-models/src/lib.rs
use network_models::Station;
use rind::prelude::*;

/// A train: an engine and the wagons it pulls.
#[derive(Debug, Clone, Model)]
#[model(table = "fleet_train")]
#[reverse(name = wagons, model = Wagon, fk = "train_id")]
pub struct Train {
    pub id: i64,
    #[column(max_length = 10, unique)]
    pub number: String,
    #[column(max_length = 100)]
    pub name: String,
    /// `passenger` or `freight`.
    #[column(max_length = 10)]
    pub kind: String,
    /// `active`, `maintenance` or `retired`.
    #[column(max_length = 12, default = "'active'", index)]
    pub status: String,
    /// The station it is kept at.
    #[fk(Station, on_delete = restrict, name = depot, reverse = depot_trains)]
    pub depot_id: i64,
}
}

Read it from top to bottom:

  • use rind::prelude::*; brings the derive and the query types (Query, Insert, Db…) into scope. Every models crate starts with it.
  • #[derive(Debug, Clone, Model)]: Model is the derive that does the work. Debug and Clone are not required, but you will want them.
  • #[model(table = "fleet_train")] names the table. It is required: rind does not make up a name from the crate and the struct.
  • Each field is a column, and the field’s Rust type gives the column’s SQL type: an i64 is a bigint, a String with max_length = 10 is a character varying(10).
  • id is the primary key, because it is called id.
  • #[column(..)] adds what the type cannot say: a length, a default, a unique constraint, an index.
  • depot_id is a foreign key to the stations. The relation is called depot.
  • #[reverse(..)] declares the other side of a foreign key that another model holds: the wagons point to their train, so a train has wagons.
  • The doc comments (///) are kept. They describe the fields in the OpenAPI document, as Django’s help_text does.

The table this model describes, as rind schema prints it:

CREATE TABLE "fleet_train" (
    "id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    "number" character varying(10) NOT NULL CONSTRAINT "fleet_train_number_key" UNIQUE,
    "name" character varying(100) NOT NULL,
    "kind" character varying(10) NOT NULL,
    "status" character varying(12) NOT NULL DEFAULT 'active',
    "depot_id" bigint NOT NULL
);

CREATE INDEX "fleet_train_status_idx" ON "fleet_train" ("status");

ALTER TABLE "fleet_train" ADD CONSTRAINT "fleet_train_depot_id_fkey" FOREIGN KEY ("depot_id") REFERENCES "network_station" ("id") ON DELETE RESTRICT;
CREATE INDEX "fleet_train_depot_id_idx" ON "fleet_train" ("depot_id");

There is nothing in the table that the struct does not say, and nothing in the struct that the table does not have.

What the derive gives you

With this struct, you can already read trains:

#![allow(unused)]
fn main() {
let active: Vec<Train> = db
    .all(&Query::<Train>::new().filter(Train::status().eq("active")))
    .await?;
}

The derive gave the struct everything a Django model class has:

  • It can be read from a row. db.all(&query) answers a Vec<Train>, db.first(&query) an Option<Train>.
  • It has a typed path to each column, Train::number(), and to each relation, Train::depot() and Train::wagons(). You write queries with them, as you would write Train.objects.filter(depot__city="Paris") in Django: Train::depot().city().eq("Paris"). A misspelt name does not compile.
  • Its schema is known. The migrations compare it with the database and write what changed (Migrations).
  • It can write itself: train.insert(&db), train.save(&db), train.delete(&db) (Writing objects).

The paths are typed. Train::number() is a path to a String, so it can be compared with a text, and not with a number:

error[E0277]: the trait bound `{integer}: Operand<std::string::String>` is not satisfied
   |
   | Query::new().filter(Train::number().eq(3))
   |                                     -- ^ the trait `Operand<std::string::String>` is not implemented for `{integer}`

Reference lists everything the derive writes.

Coming from Django: there is no automatic id field, no automatic table name, and no automatic reverse relation (wagon_set). Everything a model has is written in the struct. This costs a few lines, and it means that what you read is what the database has.

From the struct to the table

A model does not create its table by itself. Three steps, which rind add model prepares for you:

  1. The model is listed in the schema() function of its crate. A model that is not listed has no table, and nothing warns you:

    #![allow(unused)]
    fn main() {
    // sample/crates/fleet/fleet-models/src/lib.rs
    pub fn schema() -> Vec<rind::schema::Table> {
        use rind::schema::Table;
        vec![Table::of::<Train>(), Table::of::<Wagon>(), Table::of::<Driver>()]
    }
    
    pub fn migrations() -> rind::migrations::Domain {
        rind::migrations::domain!("fleet", schema())
    }
    }
  2. The domain is in the application: app() has .models(fleet_models::migrations()).

  3. A migration is written and applied: rind make, then rind migrate (Migrations).

After that, every change to the struct is a new rind make. rind check fails when the struct and the migrations disagree.

Where models live

A model lives in the models crate of its domain (crates/fleet/fleet-models): the crate that every other layer of the domain depends on. Keep this crate free of HTTP: no serializers, no resources. A model may point to the models of the domains before its own, never after (Organising an application).

Next: Fields and column types.