Skip to content

Functions and data ​

Define tables and functions in backend modules such as src/tasks.rs. Declare each module in main.rs with mod tasks;; the macros register compiled tables and functions automatically.

The examples on this page build on one task table. Start with use rxferrix::prelude::*; in the module.

Define a table ​

rust
use rxferrix::prelude::*;

#[table(name = "tasks")]
#[index(by_done = [done])]
pub struct Task {
    pub text: String,
    pub done: bool,
}

A stored document adds an ID and creation time to these fields. Rust uses Doc<Task> with .id and .creation_time; the client sees _id and _creationTime. Creation time is milliseconds since the Unix epoch.

The table macro provides serialization, TypeScript types, and typed field/index handles such as Task::done and Task::by_done. You do not need a separate schema file. See Types for custom result types and field naming, and Migrations before changing fields in a table that already contains data.

Read with a query ​

rust
#[query]
pub async fn list(ctx: &QueryCtx, done: Option<bool>) -> Result<Vec<Doc<Task>>> {
    let query = match done {
        Some(done) => ctx.db.query::<Task>().by(Task::by_done, done),
        None => ctx.db.query::<Task>(),
    };
    query.order(Order::Desc).take(100).await
}

done: None lists all tasks; Some(false) uses the index to list open tasks. Order::Desc returns newer documents first within the selected range. Clients call api.tasks.list with { done: false } or omit the optional argument.

Order comes from the prelude. A table struct of your own named Order hides it, and Order::Desc then fails to compile; write rxferrix::Order::Desc, or import it under another name (use rxferrix::Order as SortOrder;).

A query reads one consistent snapshot. Subscriptions rerun when a write touches what the query read. Keep the result deterministic: use tracked context inputs, avoid external I/O, and sort collections whose iteration order may vary.

ReadResult
ctx.db.get(id).await?One document or None.
query.take(100).await?Up to 100 matching documents.
query.first().await?The first match or None.
query.unique().await?One match or None; an error if there is more than one.
query.count().await?The number of matches.
query.paginate(opts).await?A live page with continuation information.
query.collect().await?Every match; use it only when the range is bounded.

Write with a mutation ​

rust
#[mutation]
pub async fn add(
    ctx: &MutationCtx,
    #[validate(trim, non_empty, code = "empty_text", message = "A task needs some text")] text: String,
) -> Result<Id<Task>> {
    ctx.db.insert(Task { text, done: false }).await
}

#[mutation]
pub async fn set_done(ctx: &MutationCtx, id: Id<Task>, done: bool) -> Result<()> {
    let task = ctx.db.get(id).await?
        .or_user("not_found", "This task no longer exists")?;
    if task.done != done {
        ctx.db.patch(id, patch!(Task { done })).await?;
    }
    Ok(())
}

All reads and writes in one mutation share a transaction. An error rolls them back. insert returns an ID, patch changes named fields, replace supplies a complete new value, and delete removes a document.

patch!(Table { field: value, ... }) names fields as the struct does, and the compiler checks each one: a field the table doesn't have, or a value of the wrong type, doesn't build. field alone is shorthand for field: field, as in a struct literal. An Option field takes None to clear it, or a plain value. Fields are written the way the table stores them, under their JSON names (completed_at is "completedAt"):

rust
ctx.db.patch(id, patch!(Todo { done, completed_at: done.then(|| ctx.now()) })).await?;

To build a patch step by step, start from Patch::new() and call .set(Todo::done, true). patch also takes a JSON object (json!({ "completedAt": null })), keyed by JSON names; a key the table doesn't have is an error at runtime.

Validate arguments and permissions in the function. A typed ID identifies a table; it does not prove that the caller may read or change that document. See authorization.

Choose indexes for your reads ​

An index with fields [owner, done] supports an equality prefix on owner, then an equality or range on done. Constraints follow declared field order. A post-read .filter(...) does not replace an index: it still scans the selected range.

For equalities only, pass the values to .by: the first field's value, or a tuple of the first fields' values, in field order. The compiler checks each value against its field's type. An index over a field with #[serde(with = "...")] or serialize_with, or with serde attributes inside a cfg_attr, takes with_index instead (its bounds go through the field's codec), as does an index over more than 8 fields.

rust
// #[index(by_owner_done = [owner, done])]
// #[index(by_owner_due = [owner, due])]
ctx.db.query::<Task>().by(Task::by_owner_done, owner)              // one owner's tasks
ctx.db.query::<Task>().by(Task::by_owner_done, (owner, false))     // their open tasks
ctx.db.query::<Task>()                                             // a range: with_index
    .with_index(Task::by_owner_due, |q| q.eq(Task::owner, owner).lt(Task::due, now))

Every ordinary index ends with _creationTime and _id. Equal declared fields therefore sort by creation time. After constraining all declared fields with eq, you can bound creation time with a handle such as Task::_creation_time.

Use .count() when you only need a count. Without a filter it counts the index range without deserializing the documents. For frequently displayed grouped counts or sums, use aggregates.

Paginate a growing list ​

Use pagination when a list can grow beyond a small fixed result. The argument must be named pagination_opts in Rust so clients see paginationOpts:

rust
#[query]
pub async fn page(ctx: &QueryCtx, pagination_opts: PaginationOpts)
    -> Result<PaginationResult<Doc<Task>>>
{
    ctx.db.query::<Task>()
        .order(Order::Desc)
        .paginate(pagination_opts)
        .await
}

On the client, use usePaginatedQuery(api.tasks.page, {}, { initialNumItems: 20 }). The hook manages cursors and keeps loaded pages subscribed. Do not interpret cursor strings or reuse them with another range or sort order.

