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 a project

In Django, django-admin startproject writes a project and manage.py startapp adds an app to it. rind has one tool for both jobs: the rind command. It writes a new project that builds, passes its checks and serves an (empty) API. Then it grows the project one piece at a time: a domain, a model, a resource.

This chapter describes the project commands of the tool: rind new, rind add and rind doctor. For a guided first project, follow the tutorial. To start from a database that already exists (as Django’s inspectdb does), read Starting from a database.

Installing the tool

You install the tool once, from a checkout of rind:

cargo install --path crates/rind-cli       # or: make install-cli

This installs two programs: rind, and cargo-rind. The second one lets you type cargo rind … instead of rind …; both do the same thing.

Creating a project

rind new library --domain catalog

This creates the folder library/. The name of the folder is the name of the project. --domain catalog also creates a first domain, called catalog. A domain is a part of the application about one subject, a bit like a Django app; it is made of several crates, one per layer. Organising an application explains why. You can repeat --domain to create several domains at once, or leave it out and add them later.

The tool writes these files:

library/
  Cargo.toml             the workspace
  docker-compose.yml     a PostgreSQL for development
  .env, .env.example     DATABASE_URL, BIND, the test database
  .gitignore
  README.md
  app/
    Cargo.toml
    src/lib.rs           app(): the application, described once
    src/main.rs          one line: rind's commands
    tests/schema.rs      one test: what `rind check` checks, in `cargo test`
  crates/
    catalog/
      catalog-models/    the models: schema(), migrations(), migrations/embedded.rs
      catalog-api/       the resources: api()

The workspace’s Cargo.toml lists its members with a glob, ["app", "crates/*/*-*"], so a new crate needs no edit there. It also says where rind is (see Where the project finds rind).

The application crate, app/, is the equivalent of Django’s settings.py and urls.py together. Its src/lib.rs has one function, app(), that puts the domains together:

#![allow(unused)]
fn main() {
// app/src/lib.rs
pub fn app() -> rind::Application {
    rind::Application::new("Library", env!("CARGO_PKG_VERSION"))
        .models(catalog_models::migrations())
        .api(catalog_api::api())
}
}

Its src/main.rs is one line. It hands the application to rind’s command line, which gives you make, migrate, serve and the other commands (see The command line):

// app/src/main.rs
fn main() -> std::process::ExitCode {
    rind::cli::main(app::app())
}

The title of the application ("Library") comes from the folder’s name. It is the title of the OpenAPI document; --title sets another one.

Running the new project

The project is ready to run:

cd library
docker compose up -d       # starts PostgreSQL
rind check                 # the models and their migrations agree
rind migrate               # creates the tables
rind serve                 # http://127.0.0.1:8080

docker-compose.yml starts a PostgreSQL 17 on port 5432, with a user, a password and a database named after the project. Its data is kept in memory: it is lost when the container stops. If a PostgreSQL already runs on port 5432 on your machine, change the port in docker-compose.yml and in .env.

.env holds the settings for development:

DATABASE_URL=postgres://library:library@127.0.0.1:5432/library
BIND=127.0.0.1:8080
RIND_TEST_DATABASE_URL=postgres://library:library@127.0.0.1:5432/library

The rind tool reads this file and gives its variables to the application when it runs a command. A variable that is already set in your shell wins over the file. .env is in .gitignore; .env.example is the copy you commit.

Coming from Django: there is no settings.py. What Django reads from its settings, rind reads from app() (the code) and from environment variables (DATABASE_URL, BIND, and the variables of each plugin).

How the tool finds the project

You can run rind from any folder inside the project. The tool looks for a Cargo.toml with a [workspace.metadata.rind] table, in the current folder and then in each folder above it:

[workspace.metadata.rind]
app = "app"            # the package of the application
crates = "crates"      # where the domains are: crates/<domain>/<domain>-<layer>

app is required. crates is "crates" when it is left out. A project laid out in another way only has to say so here: rind’s own repository says app = "sample" and crates = "sample/crates" (see The railway, a sample application).

Adding a domain

rind add domain loans

This writes the crates of a new domain, loans-models and loans-api, and adds them to the application: one dependency per crate in app/Cargo.toml, and one line per crate in app():

#![allow(unused)]
fn main() {
pub fn app() -> rind::Application {
    rind::Application::new("Library", env!("CARGO_PKG_VERSION"))
        .models(catalog_models::migrations())
        .models(loans_models::migrations())
        .api(catalog_api::api())
        .api(loans_api::api())
}
}

