Elyra
Elyra The coding agent eTerm The terminal that knows where each command ends Huskarl AI colleagues on your own Mac Starf An activity monitor for Apple silicon that never invents a number etrans An SSH and SFTP client for macOS Elyra VM Virtual machines for macOS, Linux and Windows on your Mac Litr A small, native web browser for macOS Notr A notebook for macOS e The native code editor Elyra Grove Native local development environment Askr The real server for Laravel & PHP Elyra Framework Rust + Svelte 5 framework for desktop apps Elyra Conductor Local project conductor Refr Local-first PDF workspace for macOS Elyra Workspace A desktop workspace for coding agents eDock A container runtime for the Mac Elyra SQL Server MySQL-compatible SQL server in Rust Elyra Félagi Agents as teammates on one board Elyra SQL Client Native desktop SQL workbench Elyra SQL Anywhere Replication-ready SQL engine Elyra Sjá SEO & GEO workspace for macOS Elyra DataGrid Server-driven data grid for Laravel
Reference
Ratatosk CLI
Roadmap
RFC 0001: make:resource
RFC 0002: live queries
RFC 0003: MCP server
RFC 0004: MCP resource templates
RFC 0005: a Laravel backend
RFC 0006: Laravel broadcasting
RFC 0007: offline and sync
RFC 0008: Laravel notifications
RFC 0009: Files
RFC 0010: Laravel abilities
RFC 0011: an assistant in the app
RFC 0012: @elyra/ui
RFC 0013: the assistant sees the window
RFC 0014: Elyra Inspector
RFC 0015: presence
RFC 0016: capabilities per window
RFC 0017: record invalidation
RFC 0018: the assistant's answer, streamed
RFC 0019: a window from the tray
RFC 0020: an app that stays in the tray
RFC 0021: a server chosen at sign-in
RFC 0022: signed in to more than one server
RFC 0023: private channels a window listens to
RFC 0024: updates from the backend
RFC 0025: commands and configuration
RFC 0026: the running app, for coding agents
RFC 0027: the assistant's code mode
RFC 0028: the tray's icon, and the app's
RFC 0029: installers
RFC 0030: the app's identity on Windows
RFC 0031: a token per workspace
RFC 0032: the microphone
RFC 0033: diagnostics the user can send
RFC 0034: one screen in several states at once
RFC 0035: point at it, and hand it to the agent
RFC 0036: rata check, the app checked as a whole
RFC 0037: Theme Studio
RFC 0038: edit it in its own app
RFC 0039: a write shown at once in every window
RFC 0040: the two halves agree
RFC 0041: Quick Look
RFC 0042: follow a colleague
RFC 0043: every write seen
RFC 0044: composite keys
RFC 0045: bigint all the way
RFC 0046: pivot columns
RFC 0047: relations on any key
RFC 0048: more providers
RFC 0049: OpenAI web search
RFC 0050: integer-keyed arguments
RFC 0051: citations
RFC 0052: open documents
RFC 0053: exit hooks
RFC 0054: the gui feature
RFC 0055: menus that change
RFC 0056: the framework's own words
RFC 0057: rata upgrade
RFC 0058: @elyra/charts
RFC 0059: all of WireCharts
RFC 0060: exporting a chart
RFC 0061: zoom
RFC 0062: printing
RFC 0063: linked charts
RFC 0064: report pages
RFC 0065: marks
RFC 0066: taking a table out
RFC 0067: totals
RFC 0068: columns the user picks
RFC 0069: filters
RFC 0070: saved views
RFC 0071: lists over Laravel
RFC 0072: targets
RFC 0073: every row out
RFC 0074: grouped rows
RFC 0075: pinned columns
RFC 0076: views on the server
RFC 0077: every match selected
RFC 0078: editing in the table
RFC 0079: many cells at once
RFC 0080: a value for the selected rows
RFC 0081: a new row in the table
RFC 0082: a related record in a cell
RFC 0083: a filter by a related record
RFC 0084: one write for many rows
RFC 0085: the keys shown
RFC 0086: many rows in Laravel
RFC 0087: many rows deleted
RFC 0088: the trash
Release notes
Changelog
Elyra

Models

#[derive(Model)] is Elyra's Eloquent — a thin Active-Record layer over the Database pool (not a second ORM engine). Feature-gated behind database.

