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

Column options

The Rust type of a field gives the SQL type of its column. Everything else about the column is said with #[column(..)], written above the field:

#![allow(unused)]
fn main() {
#[column(max_length = 12, default = "'active'", index)]
pub status: String,
}

This page takes each key in turn. There are seven:

KeyWhat it doesDjango
max_length = na text of at most n charactersmax_length=
default = "SQL"the column’s default, in SQLdefault=, db_default=
uniquea unique constraint on the columnunique=True
indexan index on the columndb_index=True
sql = "type"the SQL type, when rind cannot tell ita custom field’s db_type()
generated = "SQL"a column the database computesGeneratedField
read = "SQL"an expression the column is read through

A key that does not exist is a compile error that lists the right ones:

error: unknown key: expected `max_length`, `sql`, `default`, `unique`, `index`, `read` or `generated`
   |
   | #[column(max_lenght = 3)]
   |          ^^^^^^^^^^

max_length: the length of a text

#![allow(unused)]
fn main() {
#[column(max_length = 50)]
pub short: String,               // "short" character varying(50) NOT NULL

#[column(max_length = 20)]
pub codes: Vec<String>,          // "codes" character varying(20)[] NOT NULL
}

On a String, it makes a character varying(n) instead of a text. On a Vec<String>, it applies to each element. On a File, it is the length of the file’s key.

The database refuses a longer value. The input checks it earlier, with a clear message, when it has the same key: #[input(max_length = 50)].

default: the column’s default value

#![allow(unused)]
fn main() {
#[column(default = "'draft'", max_length = 10)]
pub status: String,              // "status" character varying(10) NOT NULL DEFAULT 'draft'
#[column(default = "0")]
pub count: i32,                  // "count" integer NOT NULL DEFAULT 0
#[column(default = "false")]
pub archived: bool,              // "archived" boolean NOT NULL DEFAULT false
#[column(default = "now()")]
pub created: DateTime<Utc>,      // "created" timestamp with time zone NOT NULL DEFAULT now()
#[column(default = "CURRENT_DATE")]
pub borrowed_on: NaiveDate,      // "borrowed_on" date NOT NULL DEFAULT CURRENT_DATE
#[column(default = "'{}'")]
pub labels: Vec<String>,         // "labels" text[] NOT NULL DEFAULT '{}'
#[column(default = "'{}'::jsonb")]
pub extra: serde_json::Value,    // "extra" jsonb NOT NULL DEFAULT '{}'::jsonb
}

The default is SQL, not Rust. The string is copied as it is after DEFAULT in the table’s definition. That is why a text default has its own quotes inside the Rust string: "'draft'" is the SQL text 'draft', while "draft" would be the name of a column, and the migration would fail.

You wantWrite
a textdefault = "'draft'"
a numberdefault = "0", default = "1.5"
a booleandefault = "false"
the time of the insertdefault = "now()"
the day of the insertdefault = "CURRENT_DATE"
an empty arraydefault = "'{}'"
an array with valuesdefault = "'{rail,night}'"
an empty JSON objectdefault = "'{}'::jsonb"
a random UUID, as textdefault = "gen_random_uuid()::text"

When the default is used. The database uses it when an INSERT does not name the column. Three cases:

  • An insert built with Insert that does not set the column:

    #![allow(unused)]
    fn main() {
    // no `status` given: the row gets 'draft'
    let order: Order = db.insert(&Insert::<Order>::new()).await?;
    }
  • A creation through a resource whose client did not send the field (when the input does not give a default of its own).

  • An insert written in SQL.

An object written with order.insert(&db) gives every column, since a Rust struct has no “missing” field, so the column’s default is not used there.

Coming from Django: Django’s default= is a Python value, computed when the object is made, and the database never sees it. rind’s default is the database’s own default, like Django 5’s db_default=. It works for every insert, whoever writes it: the API, a script, psql. A default that depends on the request (the user who creates the row) belongs to the resource’s hook.

unique: one row per value

#![allow(unused)]
fn main() {
#[column(unique, max_length = 20)]
pub code: String,
// "code" character varying(20) NOT NULL CONSTRAINT "lab_everything_code_key" UNIQUE

#[column(unique = "lab_everything_slug_uniq", max_length = 20)]
pub slug: String,
// "slug" character varying(20) NOT NULL CONSTRAINT "lab_everything_slug_uniq" UNIQUE
}

The constraint is named <table>_<column>_key, PostgreSQL’s own convention. Give a name (unique = "…") only to describe a database whose constraint already has another one.

Several NULLs do not break a unique constraint: PostgreSQL counts each NULL as different. For columns that are unique together, or to count NULLs as equal, use #[unique(..)] on the struct.

When a write breaks the constraint, a resource answers 400, not 500. Declare it on the input too (#[input(model = Train, unique(number))]) and the client gets the message on the field.

index: an index on the column

#![allow(unused)]
fn main() {
#[column(index)]
pub rank: i32,
// CREATE INDEX "lab_everything_rank_idx" ON "lab_everything" ("rank");

#[column(index = "lab_everything_score_idx")]
pub score: i32,
// CREATE INDEX "lab_everything_score_idx" ON "lab_everything" ("score");
}

The index is named <table>_<column>_idx, unless a name is given.

You do not need index on:

  • a foreign key: it gets an index by itself (Foreign keys);
  • a unique column: the unique constraint is an index already;
  • the primary key.

Add one on a column that lists often filter or sort on (a status, a date). For an index on several columns, on an expression, or of another kind than a B-tree, see Indexes and constraints.

sql: the SQL type, said explicitly

#![allow(unused)]
fn main() {
#[column(sql = "inet")]
pub address: rind::db::types::Inet,

#[column(sql = "numeric(10, 2)")]
pub price: rind::db::types::Decimal,

#[column(sql = "geography(Point,4326)")]
pub position: Option<rind::db::geo::Point>,
}

sql replaces the type rind would choose. It is required for the types listed in Types that need their SQL type and for your own types. The string is copied as it is into the table’s definition.

It can also replace a type rind knows, when an existing database has another one: #[column(sql = "character varying(254)")] pub email: String describes a column whose length is not a rule you want to repeat in max_length.

generated: a column the database computes

#![allow(unused)]
fn main() {
#[column(generated = "md5(body)")]
pub body_hash: String,
// "body_hash" text GENERATED ALWAYS AS (md5(body)) STORED NOT NULL
}

A generated column is computed by PostgreSQL from the other columns of its row, at every insert and update: Django’s GeneratedField. The expression is SQL, and can only use columns of the same row.

rind never writes a generated column: not in an object’s insert or save, not in an input. It reads it like any other column, filters and sorts on it. Uses: a hash for a uniqueness, a lower-case copy for a search, a total of two columns.

read: a column read through an expression

#![allow(unused)]
fn main() {
#[column(sql = "geometry(Point,4326)", read = "ST_AsGeoJSON({})::jsonb")]
pub geom: serde_json::Value,
}

read is SQL that the column is read through: {} stands for the column. Here the database stores a PostGIS geometry, and rind reads it as GeoJSON, into a serde_json::Value.

Filters and orderings still see the stored column, not the expression. And since rind could not write the value back in the stored type, it never writes a column that has read: it is read-only for rind.

read is mostly for databases you describe but do not control. For geography, the Point and shape types are usually better: they read and write.

Combining keys

Keys combine, in any order:

#![allow(unused)]
fn main() {
#[column(max_length = 10, default = "'draft'", index)]
pub status: String,
}

Some combinations make no sense, and the derive does not always stop them: a default on a generated column, an index on a unique one. Keep each column to the keys it needs.

Next: Types of your own.