A domain gets the models and api layers by default. --layers chooses others, among models, shared, ops and api:

rind add domain accounts --layers models,ops

The models layer is always there, even when you do not name it. Only the models and api crates have a line in app(): the other layers are used by the crates above them.

A new domain’s .models(…) line goes after the last one. The order of these lines matters: a domain’s models may point only to the models of the domains before it (Domains, in an order). So add the domains in that order.

A domain’s name is made of lowercase letters, digits and -, and starts with a letter. rind is refused, because its crates would have the names of rind’s own crates (rind-api).

Adding a layer to a domain

rind add layer catalog shared

This adds a layer that the domain did not have yet. The new crate depends on the layers of its domain below it (here, catalog-models), and the layers above it now depend on it (here, catalog-api). The tool edits those manifests for you. A dependency on another domain’s crate is yours to add, in the manifest.

Adding a model

rind add model catalog Book title:String year:i32

This adds a struct to catalog-models/src/lib.rs, just before fn schema(), and adds the struct to the list that schema() returns:

#![allow(unused)]
fn main() {
// crates/catalog/catalog-models/src/lib.rs
/// A book.
#[derive(Debug, Clone, Model)]
#[model(table = "catalog_book")]
pub struct Book {
    pub id: i64,
    pub title: String,
    pub year: i32,
    // rind: syntax reminder, delete when done ----------------------------
    // #[column(max_length = 100, unique)]          pub code: String,
    // #[column(default = "'open'", index)]         pub status: String,
    // #[fk(Other, on_delete = cascade)]            pub other_id: i64,
    // #[fk(table = "other_table", on_delete = set_null)]   a key to a domain above
    //                                              pub other_id: Option<i64>,
    // on the struct: #[index(on(a, b))]  #[unique(on(a, b))]  #[check(name = "…", sql = "…")]
    // ---------------------------------------------------------------------
}

/// The tables of this domain.
pub fn schema() -> Vec<rind::schema::Table> {
    vec![
        rind::schema::Table::of::<Book>(),
    ]
}
}

The table is named <domain>_<model> in snake case, as Django names <app>_<model>. Every model gets an id: i64 key.

Each field is given as name:RustType, and nothing more. Lengths, keys, defaults and indexes are written in Rust, in the struct, with the attributes of Models. The block of comments recalls their syntax; delete it once you have read it, or pass --bare to leave it out. When a type names chrono:: (published:chrono::NaiveDate), the tool also adds chrono to the crate’s dependencies.

add model writes no migration. You first edit the struct until it is what you want, and then rind make writes the migration, as Django’s makemigrations does:

rind add model catalog Book title:String year:i32
# edit the struct: lengths, keys, indexes
rind make
rind migrate

Adding a resource

A resource is a model served over HTTP, with its list, its detail and its writes: what Django REST framework calls a ModelViewSet, with its serializer and its filter set. See Resources.

rind add resource catalog Book

This writes a folder for the resource in catalog-api/src/books/:

FileHolds
serializers.rsBookOut, what is sent: every column of the model; BookIn, what can be written: every column but id
filters.rsBookFilters, an empty filter set
views.rsBookResource: the model, its path, its serializers, its filters, and who may use it
mod.rsthe three modules, and their types re-exported

Then it adds pub mod books; and .resource::<books::BookResource>() to catalog-api/src/lib.rs. The resource is served at /books: the name of the model in snake case, in the plural. --path gives another path.

The tool finds the model in whichever domain’s models crate has it. The model can be in another domain: the api crate then gets a dependency on that domain’s models crate, and on the crates that the model’s field types come from (chrono, for instance). When two domains have a model of that name, say which one with --models DOMAIN.

Who may use the new resource

The resource that the tool writes is for the staff only:

#![allow(unused)]
fn main() {
// crates/catalog/catalog-api/src/books/views.rs
/// The staff read and write the books.
#[derive(Resource)]
#[resource(
    model = Book,
    path = "books",
    out = BookOut,
    filters = BookFilters,
    input = BookIn,
    delete
)]
#[rule(staff)]
pub struct BookResource;
}

This is on purpose. What a generator leaves open by default is what gets deployed open, so you have to ask for it: --rule anyone, --rule authenticated, --rule staff (the default) or --rule superuser. You can also change the #[rule(..)] line later (see Permissions).