use elyra::Model;

#[derive(Model, serde::Serialize, serde::Deserialize, specta::Type)]
#[model(table = "todos", timestamps)]
struct Todo {
    #[model(id)] id: i64,
    title: String,
    done: bool,                          // <-> INTEGER 0/1 column
    #[model(column = "body")] text: String,
    created_at: i64,
    updated_at: i64,
}

Because models are plain structs, a command returning Vec<Todo> becomes Promise<Todo[]> through codegen.

Generated methods

Todo::all(&db).await?;                        // Vec<Todo>
Todo::find(&db, 1).await?;                     // Option<Todo>

let mut t = Todo { id: 0, title: "milk".into(), done: false, text: "".into(),
                   created_at: 0, updated_at: 0 };
t.insert(&db).await?;                          // sets t.id (+ timestamps)
t.done = true;
t.save(&db).await?;                            // insert-if-new (id == 0) else update
t.update(&db).await?;                          // UPDATE ... WHERE id = ?
t.delete(&db).await?;                          // DELETE ... WHERE id = ?
  • insert sets the primary key from the database (RETURNING on sqlite/postgres, last_insert_id() on MySQL).
  • save inserts when id == 0, otherwise updates.
  • all and find go through the query builder, so they respect soft deletes and global scopes like every other read.

Query builder

Todo::query()
    .where_eq("done", false)
    .where_gt("id", 10)
    .where_in("id", [1, 2, 3])
    .order_by("id")            // or .order_by_desc("id")
    .limit(50)
    .get(&db).await?;          // Vec<Todo>

Todo::query().where_eq("title", "milk").first(&db).await?;   // Option<Todo>

Comparisons: where_eq, where_ne, where_lt, where_gt, where_lte, where_gte, plus where_in. Values implement Into<Value> (i64, i32, i16, bool, f64, f32, &str, String, &String, and Option<T> of any of them — None binds as NULL).

