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

Starting from a database

You may start a rind project from a database that already exists: one a Django application created, or any other PostgreSQL database. Django has inspectdb for this; it prints draft models that you then fix by hand. rind inspect goes further. It writes:

  • a models crate per domain (a group of tables, like a Django app);
  • a model per table, which keeps every name the database has (tables, columns, constraints, indexes), so that the models describe the database exactly;
  • an API over them: a resource per model, open to superusers by default;
  • tests that check the models read and write the real rows.

It works in two steps, with a person in between. The first step writes a plan, a TOML file of decisions. You read it and correct it. The second step applies the plan and writes the project.

rind inspect postgres://…/shop > inspect.toml      # 1. the plan
$EDITOR inspect.toml                               #    domains, names, tables left out
rind inspect --apply inspect.toml --new shop       # 2. the project

rind inspect reads only the catalogue of the database (the description of its tables), never a row, so a replica will do. Without an address, it reads DATABASE_URL, or the project’s .env.

Once the project is written, Migrations explains how rind takes over the database.

The plan

The first step writes what it would do, as TOML. The plan holds decisions, not the schema: when you apply it, the tables are read again from the database. A plan looks like this:

# A domain per prefix of the tables' names.
[domains]
catalog = "catalog"
_legacy = "legacy"

# The extensions the tables need, with the domains whose first migration
# creates them.
[extensions]
postgis = ["locations", "structures"]
pg_trgm = ["catalog"]

# Types, functions and configurations the tables need.
[objects]
"normalize_text(text)" = "catalog"

# Every table modelled, in its domain.
[tables]
catalog_family = "Family"
catalog_family_labels = { model = "FamilyLabels", m2m = "Family.labels" }
users_user = { model = "User", domain = "accounts" }

# Left out, with why.
[skip]
spatial_ref_sys = "a table of an extension"

# The API: a resource per model, for superuser, staff, authenticated or
# anyone; `none` writes no API.
[api]
rule = "superuser"

# The models without a resource, with why.
[api.skip]
factlink_fix_missing = "its key is not an integer (date)"

Here is what each part means, and what you may change.

  • A domain is the prefix of a table’s name: what comes before its first _ (a leading _ belongs to the prefix, so _legacy_log is in _legacy). In [domains], you can rename a domain, or give two prefixes the same domain. To move a single table to another domain, add domain = "…" to its entry in [tables].
  • A struct is named after the rest of the table’s name, in CamelCase, cut on _. A Django table has no word boundaries (articletariftemplate becomes Articletariftemplate), so rename the structs here.
  • A link table becomes a model too. A link table has a key, two foreign keys and the pair unique: what Django makes for a ManyToManyField. m2m = "Family.labels" declares the many-to-many relation labels through it, on the model of its first key. Both ends must be modelled in the same domain. Remove m2m to keep only the model.
  • Every table is in the plan, either modelled or skipped. To leave a table out, move it to [skip]: Django’s own tables, or a table that another program owns. A foreign key to a skipped table stays in the model, by the table’s name.
  • An extension or an SQL object can be skipped too, by its name in [skip]. A project that ports only part of a database should not create what only the other parts use (vector = "only classify uses it").
  • A table rind cannot model is skipped, with the reason. It may have a column of a type rind does not know, a key on several columns, or no primary key. The first step then ends with a failure, so that you see it. rind never reads something as what it is not.

Some tables are left out without asking: rind’s own (rind_migrations, and the tables of rind’s plugins, named rind_…), the tables of an extension, and the partitions of a partitioned table.

Updating the plan

The database may change while you port it. This command brings the plan up to date with the database as it is now, and keeps every decision you made:

rind inspect postgres://…/shop --update inspect.toml

