Indexes and constraints

Indexes and constraints are part of the model, like its columns. The migrations write them, so nothing about the schema lives only in a migration file, and rind check notices when the model and the migrations disagree.

Column options showed the simple cases, on one column (#[column(unique)], #[column(index)]). This page shows the attributes written on the struct, for everything else:

AttributeWhat it isDjango
#[index(on(a, b))]an index on several columnsMeta.indexes = [Index(fields=[…])]
#[index(name, sql)]an index on an expression, partial, GIN…Index(expressions…, condition=…), GinIndex
#[unique(on(a, b))]columns unique togetherUniqueConstraint(fields=[…]), unique_together
#[check(name, sql)]a condition every row must meetCheckConstraint

The examples come from one model:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Model)]
#[model(table = "lab_article")]
#[index(on(author_id, published))]
#[index(name = "lab_article_title_lower_idx", sql = "(lower(title))")]
#[index(name = "lab_article_one_draft_idx", unique, sql = "(author_id) WHERE NOT published")]
#[index(name = "lab_article_words_idx", sql = "USING gin (words)")]
#[unique(on(author_id, title))]
#[unique(name = "lab_article_ref_uniq", on(reference, version), nulls_not_distinct)]
#[check(name = "lab_article_version_check", sql = "version > 0")]
pub struct Article {
    pub id: i64,
    pub title: String,
    pub published: bool,
    pub words: Vec<String>,
    pub reference: Option<String>,
    pub version: i32,
    #[fk(Tag, on_delete = cascade)]
    pub author_id: i64,
}
}

An index on several columns

#![allow(unused)]
fn main() {
#[index(on(author_id, published))]
}
CREATE INDEX "lab_article_author_id_published_idx" ON "lab_article" ("author_id", "published");

An index on (a, b) helps the queries that filter on a, or on a and b. The order of the columns matters: put first the column the queries always filter on.

The name is <table>_<columns>_idx. Give name = "…" to describe an existing database whose index has another name.

An index written in SQL

An index that a list of columns cannot describe is written in SQL. sql is what follows ON <table> in CREATE INDEX, and such an index must have a name:

#![allow(unused)]
fn main() {
// an index on an expression: for filters on lower(title)
#[index(name = "lab_article_title_lower_idx", sql = "(lower(title))")]
// CREATE INDEX "lab_article_title_lower_idx" ON "lab_article" (lower(title));

// a GIN index on an array: for "contains" and "overlaps" filters
#[index(name = "lab_article_words_idx", sql = "USING gin (words)")]
// CREATE INDEX "lab_article_words_idx" ON "lab_article" USING gin (words);
}

With unique, it is a unique index. Combined with a WHERE, it makes a partial uniqueness: here an author may have only one draft at a time, but any number of published articles:

#![allow(unused)]
fn main() {
#[index(name = "lab_article_one_draft_idx", unique, sql = "(author_id) WHERE NOT published")]
// CREATE UNIQUE INDEX "lab_article_one_draft_idx" ON "lab_article" (author_id) WHERE NOT published;
}

The sample uses one so that a seat is booked once per journey, the cancelled reservations left aside:

#![allow(unused)]
fn main() {
// sample/crates/booking/booking-models/src/lib.rs
#[index(
    name = "booking_reservation_seat_idx",
    unique,
    sql = "(journey_id, wagon_id, seat) WHERE status = 'booked' AND seat IS NOT NULL"
)]
}

Other common indexes, written the same way:

Indexsql = …
a trigram index, for searches with contains"USING gin (upper(name) gin_trgm_ops)" (extension pg_trgm)
a spatial index"USING gist (position)"
a full-text index"USING gin (to_tsvector('french', title))"
a descending index"(created DESC)"

An index that needs an extension needs the extension declared on the domain: rind::migrations::domain!("network", schema()).extension("pg_trgm").

Unique together

#![allow(unused)]
fn main() {
#[unique(on(author_id, title))]
}
ALTER TABLE "lab_article" ADD CONSTRAINT "lab_article_author_id_title_key" UNIQUE ("author_id", "title");

Two articles of the same author cannot have the same title; two authors can. This is Django's UniqueConstraint(fields=["author", "title"]) (or the older unique_together). The sample uses it so that each place of a train has one wagon:

#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-models/src/lib.rs
#[unique(on(train_id, position))]
pub struct Wagon { … }
}

NULLs. By default PostgreSQL counts each NULL as different: two rows (NULL, 1) do not break the constraint. nulls_not_distinct counts them as equal (PostgreSQL 15 and later):

#![allow(unused)]
fn main() {
#[unique(name = "lab_article_ref_uniq", on(reference, version), nulls_not_distinct)]
// ALTER TABLE "lab_article" ADD CONSTRAINT "lab_article_ref_uniq" UNIQUE NULLS NOT DISTINCT ("reference", "version");
}

The derive checks the names of the columns:

error: the model has no column `nope`
   |
   | #[unique(on(id, nope))]
   |                 ^^^^

When a write through the API breaks the constraint, the answer is a 400. To have the message on a field, declare the uniqueness on the input too.

Checks

#![allow(unused)]
fn main() {
#[check(name = "lab_article_version_check", sql = "version > 0")]
}
ALTER TABLE "lab_article" ADD CONSTRAINT "lab_article_version_check" CHECK (version > 0);

A check constraint is a condition, in SQL, that every row must meet: Django's CheckConstraint(condition=Q(version__gt=0)). The condition can use every column of the row, not the other rows.

name and sql are both required. A write that breaks it is refused by the database:

database: ERROR: new row for relation "lab_article" violates check constraint "lab_article_version_check"

Through the API, it is a 400. Checks are the place for rules that must hold whoever writes: a positive number ("capacity > 0"), an order between two dates ("arrives_at > departs_at"), a value in a list ("status IN ('draft', 'sent', 'paid')").

Names an existing database already has

Every constraint and index rind writes has a name, built from PostgreSQL's conventions (_key, _idx, _fkey, _pkey). To describe a database made by Django or by hand, give each its existing name, so that the migrations do not rename it: name = "…" on these attributes, unique = "…" and index = "…" on columns, constraint and index on foreign keys, key_name on the model. rind constraints lists those that differ. See Migrations.

Next: Scopes and scoped models.