Part 2: Models and migrations
A model describes a table, as in Django. In rind, a model is a Rust
struct with #[derive(Model)]: one field per column.
Adding two models
The rind tool writes the struct for you:
rind add model catalog Author name:String
rind add model catalog Book title:String year:i32
edited crates/catalog/catalog-models/src/lib.rs (struct Author)
edited crates/catalog/catalog-models/src/lib.rs
No migration is written: `rind make` writes it, once Author is what it should be.
add model takes the domain, the name of the model, and its fields as
name:RustType. It adds the struct to the domain’s models crate, and a
line to the list of the domain’s tables. It does not write a
migration yet: you will first finish the model by hand.
Open crates/catalog/catalog-models/src/lib.rs. Each struct comes with a
block of comments that reminds you of the syntax; delete it once you
have read it. (--bare leaves it out.)
Finishing the models
Here is the file as we want it:
#![allow(unused)]
fn main() {
// crates/catalog/catalog-models/src/lib.rs
use rind::prelude::*;
/// Someone who writes books.
#[derive(Debug, Clone, Model)]
#[model(table = "catalog_author")]
#[reverse(name = books, model = Book, fk = "author_id")]
pub struct Author {
pub id: i64,
#[column(max_length = 100)]
pub name: String,
}
/// A book of the library.
#[derive(Debug, Clone, Model)]
#[model(table = "catalog_book")]
pub struct Book {
pub id: i64,
#[column(max_length = 200)]
pub title: String,
pub year: i32,
#[fk(Author, on_delete = restrict)]
pub author_id: i64,
}
/// The tables of this domain.
pub fn schema() -> Vec<rind::schema::Table> {
vec![
rind::schema::Table::of::<Author>(),
rind::schema::Table::of::<Book>(),
]
}
/// The migrations of this domain: its tables, change after change.
pub fn migrations() -> rind::migrations::Domain {
rind::migrations::domain!("catalog", schema())
}
}
Let’s read it piece by piece.
The table name is explicit. #[model(table = "catalog_book")]
names the table. The tool chose <domain>_<model>, the same convention
as Django’s <app>_<model>.
The key is id. A field id: i64 is the primary key, and the
database gives its value (a bigint identity column). This is Django’s
BigAutoField.
The SQL type comes from the Rust type. String is text, or
character varying(n) with max_length = n; i32 is integer; i64
is bigint. A column is NOT NULL unless its type is an Option:
Option<String> is Django’s null=True. The Models
chapter lists every type.
A foreign key is a field and an attribute. The column is the field
author_id. The attribute #[fk(Author, on_delete = restrict)] says
which model it points to, and what happens to a book when its author is
deleted: restrict refuses the deletion, like Django’s
on_delete=PROTECT. (cascade and set_null exist too.)
The relation gets its name from the field: author_id gives a relation
called author. You will use it in queries as Book::author().
The way back is declared too. In Django, a ForeignKey silently
gives the other model a book_set (or the related_name). In rind,
nothing is guessed: #[reverse(name = books, model = Book, fk = "author_id")] on Author says “an author has books: the rows of
Book whose author_id is this author”. You will use it in part 3 to
count each author’s books.
Coming from Django: each model has typed paths to its columns and relations:
Book::title(),Book::author(),Book::author().name(). They replace the strings of Django’s querysets ("author__name"). A typo is a compile error, not aFieldErrorat run time.
Writing the migration
rind make
catalog 0001_initial
create catalog_author
create catalog_book
key catalog_book.author_id
This is manage.py makemigrations. rind compares the models with the
state recorded by the previous migrations, and writes what changed. The
migration is plain SQL, in
crates/catalog/catalog-models/migrations/0001_initial.sql:
-- rind migration: catalog 0001_initial
-- create catalog_author
CREATE TABLE "catalog_author" (
"id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"name" character varying(100) NOT NULL
);
-- create catalog_book
CREATE TABLE "catalog_book" (
"id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"title" character varying(200) NOT NULL,
"year" integer NOT NULL,
"author_id" bigint NOT NULL
);
-- key catalog_book.author_id
ALTER TABLE "catalog_book" ADD CONSTRAINT "catalog_book_author_id_fkey" FOREIGN KEY ("author_id") REFERENCES "catalog_author" ("id") ON DELETE RESTRICT;
CREATE INDEX "catalog_book_author_id_idx" ON "catalog_book" ("author_id");
You can read it, review it in a pull request, and change it by hand if
you need to. Beside it, 0001_initial.state.json records what the
models looked like, so that the next rind make knows what changed; and
embedded.rs lists the files so that they are compiled into the
application. You commit all three.
Notice that the foreign key got an index without asking, as in Django.
Applying it
rind migrate
applied catalog 0001_initial
rind status shows what the database has applied (showmigrations):
[x] catalog 0001_initial
Changing a model
Change a model, run rind make again, and you get a second migration
with only the difference. If you rename a field, rind make cannot tell
a rename from a deletion plus an addition, so it asks you (or you say it
with --rename book.old_name=new_name).
rind check fails when a model has changed without a migration. It runs
in cargo test too, through the test that rind new wrote in
app/tests/schema.rs, so a forgotten migration does not reach
production.
What we have
Two tables, created by a migration you can read. There is still no endpoint: that is the next part.
Next: Part 3: A first resource.