Placeholders are rendered per driver; column identifiers are validated (they can't be bound), so where_eq("a; DROP TABLE", ..) is rejected, not executed. An empty where_in([]) matches nothing.

Attributes

Attribute On Meaning
#[model(table = "..")] struct Table name (default: lowercased struct name)
#[model(timestamps)] struct Auto-manage created_at / updated_at (unix seconds)
#[model(soft_deletes)] struct Hide rows whose deleted_at is set (soft deletes)
#[model(global_scope = path)] struct Constrain every query (global scopes); repeatable
#[model(id)] field Mark the primary key (default: a field/column named id)
#[model(column = "..")] field Map the field to a differently-named column
#[model(cast = "json" | "text" | Path)] field Store a non-scalar type (casts)
#[model(has_many(T, fk="..", as=".."))] struct Relation (accessor + load_* map)
#[model(has_one(T, fk="..", as=".."))] struct Relation (accessor + load_* map)
#[model(belongs_to(T, fk="..", as=".."))] struct Relation (accessor + load_* map)
#[model(belongs_to_many(T, pivot="..", fk="..", related_fk="..", as=".."))] struct Many-to-many through a pivot
#[model(belongs_to_many(T, using = P, fk="..", related_fk="..", as=".."))] struct Many-to-many with the pivot's own model (pivot columns)
#[model(has_many(T, fk=".."))] field Relation hydrated into the field (with_*)
#[model(has_one(T, fk=".."))] field Relation hydrated into the field (with_*)
#[model(belongs_to(T, fk=".."))] field Relation hydrated into the field (with_*)
#[model(belongs_to_many(T, pivot="..", fk="..", related_fk=".."))] field Many-to-many hydrated into the field (with_*)

Unknown options are compile errors, and table/column names must be bare SQL identifiers. The derive used to ignore what it didn't recognise — a misspelt global_scope would have compiled into a model that silently leaked across tenants.

Relations

#[derive(Model)]
#[model(table = "users", has_many(Post, fk = "user_id", as = "posts"))]
struct User { id: i64, name: String }

#[derive(Model)]
#[model(table = "posts", belongs_to(User, fk = "user_id"))]
struct Post { id: i64, user_id: i64, title: String }

let posts = user.posts(&db).await?;        // has_many -> Vec<Post>
let owner = post.user(&db).await?;         // belongs_to -> Option<User>
  • has_many → Vec<T>; has_one → Option<T>; belongs_to → Option<T>.
  • fk and as (the method name) are optional; defaults are derived from the type names ({type}_id, pluralized/singular lowercase name). Multi-word type names need explicit fk/as.
  • A nullable foreign key (user_id: Option<i64>) is Ok(None) from belongs_to when it's NULL, and left out of load_*.
  • A belongs_to's fk must be one of the model's own columns (a compile error otherwise).

On any key

The parent's key needn't be an i64: a String key, or a composite key, works the same way (RFC 0047). For a key of more than one column, fk is a tuple naming a column per key column, in the key's order:

#[derive(Model)]
#[model(table = "teams", has_many(Member, fk = "team_code", as = "members"))]
struct Team { #[model(id)] code: String, name: String }

#[derive(Model)]
#[model(table = "members", belongs_to(Team, fk = "team_code"))]
struct Member { id: i64, team_code: String, name: String }

#[derive(Model)]
#[model(table = "order_lines", has_many(LineNote, fk = ("order_id", "line_no"), as = "notes"))]
struct OrderLine { #[model(id)] order_id: i64, #[model(id)] line_no: i64, qty: i64 }

#[derive(Model)]
#[model(table = "line_notes", belongs_to(OrderLine, fk = ("order_id", "line_no"), as = "line"))]
struct LineNote { id: i64, order_id: i64, line_no: i64, body: String }

team.members(&db).await?;                                  // Vec<Member>
member.team(&db).await?;                                   // Option<Team>
let by_line = OrderLine::load_notes(&db, &lines).await?;   // HashMap<(i64, i64), Vec<LineNote>>
let notes = &by_line[&line.key()];
note.line(&db).await?;                                     // Option<OrderLine>
  • load_* maps are keyed by the parent's key type, Model::Key: HashMap<i64, _> for an i64 key (as always), HashMap<String, _>, HashMap<(i64, i64), _>. Model::key(&self) gives a row's key to look it up with.
  • A composite parent has no default fk: has_many and has_one from it need the tuple, with as many columns as its key (a compile error otherwise). A belongs_to with an fk of the wrong width is an error that says so.
  • Eager loading over more than one column is a row-value IN, (order_id, line_no) IN ((?, ?), …), on SQLite, MySQL and Postgres alike. Every eager load runs one query per 1000 parents.
  • load_* and with_* need a key they can read back: i64, i32, String or bool, or a tuple of two to four of them (KeyFromRow). The lazy accessors work with any key.
  • belongs_to_many still needs an i64 key on both sides: its pivot holds integers.

Eager loading

Relation accessors (user.posts(&db)) are lazy — one query each, so calling them in a loop is N+1. For a batch of parents, each relation also generates a load_<name> method that runs one query and returns a HashMap for joining:

let users = User::all(&db).await?;

// has_many: keyed by the parent's key -> Vec<child>
let by_user = User::load_posts(&db, &users).await?;   // HashMap<i64, Vec<Post>>
for user in &users {
    let posts = by_user.get(&user.id).cloned().unwrap_or_default();
}

// belongs_to: keyed by the owner's key -> owner
let posts = Post::all(&db).await?;
let owners = Post::load_user(&db, &posts).await?;      // HashMap<i64, User>
let owner = owners.get(&posts[0].user_id);

has_one generates load_<name> returning HashMap<i64, T> (first child per parent). Under the hood these use where_in + grouping (where_in_rows for a key of more than one column); you can also drop to the primitive directly:

let posts = Post::query().where_in("user_id", ids).get(&db).await?;
let notes = LineNote::query()
    .where_in_rows(&["order_id", "line_no"], [vec![42.into(), 3.into()]])
    .get(&db)
    .await?;

Auto-hydration (relation fields)

Instead of joining a HashMap yourself, declare the relation on a field and let the data hydrate straight into the struct. The field is not a column (it is skipped by COLUMNS, insert, and from_row, and defaults to empty):

#[derive(Model, Debug)]
#[model(table = "authors")]
struct Author {
    id: i64,
    name: String,
    #[model(has_many(Book, fk = "author_id"))]
    books: Vec<Book>,          // filled by `with_books`, empty otherwise
}

#[derive(Model, Debug, Clone)] // belongs_to targets must be `Clone`
#[model(table = "books")]
struct Book {
    id: i64,
    author_id: i64,
    title: String,
    #[model(belongs_to(Author, fk = "author_id"))]
    author: Option<Author>,
}

Each relation field generates a with_<field> batch hydrator that runs one query and assigns the result into every element:

let mut authors = Author::all(&db).await?;
Author::with_books(&db, &mut authors).await?;   // authors[i].books now populated

let mut books = Book::all(&db).await?;
Book::with_author(&db, &mut books).await?;      // books[i].author == Some(..)
  • has_many → Vec<T>, has_one / belongs_to → Option<T>.
  • fk defaults as for struct-level relations ({self}_id, or {target}_id for belongs_to).
  • belongs_to clones the shared owner into each child, so the target type must derive Clone.

Many-to-many (belongs_to_many)

#[derive(Model)]
#[model(table = "users", belongs_to_many(Role))]
struct User { id: i64, name: String }

#[derive(Model)]
#[model(table = "roles")]
struct Role { id: i64, name: String }

The pivot follows Laravel's conventions unless overridden: the two model names in alphabetical order (role_user), user_id pointing at the declaring model and role_id at the other. Override with pivot = "..", fk = "..", related_fk = ".."; name the methods with as = ".." (default: roles).

user.roles(&db).await?;                                  // Vec<Role>
user.roles_query().where_like("name", "a%").paginate(&db, 1, 20).await?;

user.attach_roles(&db, [admin.id, editor.id]).await?;    // rows inserted
user.detach_roles(&db, [editor.id]).await?;
user.detach_all_roles(&db).await?;

let changes = user.sync_roles(&db, ids).await?;          // exactly these, in one transaction
changes.attached; changes.detached;                      // what actually changed
user.sync_roles_without_detaching(&db, [viewer.id]).await?;  // the idempotent attach

let by_user = User::load_roles(&db, &users).await?;      // HashMap<i64, Vec<Role>>, one query
  • attach of an already-attached id is an error, as in Laravel, when the pivot's primary key covers both columns (it should). Duplicates within one call are collapsed. Use sync_roles_without_detaching for "make sure these are attached".
  • Eager loading is one query: the pivot's parent key is selected alongside the related columns, so each row already says which parent it belongs to. The related model therefore doesn't need Clone, even when parents share a row.
  • On a field (#[model(belongs_to_many(Role, pivot = "role_user", fk = "user_id"))] roles: Vec<Role>), with_roles hydrates the field, and the write methods are named by the field.
  • Both keys are i64; a model with another primary-key type can't declare the relation (compile error). For pivot columns beyond the two keys, see Pivot columns.

A pivot migration:

Schema::create("role_user", |t| {
    t.foreign_id("role_id", "roles").on_delete_cascade();
    t.foreign_id("user_id", "users").on_delete_cascade();
    t.primary(&["role_id", "user_id"]);
})

Pivot columns

A pivot that says more than its two keys (who granted a role, when it expires, the quantity in a cart) is a model of its own: the two keys are its composite key, and the relation names it with using (RFC 0046). Laravel's withPivot and withTimestamps, typed:

#[derive(Model, Default)]
#[model(table = "role_user", timestamps)]
struct RoleUser {
    #[model(id)]
    user_id: i64,
    #[model(id)]
    role_id: i64,
    granted_by: Option<i64>,
    created_at: i64,
    updated_at: i64,
}

#[derive(Model)]
#[model(table = "users", belongs_to_many(Role, using = RoleUser))]
struct User { id: i64, name: String }

let roles: Vec<(Role, RoleUser)> = user.roles_with_pivot(&db).await?;
let by_user = User::load_roles_with_pivot(&db, &users).await?;  // HashMap<i64, Vec<(Role, RoleUser)>>

let grant = RoleUser { granted_by: Some(me.id), ..RoleUser::default() };
user.attach_roles_with(&db, [(admin.id, grant)]).await?;         // the keys come from the relation
user.update_role_pivot(&db, admin.id, |p| p.granted_by = None).await?;  // false if not attached
let changes = user.sync_roles_with(&db, [(admin.id, RoleUser::default())]).await?;
changes.updated;                                                 // attached rows whose data changed

// Narrowing on a pivot column: the relation's query already joins it.
user.roles_query().where_eq("role_user.granted_by", me.id).get(&db).await?;
  • The pivot table is the model's (RoleUser::TABLE), so pivot = ".." beside using is a compile error; fk and related_fk keep their defaults and must both be among the model's key columns (an Error::Query naming the missing one if not).
  • The model implements Default (a compile error at using if not): attach_roles and sync_roles by ids insert RoleUser::default() with the keys set, so timestamps and column defaults are filled. A plain two-column insert would fail on a NOT NULL timestamp.
  • Reading is two queries: the related rows through the join, then the pivot rows, paired in memory. A related row without its pivot row (deleted in between) is left out.
  • sync_*_with updates only what differs: the database compares each column other than the keys and the timestamps (null-safe), so an unchanged row isn't written and updated_at stays. Writes with rows run in one transaction.
  • update_<one>_pivot is named by the relation without its trailing s (roles → update_role_pivot, members → update_member_pivot). The keys stay the relation's, whatever the closure does to them.
  • The field form hydrates a Vec<(Role, RoleUser)> field with with_roles; a Vec<Role> field with using hydrates the related rows only. Both get the _with writers.
  • The pivot model is an ordinary model too: RoleUser::find(&db, (user.id, admin.id)), save, delete, factories.

Casts

The Any driver behind every model decodes SQL scalars only, so a Vec<String>, a struct or an enum can't be a plain field. A cast bridges it — Laravel's $casts:

#[derive(Model)]
struct Post {
    id: i64,
    #[model(cast = "json")] tags: Vec<String>,        // TEXT, JSON-encoded
    #[model(cast = "json")] meta: Option<Meta>,       // NULL <-> None
    #[model(cast = "text")] status: Status,           // TEXT, via Display / FromStr
    #[model(cast = Cents)]  price: Money,             // your own caster
}
Cast Field type Column
"json" any Serialize + DeserializeOwned TEXT (NULL ⇄ None)
"text" any Display + FromStr TEXT
a path whatever it implements Cast<T> for whatever it encodes

A custom cast is a marker type implementing elyra::db::cast::Cast<T>:

use elyra::db::cast::Cast;
use elyra::db::sqlx::{any::AnyRow, Row};

struct Cents;
impl Cast<Money> for Cents {
    fn encode(v: &Money) -> elyra::db::Result<Value> { Ok(Value::Int(v.cents())) }
    fn decode(row: &AnyRow, col: &str) -> elyra::db::Result<Money> {
        Ok(Money::from_cents(row.try_get::<i64, _>(col)?))
    }
}

A value that won't decode (an unknown enum spelling, malformed JSON) is an error naming the column, not a panic.

A "json" cast works with a t.text() column or a t.json() one (JSONB on Postgres, TEXT elsewhere). On Postgres the value is converted in SQL both ways, since the Any driver can't bind or decode JSONB itself. A TEXT column keeps the JSON exactly as written; a JSONB one normalizes it (key order, whitespace), and it reads back as the same value. A custom cast whose column needs converting in SQL overrides Cast::select (how a SELECT reads it) and Cast::bind (how a write binds it); both default to the column and the placeholder as they are.

In a bulk Query::update, pass the encoded value yourself — ("tags", Json::encode(&tags)?) — into a TEXT column; the conversion above applies to model writes and reads, not to values you bind by hand.

Scopes

Local scopes

A local scope is any fn(Query<M>) -> Query<M> — Laravel's scopeActive, without the naming magic:

fn active(q: Query<User>) -> Query<User> { q.where_eq("active", true) }
fn admins(q: Query<User>) -> Query<User> { q.where_eq("role", "admin") }

User::query().scope(active).scope(admins).get(&db).await?;

when and when_some apply a clause only when there is something to filter on — the shape a search form produces:

User::query()
    .when(filter.only_active, active)
    .when_some(filter.name, |q, name| q.where_like("name", format!("%{name}%")))
    .paginate(&db, filter.page, 25).await?;

Global scopes

A global scope constrains every query for the model — query(), find, all, counts, bulk update / delete, and relation queries into the model:

fn current_workspace(q: Query<Doc>) -> Query<Doc> {
    q.where_eq("workspace_id", workspace::current())
}

#[derive(Model)]
#[model(table = "docs", global_scope = current_workspace)]
struct Doc { id: i64, workspace_id: i64, title: String }

Doc::find(&db, id).await?;                                // None if it's another workspace's
Doc::query().without_global_scopes().count(&db).await?;   // an explicit, greppable opt-out

A scope is a plain function with no Ctx, so a runtime value like the current workspace comes from state your app owns — an AtomicI64 or OnceLock it sets on sign-in, the same way Laravel's scopes read auth()->user().

Only the scope's where constraints apply; ordering, limits or joins it sets are ignored rather than silently changing every query. Soft deletes are independent — without_global_scopes doesn't include trashed rows; with_trashed does.

Factories

A factory is a recipe for a valid row — Laravel's User::factory():

use elyra::Factory;

impl Factory for User {
    fn definition(n: u64) -> Self {
        User { id: 0, name: format!("User {n}"), email: format!("user{n}@example.test"), admin: false }
    }
}

let users = User::factory().count(3).create(&db).await?;              // inserted, ids set
let admin = User::factory().state(|u| u.admin = true).create_one(&db).await?;
let drafts = User::factory().count(10).make();                        // not inserted
User::factory().count(4).sequence(|u, i| u.admin = i == 0).create(&db).await?;

// Related rows: the child's factory, pointed at the parent.
Post::factory().count(5).state(move |p| p.user_id = admin.id).create(&db).await?;

n is unique for the life of the process — across models and builders — so it is safe for columns with a unique constraint. States apply in the order they were added, after the definition. Factories work in tests and in seeders alike.

bool columns

bool fields map to an INTEGER 0/1 column: bind 0/1, decode != 0. This is portable across all three drivers — the Any driver can't read SQLite's native BOOLEAN type, so models never use one. Declare such columns INTEGER in your migration.

Primary keys

The default is a single i64 autoincrement column: the database assigns it and insert reads it back (RETURNING on SQLite/Postgres, last_insert_id on MySQL); save() treats 0 as unsaved.

A non-i64 single-column key (e.g. String) is also supported — mark it with #[model(id)]:

#[derive(Model)]
#[model(table = "settings")]
struct Setting {
    #[model(id)]
    key: String,   // app-supplied; included in INSERT, not read back
    value: String,
}

Setting { key: "theme".into(), value: "dark".into() }.insert(&db).await?;
let s = Setting::find(&db, "theme".to_string()).await?;

For an app-supplied key the value is inserted as-is (no key retrieval), and find takes that key type. save() uses the type's Default as the "unsaved" sentinel ("" for String), so prefer explicit insert / update when the key is always set. Relations to and from it work as for an i64 key; see On any key.

Composite keys

A row named by more than one column: mark each with #[model(id)] (RFC 0044). The key is a tuple of those fields, in the order they're declared:

#[derive(Model)]
#[model(table = "order_lines", timestamps, belongs_to(Order, fk = "order_id"))]
struct OrderLine {
    #[model(id)]
    order_id: i64,
    #[model(id)]
    line_no: i64,
    product: String,
    qty: i64,
    created_at: i64,
    updated_at: i64,
}

let line = OrderLine::find(&db, (42, 3)).await?;
OrderLine::query().with_trashed().find(&db, (42, 3)).await?;
OrderLine::query().where_key((42, 3)).soft_delete(&db).await?;
  • The app supplies it: insert writes every column as written, and nothing is read back, even for i64 key columns.
  • update and delete use every key column in their WHERE.
  • save() is an upsert on the key (INSERT … ON CONFLICT (…) DO UPDATE on SQLite and Postgres, ON DUPLICATE KEY UPDATE on MySQL), since there's no "unsaved" value to tell. It needs the key's columns to be the table's primary key or a unique index (t.primary(&["order_id", "line_no"])). With timestamps, created_at is set when it's 0 and never overwritten in the row; updated_at always.
  • Relations from and to it work, with fk as a tuple (On any key); it can't be a side of belongs_to_many, whose pivot holds one i64 per side (a compile error). At most four key columns.
  • Model::KEY lists the key's columns (one for a single key), and Model::Key is its type. Query::find and where_key take anything Into<Model::Key>: find(&db, 42), find(&db, "theme") and an i32 for an i64 key all work.

Query builder

// Filtering
let users = User::query()
    .where_eq("active", true)
    .where_like("email", "%@example.com")
    .where_between("age", 18, 65)
    .where_not_null("verified_at")
    .or_where_eq(&[("role", "admin".into()), ("role", "owner".into())])
    .or_where_like(&["name", "email"], format!("%{term}%"))   // a search box: (name LIKE ? OR email LIKE ?)
    .where_contains("notes", "50% off")  // contains, ignoring case; `%` and `_` are themselves
    .order_by("name")
    .order_by_desc("created_at")        // chains: ORDER BY name ASC, created_at DESC
    .limit(20)
    .offset(40)
    .get(&db)
    .await?;

// A list's filters (RFC 0069): each `None` or empty one is no filter.
use elyra::db::filter::{Dates, Range};
let invoices = Invoice::query()
    .filter_options("status", Some(vec!["open", "overdue"]))       // IN (…)
    .filter_range("amount", Some(Range { min: Some(10_000.0), max: None }))
    .filter_dates("due", Some(Dates { from: Some("2026-11-01".into()), to: Some("2026-11-30".into()) }))
    .filter_text("customer", Some("ada".into()))                    // where_contains
    .get(&db)
    .await?;
// `to` is "before the next day": a time on 30 November is in.

// Aggregates (limit/offset are ignored, filters are not)
let total   = User::query().count(&db).await?;
let any     = User::query().where_eq("active", true).exists(&db).await?;
let sum     = Order::query().sum(&db, "total").await?;      // Option<f64>
let average = Order::query().avg(&db, "total").await?;
let oldest  = User::query().min(&db, "created_at").await?;  // Option<i64>

// Pagination
let page = User::query().order_by("id").paginate(&db, 2, 25).await?;
page.data;         // Vec<User>
page.total;        // matching rows
page.last_page;    // page count
page.has_more();   // bool
(page.from(), page.to());
// A command can return the page as-is: it's Serialize + specta::Type, and the
// frontend gets `Promise<Page<User>>` with a generic `Page<M>` in bindings.ts.

// Grouped (RFC 0074): ordered by the column first, then the query's order;
// `page.groups` has each group on the page with its count over every match,
// keyed by the value as text ("" for none), as a `Table` reads them. The
// column must be the model's (a key from the frontend, checked first).
let page = Invoice::query().order_by("due").paginate_grouped(&db, 1, 25, "customer").await?;
page.groups.unwrap()["Ada Lovelace"].count; // every invoice of hers, not the page's

// Joins (identifiers may be table-qualified)
let recent = Product::query()
    .join("orders", "orders.product_id", "products.id")
    .where_gte("orders.quantity", 2)
    .get(&db)
    .await?;

// Bulk writes
let updated = User::query()
    .where_eq("active", false)
    .update(&db, &[("active", true.into()), ("note", "reactivated".into())])
    .await?;
let removed = User::query().where_lt("age", 13).delete(&db).await?;

// Batching without loading everything at once
User::query().chunk(&db, 500, |batch| {
    for user in batch { /* … */ }
    Ok(())
}).await?;

Soft deletes

#[derive(Model)]
#[model(table = "accounts", soft_deletes)]
struct Account {
    id: i64,
    email: String,
    deleted_at: Option<i64>,
}

deleted_at (unix seconds, nullable) makes every query skip trashed rows — including find and all:

Account::query().count(&db).await?;                        // live rows only
Account::query().with_trashed().count(&db).await?;         // include trashed
Account::query().only_trashed().get(&db).await?;           // just the trashed

Account::query().where_eq("email", &email).soft_delete(&db).await?;  // set deleted_at
Account::query().where_eq("email", &email).restore(&db).await?;      // clear it
Account::query().where_eq("email", &email).delete(&db).await?;       // hard delete

Account::query().with_trashed().find(&db, id).await?;                // reach a trashed row by id

The instance method account.delete(&db) is a hard delete; soft-delete a single row through the builder, as above.

Add the column with the schema builder's t.soft_deletes().

v1 assumptions

  • A model with a composite key can't be a relation's parent, and a pivot's own columns aren't on the models belongs_to_many returns (Laravel's withPivot); read and write them through the pivot's own composite-key model.
  • group_by/having, first_or_create/update_or_create/upsert, polymorphic relations, has_many_through, model events/observers and accessors/mutators are not implemented yet.
  • Column name equals field name unless overridden with #[model(column)].
  • SQLite is test-covered; MySQL/Postgres run in CI against real servers.

Related