The file is edited in place: its comments, blank lines and order stay as you wrote them.

  • What appeared goes to [skip], marked # new. Its reason says what the tool proposes, so that the next --apply writes nothing nobody asked for (a plan may cover only part of a database). To model a new table, move it to [tables] with the proposal from its reason:

    [skip]
    orders_ordernotification = "new: proposed as \"Ordernotification\""  # new
    

    A new extension or SQL object is added the same way, with the domains proposed for it. A new table that rind cannot model gets its reason, and the update ends with a failure, as the first step does.

  • What is gone is removed from every section, and listed at the end of the file (# gone from the database: …).

  • An extension or an object named in [skip] is kept for as long as the database has it.

Updating a plan that is already up to date changes nothing.

Applying the plan

--apply reads the plan and the database again. It writes nothing if they do not agree, and lists every problem at once:

  • a table of the database that is neither in [tables] nor in [skip];
  • a table of the plan that the database no longer has;
  • a column of a type rind does not know;
  • a name that cannot be a crate’s or a type’s;
  • two tables with the same struct name in one domain;
  • a table that a model of the project already describes, in another domain than the plan says.

With --new FOLDER, the project is created as rind new makes it, and the models go into it.

Applying again, in a project

Run without --new, inside a project, --apply writes only what the project does not have yet. So the plan can grow with the port: you move a table from [skip] to [tables], then apply again.

  • A table that a model of the project already describes (#[model(table = "…")]) is kept as it is, whatever you changed in it.
  • A new domain is written whole, as with --new.
  • In a domain that exists, the new models get their files, and the domain’s lib.rs is edited, not rewritten: the mod, pub use and Table::of::<…>() lines of schema() are added, and the rest is kept. The same goes for the tests that inspect wrote (read.rs, copy.rs, api.rs): the new tables’ lines are added.
  • With [api], resources are written for the new tables only. An API crate that exists gets the pub mod and .resource::<…>() lines. A table modelled before keeps the API the application gave it, under its own names.
  • What cannot be placed (a file that is no longer as inspect wrote it) is printed as NOT edited, with the line to add by hand.

Then rind make writes the first migration of the new tables.

What a model looks like

A table becomes a model that says everything the database has: its lengths, its unique constraints and its indexes, each under the name the database gives it.

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Model)]
#[model(table = "logs_processor")]
#[index(name = "logs_processor_name_3e149381_like", sql = "USING btree (name varchar_pattern_ops)")]
pub struct Processor {
    pub id: i64,
    #[column(max_length = 255, unique = "logs_processor_name_3e149381_uniq")]
    pub name: String,
    pub last_id: Option<i64>,
    pub description: String,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}
}

The _like index is the one Django adds on PostgreSQL beside an indexed text column. rind has no attribute for it, so it is kept as SQL.

