The command line
A Django project has manage.py: makemigrations, migrate,
runserver, check, and the management commands that apps add. In rind,
the application’s own binary plays that part. Its commands come from
rind, in the library, and you add your own beside them, as Django’s
management commands.
This chapter describes those commands, the Application value they work
on, how to serve it, and how to test it.
The application’s binary
The main of an application is one line. No change of the application
ever has to touch it:
// app/src/main.rs: the whole file
fn main() -> std::process::ExitCode {
rind::cli::main(app::app())
}
rind::cli comes with the cli feature of rind, which is on by default.
You can run the commands in two ways. With cargo, from the workspace:
cargo run -p app -- migrate
Or with the rind tool (Starting a project), from any
folder of the project:
rind make
rind check
rind migrate
rind openapi --out openapi.json
The tool finds the application’s package, runs
cargo run -q -p <app> -- <command>, and gives it the variables of the
project’s .env file (a variable already set in your shell wins). Every
command that the tool does not know itself goes to the application in
this way.
The two lists of commands are separate. rind --help lists the tool’s
own commands (new, add, doctor, inspect). rind help-app lists
the application’s: the same list as cargo run -p app -- help.
Coming from Django:
manage.pyis a script that loads the settings. Here the commands are compiled into your application’s binary, so they always see the same models and resources as the server.
The commands rind gives you
Here are the commands, grouped by what they work on, with their closest Django equivalent. The Reference has the complete list of options.
Migrations
| rind | Django | Does |
|---|---|---|
make | makemigrations | Writes the migrations of what changed in the models. |
check | makemigrations --check | Fails if the models do not hold together, or have changes without a migration. |
status | showmigrations | Lists the migrations the database has applied, and those it has not. |
migrate | migrate | Applies the migrations the database does not have. |
make asks you, as Django does, when a change looks like a rename (“Was
catalog_book.name renamed to catalog_book.title?”). --rename answers
in advance: --rename old_table=new_table, or
--rename table.old_column=new_column. --name gives the new migration a
name.
migrate --fake records the migrations as applied without running them,
as Django’s migrate --fake. migrate --only a,b applies the migrations
of the named domains only. Every domain is still put in order, so a
domain’s migrations still come after those it depends on.
Migrations explains how they are written, stored and applied.
The schema and the database
These commands compare the models with a real database. They are most useful when an application takes over a database that already exists (Starting from a database).
schemaprints the SQL (DDL) that creates the tables of the models, as Django’ssqlmigratedoes for one migration.schema diffprints a draft of the SQL that would make the database match the models. It is a draft to read, not a migration.dbcheckcompares the models with the database: the tables, the columns and their types, and the foreign tables and their keys. With--rules FILE, it also compares each key’son_deletewith the rules of the old Django application (Answering as Django did).constraintslists the constraints and indexes that the models and the database do not have alike.--sqlprints the statements that give the database the models’ names.verifyapplies every migration to a new, empty schema, compares the result with the models, and drops the schema. With--against URL [--schema S], it also compares the result with the database the models were written from.
The API
openapiprints the OpenAPI document;--out FILEwrites it to a file.routeslists the routes, by domain, asshow_urlsof django-extensions does.serveruns the server (Serving), asrunserverdoes.helpprints the list of commands, with those of the plugins and of the application.
Which database a command uses
A command that needs a database reads its address from DATABASE_URL, or
from --database URL when you give it:
rind migrate --database postgres://library:library@127.0.0.1:5432/library
Commands that use no database (make, check, schema, openapi,
routes) refuse --database.
The first versions of the commands took the address bare
(migrate postgres://…). This is still accepted for a while.
What the commands print, and logging
The commands write rind’s events to the standard error, through
tracing. RUST_LOG says what is written (info by default;
RUST_LOG=rind::sql=debug adds every SQL statement and its duration).
RIND_LOG=json writes one JSON object per line, for a log collector. See
Logging.
The application, described once
Every command works on one value: the Application that app() returns.
#![allow(unused)]
fn main() {
// sample/src/lib.rs (shortened)
pub fn app() -> rind::Application {
rind::Application::new("The railway", env!("CARGO_PKG_VERSION"))
.models(network_models::migrations())
.models(accounts_models::migrations())
// …
.api(network_api::api())
.api(fleet_api::api())
// …
.auth(accounts_ops::TokenAuth)
}
}
Each domain gives its parts. A models crate gives its tables and its
migrations (migrations()), and an api crate gives its resources, each
named once (api()):
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/lib.rs (shortened)
pub fn api() -> rind::api::Api {
rind::api::Api::new("network")
.resource::<stations::StationResource>()
.resource::<lines::LineResource>()
}
}
The application adds how users sign in (.auth(…), see
Authentication) and its plugins (.with(…), see
Plugins).
Everything else follows from this one value. What a Django project lists
in INSTALLED_APPS, urls.py and its settings, rind reads from it:
| What | From the value |
|---|---|
| every table | app.schema() |
| every migration | app.migrations() |
| the OpenAPI document | app.openapi() |
| the state the resources share | app.state(db) |
| the routes | app.router(state) (axum), app.configure(cfg) (actix-web) |
An api crate depends on no web framework, and needs none of rind’s web features. Only the application chooses axum or actix-web, so the same domain crates serve on both.
Routes that are not resources
Not every route is a resource: a health check, a webhook, static files.
Application never stands in the way of these. A domain adds its own
routes beside its resources:
#![allow(unused)]
fn main() {
// a domain's api crate (fragment)
pub fn api() -> rind::api::Api {
rind::api::Api::new("booking")
.resource::<reservations::ReservationResource>()
.axum(|| axum::Router::new().route("/payments/webhook", post(webhook)))
}
}
The function given to .axum(..) returns an axum::Router<AppState>,
so a handler can read the application’s state. For actix-web, .actix(..)
takes a function that adds services to a ServiceConfig. A route that
belongs to no domain goes on the application itself, with the same
.axum(..) and .actix(..).
.axum and .actix exist only with rind’s feature of the same name. So
only the crate that uses them depends on the web framework.
What the application gives is ordinary, so you can combine it with
anything else. app.router(state) is an ordinary axum::Router, and
app.routes() is the same router before it is given its state.
app.configure is an ordinary actix-web configuration. You can merge,
nest and wrap them with layers like any other.
These routes are not in the OpenAPI document by themselves, because rind
does not know what they take and return. .describe(..), on an Api or
on the Application, adds them:
#![allow(unused)]
fn main() {
.describe(|document| document.path("/payments/webhook", "post", json!({…})))
}
The application’s own commands
These are Django’s management commands. You give each one a name, a line of help and an async function:
// app/src/main.rs
fn main() -> std::process::ExitCode {
rind::cli::Cli::new(app::app())
.command("import-stations", "loads stations from a CSV file", import_stations)
.main()
}
async fn import_stations(
app: &rind::Application,
args: &[String],
) -> Result<(), Box<dyn std::error::Error>> {
// …
}
The function is given the application and the arguments that follow the
command’s name, unparsed. It is not given a database: connect with
rind::db::Db::connect(&std::env::var("DATABASE_URL")?) when it needs
one. An error it returns is printed, and the command exits with a
failure.
The command is listed by help, and runs like the others:
rind import-stations stations.csv
When a command of yours has the name of one of rind’s, yours runs.
Plugins add commands too: cache-clear, usage-prune,
storage-orphans, mail-prune, auth-clean, and the jobs-… commands
of Jobs. A plugin’s command is given the application and its
database (--database, or DATABASE_URL).
Serving
serve reads DATABASE_URL and BIND (127.0.0.1:8080 by default; or
--bind ADDR), connects to the database, and serves every route of the
application with its CORS. It serves on the framework the
application is built with, and on actix-web when it is built with both.
rind’s server is enough for a simple application, and for the first weeks of a larger one. When you need more (other middleware, several listeners, a shutdown that waits for the requests in progress), give the command a server of your own. The command, its options and its place in the list stay rind’s:
// app/src/main.rs (fragment)
fn main() -> std::process::ExitCode {
rind::cli::Cli::new(app::app()).serve(serve).main()
}
async fn serve(app: &rind::Application, settings: rind::cli::Serve) -> std::io::Result<()> {
let router = app
.router(app.state(settings.db))
.layer(TraceLayer::new_for_http());
axum::serve(TcpListener::bind(&settings.bind).await?, router)
.with_graceful_shutdown(signal())
.await
}
settings holds the connected database (db), the address to listen on
(bind) and the database’s address as it was given (database_url).
rind new --serve own starts the project with this form, in
app/src/serve.rs. With axum, app.router(..) already has the CORS
layer. With actix-web, CORS is a middleware of the App, so your server
wraps it itself:
#![allow(unused)]
fn main() {
// app/src/serve.rs, as `rind new --web actix --serve own` writes it (fragment)
App::new()
.wrap(app.actix_cors())
.app_data(web::Data::new(state.clone()))
.configure(move |cfg| app.configure(cfg))
}
Going further: the client’s address
rind’s axum server gives each request the client’s address
(into_make_service_with_connect_info::<SocketAddr>()), which hooks such
as the usage log read. A server of your own on axum should do
the same if it uses them.
The tests
The test that rind new writes runs, in cargo test, what rind check
checks:
#![allow(unused)]
fn main() {
// app/tests/schema.rs
#[test]
fn the_application_holds_together() {
rind::testing::check(&app::app());
}
}
It fails when the models do not hold together across domains, when a
change has no migration, or when a folder’s index of migrations is stale.
Its message says to run rind make.
A test that needs PostgreSQL gets a schema of its own, with the application’s migrations applied:
#![allow(unused)]
fn main() {
#[tokio::test]
async fn stations_are_listed() {
let Some(db) = rind::testing::fresh_schema(&app::app(), "stations_listed").await else {
return; // RIND_TEST_DATABASE_URL is not set: the test is skipped
};
// …
}
}
fresh_schema returns None when RIND_TEST_DATABASE_URL is not set,
so the tests that need a database are skipped on a machine without one.
The schema is dropped first if it is already there, so each test starts
from nothing. Give each test its own schema name, as tests run in
parallel.
rind::testing::empty_schema(name) does the same without the
migrations.
Coming from Django: Django creates one test database and wraps each test in a transaction. rind gives each test a PostgreSQL schema of its own instead, so tests can commit and run in parallel.
Reference
Commands
| Command | Does |
|---|---|
make [--name N] [--rename OLD=NEW]… | Writes the migrations of what changed in the models. --rename old_table=new_table or table.old_column=new_column; otherwise asked. |
check | Fails if the models do not hold together across domains, have changes without a migration, or if a folder’s index (embedded.rs) is not what its files are. |
status | What the database has applied, and has not. |
migrate [--fake] [--only a,b] | Applies what the database has not. --fake: only records it. --only: these domains only. |
constraints [--sql] | The constraints and indexes that the models and the database do not have alike. --sql: the statements that rename them. |
verify [--against URL [--schema S]] | Applies every migration to an empty schema, compares the result with the models (and with the database at URL: Starting from a database), drops the schema. --schema is public by default. |
schema | The DDL of the models. |
schema diff | A draft of what would make the database match the models. |
dbcheck [--rules FILE] | Compares the models with the database: tables, columns, types; the foreign tables and their keys; with --rules FILE, each key’s on_delete with the old application’s rules. |
openapi [--out FILE] | The OpenAPI document. |
routes | The routes, by domain. |
serve [--bind ADDR] | The server, on the framework the application is built with. |
help | The list, with the plugins’ commands and the application’s own. |
Every command that uses a database takes --database URL.
Environment variables
| Variable | Read by |
|---|---|
DATABASE_URL | Every command that uses a database. |
BIND | serve: the address to listen on. 127.0.0.1:8080 by default. |
RUST_LOG, RIND_LOG | What is logged, and how (Logging). |
RIND_TEST_DATABASE_URL | rind::testing: the database of the tests. |
rind::cli
| Item | Is |
|---|---|
rind::cli::main(app) | The command line with rind’s commands only. |
Cli::new(app) | A command line, to add to. |
.command(name, about, f) | A command of the application’s own; f is async fn(&Application, &[String]) -> Result<(), Box<dyn Error>>. |
.serve(f) | What serve runs; f is async fn(&Application, rind::cli::Serve) -> std::io::Result<()>. |
.main() | Runs the command of the process’s arguments. |
rind::cli::Serve | What a server is given: db, bind, database_url. |
Application
| Method | Does |
|---|---|
Application::new(title, version) | The application, with its title and version (for OpenAPI and help). |
.models(domain) | A domain’s tables and migrations: <domain>_models::migrations(). |
.api(api) | A domain’s resources: <domain>_api::api(). |
.auth(authenticator) | How users sign in (Authentication). |
.with(plugin) | A plugin. |
.axum(..), .actix(..) | Routes that belong to no domain. |
.describe(..) | Adds paths to the OpenAPI document. |
.schema(), .migrations(), .openapi() | What the commands read. |
.state(db) | The state the resources share. |
.router(state), .routes() | The routes, for axum. |
.configure(cfg), .actix_cors() | The routes and the CORS middleware, for actix-web. |