Relations
A relation is a field of a #[derive(Model)] struct that holds rows of another model instead of a column. You declare it with an attribute, then load it eagerly for many rows at once (one statement per level, never one per row), lazily for rows you already have, filter on it, count it, and, for many-to-many, link and unlink rows. This page also covers foreign keys.
Declaring relations
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
#[rdb(table = "users")]
struct User {
#[rdb(primary_key, serial)]
id: i64,
name: String,
#[rdb(has_many(Post, foreign_key = "user_id"))]
posts: Vec<Post>,
#[rdb(has_one(Profile, foreign_key = "user_id"))]
profile: Option<Profile>,
#[rdb(many_to_many(Tag, through = UserTag, local = "user_id", foreign = "tag_id"))]
tags: Vec<Tag>,
#[rdb(count_of = "posts")]
posts_count: i64,
}
#[derive(Model, Debug, Clone)]
#[rdb(table = "posts")]
struct Post {
#[rdb(primary_key, serial)]
id: i64,
#[rdb(index, references = "users(id)", on_delete = "cascade")]
user_id: i64,
title: String,
published: bool,
#[rdb(belongs_to(User, foreign_key = "user_id"))]
author: Option<Box<User>>,
#[rdb(has_many(Comment, foreign_key = "post_id"))]
comments: Vec<Comment>,
}
#[derive(Model, Debug, Clone)]
#[rdb(table = "comments")]
struct Comment {
#[rdb(primary_key, serial)]
id: i64,
#[rdb(index, references = "posts(id)", on_delete = "cascade")]
post_id: i64,
body: String,
}
#[derive(Model, Debug, Clone)]
#[rdb(table = "profiles")]
struct Profile {
#[rdb(primary_key, references = "users(id)", on_delete = "cascade")]
user_id: i64,
bio: String,
}
#[derive(Model, Debug, Clone)]
#[rdb(table = "tags")]
struct Tag {
#[rdb(primary_key, serial)]
id: i64,
name: String,
}
/// The join table: a key over both columns, so a link is stored once.
#[derive(Model, Debug, Clone)]
#[rdb(table = "user_tags")]
struct UserTag {
#[rdb(primary_key, references = "users(id)", on_delete = "cascade")]
user_id: i64,
#[rdb(primary_key, references = "tags(id)", on_delete = "cascade")]
tag_id: i64,
}
#[tokio::main]
async fn main() -> Result<()> {
let db = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
// Parents before children, so each foreign key finds its table.
db.create_table::<User>().await?;
db.create_table::<Post>().await?;
db.create_table::<Comment>().await?;
db.create_table::<Profile>().await?;
db.create_table::<Tag>().await?;
db.create_table::<UserTag>().await?;
Ok(())
}| attribute | field type | matches |
|---|---|---|
belongs_to(C, foreign_key = "c_id") | Option<C> or Option<Box<C>> | this model's c_id against C's primary key; owner_key = "col" to match another column of C |
has_one(C, foreign_key = "p_id") | Option<C> or Option<Box<C>> | C's p_id against this model's primary key; local_key = "col" for another column of this model |
has_many(C, foreign_key = "p_id") | Vec<C> | as has_one, every matching row |
many_to_many(C, through = J, local = "p_id", foreign = "c_id") | Vec<C> | rows of the join table J linking this model's key (local_key) to C's (related_key) |
count_of = "posts" | i64 | the count with_count loads for the named relation |
- The related model's type comes first in the attribute.
throughtakes a join model's type (through = UserTag) or a table name in quotes (through = "user_tags").localandforeignname the join table's columns for this model and for the related one.local_key,owner_keyandrelated_keyname the matched column when it is not that model's primary key.- A relation field is not a column. It holds its
Default(an emptyVec,None, 0) until loaded. - The related model must be
CloneandSend(a belongs-to or many-to-many row can be shared by several parents).Option<Box<C>>lets two models refer to each other.
The derive gives every relation field a constant named as the field (User::posts, a Relation<User, Post>), which every call below takes.
A wrong combination (a has_many without foreign_key, a many_to_many without through, local and foreign) is a compile error.
Eager loading
with loads a relation into every row a query reads, with one statement per relation level, whatever the number of rows: first the parents, then SELECT … FROM posts WHERE user_id IN (<every user's id>), and the rows are matched to their parents in your process. A many-to-many level takes two statements: the join rows, then the related rows they name.
use rasterizeddb_client::prelude::*;
// User, Post and Comment as declared above.
async fn feed<E: Executor>(db: &E) -> Result<Vec<User>> {
// Three statements, plus one for the counts.
User::query()
.with(
User::posts
.filter(Post::published.eq(true))
.order_by(Post::id.desc())
.limit(3) // per user
.with(Post::comments),
)
.with_count(User::posts)
.all(db)
.await
}
async fn posts_with_authors<E: Executor>(db: &E) -> Result<Vec<Post>> {
Post::query().with(Post::author).all(db).await
}A relation is narrowed with the same methods as a query:
on a relation (User::posts) | does |
|---|---|
filter(expr) | only related rows matching expr |
order_by(order) | the order of each parent's related rows |
limit(n) | at most n related rows per parent |
with(nested) | loads a relation of the related rows too, nested to any depth |
with_count(nested) | counts a relation of the related rows |
with_deleted(), only_deleted() | with a soft-delete column: include marked rows, or only them |
all() | the relation as it is, for calls that want a narrowed one |
with_count(User::posts) fills the field marked #[rdb(count_of = "posts")], with one GROUP BY statement; filters on the relation narrow what is counted.
A per-relation limit is applied per parent in your process: every matching related row is read, and each parent keeps its first n. Filter and order are applied by the server. Past RELATION_CHUNK (1,000) parents, a level takes one statement per thousand parents; each parent's related rows are always read by one statement, so the order holds.
Lazy loading
For rows you already have: load on one row (the ModelRelations trait, in the prelude), or load on a narrowed relation for a whole slice, which loads them all in one statement.
use rasterizeddb_client::prelude::*;
// User and Post as declared above.
async fn lazily(db: &Client) -> Result<()> {
if let Some(mut user) = db.find::<User>(1i64).await? {
user.load(User::posts, db).await?;
println!("{} has {} posts", user.name, user.posts.len());
}
let mut users: Vec<User> = User::query().all(db).await?;
User::posts.all().load(&mut users, db).await?;
Ok(())
}Filtering on a relation
where_has and where_doesnt_have keep the rows that have, or have no, related row matching the relation's filters. Each adds one subquery to the same statement: WHERE id IN (SELECT user_id FROM posts WHERE user_id IS NOT NULL AND …).
use rasterizeddb_client::prelude::*;
// User and Post as declared above.
async fn writers_and_lurkers(db: &Client) -> Result<()> {
let writers: Vec<User> = User::query()
.where_has(User::posts.filter(Post::published.eq(true)))
.all(db)
.await?;
let lurkers: u64 = User::query().where_doesnt_have(User::posts).count(db).await?;
println!("{} writers, {lurkers} lurkers", writers.len());
Ok(())
}where_doesnt_have keeps a row whose key is NULL (it has nothing related), and the subquery leaves out NULL keys, so the usual NOT IN traps with NULLs do not apply.
Linking many-to-many rows
attach, detach, detach_all and sync write the join table:
use rasterizeddb_client::prelude::*;
// User and Tag as declared above.
async fn tagging(db: &Client, user: &User, rust: &Tag, sql: &Tag) -> Result<()> {
let added: u64 = User::tags.attach(user, [rust, sql], db).await?; // INSERT … ON CONFLICT DO NOTHING
let removed: u64 = User::tags.detach(user, [sql], db).await?; // DELETE … AND tag_id IN (…)
let synced = User::tags.sync(user, [rust], db).await?; // exactly these
println!("{added} {removed} -{} +{}", synced.detached, synced.attached);
User::tags.detach_all(user, db).await?; // every link of this user
Ok(())
}| call | returns | sends |
|---|---|---|
attach(&parent, children, db) | u64 links added | INSERT INTO <join> … ON CONFLICT DO NOTHING; a link already there is skipped |
detach(&parent, children, db) | u64 links removed | one DELETE |
detach_all(&parent, db) | u64 links removed | one DELETE of every link of parent |
sync(&parent, children, db) | Synced { detached, attached } | a DELETE of links to other rows, then an INSERT of the missing ones |
attach relies on a primary or unique key over the join table's two columns; without one, a repeated link is stored twice. sync is two statements: outside a transaction, a failure between them leaves the old links removed and the new ones not yet added, so run it in a transaction to make it one change.
Foreign keys
#[rdb(references = "users(id)")] on a column declares a foreign key in the CREATE TABLE the ORM writes, and in a migrator's ADD COLUMN when the field is new:
| attribute | values |
|---|---|
references = "table(column)" | the referenced table and one column: its primary key or a unique column |
on_delete = "…" | cascade, restrict, set null, set default, no action |
on_update = "…" | the same, on a change of the referenced key |
The server enforces it: a row pointing at a missing parent is refused, and on_delete = "cascade" deletes the children with the parent. Create the referenced table first.
Foreign keys are independent of relation attributes: a relation loads rows whether or not a foreign key backs it, and a foreign key is checked whether or not a relation reads it. Declaring both is the usual setup.
A foreign key over several columns, or one added to a column that already exists, is SQL in a migration step:
ALTER TABLE order_lines ADD CONSTRAINT order_lines_order_fk
FOREIGN KEY (tenant_id, order_id) REFERENCES orders (tenant_id, id) ON DELETE CASCADELimits
- Related rows are loaded in separate statements and matched in your process; the ORM writes no joins.
- A per-relation
limitreads every matching related row and trims per parent in your process. referencesnames one column. Composite foreign keys are SQL.- The model sync does not compare foreign keys on columns that already exist: changing
referenceson an existing field does nothing to the table. Change it with SQL in a migration step. syncis two statements; run it in a transaction for one change.