A new application signs nobody in yet, so nobody is staff, and nobody can reach the resource. The tool warns you:

books/views.rs: #[rule(staff)], and this application signs nobody in.
Nobody can reach /books until it does (the book, "Authentication"),
or until the rule is another: --rule anyone

The warning goes away once app() has an .auth(…) line (see Authentication).

How the tool edits your files

The tool only adds things. It does not rename and it does not remove: a rename is a job for your editor, and rind make then asks you whether a table or a column was renamed.

New files are written from templates compiled into the tool. A file that already exists is never overwritten: the command stops with an error instead.

Manifests (Cargo.toml) are edited with their comments and their order kept.

Rust files are edited only in the lists that the tool itself wrote:

  • the chain of calls in app() (.models(…), .api(…));
  • the vec![…] that schema() returns, and the place before fn schema() where a new model goes;
  • the chain of calls in api() (.resource::<…>()), and the pub mod lines of the api crate.

A line is inserted; nothing else in the file is reformatted. When a list is no longer as the tool wrote it (you rewrote it by hand, for instance with a call on the same line as Application::new(…)), the tool changes nothing in that file. It prints the line to add, and where, and you add it yourself:

  NOT edited app/src/lib.rs: `.models(…)` is not on a line of its own, as the tool writes it.
  Add it by hand: `.models(loans_models::migrations())` in the chain of `app()`

Checking how the crates depend on each other

Organising an application gives rules about which crate may depend on which. The compiler enforces some of them (crates cannot depend on each other in a circle), but not all. rind doctor checks the others:

rind doctor
loans-api depends on catalog-api: an api crate never depends on another (…); what both need goes in a shared crate
1 problems.

It reads the project with cargo metadata, without building anything, so it is fast. It reports:

  • an api crate that depends on another api crate;
  • a crate that depends on a crate of a higher layer: a models crate on a shared, ops or api crate, a shared crate on an ops crate, and so on;
  • a models crate that app() does not list (its tables would never be migrated), and an api crate that app() does not mount;
  • a models crate without its migrations/embedded.rs (it does not compile without it);
  • a rind tool and a rind library of different versions.

It prints Nothing to report. and succeeds when all is well, and fails otherwise, so you can run it in CI. When app() is not a chain the tool can read, it says so and does not check what app() mounts.

Where the project finds rind

While rind is not published on crates.io, a new project depends on rind by path. By default this is the checkout that the tool was built from: the tool remembers it. If that checkout has moved, rind new stops and asks for --rind PATH, the folder of rind’s workspace. --rind-git URL depends on rind by git instead.

Reference

rind new PATH

OptionMeaning
--web axum or --web actixThe web framework. axum by default.
--domain NAMEA first domain, with its models and api crates. Can be repeated.
--serve rind or --serve ownWho serves: rind’s serve (the default), or a server of the application’s own, written in app/src/serve.rs (see The command line).
--rind PATHThe checkout of rind to depend on. By default, the one the tool was built from.
--rind-git URLDepend on rind by git instead.
--title TITLEThe title of the application, in its OpenAPI document. By default, the folder’s name.

The folder must not exist, or be empty. At the end, the tool prints the next commands to run.

rind add

CommandOptionsWritesEdits
add domain NAME--layers models,shared,ops,api (default models,api)the crates of the domain; an empty migrations/embedded.rsapp/Cargo.toml, and one line per models or api crate in app()
add layer DOMAIN LAYERthe crate, depending on the layers below itthe manifests of the layers above it; app() for a models or api layer
add model DOMAIN NAME [field:Type]…--barethe struct, with id and the fields giventhe vec! of schema(); use rind::prelude::*; if it is missing; chrono in the manifest when a type needs it
add resource DOMAIN MODEL--rule anyone|authenticated|staff|superuser (default staff), --path PATH, --models DOMAIN, --barethe folder of the resource: mod.rs, serializers.rs, filters.rs, views.rspub mod and the chain of api(); the api crate’s manifest when the model is another domain’s, or its fields need a crate

A model’s name is in CamelCase, as a Rust type (Book, RailCar). A field cannot be called id: the tool writes that one.

rind doctor

Takes no option. Exits with a failure when it finds a problem.

Other commands of the tool

CommandDoes
rind inspectWrites models from an existing database (Starting from a database).
rind help-appThe application’s list of commands (The command line).
rind --helpThe tool’s own list of commands.
any other commandRun by the application: rind migrate is cargo run -q -p app -- migrate.