To return enriched rows, transform the page with map, map_async, try_map, or try_map_concurrent; these preserve its pagination metadata. See the pagination reference for boundary and scan-limit behavior.

Use an action for external work ​

An action has no direct transaction. It calls queries and mutations through typed function references:

rust
#[action]
pub async fn add_samples(ctx: &ActionCtx, count: u32) -> Result<u32> {
    ensure_user!(count <= 100, "too_many", "Add at most 100 samples at once");
    for i in 1..=count {
        ctx.run_mutation::<add>((format!("Sample task #{i}"),)).await?;
    }
    Ok(count)
}

Each run_mutation commits independently. If a later call fails, earlier inserts remain. Use ctx.run_query::<f>(args) and ctx.run_action::<f>(args) in the same way. Arguments are tuples, () for none, or the value itself for one parameter.

For email or network calls that should follow a committed write, schedule an action from the mutation. See Scheduler.

To call an HTTP API, add an async HTTP client such as reqwest to your app's dependencies (reqwest = { version = "0.13", features = ["json"] }, and serde_json for the example below). Read its address and keys from ctx.env, so they can change without a rebuild and tests can point them at a fake service:

rust
#[action]
pub async fn fetch_rate(ctx: &ActionCtx, currency: String) -> Result<f64> {
    let base = ctx.env.require("RATES_URL").await?;
    let response = reqwest::get(format!("{base}/rates/{currency}")).await?.error_for_status()?;
    let body: serde_json::Value = response.json().await?;
    body["rate"].as_f64().or_user("no_rate", "No rate for this currency")
}

Share code between functions ​

Queries and mutations share logic through ordinary Rust functions; a direct call creates no transaction of its own. A helper that only reads takes &QueryDb, the type of a query's ctx.db. A mutation's ctx.db (a MutationDb) passes as one too, so the same helper serves both. A helper that writes takes &MutationDb. Both are in the prelude:

rust
use rxferrix::auth::User;

// For a `Task` with an `owner: Id<User>` field, as in the index examples above.
pub async fn own_task(db: &QueryDb, id: Id<Task>, user: Id<User>) -> Result<Doc<Task>> {
    let task = db.get(id).await?.or_user("not_found", "No such task")?;
    ensure_user!(task.owner == user, "forbidden", "This task belongs to someone else");
    Ok(task)
}

#[query]
pub async fn get(ctx: &QueryCtx, SignedIn(user): SignedIn, id: Id<Task>) -> Result<Doc<Task>> {
    own_task(&ctx.db, id, user).await
}

#[mutation]
pub async fn rename(ctx: &MutationCtx, SignedIn(user): SignedIn, id: Id<Task>, text: String) -> Result<()> {
    own_task(&ctx.db, id, user).await?;
    ctx.db.patch(id, patch!(Task { text })).await
}

A helper runs in its caller's transaction and checks nothing on its own: put access checks like this one in a helper and call it at the top of every function that needs them.

Validate arguments ​

#[validate(..)] on an argument checks it before the function runs, and trim tidies it first:

rust
#[mutation]
pub async fn create_channel(
    ctx: &MutationCtx,
    #[validate(trim, length(1..=32), pattern = "[a-z0-9-]+")] name: String,
    #[validate(range(2..=500))] seats: u32,
    #[validate(trim, length(..=200))] topic: Option<String>,
) -> Result<Id<Channel>> {
    // `name` is trimmed, 1 to 32 characters, and only lowercase letters, digits and dashes.
}

The rules are trim, non_empty, length(..) (characters of a string, items of a list, bytes of Bytes), range(..) for numbers, and pattern = "..", a regular expression the whole value must match. A length bound is a usize and a range bound has the argument's type (range(0.0..=1.0) for an f64); either may be a const. They run in the order written, so trim comes before the checks it should affect. An Option that is None passes.

A failed rule is a user error with the code invalid_argument, a message such as name must have 1 to 32 characters, and { "argument": "name" } as its data, which a form can use to highlight the field. Give your own with code and message; they apply to the rules of that attribute, so split the rules over several attributes for different errors:

rust
#[validate(trim, non_empty, code = "empty_name", message = "Choose a name")]
#[validate(length(..=32), code = "long_name", message = "Names are at most 32 characters")]
name: String,

The checks run for every call through rxferrix: clients, ctx.run_mutation, scheduled jobs and tests. A scheduled job's arguments are checked when the job runs, so a bad value fails the job rather than the call that scheduled it: check them there too if the caller should hear about it. Calling the function directly as a Rust function skips them, and a #[workflow] doesn't take them: check its arguments in the function that starts it. Checks that need the database, such as a name already being taken, stay in the body.

Arguments that don't decode at all, such as a missing one, a number sent for a string, or an unknown enum value, fail the same way before any rule runs: invalid_argument with the argument's name as data (null when the arguments aren't an object), and a message from the decoder.

Return useful errors ​

A UserError reaches clients with its code, message, and optional data. Use it for expected failures:

rust
ensure_user!(!text.trim().is_empty(), "empty_text", "A task needs some text");
let task = ctx.db.get(id).await?.or_user("not_found", "This task no longer exists")?;

bail_user!("locked", "{} is locked", task.text) returns a user error immediately. Other errors become "Server Error" in production; --dev exposes their details. Tests can inspect expected failures with UserError::of(&error).

Keep server helpers internal ​

Use #[internal_query], #[internal_mutation], or #[internal_action] for functions clients should not call directly. Actions, scheduled jobs, and trusted server code can still call them.

Use #[action(dev_only)] or the equivalent query/mutation attribute for seeds and dev inbox helpers. These run only in development mode and appear in generated devApi rather than api. ctx.is_dev() reports the runtime mode.