A foreign key to a model of the same domain carries a relation (#[fk(Family, …)]). It also gives the target a relation back, under the name Django gives it by default: <model>_set (Group::usergrouplink_set()), or <model>_<key>_set when the table has several keys to the same target (Location::distance_location_a_set()). Rename them to the related_name the Django application used. The relation back is a trait, written beside the key (GroupUsergrouplinkSet). The domain’s lib.rs re-exports each model’s module whole (pub use usergrouplink::*;), so use users_models::* brings the trait into scope.

A foreign key to another domain is written by its table’s name, and unfollowed: #[fk(table = "users_user", unfollowed, …)]. The domains of a database point to each other, but their crates cannot depend on each other in both directions.

A parent_id key to the table itself makes the model a tree (tree = "parent_id", which gives descendants and ancestors), as the models of django-tree-queries and django-mptt are.

A model whose fields all have a default derives Default, so that a test writes a row with only the values it cares about: Storage { cvva: "AD1".into(), ..Default::default() }.

Once everything is written, inspect runs cargo fmt --all on the project. The generated code is formatted as the rest is, and a later cargo fmt changes nothing. Without rustfmt, inspect says so and leaves the files as written.

Deletion rules and foreign tables

A key’s on_delete comes from the database (ON DELETE CASCADE). But a Django database says nothing there: every Django key is NO ACTION, and the rules live in the Python code. The models then need the rules from that code. You give them with --rules rules.json, a file the old application writes itself (for Django, with the script of the Django chapter). With it:

  • A new model’s key whose rule the database does not hold gets the file’s rule: #[fk(.., on_delete = cascade, in_code, ..)]. The database key stays as it is, and rind’s deletion applies the rule (Models). Django’s SET_DEFAULT and SET(..), which rind does not have, are written as the database says, with a note.
  • The models kept from an earlier apply get it too: their #[fk(..)] lines are rewritten, and a key that is already right is left as it is. So do the external keys (to a table no model describes), because their target may be a foreign table, which a cascade reaches.

Every apply also writes the foreign tables: the tables left out ([skip]) that a deletion of the models’ rows reaches. These are the skipped tables with a key to a modelled table; then, for those whose key cascades, the skipped tables that point to them, and so on. They go into a crate of their own, crates/foreign/foreign-tables, as Table::foreign(..) values. The crate is rewritten whole by every apply, and given to the application:

#![allow(unused)]
fn main() {
.foreign_tables(foreign_tables::tables())
}

See Tables no model describes for what rind does with them. A table without a primary key of one integer column cannot be walked: inspect says so, and the database refuses a deletion that reaches it.

Afterwards, rind dbcheck --rules rules.json compares every key of the models and of the foreign tables with the file. A rule copied by hand, or changed in the old application since, shows up.

The tests inspect writes

The application gets two tests of the models:

  • app/tests/read.rs reads rows of every table through its model, when RIND_INSPECT_SOURCE names the database.
  • app/tests/copy.rs also needs RIND_INSPECT_REBUILD: a server where it migrates a schema of its own from nothing. It copies rows of every table into it through the models (Insert), reads them back, and compares them. The keys are not checked while it copies (a table’s rows may come before the rows they point to), which needs a superuser on that server.

The API

Over the models, inspect writes an API crate per domain. Each model gets a resource at /<domain>/<table without its prefix> (/catalog/family), with the rule of [api], and five actions: list, retrieve, create, update and delete.

  • Its serializer sends every column.
  • Its input writes every column the database does not compute itself (a generated column, or a key the database gives, are left out). A text may be blank and keeps its spaces (allow_blank, keep_spaces), because Django keeps both. A column with a default is optional: it is left out if the client does not send it.
  • Its filters are empty.

A model whose primary key is not an integer has no resource, because a resource finds its objects by an integer id. The plan lists it in [api.skip] with that reason.

Nothing is guessed beyond that. Which fields a client may write, the filters, the search, the relations sent nested, the rules of each action: you write them yourself, resource by resource.

With any rule other than anyone, nobody can reach the resources until the application signs its users in (.auth(..) in app(), see Authentication). The plan cannot know how a database’s users prove who they are.

app/tests/api.rs tests the whole API (with axum). A request without credentials must be refused. Then, signed in as a superuser by an authenticator of its own, the test lists the rows of each resource in the database, creates each row again through the API’s JSON in a schema migrated from nothing, changes it, deletes it, and checks it is gone. It needs RIND_INSPECT_SOURCE and RIND_INSPECT_REBUILD, as copy.rs does.

The round trip

When the project is written, each of these checks says that the project is the database:

What is checkedCommandExpected
it buildscargo build, rind doctornothing to report
the migrationsrind make, rind checka first migration per domain
the models are the databaserind dbcheck, rind constraints (on it)0 differences
the migrations are the models, and the databaserind verify --database <empty server> --against <the database>the same tables, names and definitions
the models read the rowsRIND_INSPECT_SOURCE=… cargo test -p app --test readevery table read
the models write them back… RIND_INSPECT_REBUILD=… cargo test -p app --test copyevery row read back the same
the API… cargo test -p app --test apirefused without credentials; every row created, changed, deleted

verify --against migrates an empty schema from nothing and compares it with the database the models were written from: every column, key, uniqueness, condition, index, default, type and function, by name and by definition. The server it migrates needs the extensions the database has.

On the database of a real Django application (261 tables, used by Django and by two other services), this gave 260 models in 26 domains and 37 migrations, with 0 differences at each step. The rows of every table were read, and 33,882 of them written back the same. The 259 resources created, changed and deleted 1,052 rows.

What is left to do then is the takeover (Migrations): record the migrations on the database (rind migrate --fake), then change it through them.

What is not modelled

Views, triggers, partitioned tables, sequences that are not a key’s, and schemas other than the one inspected (--schema, public by default). The plan’s header lists what the schema has of them.

rind’s own tables are left out: rind_migrations, and every table named rind_…, such as rind_usage of the usage log or rind_mail of the mail. Their plugins model them. A prefix rind is not a domain, because its crates would be named like rind’s own.

Reference

Options

rind inspect [URL] [--schema S]                     # the plan, on standard output
rind inspect [URL] --update PLAN                    # the plan brought up to date, in place
rind inspect [URL] --apply PLAN [--rules FILE]      # the models, in the project
rind inspect [URL] --apply PLAN --new FOLDER [--web axum|actix] [--rind PATH | --rind-git URL] [--title T]
OptionMeans
URLthe database; by default DATABASE_URL, or the project’s .env
--schema Sthe schema to read (public)
--update PLANrewrites the plan from the database, keeping its decisions
--apply PLANwrites the models, the API and the tests the plan says
--new FOLDERwith --apply: a new project in this folder, as rind new makes it
--web, --rind, --rind-git, --titlewith --new: as for rind new
--rules FILEwith --apply: the deletion rules the database does not hold

The plan’s sections

SectionEntryMeans
[domains]prefix = "domain"the domain of the tables with this prefix
[extensions]name = ["domain", …]the domains whose first migration creates the extension
[objects]"name(args)" = "domain"the domain that creates this type, function or configuration
[tables]table = "Struct"the table is modelled as Struct, in its prefix’s domain
[tables]table = { model = "…", domain = "…", m2m = "Model.relation" }the same, in another domain, or as a link table
[skip]name = "why"a table, an extension or an object left out
[api]rule = "…"superuser, staff, authenticated, anyone, or none for no API
[api.skip]table = "why"a modelled table without a resource

The environment of the tests

VariableUsed byIs
RIND_INSPECT_SOURCEread.rs, copy.rs, api.rsthe database the models were written from
RIND_INSPECT_REBUILDcopy.rs, api.rsa server where a schema is migrated from nothing; copy.rs needs a superuser there