Skip to content

Latest commit

 

History

History
4010 lines (3183 loc) · 169 KB

models.md

File metadata and controls

4010 lines (3183 loc) · 169 KB

Models

Models manage data and business logic in your MVC application. SoliLang provides a simple OOP-style interface for database operations.

To bind a model to a named database (SoliDB, Postgres, MySQL, or SQLite), use class-body connection "name" with config/database.toml — see Multiple Databases.

Which backends support what

This page documents the full surface, which is what SoliDB (the default) provides. The SQL adapters — postgres, mysql, sqlite — run the portable part of it; anything they do not implement raises an error naming the feature rather than returning wrong rows.

Area SoliDB Postgres / MySQL / SQLite
Model.find_by_sql(sql, binds?) ✗ (use Model.query with SDBQL) ✓
CRUD, validations, callbacks, scopes, soft delete ✓ ✓
Hash .where, order/limit/offset, count, exists ✓ ✓
Aggregations (sum/avg/min/max/count), multi-row group_by ✓ ✓
pluck / select, delete_all / update_all, batch ops ✓ ✓
.includes for belongs_to / has_many / has_one / HABTM ✓ ✓ (batched)
Transactions (Model.transaction) ✓ ✓
Raw SDBQL string .where("doc…") ✓ ✗ (use Model.find_by_sql)
A raw string .where chained onto a hash .where ✓ ✗ — refused, not silently dropped
.join (relation existence filter), .having ✓ ✓ on document tables
.includes with through: ✓ (accessor only) ✓ on document tables (three batched queries)
Graph/edge models, vector search, timeseries, columnar ✓ ✗
grouped {} read coalescing ✓ (one combined statement) ✓ on Cloudflare D1 (one batch()); Postgres, MySQL and SQLite run the reads one by one
Encrypted attributes (encrypts), STI, counter caches ✓ ✓ (column mode: encrypts on text columns; STI needs a string type column)

On a SQL adapter, mixing the two .where forms is an error rather than a partial query:

# Refused on SQL — the raw predicate is SoliDB syntax and cannot be compiled.
User.where({ "active": true }).where("doc.age >= @min", { "min": 18 })

# Express both conditions in the hash form instead.
User.where({ "active": true, "age": { "gte": 18 } })

The raw filter used to be discarded silently, so that first query returned minors. It now raises with the hash equivalent named in the message.

Merge-patch semantics

update(hash) / save(hash) / .update_all(hash) merge rather than replace, following RFC 7396 on every adapter:

  • a key with an object value merges recursively, keeping the stored object's other keys
  • a key with a null value removes the key
  • anything else replaces the key
  • arrays replace wholesale — they are never merged element-wise
# stored: { "prefs": { "theme": "dark", "lang": "fr" }, "note": "hi" }
record.update({ "prefs": { "theme": "light" }, "note": null })
# result: { "prefs": { "theme": "light", "lang": "fr" } }

Earlier cuts diverged here: Postgres used a shallow merge that stored a null, while SQLite and MySQL applied RFC 7396 — so the same call destroyed unrelated nested keys on one adapter and not the others. Removing a key rather than storing a null makes no difference to record.field (both read as nil) or to the soft-delete scope (both satisfy IS NULL).

On Postgres, a patch containing a nested object needs a read-modify-write under a row lock rather than a single statement. Inside a Model.transaction that nests with a SAVEPOINT, so it is atomic on its own and still rolls back with the enclosing block; outside one it runs in a transaction of its own. Either way two concurrent merges of the same row serialize instead of clobbering each other.

A model that declares table "orders" runs in column mode against a real relational schema — one you already have, or one a migration creates with a column hash. Its narrower support line is documented under Column-aware models.

Defining Models

Create model files in app/models/. The collection name is automatically derived from the class name:

  • User → "users"
  • BlogPost → "blog_posts"
  • UserProfile → "user_profiles"

Automatic Collection Creation: When you call a Model method (like create(), all(), find(), etc.) on a collection that doesn't exist yet, SoliLang will automatically create the collection for you. If the configured database doesn't exist yet either, it is created on that same first call before the collection. This means you can start using your models immediately without running migrations first.

  • User → "users"
  • BlogPost → "blog_posts"
  • UserProfile → "user_profiles"
# app/models/user.sl
class User < Model
end
# app/models/blog_post.sl
class BlogPost < Model
end

That's it! No need to manually specify collection names or field definitions.

Auto-Loading

Every .sl file under app/models/ is loaded automatically at startup — by soli serve (in each worker), the REPL, soli db:migrate, and soli db:seed. Model classes are therefore available everywhere (controllers, views, other models, migrations, seeds, the REPL) without an import statement.

# app/controllers/users_controller.sl — no import needed
class UsersController < Controller
  def index
    @users = User.all
  end
end

Loading is recursive — subdirectories are walked too, so app/models/billing/invoice.sl is auto-loaded just like a top-level file. The same recursive auto-loader also covers two sibling directories, loaded before controllers so they can be referenced freely:

  • app/services/ — integration / domain-service classes (Stripe, mailers, etc.)
  • app/policies/ — authorization policies (see Authorization)

Within a directory, files load in alphabetical order and before their subdirectories (top-down). Soli executes files eagerly, so if one class extends another defined in a different file, keep the base class at an equal-or-shallower depth (e.g. app/models/application_record.sl) so it loads first.

In --dev, edits to nested files under these directories hot-reload without a restart.

If you run a model, service, or controller file directly with soli path/to/file.sl, the auto-loader does not run — in that case you still need explicit imports.

CRUD Operations

Auto-creation: All Model operations automatically create the collection — and the database itself, if it's missing too — when it doesn't exist. This only happens on the first call that encounters a missing collection or database.

Creating Records

user = User.create({
  "email": "alice@example.com",
  "name": "Alice",
  "age": 30
})
# Returns the User instance: user._key, user.email, ...
# On validation failure it is the unsaved instance with
# user._errors = [{ "field": "email", "message": "can't be blank" }, ...]
# (`_errors` is nil on success)

Building without saving

User.new(attrs) builds an instance without writing it: the attributes, plus the fields declared with a literal default (views: Int = 0). A declared field it is not given and that has no literal default stays unset — not nil — so a later save treats it as User.create(attrs) would: no nil is validated or written for it, and the column's own default applies.

class User < Model
  name: String
  age: Int
  views: Int = 0
end

user = User.new({"name": "Ann"})
user.to_h        # {name => Ann, views => 0} — no `age`
user.save        # writes name and views; the column default fills age

User.create(attrs) writes the same thing in one step: the literal defaults are validated, stored and on the instance it returns — as they are for create_many and for the record find_or_create_by creates. A value the caller gives wins over the default.

A value_field given as a hash is a value object on the instance new, create, update and save hand back, as it is on a record read from the database:

order = Order.create({"label": {"fr": "bonjour", "en": "hello"}})
order.label.text     # the value object's method — no need to re-read the record

Choosing the key

The attributes hash never chooses the document key: create drops every _-prefixed key (_key, _id, _rev, _from, _to) so a request body passed straight in cannot pick, squat or collide with ids. When your code means to name the record, say so in the second, options argument:

token = InboundToken.create({ "user": "joe" }, { "key": "joe_inbound_token" })
token._key                                      # "joe_inbound_token"
InboundToken.find("joe_inbound_token")          # found
InboundToken.find_by("_key", "joe_inbound_token")

InboundToken.create({ "_key": "joe_inbound_token", "user": "joe" })
# the `_key` attribute is dropped — the row gets a server-chosen key

Validations and callbacks run as for any create. A key that already exists is not overwritten: the insert fails and the instance comes back with _errors. To create-or-replace by key, use Model.upsert(key, data). "key" is the only option; an unknown one, or a key that is not a non-empty string, raises.

Finding Records

# Find by ID
user = User.find("user123");

# Find all
users = User.all;

# Find with where clause — Hash form (recommended for user input)
# Each key is validated as an identifier and values flow through
# bind parameters, so attacker-controlled values can never reach the
# query template. Top-level keys join with AND.
admins = User.where({ "role": "admin", "active": true }).all;
alice  = User.where({ "email": "alice@example.com" }).first;

# Comparisons, IN, LIKE, and OR are portable — they compile on SoliDB
# and on every SQL adapter (document tables and column-aware models):
adults = User.where({ "age": { "gte": 18 } }).all;
open   = Order.where({
  "status": ["open", "draft"],
  "total": { "gt": 100 },
  "email": { "ilike": "%@example.com" },
  "or": [{ "state": "draft" }, { "state": "open" }]
}).all;

# Find with where clause — string form (developer-trusted only)
# Use this when you need an expression the hash vocabulary cannot
# express. The string MUST NOT come from untrusted input.
results = User.where("doc.age >= @min_age AND doc.role == @role", {
  "min_age": 21,
  "role": "admin"
}).all;
Hash value Meaning
scalar ("open", 18, true, null) equality (==)
{ "gt" } / { "gte" } / { "lt" } / { "lte" } comparison (>, >=, <, <=); eq / ne also accepted
{ ">": 100 }, { "!=": "open" }, … the symbols are accepted spellings of the same operators
[1, 2, 3] or { "in": [1, 2, 3] } IN (an empty list matches nothing)
{ "like": "INV%" } / { "ilike": "%@x.com" } SQL LIKE / case-insensitive LIKE (% any run, _ one character)
"or": [ {…}, {…} ] / "and": [ {…}, {…} ] boolean grouping

Operator reference

All of this is verified behaviour, not intent — the surprises are per-backend and worth knowing before you rely on one.

The three value forms. A scalar means equality, an array means IN, and a hash means comparisons. Several operators on one field are ANDed, and several fields are ANDed:

Order.where({
  "status": "open",                       # equality
  "total":  { "gte": 100, "lt": 500 },    # both, ANDed
  "region": ["eu", "us"],                 # IN
  "or": [{ "rush": true }, { "vip": true } ]
})

or and and take an array of hashes (an empty array is an error) and may nest. Any hash inside them is a full filter again.

Ordering comparisons follow the value's type. A number compares numerically; a string compares as text, which is what makes ISO-8601 dates and timestamps work — they sort correctly as strings:

Invoice.where({ "issued_at": { "gte": "2026-01-01", "lt": "2026-07-01" } })

null and missing keys. { "field": null } is IS NULL and { "field": { "ne": null } } is IS NOT NULL; any other operator against null is an error rather than a clause that silently never matches. A document that never had the key reads as NULL, so { "nope": null } matches every row.

IN details. An empty list matches nothing (it compiles to a false predicate, not a syntax error). A null inside the list adds IS NULL, because SQL IN never matches NULL. Each element keeps the type semantics equality would give it, so a list may mix strings and numbers.

like / ilike need a string pattern (% = any run, _ = one character). Case sensitivity is where the backends genuinely differ:

like ilike
Postgres case-sensitive ILIKE
SQLite case-insensitive for ASCII (its LIKE is) LOWER(x) LIKE LOWER(?)
MySQL depends on the column/collation LOWER(x) LIKE LOWER(?)
SoliDB SDBQL LIKE also LIKE — no separate case-folding

If case behaviour matters, use ilike and get the same answer everywhere.

Numbers compare differently per backend on document tables. Postgres compares jsonb numerically, so { "v": 10 } matches a stored 10.0; MySQL and SQLite compare the JSON representation, where it does not. Store numbers consistently if you filter on them.

Index interaction. String equality and string IN compile to the JSON text extract — the expression an index declaration creates — so they can use it. Numeric comparisons use a numeric cast, which an expression index on the text form does not cover. See index on the SQL adapters.

On column-aware models (table "orders") the same hash compiles against the real columns with typed binds, so each comparison is the column's own type and ordering on a text column follows the database's collation. A field that is not a column is refused by name, listing the columns that exist.

Operator spellings. Each comparison also answers to its symbol, so { "total": { ">": 100 } } and { "total": { "gt": 100 } } compile to the same predicate: > >= < <= for the four comparisons, == or = for eq, and != or <> for ne. or / and are matched case-insensitively.

Errors name the vocabulary. An unknown operator reports gt, gte, lt, lte, eq, ne, like, ilike, in and the symbols; a field name that is not an identifier is refused before anything is compiled.

Security — where(...) filter forms. The Hash form (where({field: value, ...})) is safe for user input: keys are validated as [A-Za-z_][A-Za-z0-9_]* identifiers of at most 128 characters (the same cap applies to order and find_by field names, on every adapter), operators are a fixed vocabulary, and values are bound, so nothing from req["params"] can become AQL or SQL syntax. The string form (where("doc.foo == @foo", {...})) splices the filter argument verbatim into the query — treat it as developer-trusted only, like a format!() template. Building a filter string from request data will leak injection. Prefer the hash form whenever it can express the predicate, including on the SQL adapters.

Updating Records

# Static method: update by ID
User.update("user123", {
  "name": "Alice Smith",
  "age": 31
});

# Instance method: modify fields and save
user = User.find("user123");
user.name = "Alice Smith";
user.age = 31;
user.save();

# Instance method with bulk-update hash (same merge-then-persist path,
# one call instead of N assignments + save)
user = User.find("user123");
user.save({ "name": "Alice Smith", "age": 31 });

# `.update(hash)` is equivalent on an existing record
user.update({ "name": "Alice Smith", "age": 31 });

An update writes a row that is there. If the record was deleted since it was read — by another request, a cleanup job — nothing is written: save / update answer false, touch raises, and Model.update(id, …) and a soft delete hand back the "Error: … not found" string a delete of a missing row gives. This is the same on every adapter. (On Postgres, MySQL and SQLite an update used to insert the row, written whole from the copy the request held — a revoked token came back.) To create a row when it is missing, say so: Model.upsert(key, data).

instance.to_h() returns the record's user fields as a Hash, dropping the _-prefixed framework fields (_key, _id, _rev, _errors, …). Handy for serialization, diffing, and content hashing:

user = User.find("user123");
user.to_h();   # { "name": "Alice Smith", "age": 31 }

Deleting Records

User.delete("user123")   # by key
user.delete              # this record: callbacks and `dependent:` rules run

The method is delete. A model has no destroy: calling it raises and says so (it used to do nothing, silently). A model may define its own.

Counting Records

total = User.count;

Query Builder Chaining

Chain methods to build complex queries:

results = User
  .where("doc.age >= @age", { "age": 18 })
  .where("doc.active == @active", { "active": true })
  .order("created_at", "desc")
  .limit(10)
  .offset(20)
  .all;

# Get first result only
first = User.where("doc.email == @email", { "email": "alice@example.com" }).first;

# Count with conditions
count = User.where("doc.role == @role", { "role": "admin" }).count;

Static Methods Reference

Method Description
Model.create(data, opts?) Insert a new document. { "key": "k" } in opts chooses its _key (an _key inside data is dropped) — see Choosing the key
Model.create_many([data, ...]) Batch insert multiple documents in one round trip (one SQL statement per chunk, or one SoliDB BulkInsert / one INSERT query), returns { created, errors }. An open transaction inserts one row at a time so each row joins the transaction. On SoliDB the batch succeeds or reports one error in errors; rows before the failing one may already be stored, so wrap it in transaction when you need all-or-nothing.
Model.find(id) Get document by ID. Raises RecordNotFound if missing (auto-mapped to a 404 HTTP response). Use find_by for optional lookups. A key that is empty, . or .. is refused (invalid document key) here and in update/delete — as are such collection names in the raw SoliDB client (invalid path segment) — so a request-supplied id can never address a different path.
Model.find_by(field, value) Find first record by field value. Returns null when missing.
Model.first_by(field, value) Find first record by field with ordering
Model.find_or_create_by(field, value, data?) Find by field, or create if not found
Model.where(hash) Hash filter — safe for user input (keys validated, values bound). Returns QueryBuilder
Model.where(string, bind_vars) SDBQL filter string — developer-trusted only, never feed req[...] into the string. Returns QueryBuilder
Model.all Get all documents
Model.find_each(block, opts?) Walk every document one at a time in keyset-paged batches, holding one batch in memory. See Batch Iteration.
Model.in_batches(block, opts?) Same paging, but the block receives each batch as an array. Alias: find_in_batches.
Model.update(id, data) Update a document
Model.upsert(id, data) Insert or update document by ID
Model.delete(id) Delete a document
Model.delete_all Wipe every document in the collection (primarily for test setup/teardown). Use Model.where(...).delete_all for filtered bulk deletes.
Model.count Count all documents
Model.reset_counters(id, relation) Recount a has_many relation's children (minus soft-deleted) and write the counter cache column; returns the fresh count
Model.transaction do … end Run a block in a transaction — commit on success, roll back on throw
Model.transaction("aql") Execute a single AQL statement transactionally
Model.transaction() Get transaction handle for manual control
Model.<scope_name> Invoke a named scope declared with scope(name, fn) (returns QueryBuilder)
Model.with_deleted() Include soft-deleted records (QueryBuilder)
Model.only_deleted() Query only deleted records (QueryBuilder)
Model.includes(rel, ...) Eager load relations (returns QueryBuilder)
Model.includes(rel, filter, binds) Eager load with filter condition (returns QueryBuilder)
Model.includes({ rel: [fields] }) Eager load with field selection (returns QueryBuilder)
Model.includes_count(rel, ...) Eager load <rel>_count field per parent (HasMany/HABTM only)
Model.select(field, ...) Select specific fields (returns QueryBuilder)
Model.fields(field, ...) Alias for select() (returns QueryBuilder)
Model.join(rel, filter?, binds?) Filter by related existence (returns QueryBuilder)
Model.order(field, dir?) Order results (returns QueryBuilder). Also Model.order({field: dir, …})
Model.limit(n) Limit results (returns QueryBuilder)
Model.offset(n) Offset results (returns QueryBuilder)
Model.timeout(secs) Raise this query's request timeout (returns QueryBuilder). See Query timeouts.
Model.paginate(hash) Terminal: fetch paginated results + metadata. See Pagination below.
Model.time_bucket(interval, aggs?) Timeseries models only: bucketed aggregation (returns QueryBuilder, chain .all). See Timeseries Models.
Model.prune(cutoff?) Timeseries models only: delete rows older than a duration ("30d") or RFC3339 cutoff; without an argument uses the declared retention:. Returns the number deleted.
Model.group_by(fields) Grouped aggregation — field name or array; without aggregate yields a count per group (n). Returns QueryBuilder, chain .all. See Analytics.
Model.aggregate(spec) Multi-aggregate spec { alias: [func, field] } (or ["count"]); with group_by one row per group, without it one row (chain .first). See Analytics.
Model.median(field) / stddev / variance / count_distinct Statistical aggregation terminals (returns QueryBuilder, chain .first)
Model.similar(query, field?, k?, opts?) Vector similarity search; with a declared vector_index pushes down to the HNSW ANN index. opts: { "exact": true }. See Search.
Model.search(query, opts?) Fulltext search (requires fulltext_index); eager, ranked, results carry _search_score. See Search.
Model.near(lat, lon, opts?) Geo search sorted by distance (requires geo_index); results carry _distance in meters. See Search.
Model.within(lat, lon, radius) Geo search inside a radius in meters (requires geo_index). See Search.
Model.insert_rows(rows) Columnar models only: batch append, returns { "inserted": n, "ids": [...] }. See Analytics.
Model.aggregate(field, op, opts?) Columnar models only: scalar aggregate, or per-group rows with { "group_by": [...] }
Model.query(spec) Columnar models only: fetch rows (columns / one filter / limit)
Model.add_column_index(field, kind?) / column_indexes / drop_column_index(field) Columnar models only: manage column indexes (sorted default, hash, bitmap, bloom)
Model.columnar_stats Columnar models only: store-level statistics

Relationship DSL

Method Description
has_many(name) Declare a one-to-many relationship
has_one(name) Declare a one-to-one relationship
belongs_to(name) Declare an inverse relationship
edge from:, to: Declare an edge model over a SolidB edge collection. See Graph Models.

Options accepted by has_many/has_one/belongs_to (a bad option raises at class load with an actionable message):

Option On Description
class_name: all Override the related class (has_many "posts", class_name: "Article")
foreign_key: all Override the FK field name
dependent: has_many, has_one Cascade strategy on hard owner delete: "delete" (per-row, callbacks + nested cascades; "destroy" is an alias), "delete_all" (one bulk REMOVE, no callbacks), "nullify" (bulk FK → null). See Cascade Deletes.
through: has_many Traverse an intermediate relation (has_many "teams", through: "memberships"). See Through Associations.
source: has_many + through Relation name on the through model when it differs from the singularized name
counter_cache: belongs_to Maintain a <children>_count column on the parent (true or a custom column name). See Counter Caches.
polymorphic: belongs_to The record belongs to any of several models: stores {name}_id + {name}_type, resolved at runtime. See Polymorphic Relations.
as: has_many, has_one Declare the inverse of a polymorphic belongs_to (has_many "comments", as: "commentable") — queries are type-guarded to this class.

Fields the database assigns

SoliDB answers an insert with the document as it stored it. create and save take from that answer any field the record does not hold, so a field the database fills in is on the record without a second read. That is how a counter field (an invoice number SoliDB gives on insert, declared with db.create_counter in a migration) reaches the model:

invoice = Invoice.create({ "total": 120 })
invoice.number   # "INV-2026-11-0041"

Foreign keys

A foreign key declared in a migration (db.add_foreign_key("orders", "customer_id", "customers")) is enforced by SoliDB for every writer, the ORM or not. The model reports its refusals as validation errors:

order = Order.create({ "customer_id": "nobody" })
order._key      # nil: nothing was saved
order._errors   # [{ "field": "customer_id", "message": "must reference an existing record" }]

customer.delete   # false when orders still refer to it (on_delete: "restrict")
customer._errors  # [{ "field": "_base", "message": "is still referenced by other records" }]

save answers false the same way. With on_delete: "cascade" or "set_null" the parent's delete goes through and SoliDB deletes the children, or empties their field, in the same write: no callback of the child model runs for them. Keep dependent: "delete" on the relation when the children's callbacks have to run; it deletes them first, one by one, and works with any key. A key knows nothing of soft deletes: a parent that is soft-deleted is still there for it.

A field the application set is never replaced. A record created inside Model.transaction do … end has no number until the transaction commits: read it back after the block.

Storage & Index DSL

Class-body declarations for the multi-model and search features:

Declaration Description
columnar options? Declare a columnar-store model (compression: "lz4" default, or "none"). See Analytics & Columnar Stores.
column name, type, options? Declare a typed column on a columnar model (nullable:, indexed:)
vector_index field, dimension:, metric: Declare an HNSW vector index (optional m:, ef_construction:, quantization:, name:). See Search.
fulltext_index field, ... Declare a fulltext index over one or more fields
geo_index field Declare a geospatial index ({ "lat": ..., "lon": ... } field)
index field_or_fields, options? Declare a secondary index (unique:, type: — "persistent" default / "hash" / "fulltext" / "bloom" / "cuckoo", name:)
connection name Bind the model to a named connection from config/database.toml. See Multiple Databases.
table name Bind the model to an existing SQL table and read/write its real columns instead of _key + doc. Schema (columns, types, primary key) is introspected at boot; Soli never creates or alters the table. See Column-aware models.

Index declarations are metadata-only at load: dev ensures them at server boot; in production run soli db:indexes or create them in migrations. See Search — sync strategy.

index on the SQL adapters

index works on postgres, mysql, and sqlite too. A document table stores fields inside doc, so Soli creates an expression index on the JSON field:

class Post < Model
  index "status"
  index "slug", unique: true
  index ["author", "status"]
end
Adapter What is created
Postgres CREATE INDEX ON posts ((doc->>'status'))
SQLite CREATE INDEX ON posts ((doc ->> '$.status'))
MySQL a generated STORED column per field, then an index on it — MySQL cannot index a JSON extract directly

Two things follow from how SQL planners work:

  • String filters use these indexes; numeric ones do not. .where({ "status": "open" }) compiles to the same JSON-text expression the index holds. A number or boolean filter keeps JSON comparison instead, which no expression index covers — and which means different things per backend: Postgres compares jsonb numerically, so 10 matches a stored 10.0; MySQL and SQLite compare the JSON representation, where it does not. Store numbers consistently if you filter on them.
  • type: values beyond the default ("fulltext", "bloom", "cuckoo") and vector_index / geo_index are SoliDB engine features; on SQL they are reported as skipped rather than silently ignored.

Migrations can create the same thing with a doc. prefix — db.add_index("posts", ["doc.status"], { "unique": true }) — see Migrations.

QueryBuilder Methods

Method Description
.where(filter, bind_vars) Add filter condition (ANDed with existing)
.order(field, direction) Add a sort criterion ("asc" or "desc"). Chained calls add up: .order("status").order("created_at", "desc") sorts by status, then by date
.order({field: direction, …}) Several criteria in one call, in the order written
.reorder(...) Replace every criterion set so far (takes what .order takes); .reorder alone removes the sort
.limit(n) Limit results to n documents
.offset(n) Skip first n documents
.timeout(secs) Allow this one query secs seconds instead of the 10s default. See Query timeouts.
.includes(rel, ...) Eager load relations via subqueries
.includes(rel, filter, binds) Eager load with filter and optional "fields" key
.includes({ rel: [fields] }) Eager load with field projection
.includes_count(rel, ...) Eager load count as <rel>_count (HasMany/HABTM only)
.find_each(block, opts?) Iterate the whole match one record at a time, one batch ({ "batch_size": 1000 }) in memory. Keyset-paged by _key, so it cannot be combined with .order/.limit/.offset/.pluck, with an aggregate or grouping mode, or with grouped(...) — each is refused rather than ignored. Returns null. See Batch Iteration.
.in_batches(block, opts?) As .find_each, but the block receives the batch as an array. Alias: find_in_batches.

These also work on an already-loaded array. A has_many/has_one accessor returns a plain array rather than a query builder, so a Rails-style chain lands on one:

# org.contacts is already an array — order/all/includes still work on it
let sorted = org.contacts.order("name").all()

On an array, .order(field, dir?) sorts in memory, and .all() / .includes(...) return it unchanged so the chain reads the same whether it ran in the database or not. Rows missing the ordered field sort first. For several criteria on an array use the hash form — contacts.order({"city": "asc", "name": "asc"}) — since each .order there sorts again rather than adding to the last one.

Ordering by several fields

# status first, newest first within a status
Order.order("status").order("created_at", "desc").all
Order.order({"status": "asc", "created_at": "desc"}).all      # the same query

# a scope that sorts, and a caller that wants another order
Order.recent.reorder("total", "desc").all

.order adds a criterion; through 2.36.3 a second .order silently replaced the first. A scope or relation that already sorts therefore keeps its order as the primary one when the caller chains .order — use .reorder to start over. Field names and directions go through the same checks in every form, so a request parameter cannot reach the SORT clause. Supported on SoliDB, PostgreSQL, MySQL and SQLite, on column-aware models, and in grouped queries (where each criterion must be a group field or an aggregate alias).

| .select(field, ...) | Select specific fields on the main collection | | .fields(field, ...) | Alias for .select() | | .join(rel, filter?, binds?) | Filter by existence of related records | | .pluck(field, ...) | Return only specified fields (single or array) | | .all | Execute query, return all results | | .first | Execute query, return the first record, or null when there is none | | .first(n) | Execute query, return the first n records as an array. Equivalent to .limit(n).all; an existing .limit() is overridden. Not available on aggregate or exists queries, which return a single value rather than rows. | | .count | Execute query, return count | | .exists | Returns a QueryBuilder; chain .first for the boolean (User.where(...).exists.first) | | .delete_all | Bulk delete of every matching row: one DELETE on SQL; on SoliDB the matching keys are read, then removed by key (a thousand per statement), so nothing outside the match can be reached. Hard delete (ignores soft-delete mode); order/limit/offset/select/group_by are ignored since they don't compose with REMOVE. Returns null. | | .update_all(hash) | Execute as a bulk UPDATE — every matching row is patched with hash in a single statement, applying merge-patch semantics. Skips validations and lifecycle callbacks; order/limit/offset/select/group_by are ignored since they don't compose with UPDATE. Returns null. A write the database refuses raises (as a failed .first, .exists.first or delete_all does) — it is never returned as a value. record.delete raises on a refused delete too, with three in-band answers left: false when a before_delete or a foreign key says no (_errors says why), and on SoliDB an "Error: … not found" string for a row that is already gone — test == false or type(result) == "string", not truthiness. find_by / first_by raise on SoliDB as on SQL. sum over no rows is 0 on SoliDB and nil on the SQL adapters — read it with ?? 0. Model.transaction(sdbql) and the static Model.update(id, …) / Model.delete(id) raise on a refusal too; like record.delete, they keep one in-band answer, an "Error: … not found" string for a row that is not there. On Postgres a patch containing a nested object is refused — merging into a stored object needs per-row recursion, which a bulk statement cannot do. | | .sum(field) | Sum of field (chain .first). | | .avg(field) | Average of field (chain .first). | | .min(field) | Minimum of field (chain .first). | | .max(field) | Maximum of field (chain .first). | | .group_by(field, func, agg_field) | Legacy grouping aggregation — returns [{group, result}] (chain .all) | | .group_by(fields) | Grouped mode — field name or array of names; combine with .aggregate (alone: implicit count per group as n). Chain .all. See Analytics. | | .aggregate(spec) | Multi-aggregate spec { alias: [func, field] } or { alias: ["count"] } — funcs: sum, avg, min, max, count, count_distinct, median, stddev, variance | | .having(expr, binds?) | Post-COLLECT filter over bare group fields / aggregate aliases. Developer-trusted string — never build from user input. | | .median(field) / .stddev(field) / .variance(field) / .count_distinct(field) | Statistical aggregation (chain .first) | | .similar(query, field?, k?, opts?) | Vector similarity search — pushes down to the HNSW index when a vector_index is declared; opts: { "exact": true } forces exact client-side cosine. See Search. | | .time_bucket(interval, aggs?) | Timeseries models only: group into fixed time buckets with per-bucket aggregates (chain .all). See Timeseries Models. | | .paginate(hash) | Terminal: fetch paginated results + metadata. See Pagination below. | | .to_query | Return the generated SDBQL string (for debugging) | | record.traverse(EdgeModel, opts?) | Instance method: start a graph-traversal QueryBuilder from a saved record. See Graph Models. | | record.shortest_path(other, via:, direction?) | Instance method, executes immediately: vertices along the shortest path ([] when unconnected). |

Query timeouts

Every read reaches SoliDB over HTTP, and that client gives a request 10 seconds. The limit is deliberately tight — it is the backstop that keeps a stalled connection from pinning a worker — but a genuine long-running query outgrows it: a report over a large collection, a multi-aggregate group_by, a db:import-sized scan. Such a query fails with Error: HTTP error: error sending request for url … after ten seconds, no matter how healthy the database is.

.timeout(secs) raises the limit for one query:

# A slow report gets two minutes; every other query on the process
# keeps the 10s default.
let rows = Order
    .where({ "created_at": { "gte": start_of_year } })
    .group_by(["region", "channel"])
    .aggregate({ "revenue": ["sum", "total"], "n": ["count"] })
    .timeout(120)
    .all()
  • Seconds, Int or Float — .timeout(0.5) is a valid half-second budget. A zero, negative, or non-numeric value raises rather than being ignored, so a typo cannot silently leave the 10s default in place.
  • Chainable and position-independent, like .limit. It also exists as a static entry point, so Order.timeout(120).all() works without a .where.
  • Scoped to the one query. The override is installed for that request and reverted as soon as it finishes, including on error — it never leaks into the next query.
  • Lower it too. Nothing stops .timeout(2) on a query you would rather see fail fast than have a user wait on.

Inside a grouped(fn() { … }) block the reads become a single request, and the batch runs under the largest .timeout any member asked for — one slow member is not capped by the fast reads sharing its round-trip. A raw db.query read against the same host and database joins that batch, so a sibling Model.timeout(120) covers it; a write via db.query still runs immediately, like Model create/update/delete.

grouped(fn() {
  @summary = Order.group_by(["region"]).timeout(120).all   # the slow one
  @tags    = Tag.all                                       # rides along
  @heavy   = db.query("FOR d IN orders COLLECT … RETURN d") # joins the batch
})
# one request, 120s of room

The QueryBuilder form does not apply to a Solidb client. Raise that path with db.timeout(secs).query(sdbql) (persists on the client until you change it) or a per-call options hash:

rows = db.timeout(60).query(sdbql)
rows = db.query(sdbql, binds, { "timeout": 60 })

In --dev, grouped does not coalesce (so the query log stays one row per read). Put .timeout on each slow query, including db.query.

On the SQL adapters (Postgres / MySQL / SQLite) .timeout has no effect. Those adapters talk to the database over their own connection pool rather than HTTP, so the 10s cap this option lifts does not exist there and there is no statement timeout to set in its place. The call is accepted so a query stays portable across adapters, but on SQL the query runs as long as the server lets it. Use the server's own knob — Postgres statement_timeout, MySQL max_execution_time — to bound it.

Pagination

Model.paginate(hash) (static) and .paginate(hash) (chainable on a QueryBuilder) are terminal methods that execute the query with pagination and return a hash with both records and pagination metadata.

Arguments

Key Default Description
page 1 Page number (1-indexed, clamped to valid range)
per 25 Results per page

Return Value

{
  "records": [...],                // Array of model instances for this page
  "pagination": {
    "page":        1,              // Current page (clamped)
    "per":         25,             // Results per page
    "total":       100,            // Total matching records (unpaginated)
    "total_pages": 4               // Total number of pages
  }
}

Usage

Chain from any QueryBuilder — all filters, includes, ordering, etc. are preserved:

let result = Contact
    .search(@q)
    .includes("organisation")
    .order("name", "asc")
    .paginate({ page: this._page_param(), per: 25 });

@contacts   = result["records"];
@pagination = result["pagination"];

The paginate method:

  1. Runs count first to get the total matching records
  2. Computes total_pages = ceil(total / per)
  3. Clamps page to valid range (1..total_pages)
  4. Sets offset = (page - 1) * per and limit = per
  5. Fetches the records
  6. Returns the result hash

If total is 0, total_pages is set to 1 and page is clamped to 1 (returning an empty records array with no error).

Direct static call also works:

let result = Contact.paginate({ page: 2, per: 10 });

Mass Assignment Protection

By default, Model.create(hash) and instance.update(hash) write every key in the supplied hash straight to the document. If hash came from a request body, that includes any field a client decides to send — role, is_admin, password_digest, etc. Declare attr_accessible(...) on the model to lock down which keys mass-assign accepts.

class User < Model
  # Variadic form
  attr_accessible("name", "email", "bio")

  # …or pass a single array — equivalent
  # attr_accessible(["name", "email", "bio"])
end

User.create({
  "name":  "Alice",
  "email": "alice@example.com",
  "role":  "admin"   # silently dropped — not in the whitelist
});

Filtering applies to every mass-assign path: Model.create(hash), Model.update(id, hash), instance.update(hash), instance.save(hash). Non-permitted keys are dropped before validation runs and before the document is written, so they cannot be probed via validation errors either.

What a hash of attributes never sets, with or without a whitelist. The record's key and the other _-prefixed fields (_key, _id, _rev, an edge's _from / _to), and on a single-table-inheritance model its type: create, create_many, find_or_create_by, upsert, update(hash) / save(hash) and update_all drop them. Nor is an id field read as the key — on the SQL adapters an insert is an upsert, and Post.create(params) with {"id": "<another row's key>"} replaced that row. Choose a key with the options hash: Post.create(attrs, {"key": "…"}).

Empty list = full lock-down. attr_accessible([]) declares that the model accepts no mass-assigned attributes; everything must be set by trusted server code via direct field assignment (user.role = "admin").

Models without a declaration keep the legacy "all keys accepted" behaviour for backwards compatibility. New models that take request data should always declare attr_accessible. The CLAUDE.md security guidance recommends auditing every Model.create/Model.update call site against an explicit whitelist.

How this relates to permit(). permit(params, shape) is the primary mass-assignment filter — it lives in the controller, where assignability is actually decided (an admin form and a public form permit different fields against the same model), and it understands nested shapes. attr_accessible is optional defense-in-depth for high-stakes models (User blocking role/is_admin even if a controller forgets to filter) and covers paths that bypass controllers — jobs, websocket handlers, a raw Model.create(params). Both are whitelists, so the effective result is their intersection: if you use both on a model, attr_accessible must list every top-level key any controller permits, or the value is dropped at the model layer. attr_accessible is flat — for nested assignable fields, list the top-level key and let permit control the sub-shape. In --dev, a mass-assign that hits the whitelist logs [WARN] attr_accessible on User dropped mass-assign key(s): … so the drift is visible.

For controller-side filtering (when you'd rather hand-pick keys at the boundary), the existing hash.slice(["a", "b"]) returns a new hash with only the listed keys — handy when you need different whitelists per action:

def update
  let user = User.find(req["params"]["id"]);
  let safe = req["json"].slice(["name", "bio"]);
  user.update(safe);
  redirect("/users/" + user._key);
end

Validations

Define validation rules in your model class:

class User < Model
  validates("email", { "presence": true, "uniqueness": true })
  validates("name", { "presence": true, "min_length": 2, "max_length": 100 })
  validates("age", { "numericality": true, "min": 0, "max": 150 })
  validates("website", { "format": "^https?://" })
end

Validation Options

Option Description
presence: true Field must be present and not empty
uniqueness: true Field value must be unique in collection
min_length: n String must be at least n characters
max_length: n String must be at most n characters
format: "regex" String must match regex pattern
numericality: true Value must be a number
min: n Number must be >= n
max: n Number must be <= n
inclusion: [...] (or one_of: [...]) Value must be one of the listed values — "is not included in the list"
type: "string" Value must have that type: "string", "int"/"integer", "float", "number", "bool"/"boolean", "array", "hash" — "must be a <type>"
allow_nil: true (or allow_null: true) Skip the whole rule when the value is nil or absent
custom: "method_name" Call an instance method of the model — see Custom Validators
custom: fn(value, record) { ... } Call a closure — same return rules as the method form
message: "text" / message: :key Replace the rule's message: a sentence, or a translation key (see Validation messages)
on: "create" / on: "update" Only run the rule for that operation
if: fn(record) { ... } Only run the rule when the closure is truthy
unless: fn(record) { ... } Skip the rule when the closure is truthy

Options are strict: an unknown key ("within": [...], a typo like "presense") or a known key with a wrong-typed value ("min_length": "3") raises when the class loads, with a message listing the known options. A misspelt rule used to be ignored silently — it read like protection and checked nothing.

Inclusion, Type and Nil

class Invoice < Model
  validates("status", { "presence": true, "inclusion": ["draft", "sent", "paid"] })
  validates("priority", { "one_of": [1, 2, 3] })     # compared by type: "1" is not 1
  validates("paid", { "type": "boolean" })
  validates("nickname", { "allow_nil": true, "min_length": 3 })
end

invoice = Invoice.create({ "status": "pending", "priority": "1", "paid": "yes" })
# invoice._errors:
#   status:   is not included in the list
#   priority: is not included in the list
#   paid:     must be a boolean

inclusion and type skip a nil or absent value — pair them with presence: true when the field is required. allow_nil: true goes further and skips every check of that validates call (presence, length, custom…) when the value is nil or absent.

Custom Validators

custom: "method_name" calls that instance method on a record built from the data being validated, so @field reads work. The method can be declared anywhere in the class, including under private. It fails the field by:

  • pushing {"field": "...", "message": "..."} entries onto @_errors (any field, any number of them);
  • returning false — reported as "is invalid";
  • returning a String — reported as that message.

Returning nil or true passes. A method that declares one parameter receives the field's value.

class Event < Model
  validates("ends_at", { "custom": "_ends_after_start" })
  validates("title", { "custom": "_no_shouting" })
  validates("code", { "custom": fn(value, record) { value.nil? || value.starts_with?("EV-") ? true : "must start with EV-" } })

  private

  def _ends_after_start
    return true if @ends_at.nil? || @starts_at.nil?

    @_errors = @_errors ?? []
    @_errors.push({ "field": "ends_at", "message": "must be after starts_at" }) if @ends_at <= @starts_at
  end

  def _no_shouting(title)
    return "can't be all caps" if title == title.upcase

    true
  end
end

The closure form, custom: fn(value, record) { ... }, receives the field value and the attribute hash and follows the same return rules. Before, custom: was accepted but never ran.

On an update — record.update(attrs), save on a loaded record, Model.update(id, attrs) — the record a validator sees is the merged one about to be written, identity included: @_key (and record["_key"] in the closure form) is the key being updated, and @id is the row's own id, or that key when the record has none. That is what "unique except me" needs:

class Site < Model
  validates("slug", { "custom": "_slug_free" })

  private

  def _slug_free(slug)
    taken = Site.find_by("slug", slug)
    taken.nil? || taken._key == @_key || "is taken"
  end
end

Before, the instance paths built that record from the non-_ fields only, so @_key was nil and such a validator refused every update of a record that already held the value. The built-in uniqueness: true always excluded the record being updated.

Conditional and Per-Operation Rules

Every rule in a validates(...) call can be restricted to one persistence operation with on:, or gated on the record's data with an if: / unless: closure. The closure receives the attribute hash being validated (declare zero parameters if you don't need it) and its truthiness decides.

class User < Model
  # Only enforced when the record is first created
  validates("password", { "presence": true, "min_length": 8, "on": "create" })

  # Only enforced on updates (e.g. a moderation field set later)
  validates("reviewer", { "presence": true, "on": "update" })

  # Enforced only for a subset of records
  validates("company_name", { "presence": true, "if": fn(record) { record["kind"] == "business" } })

  # Skipped for privileged records
  validates("bio", { "presence": true, "unless": fn(record) { record["role"] == "admin" } })
end

Model.create counts as create; instance.update() and instance.save() on a record that already has a _key count as update. if: and unless: can be combined on one call — the rule runs only when if: is truthy and unless: is falsy. Passing anything other than "create"/"update" to on:, or a non-function to if:/unless:, raises at class-load time rather than silently running the rule unconditionally.

Validation Results

Model.create() always returns an instance of the class. On validation or database failure, the instance is not persisted and its _errors field holds an array of error entries. On success, _errors is nil.

user = User.create({ "email": "" });

if user._errors
  for error in user._errors
    print(error["field"] + ": " + error["message"]);
  end
else
  print("Created user: " + user.id);
end

The messages read in the request's locale: Soli ships them for en, fr, de, es, it and pt, and config/locales/*.yml overrides any of them or adds a language — see Validation messages. user.full_messages gives each error as a sentence naming its field (["Email can't be blank"], with the field's translated name when the locale file has one).

Atomic uniqueness

uniqueness: true issues a SELECT … LIMIT 1 before the write, but that check is best-effort: two concurrent User.create({ "email": "x" }) calls can both pass the SELECT and both insert. To make uniqueness atomic, declare a unique index on the column at deploy time and let the database enforce it. Soli detects the resulting violation from Model.create, instance.save, instance.update, Model.upsert, and Model.find_or_create_by, and turns it into the same _errors entry the SELECT path produces (field: "has already been taken"), so callers handle the race identically.

# Declare the index on the model — it is created on every backend:
class User < Model
  index "email", unique: true
  validates("email", { "uniqueness": true })
end

Without the index, the SELECT is the only line of defense and the race is silently lost.

On the SQL adapters the database's own error is classified, so a violation becomes a field error even for a constraint the model never declared:

Violation Reported as
unique index / constraint { field, "has already been taken" }
foreign key { field, "must reference an existing record" }
NOT NULL column { field, "can't be blank" }
CHECK constraint { field, "is invalid" }

The field comes from whatever the database names — Postgres reports the column in DETAIL, SQLite names table.column (or the index, for an expression index), MySQL names the index — and falls back to _base when there is nothing to go on. Anything that is not a constraint violation is still reported as-is, so a connection failure never masquerades as a validation error.

A uniqueness rule on a SQL adapter also runs the rest of its validates call: validates("email", { "uniqueness": true, "format": "email" }) checks the format too (the SQL path used to skip that call's format/numericality/min/max).

Value Fields and Invariants

A model can hold a value object in a field and state rules about the whole record — the aggregate side of domain-driven design, without leaving Model.

# app/models/values/amount.sl — value objects load before the models
class Amount < ValueObject
  cents: Int
  currency: String = "EUR"
  invariant(:cents, "must not be negative") { @cents >= 0 }
end

# app/models/invoice.sl
class Invoice < Model
  value_field :total, Amount
  validates("number", {"presence": true})
  invariant(:total, "total must be positive") { @total.cents > 0 }
end

value_field :name, ValueClass stores the value object as an object of its fields ({"cents": 900, "currency": "EUR"} — a JSON column on the SQL adapters) and reads it back as the value object:

invoice = Invoice.create({"number": "F-1", "total": Amount.new(900)})
Invoice.find(invoice._key).total                   # Amount(cents: 900, currency: "EUR")
Invoice.find(invoice._key).total == Amount.new(900) # true

The field accepts the value object or a hash of its fields; anything else is a validation error ({ field: "total", message: "must be a Amount" }). The class can also be named as a string (value_field :total, "Amount").

A list of value objects — an invoice's lines, kept as values rather than as a related model — is value_field :lines, [Line]: stored as an array of objects, read back as an array of Line, and refused (must be a list of Line) unless every element is a Line or a hash of its fields:

class Line < ValueObject
  label: String
  cents: Int
end

class Quote < Model
  value_field :lines, [Line]
  invariant(:lines, "a quote has at least one line") { @lines.length > 0 }
end

quote = Quote.create({"lines": [Line.new("design", 300), Line.new("build", 900)]})
Quote.find(quote._key).lines[1]      # Line(label: "build", cents: 900)

invariant(...) on a model is a validation rule: a falsy block adds { field, message } to _errors (field _base when the invariant names none) and the record is not saved. Invariants run after every other validation has passed, on a record whose value fields are value objects, so @total.cents is safe — a missing total is reported by presence, not by a crash in the rule. They run on create, save, update and static Model.update(key, changes) alike:

invoice = Invoice.create({"number": "F-2", "total": Amount.new(0)})
invoice._errors     # [{"field": "total", "message": "total must be positive"}]

Raising instead of collecting is what a domain error is for: throw a DomainError from a service and an uncaught one answers 422 with its message (see Error handling → Error classes).

Domain Events

A domain event says that something happened in the domain — an order was paid, an account was closed — so other parts of the app can react without the code that made it happen knowing about them. An event is a value object that inherits DomainEvent:

# app/models/order_paid.sl
class OrderPaid < DomainEvent
  number: String
  cents: Int
end

Publishing. A model records events on itself with record_event; they are published when the record is saved — so a method that raises an event and then fails to save publishes nothing. Elsewhere, publish(event) publishes at once.

class Order < Model
  def pay
    @status = "paid"
    @record_event(OrderPaid.new(@number, @cents))
  end
end

order.pay
order.save            # OrderPaid is published here, if the save succeeds

Subscribing. Subscriptions live in app/subscribers/, loaded after the models, services and jobs:

# app/subscribers/orders.sl
subscribe(OrderPaid) do |event|
  LedgerEntry.create({"number": event.number, "cents": event.cents})
end

subscribe(OrderPaid, ReceiptJob)   # ReceiptJob.perform(args) gets event.to_h

A subscription to a class also receives its subclasses' events (subscribe(DomainEvent) do … end sees them all).

When handlers run. Events wait for the data:

  • A block handler runs in the same process once the data is committed — right away outside a transaction, after the outermost commit inside one, and never if the transaction rolls back. A handler that throws fails the request, but the data is already committed: use a job for anything that can fail.
  • A job handler is enqueued when the event is published, with the event's fields as its arguments. Inside a transaction the job row is written by that transaction (_jobs lives on the default connection), so it commits or rolls back with the data — the transactional outbox — and the job queue retries delivery. On Cloudflare Workers jobs go to a Queue, which is not transactional.

A block handler must come from an application file; subscribe with a block in a standalone script runs that script on the tree-walker.

Streaming to ES. subscribe(OrderPaid, {"stream": "billing", "key": "number"}) appends each event to a topic of an ES broker (ES_BROKER), for other services to consume. The record is {"type": "OrderPaid", "data": {…the event's fields}, "occurred_at": "…"}, keyed by the named field (one partition per order, here). It goes through the outbox: publishing enqueues the built-in EventStreamJob in the transaction, and the job appends the record once the data is committed, with the job queue's retries — so a stream receives every committed event, at least once, and never one that was rolled back.

Versioning events. An event that changes shape declares static version: Int = 2; stream records carry the version they were written with. A consumer meeting an older record calls the class's static def upcast(data, from_version), which returns the fields in the current shape. A record from an older version without upcast, or from a newer version than the class, stops EventStream.consume with an error before it is committed — nothing is dropped silently.

class InvoicePaid < DomainEvent
  static version: Int = 2
  number: String
  cents: Int

  # v1 called the field `amount`.
  static def upcast(data: Hash, from_version: Int) -> Hash
    return data unless from_version == 1

    {"number": data["number"], "cents": data["amount"]}
  end
end

Consuming a stream. The other side — an application that reacts to another service's events — reads the topic with a consumer group and publishes each record here, to its own subscribers:

# app/jobs/billing_events_job.sl
class BillingEventsJob
  static cron: String = Cron.every("1 minute")

  static def perform(args: Hash)
    EventStream.consume("billing", {"group": "shipping"})
  end
end

EventStream.consume(topic, {"group": …, "partitions": 1, "max_records": 100}) rebuilds each record as its DomainEvent (by the type a stream subscription wrote) and publishes it: block and job subscribers run, stream subscriptions do not, so nothing is echoed back. The group's offset is committed after each record, so delivery is at least once — a handler that fails stops the run before its record is committed. A record whose event class this application does not declare is skipped. It returns how many events it published.

Event Sourcing

A model stores the current state; an event-sourced aggregate stores what happened and rebuilds its state from that. Subclass EventSourced, change state only in apply(event), and record each change with emit:

class AccountOpened < DomainEvent
  owner: String
end

class Deposited < DomainEvent
  cents: Int
end

class Account < EventSourced
  owner: String
  balance: Int = 0

  def open(owner: String)
    @emit(AccountOpened.new(owner))
  end

  def withdraw(cents: Int)
    throw InsufficientFunds.new("balance #{@balance}") if cents > @balance

    @emit(Deposited.new(-cents))
  end

  def apply(event)
    match event.class {
      "AccountOpened" => @owner = event.owner,
      "Deposited" => @balance = @balance + event.cents,
      _ => nil
    }
  end
end

account = Account.new()
account.open("Acme")
account.save                         # appends AccountOpened; account.id is set
again = Account.load(account.id)   # replays the stream: owner "Acme", version 1

emit applies the event at once and keeps it pending; save appends the pending events to the aggregate's stream ("Account:<id>", with a fresh UUID as id when none was set) in one transaction and publishes each one after the commit, so subscribers, stream: options and the outbox see them as any other domain event. Account.load(id) reads the stream back in order and calls apply for each event — upcasting old versions first (see Versioning). version is the number of the last event applied.

Events live in one collection, soli_event_store_records, a row per event with stream, version, event_type, event_version and data. The row key is the stream and the version, so two writers that loaded the same version cannot both append the next one: the second save throws StaleRecord (409 in a served app), its events not stored. Load the aggregate again and retry.

Snapshots

A long stream costs its whole length on every load. Declare static snapshot_every: Int = N and save also writes a snapshot of the aggregate each time its version crosses a multiple of N — in the same transaction as the events — and load restores the snapshot, then replays only the events after it.

class Account < EventSourced
  static snapshot_every: Int = 100
  owner: String
  balance: Int = 0
  # …
end
  • The default snapshot keeps every field but id, version and the pending events, and only plain values — Int, Float, String, Bool, nil, arrays and hashes. A field holding anything else (a DateTime, a value object) fails the save with its name; define snapshot_state -> Hash and restore_snapshot(state) to keep it your way.
  • When the shape of the state changes, raise static snapshot_version: Int: a snapshot written under another version is ignored (the whole stream is replayed) and the next snapshot replaces it.
  • aggregate.take_snapshot writes one now, at the current version — to backfill after turning snapshots on. It refuses while events are pending.

Snapshots live in soli_event_snapshots, one row per stream (stream, version, schema, state). The events stay the source of truth: deleting the snapshots only makes the next loads replay everything.

Aggregate Roots

An aggregate is a root and the entities that only exist through it — an invoice and its lines. part_of :invoice on the child makes the root the only way in: its create, save, update, delete, upsert and create_many are refused unless an Invoice.transaction do … end is running (that one, or one it joins).

module Billing
  class Invoice < Model
    has_many("lines")
  end

  class Line < Model
    part_of :invoice                # Billing::Invoice
  end
end

Billing::Line.create({...})         # error: Billing::Line is part of the
                                    # Billing::Invoice aggregate
Billing::Invoice.transaction do
  invoice.lines << Billing::Line.new({"cents": 100})   # fine
end

Deleting an invoice that cascades to its lines (dependent:) writes the lines too, so it goes inside Invoice.transaction as well. Reads are not restricted.

Bounded Contexts

Models can live in modules, one per part of the domain — Billing, Shipping — each with its own names. A class nested in a module is Billing::Invoice, its collection is billing_invoices, and a module may be declared in several files:

# app/models/billing/invoice.sl
module Billing
  class Invoice < Model
    belongs_to("customer")          # Billing::Customer
  end
end

# app/models/billing/customer.sl
module Billing
  class Customer < Model
    has_many("invoices")
  end
end

# app/models/shipping/invoice.sl
module Shipping
  class Invoice < Model
  end
end

Inside the module its classes are read unqualified (Invoice in a Billing service is Billing::Invoice). Relations default to models of the same context; class_name: names any other (belongs_to("user", {"class_name": "User"})). Two files that declare the same qualified class stop the boot, as two top-level classes do.

The context map

private class keeps a context's internals to itself. Which contexts may depend on which is a decision of its own; write it in soli.toml, and soli lint holds the code to it (smell/context-boundary):

[contexts]
Shipping = ["Billing:events"]     # only Billing's domain events
Reporting = ["Billing", "Shipping"]
Billing = []                      # nothing from another context

A context listed there may use, from another context, only what its entry names: "Billing" for its classes, "Billing:events" for its DomainEvent subclasses only. A use is a qualified name in the module's code (Billing::Invoice) or a string naming a class of another context ({"class_name": "Billing::Invoice"}, is_a?("Billing::InvoicePaid")):

app/models/shipping.sl:10:1 - [smell/context-boundary] `Shipping` uses
`Billing::Invoice`, but soli.toml [contexts] lets it use only `Billing`'s domain events

A context not listed is not restricted, code outside every module (controllers, top-level services) is not a context, and without a [contexts] table nothing is checked. A name in the table that is not a top-level module of the application is reported, so a typo does not silently switch a rule off.

Optimistic Locking

Two people edit the same record: both load version 3, the first saves, and the second save would silently overwrite the first. Declare optimistic_lock and the second save is refused instead:

class Order < Model
  optimistic_lock
end

order = Order.create({"number": "A-1"})   # lock_version: 0
a = Order.find(order._key)
b = Order.find(order._key)
a.number = "A-2"
a.save                  # true — lock_version is now 1
b.number = "A-3"
b.save                  # false
b.stale?                # true
b._errors               # [{"field": "lock_version", "message": "is stale: the record was changed since it was read — reload it and try again"}]

Every update checks that the stored lock_version is still the one the record was read with, and bumps it; the check and the write are one atomic step (a conditional UPDATE on the SQL adapters, an If-Match on the revision on SoliDB). The static Model.update(key, changes) checks the lock_version in changes when there is one — a form's hidden field, so a form submitted after someone else's edit is refused — and the stored one otherwise. To answer HTTP, throw the built-in StaleRecord (a DomainError whose http_status is 409):

throw StaleRecord.new("order #{order.number} changed since you opened it") unless order.save

On a column-mode table (an existing SQL schema, table "orders") the table needs a lock_version integer column; the update is one UPDATE … WHERE id = ? AND lock_version = ?. increment and decrement bump the version too, so a save from a copy read before them is stale.

Callbacks

Define lifecycle callbacks to run code at specific points. The method name can be passed as a string or a symbol:

class User < Model
  before_save("normalize_email")   # both strings and symbols work
  before_save(:normalize_email)    # Ruby-style symbol shorthand
  after_create("send_welcome_email")
  before_update("log_changes")
  after_delete("cleanup_related")

  def normalize_email
    @email = @email.downcase
  end

  def send_welcome_email
    # send the email
  end
end

Available Callbacks

Callback When it runs
before_save Before create or update
after_save After create or update
before_create Before inserting new record
after_create After inserting new record
before_update Before updating existing record
after_update After updating existing record
before_delete Before deleting record
after_delete After deleting record

Firing order per persistence method

Both class-level methods (Model.create, Model.update) and instance-level mutators run the matching callbacks. Rails-style: the _save callbacks fire on every persistence path, plus the more specific event for the operation.

Method Before-callbacks (in order) DB write After-callbacks (in order)
Model.create(attrs) before_save → before_create INSERT after_create → after_save
Model.update(id, attrs) before_save → before_update UPDATE after_update → after_save
instance.save([attrs]) — new record (no _key) before_save → before_create INSERT after_create → after_save
instance.save([attrs]) — persisted record before_save → before_update UPDATE after_update → after_save
instance.update(attrs) before_save → before_update UPDATE after_update → after_save
instance.restore() before_save → before_update UPDATE after_update → after_save
instance.increment(field, n?) before_save → before_update UPDATE after_update → after_save
instance.decrement(field, n?) before_save → before_update UPDATE after_update → after_save
instance.touch() before_save → before_update UPDATE after_update → after_save
instance.delete() (soft + hard) before_delete UPDATE / DELETE after_delete

After-callbacks only fire when the persist call succeeds. If the native method returns false (validation or DB error) the after-callbacks are skipped and the instance carries _errors.

record.save, record.update and record.delete run every callback in this table with or without parentheses, and so do the static calls: Model.delete_all, Model.with_deleted and Model.only_deleted (which, written bare, used to evaluate to the function and do nothing).

instance.update(attrs) and instance.save(attrs) run before_save, but the hash's values are what gets written: a field the callback rewrites keeps the value from attrs. A downcasing before_save therefore does not apply to user.update({ "email": "A@X.COM" }). Assign the fields and call save() instead, or use Model.update(key, attrs), which writes the callback's value.

In the after-callbacks of Model.create(attrs), this is the record create returns, so a field a callback sets is visible on it. For Model.update(id, attrs), this holds the attributes passed (after the before-callbacks), plus _key/id and the metadata the database returned — not the whole stored row; load it with find when a callback needs the rest.

Every callback in the table fires on both engines. A callback declared as a method name runs on the bytecode VM in production; a closure-form callback (before_save do … end) runs on the tree-walking interpreter, because it needs the scope it was declared in. The handler falls back automatically and before any write happens, so the only difference is speed — the callbacks themselves, and their ordering, are identical either way.

On hard deletes, dependent: cascades run between before_delete and the owner row's removal — a before_delete veto skips them, and a failing cascade aborts the owner delete before after_delete.

Vetoing persistence from a before_* callback

Returning false from any before_* callback aborts the operation. The native DB write is skipped, after-callbacks don't run, and the instance picks up an _errors entry of the form [{"message": "before_<event> callback returned false; persistence aborted"}]. Callers receive false (or, for Model.create / Model.update, the instance with _errors populated) so they can branch on the result identically to a validation failure.

class Audited < Model
  before_save("can_save")  # symbols also work: before_save(:can_save)

  def can_save
    return false if User.current.is_nil?  # returns false → save() / update() aborts
  end
end

The veto fires at the first false — subsequent before-callbacks in the chain don't run. Use this for authorization gates, integrity checks, or any "deny by default" pattern. Mutating-only callbacks (the common case) just don't return false and run end-to-end as before.

Overriding save, delete and the other writes

A model's own save, update, delete, restore, touch, increment or decrement is what a call reaches — record.delete(), record.delete(true) and the paren-less record.delete alike, on both engines — not the Model method it overrides. The callbacks, the veto, dependent: cascades and the attachment purge belong to the persistence, so they run when the override defers to it with super:

class Post < Model
  before_delete("archive")

  def delete
    return false if @locked

    super.delete()   # before_delete, the veto, cascades, after_delete
  end
end

An override that never calls super replaces the write, callbacks included. A bare read of an override that takes arguments (def delete(force)) is the method itself, as for any method: post.delete hands it back uncalled, and post.delete(true) runs it.

Attachments

First-class file attachments use has_one_attached / has_many_attached. They default to the disk service (./storage/attachments, or SOLI_ATTACHMENTS_PATH) so a Postgres/SQLite app does not need SoliDB to keep files. Set service: "s3" (bucket SOLI_ATTACHMENTS_BUCKET or S3_BUCKET), service: "r2" (Cloudflare R2 — the bucket binding on a Cloudflare Worker, R2's S3 API with the s3 configuration under soli serve) or service: "solidb" to store elsewhere. SOLI_ATTACHMENTS_SERVICE changes the default for every has_*_attached declaration.

class User < Model
  has_one_attached("avatar")   # disk, 10 MiB, safe default content types
  has_many_attached("photos", {
    "service": "s3",
    "content_types": ["image/jpeg", "image/png", "image/webp"],
    "max_size": 5_000_000
  })
end

user.attach_avatar(file)       # multipart hash from find_uploaded_file / LiveView upload
user.avatar_url()
user.detach_avatar()
# destroy / User.delete(id) purges the blobs automatically

Large files: resumable and direct uploads

An ordinary attachment upload is one request buffered in memory under the body cap. Two other paths exist for big files.

Resumable (tus 1.0.0). Turn it on in config/routes.sl:

resumable_uploads()                       # /tus, 1 GiB cap, needs a session
resumable_uploads({"path": "/uploads/tus", "max_size": 5_000_000_000, "max_per_owner": 5})

Options: path, max_size, max_active (stored uploads overall, 200), max_per_owner (stored uploads per session, 20), expires_in (seconds, 86400), dir (SOLI_TUS_DIR, default ./storage/tus), require_session (true). A finished upload counts toward both caps until tus_take + attach_<field> consumes it or it expires, so finishing uploads does not free room for more. "Session" means one the session store knows: a made-up session_id cookie is refused (401), and an upload stays its owner's across session writes, the cookie driver included. An upload can only be taken by its own session, complete and unexpired — attach_<field> checks a tus_id the same way even when the hash did not come from tus_take, and reads the size and type from the upload, not from the hash.

The endpoint speaks tus creation, HEAD offset, PATCH, termination and expiration, so any tus client works — with tus-js-client:

const upload = new tus.Upload(file, {
  endpoint: "/tus",
  chunkSize: 5 * 1024 * 1024,
  metadata: { filename: file.name, filetype: file.type },
  onSuccess: () => fetch("/videos", { method: "POST", body: JSON.stringify({ upload_id: upload.url.split("/").pop() }) })
})
upload.start()   // upload.abort() pauses; start() again resumes from the server's offset

Bytes go to disk as each chunk arrives, so memory is one chunk, not the file. An upload belongs to the session that created it; another session's is a 404. When the last chunk lands, attach it:

file = tus_take(params["upload_id"])          # {filename, content_type, size, tus_id}; raises unless finished
video.attach_file(file)                        # disk and s3 move/stream it: never loaded into memory

A disk attachment renames the file into place; an S3 attachment streams it a megabyte at a time. A SoliDB uploader, or any uploader with an image transform (format, max_width), needs the bytes, so the file is loaded (up to 64 MiB) first. The uploader's content_types and max_size are checked either way. tus_discard(id) drops an upload you do not want; unfinished ones expire after expires_in.

Direct to storage (S3). For an S3 attachment the browser can send the file to the bucket without touching your server:

# POST /videos/presign
info = direct_upload_start(video, "clip", params["filename"], params["content_type"], params["size"].to_i)
return render_json(info, 422) unless info["error"].nil?     # {"error": "..."} when refused
render_json(info)      # {"id", "url", "method": "PUT", "headers": {...}, "expires_in"}

# POST /videos/attached — after the browser PUT the file to info["url"] with info["headers"]
ok = direct_upload_finish(video, "clip", params["id"])

direct_upload_start checks the declared type and size against the uploader and returns a presigned PUT (default 15 minutes, at most an hour). The URL does not pin the size or type — S3 takes what it is sent. So direct_upload_finish asks the bucket what it holds under that id, re-checks the limits against that, deletes an object that breaks them, and only then records the blob. direct_upload_finish only accepts an id that direct_upload_start issued, in the same session, for the same field (the last ten are kept in the session), so a caller cannot claim, or get deleted, a blob that is not theirs; the browser must send the session cookie on both calls. An id that was never finished leaves an orphan object; add a bucket lifecycle rule for the <collection>/ prefix. Set S3_ENDPOINT for MinIO and friends.

The default content-type allow-list

uploader(...) requires a content_types array. has_one_attached / has_many_attached are the low-ceremony form and fall back to a curated allow-list instead: common images (JPEG, PNG, GIF, WebP, AVIF, HEIC, BMP, TIFF), PDF, plain text, Markdown and CSV, JSON, Zip, the Office formats, and common audio/video.

Upgrading: has_*_attached used to accept any content type when the declaration named none. If your app stores something outside the curated list — most likely image/svg+xml, text/html, or text/xml — those uploads now get rejected. Name the types you need with content_types to opt back in; the exclusions exist for a reason, so weigh the XSS note below first.

That default deliberately excludes every type a browser executes script from — text/html, application/xhtml+xml, image/svg+xml, text/xml — because the blob route serves attachments from your application's own origin. Passing content_types narrows the list; there is no way to widen it to "any type".

The blob route also sends X-Content-Type-Options: nosniff, and Content-Disposition: attachment for anything that is not an inline-safe image or audio/video, so a stored file cannot be re-typed into a script by the browser. Images other than SVG, and audio/* / video/*, are inline: a podcast or a clip plays in the page's <audio> / <video> and in the browser's own player.

Attachments are streamed. The blob route does not load the file. The server relays it to the client chunk by chunk after the action returns — from SoliDB, from the disk file where it lies, or from an S3/R2 bucket through a short-lived presigned GET — so a 150 MB episode costs one chunk of memory per download. The client's Range is honoured, so an audio player that seeks gets 206 Partial Content with only the bytes it asked for, and 416 past the end. HEAD returns the size without the body. The blob id is the ETag, so a revalidation is a 304 with no round trip to the store. An image with a transform in the query string (?w=, ?fmt=…) is still loaded and transformed. On a Cloudflare Worker, an R2 attachment is served by the Worker from the bucket — Range, 304 and image transforms through the Images binding included (see Cloudflare Workers). For SoliDB the route uses solidb.blob_response, which your own actions can call too.

The older uploader(name, options) form still works and still defaults to SoliDB blobs (service: "solidb"). Same generated methods: attach_<field>, detach_<field>, <field>_url / <field>_urls.

Single attachment (uploader):

Single attachment:

class Contact < Model
  uploader("photo", {
    "multiple":      false,
    "content_types": ["image/jpeg", "image/png", "image/webp"],
    "max_size":      2_000_000,
    "collection":    "contact_photos"   # optional; defaults to <snake>_<field>s
  })
end

Auto-generated on each instance: attach_<field>(file), detach_<field>([blob_id]), <field>_url() (single), <field>_urls() (multiple). Failures populate _errors on the record.

Multiple attachments (array of blob ids in <name>_blob_ids):

class Contact < Model
  uploader("document", {
    "multiple":      true,
    "content_types": ["application/pdf", "image/jpeg", "image/png",
             "application/zip", "text/csv"],
    "max_size":      10_000_000,
    "collection":    "contact_documents"
  })
end
# POST /contacts/:id/documents (HTML form → redirect+flash)
def attach_document
  contact = Contact.find(params.id)
  file = find_uploaded_file(req, "document")
  if file.nil?
    Session.flash("error", "Pick a file before submitting.")
  elsif contact.attach_document(file)
    Session.flash("success", "Document filed.")
  else
    Session.flash("error", (contact._errors[0] ?? { "message": "Upload failed." })["message"])
  end
  redirect("/contacts/#{contact._key}")
end

# POST /contacts/:id/document/:blob_id/delete
def detach_document
  contact = Contact.find(params.id)
  if contact.detach_document(params.blob_id)
    Session.flash("success", "Document removed.")
  else
    Session.flash("error", "Document not found on this record.")
  end
  redirect("/contacts/#{contact._key}")
end

Uploader options

Option Default Description
multiple false true keeps an array of blob ids (<field>_blob_ids); false keeps one (<field>_blob_id).
content_types required for uploader; a safe default list for has_*_attached Allow-list of MIME types. Anything else is rejected before storage. The default never includes a script-executing type — see above.
max_size — (required) Hard cap in bytes. Above this → _errors populated, no blob stored.
service solidb for uploader; disk for has_*_attached "disk", "s3", "r2", or "solidb".
collection <snake>_<field>s SoliDB collection (solidb) or key prefix (disk/s3/r2).
format — Convert image uploads to "jpeg", "png", or "webp" before storage. Non-image uploads (PDF, csv, …) are never converted.
quality 82 Encoder quality (1–100) for lossy formats (jpeg, webp).
max_width / max_height — Downscale the original to fit within these pixel bounds before storage, preserving aspect ratio. Never upscales.
encrypted false Encrypt the file at rest with SOLI_ENCRYPTION_KEY, on every service — see Encrypted attachments.

Transform the original before storage

To avoid storing large originals (e.g. heavy PNG photos), declare a format and/or size caps. The framework decodes the upload, optionally downscales it, re-encodes it to the target format, and stores the result — updating the blob's content-type and filename extension to match. WebP is encoded lossy (via libwebp) so photos shrink dramatically; JPEG quality is honoured too.

class Listing < Model
  uploader("photo", {
    "content_types": ["image/jpeg", "image/png", "image/webp"],
    "max_size":      10_000_000,   # accept up to 10 MB on the way in
    "format":        "webp",       # …but store a lossy WebP
    "quality":       80,
    "max_width":     1600,         # downscale huge originals
    "max_height":    1600
  })
end

A 4 MB PNG uploaded here lands in storage as a downscaled ~200 KB WebP. The transform only runs for image content-types — a PDF in a multi-file uploader is stored byte-for-byte. If the bytes can't be decoded as an image, the original is stored unchanged so an upload is never blocked by a transform failure.

The same lossy WebP/quality encoding powers the read-time URL transform pipeline (photo_url({"fmt": "webp", "w": 800}) → /listings/42/photo.webp?v=…&w=800), so you can also keep a larger original and convert per-request instead.

Every URL ends in an extension. upload_url / <field>_url end the path in the stored file's extension — photo_url({"thumb": 200}) → /contacts/42/photo.jpg?v=abc&thumb=200 — or in fmt's when given (/contacts/42/photo.webp?v=abc&w=200; /contacts/42/photos/<blob_id>.webp for multiple: true), so a CDN such as Cloudflare, which caches by extension, caches the original and every variant. attach_<field> records the content type for this next to the blob id: <field>_content_type, or a {blob_id: type} hash in <field>_content_types for multiple: true. A record attached before this, a type with no settled extension, or a SQL table "…" model without that column gets no extension — add a photo_content_type column to have one.

The route answers photo.webp exactly as it answers photo?fmt=webp, and the extension-less URLs keep working. The extension wins over a fmt in the query. One that names the stored format re-encodes nothing (photo.jpg of a JPEG is the stored bytes); one an image cannot be encoded to (photo.pdf, photo.svg of a PNG) is a 404; a file that is not an image ignores it. fmt=jpg answers image/jpeg now, where it used to answer image/jpg.

Encrypted attachments

"encrypted": true encrypts the file before it reaches SoliDB, the disk, S3 or R2, and decrypts it on the way back: attach_<field>, <field>_url, read_upload and the AttachmentsController behave as before, and the store only ever holds ciphertext.

class Contract < Model
  has_one_attached("scan", {
    "content_types": ["application/pdf"],
    "encrypted":     true
  })
end

The key is SOLI_ENCRYPTION_KEY, the one encrypts uses (a separate blob key is derived from it). To rotate it, set the new key and list the old ones, comma-separated, in SOLI_ENCRYPTION_OLD_KEYS: new files are encrypted with the new key, and older files still open, since each file records which key sealed it. Storing an encrypted file without SOLI_ENCRYPTION_KEY raises.

The format is AES-256-GCM in 64 KiB segments (the STREAM construction), with a short header naming the format version and the key, about 0.02 % larger than the file. A segment cannot be removed, reordered or edited without the read failing, and a file is bound to its collection: copied into another uploader's collection, it does not open.

  • A file stored before encrypted was turned on is still served as it is.
  • An image format / max_width conversion runs before encryption, and URL transforms (photo_url({"w": 200})) after decryption.
  • An encrypted file is streamed, Range included, on SoliDB, disk, S3 and R2 alike: the server reads only the 64 KiB segments a request touches and decrypts each one as it arrives, so a download costs about one segment of memory, and a segment that fails authentication ends the response before any of its bytes is sent. read_attachment / read_upload and an image transform still decrypt the whole file, since they need its bytes.
  • direct_upload_start refuses an encrypted attachment: the browser would send the file straight to the bucket, where nothing can encrypt it. Use resumable uploads instead; a finished upload is read, encrypted and stored.
  • On the edge build, an encrypted R2 file is decrypted by the app rather than served by the Worker straight from the bucket, and URL image transforms are ignored for it: the Worker has no image codecs, and Cloudflare Images cannot read the ciphertext.

For drag-and-drop / AJAX flows that prefer JSON 204/422 over redirects, use uploads("contacts", "document") in config/routes.sl instead — that auto-mounts a generic AttachmentsController for upload, download, and per-blob delete. The first argument is the model's collection name, the segment <field>_url builds: GiftCardTemplate → uploads("gift_card_templates", "logo").

Cleanup on destroy — record.delete() and Model.delete(id) purge every attachment (disk, S3, and SoliDB) before the row is removed. detach_all_uploads(record) remains if you need to clear files without deleting the record.

def destroy
  contact = Contact.find(params.id)
  detach_all_uploads(contact) unless contact.nil?
  Contact.delete(params.id)
  redirect("/contacts")
end

Introspection — model_uploader_config(class_or_name, field) returns { name, multiple, content_types, max_size, collection, service, encrypted, … } (or null); model_uploader_fields(class_or_name) lists the declared field names.

Relationships

Declare associations using the built-in DSL. Association names accept strings or symbols:

class User < Model
  has_many("posts")      # strings and symbols both work
  has_many(:posts)       # Ruby-style symbol shorthand
  has_one("profile")
end

class Post < Model
  belongs_to("user")
  has_many("comments")
end

Naming Conventions

The DSL applies Rails-style naming conventions automatically:

Declaration Related Class Collection Foreign Key
has_many("posts") Post posts user_id (owner + _id)
has_one("profile") Profile profiles user_id (owner + _id)
belongs_to("user") User users user_id (name + _id)
has_and_belongs_to_many("tags") Tag tags join table posts_tags, FKs post_id / tag_id

Two cases the plain rule gets wrong are settled by looking at the classes that exist:

  • A singular that ends in e. Taking the s off cannot tell buses (bus) from remises (remise) or caches (cache). When no model is named OrderRemis and one is named OrderRemise, has_many("order_remises") means that one — reads, includes and dependent: cascades alike.
  • A class whose name ends in s. Bus and Address keep their name as their collection (bus, address), so has_many("buses") and has_many("addresses") read that collection, not buses / addresses.

class_name: still names any other class.

Override defaults with an options hash:

class Post < Model
  belongs_to("author", { "class_name": "User", "foreign_key": "author_id" })

  has_and_belongs_to_many("labels", {
    "class_name": "Tag",
    "join_table": "post_labels",
    "foreign_key": "post_id",
    "association_foreign_key": "label_id"
  })
end

Eager Loading (includes)

Preload related records to avoid N+1 queries. Uses LET subqueries with MERGE:

# Load users with their posts and profiles in a single query
users = User.includes("posts", "profile").all

# Combine with where clauses
active = User.where("active = @a", { "a": true }).includes("posts").first

# Inspect the generated query
print(User.includes("posts").to_query)
# => FOR doc IN users LET _rel_posts = (FOR rel IN posts FILTER rel.user_id == doc._key RETURN rel) RETURN MERGE(doc, {posts: _rel_posts})
  • has_many includes return an array of related documents
  • has_one and belongs_to includes return a single document (via FIRST())

After .all, the preloaded data is cached on each instance: subsequent instance.<rel> reads return the cached value without issuing another query. This applies to has_and_belongs_to_many, belongs_to, has_one, and polymorphic relations. (has_many accessors still return a chainable QueryBuilder, so they are not served from the preload cache — use .where(...).all if you want a materialised array.)

Join Filtering

Filter records by the existence of related records. Unlike includes, join does not preload the related data — it only filters:

# Find users who have at least one post
users_with_posts = User.join("posts").all

# Find users who have published posts
count = User.join("posts", "published = @p", { "p": true }).count

# Hash form — portable on SoliDB and every SQL adapter
count = User.join("posts", { "published": true }).count
count = User.join("posts", { "views": { "gt": 10 } }).count

# Chain with other query methods
recent = User.join("posts").order("created_at", "desc").limit(10).all

This is equivalent to ActiveRecord's joins — use includes when you need the related data, and join when you only need to filter by existence.

Filtered Includes

Filter included relations to load only matching related records:

# Only load published posts for each user
users = User.includes("posts", "published = @p", { "p": true }).all

# Hash form — portable on SoliDB and every SQL adapter (document + column)
visible = User.includes("posts", { "published": true }).all
recent  = User.includes("posts", { "where": { "views": { "gt": 10 } } }).all

# Inspect the generated query
print(User.includes("posts", "published = @p", { "p": true }).to_query)
# => ... LET _rel_posts = (FOR rel IN posts FILTER rel.user_id == doc._key AND rel.published == @p RETURN rel) ...

A hash filter here is about the related record: {"published": true} tests the post, on SoliDB as on SQL (it used to test the parent on a join, and to be ignored by a SoliDB includes). Its bind values live apart from those of .where, so the same field on both sides keeps both values. Values that arrived with the request cannot act as operators ({"ne": null}), including inside an or / and group. fields takes field names only — each is validated like a select column, and anything else raises.

When a hash filter on includes is evaluated in memory, like / ilike use a linear-time matcher (a pattern like %a%a%a%… can no longer blow up), and _ matches one character, not one byte — so it matches é as SQL does.

Combine a filter with field projection using the "fields" key in the bind hash:

# Only load title and body of published posts
users = User.includes("posts", "published = @p", {
  "p": true,
  "fields": ["title", "body"]
}).all
# => ... RETURN {title: rel.title, body: rel.body} ...

Includes with Field Projection

Use a hash argument to select specific fields on included relations (without filtering):

# Only load title and body from posts
users = User.includes({ "posts": ["title", "body"] }).all
# => ... LET _rel_posts = (FOR rel IN posts FILTER rel.user_id == doc._key RETURN {title: rel.title, body: rel.body}) ...

Chaining Multiple Includes

Chain .includes() calls to eagerly load multiple relations with different options:

# Filtered posts + unfiltered profile
users = User.includes("posts", "published = @p", { "p": true })
  .includes("profile")
  .all

Counting Relations (includes_count)

When you only need the count of a relation (not the rows), .includes_count() adds a single LET _rel_<name>_count = LENGTH(...) subquery to the parent and exposes the result as a <name>_count field on each instance. Cheaper than .includes() when you only render counts:

# Each Category gets a `products_count` integer field, in one round-trip
cats = Category.includes_count("products").all
print(cats[0].products_count)
# => 3

# Combine with .includes() and other chain steps
q = Author.where("active = @a", { "a": true })
  .includes("profile")
  .includes_count("posts")
  .order("name", "asc")
  .all
  • Only valid for has_many and has_and_belongs_to_many relations. Calling it on belongs_to, has_one, or polymorphic relations raises an error at registration time (the count is always 0 or 1, so the API doesn't earn its keep there).
  • The exposed field is always <relation_name>_count. Reads are O(1) — it's just an integer field on the instance, no extra query.

Field Selection (select / fields)

Use .select() (or its alias .fields()) to return only specific fields from the main collection. _key is always included automatically for identity:

# Only return name and email
users = User.select("name", "email").all
# => FOR doc IN users RETURN {name: doc.name, email: doc.email, _key: doc._key}

# .fields() is an alias
users = User.fields("name", "email").all
# => same query

# Combine with other query methods
users = User.where("active = @a", { "a": true })
  .select("name", "email")
  .order("name")
  .limit(10)
  .all

# Combine with includes
users = User.select("name", "email").includes("posts").all
# => ... RETURN MERGE({name: doc.name, email: doc.email, _key: doc._key}, {posts: _rel_posts})

# Full combo: select + filtered includes with field projection
users = User.select("name")
  .includes("posts", "published = @p", { "p": true, "fields": ["title"] })
  .all

Has And Belongs To Many

Many-to-many associations use a join table that stores (<foreign_key>, <association_foreign_key>) rows:

class Post < Model
  has_and_belongs_to_many("tags")
end

class Tag < Model
  has_and_belongs_to_many("posts")
end

Both classes declare the relation. The default join table is the alphabetical concatenation of the two pluralized class names — here posts_tags. The default foreign keys are post_id and tag_id.

Read — post.tags returns an array of related Tag instances:

post = Post.find(post_id)
tags = post.tags  # => [Tag, Tag, ...]

Add / remove — auto-generated mutators insert/delete join-table rows. The method name is add_<singular> / remove_<singular> derived from the relation name:

post.add_tag(tag)              # accepts a Tag instance
post.add_tag("tag_key")        # …or a raw _key
post.add_tag([tag1, tag2])     # …or an array
post.add_tag(tag1, tag2)       # …or variadic args

post.remove_tag(tag)
post.remove_tag([tag1, tag2])

Shovel operator (<<) — equivalent to add_<singular>, returns the (refreshed) relation:

post.tags << tag                # appends one tag, returns post.tags

Eager loading uses a two-stage subquery through the join table:

posts = Post.includes("tags").all
# => ... LET _rel_tags = (FOR jt IN posts_tags FILTER jt.post_id == doc._key
#                          FOR rel IN tags FILTER rel._key == jt.tag_id RETURN rel) ...

Existence filtering with .join():

tagged_posts = Post.join("tags").all              # posts that have at least one tag
tutorials = Post.join("tags", "name = @n", { "n": "tutorial" }).all

Overrides — supply an options hash to customize the join:

class Article < Model
  has_and_belongs_to_many("labels", {
    "class_name": "Tag",
    "join_table": "article_labels",
    "foreign_key": "article_id",
    "association_foreign_key": "tag_id"
  })
end

Cascade Deletes

Declare what happens to associated records when their owner is hard-deleted with dependent: on has_many/has_one:

class User < Model
  has_many "posts", dependent: "delete"       # per-row: callbacks, nested cascades
  has_many "events", dependent: "delete_all"  # one bulk REMOVE: no callbacks
  has_many "drafts", dependent: "nullify"     # one bulk UPDATE: fk → null
  has_one  "profile", dependent: "delete"
end

Semantics:

  • Ordering mirrors Rails: before_delete runs first (a false veto aborts the cascades too), then each dependent: relation in declaration order, then the owner row is removed, then after_delete.
  • "delete" (alias "destroy") loads each child and deletes it through the interpreter — child callbacks, nested cascades, the child's own soft-delete semantics, and counter-cache decrements all apply. A child veto or error aborts the remaining cascade and the owner delete.
  • "delete_all" issues one bulk REMOVE: no callbacks, hard delete even for soft-delete child models, no nesting.
  • "nullify" issues one bulk UPDATE setting the FK to null.
  • Soft-delete owners never cascade — a soft delete() keeps children, so restore() has nothing to un-do.
  • Model.delete(id) on a class that declares dependent: routes through the full instance flow (cascades — and, as a side effect, delete callbacks — fire). Bulk writes (Model.delete_all, Model.where(...).delete_all, update_all, prune) never cascade, matching Rails.
  • Cycles terminate: a document already being deleted higher up the chain is skipped, and recursion is capped at 32 levels.
  • A child that is already gone — deleted earlier in the same transaction, or by another request — is skipped rather than aborting the cascade. Any other failure aborts it, and the error names what the database answered.
  • Inside Model.transaction on SoliDB, use SoliDB 2.10.2 or later. Older servers answer a transaction's queries from committed data: a cascade does not find children the same transaction created, and leaves them behind without an error. The SQL adapters are not affected.
  • There is no per-operation rollback; wrap the delete in Model.transaction when the cascade must be atomic (every document write inside participates).

Through Associations

has_many through: traverses an intermediate relation — the document-DB equivalent of Rails' join-model association:

class User < Model
  has_many "memberships"
  has_many "teams", through: "memberships"
  # source: when the relation name doesn't match the through model's relation
  has_many("employers", {"through": "memberships", "source": "company"})
end

class Membership < Model
  belongs_to "user"
  belongs_to "team"
end

user.teams                                  # chainable QueryBuilder
user.teams.where("active == @a", {"a": true}).order("name").count()

How it works and what to know:

  • The accessor returns a chainable QueryBuilder over the target collection, filtered by a single-query membership subquery (doc._key IN (FOR jt IN memberships FILTER jt.user_id == @k RETURN jt.team_id)) — no N+1, and chained .where/.order/.count/.sum all compose.
  • The source relation on the through model is inferred by singularizing the relation name ("teams" → "team"); override with source:. Both belongs_to sources (join-model shape above) and has_many sources (distant children: has_many "comments", through: "posts") work.
  • A soft-deleting through model automatically excludes soft-deleted join rows.
  • Resolution happens lazily at first access (the through model may be defined later); a missing through or source relation raises naming exactly what was searched and suggesting source:.
  • Pushing creates the join record: user.teams << team (or << key) inserts a row in the through collection, HABTM-style — a raw join-row write (the through model's validations and callbacks are skipped; its counter caches are bumped). Only belongs_to sources are writable; a has_many-source push raises with a pointer at creating the child directly, and an unpersisted owner raises.
  • Bulk writes and eager-loading stay off: delete_all/update_all on a through association raise (they would hit target rows, not join rows — operate on the through relation's records instead), and eager-loading (includes, join, includes_count) of a through relation raises.

Counter Caches

belongs_to ..., counter_cache: keeps a children count on the parent row up to date, so lists render without a COUNT query per row:

class Comment < Model
  belongs_to "post", counter_cache: true            # maintains posts.comments_count
  belongs_to("author", {"class_name": "User", "counter_cache": "authored_count"})
end

post.comments_count                    # plain field read (0/missing until first bump)
Post.reset_counters(post._key, "comments")  # recount → write → returns Int

Semantics:

  • counter_cache: true derives the column from the child collection (comments → comments_count); a string picks a custom column. The parent needs no schema preparation — a missing column reads as 0.
  • Bumps ride the same atomic path as increment/decrement — an If-Match CAS loop on SoliDB, a single arithmetic UPDATE on the SQL adapters — and fire on child create/save, hard delete (instance and class form), FK reassignment on update/save/Model.update(id, ...) (−1 old parent, +1 new), and — for soft-deleting children — soft delete (−1) and restore (+1), so counters track default-scope-visible children.
  • Bulk writes never bump (delete_all, update_all, upsert, import, prune) and bumps are best-effort: a failing bump never fails the already-committed primary write. Counters are eventually consistent under failures — Model.reset_counters(id, relation) is the repair tool (it recounts minus soft-deleted children and returns the fresh count).

Polymorphic Relations

A polymorphic belongs_to lets one model belong to any of several others on a single association — comments on posts and photos, images on anything:

class Comment < Model
  belongs_to "commentable", polymorphic: true
end

class Post < Model
  has_many "comments", as: "commentable"
end

class Photo < Model
  has_many "comments", as: "commentable"
end

# The child stores both halves of the reference:
Comment.create({
  "body": "Nice shot!",
  "commentable_id": photo._key,
  "commentable_type": "Photo"
})

comment.commentable    # → the Photo instance (class resolved from commentable_type)
post.comments          # → chainable QB, type-guarded: commentable_type == "Post"

Semantics:

  • The child stores {name}_id and {name}_type (the model class name). The accessor reads both at runtime, resolves the class and collection from the type string, and returns the correctly-typed instance — null when either field is missing, an error naming the type when it doesn't match a known model class.
  • The as: inverse is a normal has_many/has_one whose every query — accessor, includes, includes_count, join, cascades — carries the {as}_type == "<OwnerClass>" guard, so two parents with colliding keys never see each other's children.
  • Association writers auto-set both fields: customer.comments << Comment.create({...}) and customer.comments.create({...}) stamp commentable_id and commentable_type — see Writing through associations.
  • counter_cache: works on a polymorphic belongs_to: the parent collection is resolved from the type at bump time, so each parent type maintains its own count, and a reassignment across types moves the count between collections. reset_counters recounts with the type guard.
  • dependent: works on as: relations — only the owner's typed children cascade; "nullify" clears both the FK and the type field.
  • Eager-loading a polymorphic belongs_to raises (includes/join — the target collection varies per row, which doesn't fit one query; Rails has the same restriction). Access record.commentable directly. The as: inverse eager-loads normally.
  • polymorphic: true combined with class_name: raises at class load (the target type comes from the record, not the declaration).

Single-Collection Inheritance (STI)

A model inheriting from another model shares its base's collection, with a type discriminator — Rails single-table inheritance, per-collection:

class User < Model
  validates("email", {"presence": true})
  has_many "posts"
  scope("recent", fn() { this.order("_created_at", "desc") })
end

class Admin < User
  def badge
    "admin"
  end
end

Admin.create({"email": "a@x.co"})   # stored in `users` with type: "Admin"
User.all()                           # every row — admins hydrate AS Admin
Admin.all()                          # only Admin rows (and Admin's descendants)
User.find(admin._key).badge()        # "admin" — hydration follows the type

On a column-aware model the same rules apply to a real type column:

class User < Model
  table "users"          # must include a string `type` column
end

class Admin < User
end

Admin.create({ "email": "a@x.co" })   # INSERT … type = 'Admin'
Admin.where({ "email": "a@x.co" })    # AND type IN ('Admin', …descendants)
User.find(admin.id).type              # "Admin"

Boot fails if an STI subclass's table has no type column. find / find_by / first_by on a subclass refuse a row of another type (RecordNotFound / nil), matching the document path.

Semantics:

  • Subclass writes stamp type (create, save, find_or_create_by); rows hydrate as their stored type everywhere (find, where, all, relation accessors) — a guard ignores a type value that doesn't name a model class belonging to the row's collection, so unrelated data fields called type can't hijack hydration.
  • Subclass queries are type-scoped — Admin.where/all/count/find_by/ first_by/delete_all and every chained QueryBuilder filter type IN ["Admin", ...descendants]. The base class matches every row (no filter), Rails-style. Admin.find(user_key) on a base-class row raises RecordNotFound, and class-form update(id)/delete(id) refuse rows outside the hierarchy.
  • Metadata copies down at class definition: validations, callbacks (named and closure), relations (with the base's foreign key, e.g. user_id), scopes, soft-delete, attr_accessible, encrypts, enums, and state machines all apply to subclasses; the subclass's own declarations run after the copy and append/override. Declare the parent before its subclasses (file order already guarantees this) — parent DSL added after a subclass is defined does not propagate.
  • The discriminator column is always type; avoid a user field of that name on STI hierarchies.

Manual Relationships

You can also implement relationships as custom methods for more control:

class Post < Model
  def author()
    User.find(this.author_id)
  end
end

Graph Models (Edges and Traversal)

SoliDB is multi-model: alongside document collections it supports native edge collections. Declare an edge model with the edge DSL and the Model API gains graph creation, traversal, and shortest-path queries:

class Follow < Model
  edge from: "users", to: "users"
end

from: and to: accept collection names ("users") or model class names ("User"). The declaration marks the collection as the SolidB edge type — in dev it is auto-created with that type plus hash indexes on _from and _to.

Creating Edges

Endpoints can be model instances, full "collection/key" ids, or bare keys:

f = Follow.create(from: alice, to: bob)
f = Follow.create({ "from": alice, "to": "users/bob-key", "since": 2024 })

f._from   # => "users/alice-key"
f._to     # => "users/bob-key"

Edges are ordinary model records — validations, callbacks, and extra attributes (since above) work as usual. A missing or invalid endpoint behaves like a failed validation: f._errors is set (e.g. [{ "field": "from", "message": "..." }]) and the edge is not persisted.

Traversal

Call .traverse(EdgeModel, options?) on a saved record to get a chainable QueryBuilder over the reachable vertices:

friends   = alice.traverse(Follow).all                    # OUTBOUND, depth 1..1
followers = alice.traverse(Follow, direction: "in").all   # INBOUND
network   = alice.traverse(Follow, depth: 3).all          # depth 1..3

# Full chain — vertex filters use the usual `doc` variable; prefix a filter
# with `edge.` to match edge attributes instead:
ring = alice.traverse(Follow, depth: [2, 3], direction: "any")
  .where({ "active": true })
  .where("edge.since >= @y", { "y": 2024 })
  .order("name")
  .limit(10)
  .all

n = alice.traverse(Follow).count
Option Default Description
direction "out" "out" (OUTBOUND), "in" (INBOUND), or "any"
depth 1 Int n traverses depth 1..n; a [min, max] array sets an explicit range

Depth gotcha: Soli's 1..3 range literal materializes to the exclusive-end array [1, 2]. Prefer an explicit [1, 3] array for depth ranges.

  • Results are instances of the target model — the class is resolved per document, so mixed-vertex graphs return the right class for each vertex.
  • Soft-delete models compose: the deleted-filter is applied to the vertices.
  • A traversal builder does not compose with includes, includes_count, join, group_by, update_all, or delete_all — combining them raises a clear error. .similar() does compose — rank traversal results by semantic relevance (exact client-side cosine; no HNSW pushdown on graph queries).
  • Model.graph_rag(query, options) — graph-augmented retrieval: ANN seeds, expand through an edge model, re-rank. See Graph RAG below.
  • traverse and shortest_path require a saved record (they raise otherwise).

Shortest Path

shortest_path executes immediately (no .all) and returns the vertices along the shortest path between two records — [] when they are not connected. Direction defaults to "any":

path = alice.shortest_path(bob, via: Follow)
path = alice.shortest_path("users/bob-key", via: Follow, direction: "out")

Relation Sugar

An idiomatic named relation over a traversal is just a plain method:

class User < Model
  def followers()
    this.traverse(Follow, { "direction": "in" })
  end
end

User.find(key).followers().where({ "active": true }).count

Migrations

Dev auto-create already provisions the edge type and the _from/_to hash indexes. For explicit production migrations:

def up(db: Any)
  db.create_collection("follows", "edge")
  db.create_index("follows", "idx_follows_from", ["_from"], {})
  db.create_index("follows", "idx_follows_to", ["_to"], {})
end

Graph RAG

Combine vector retrieval with graph expansion for richer RAG context. Two APIs:

Composition — rank neighbors of a seed vertex by meaning:

# Saved record required for traverse()
related = product.traverse(CompatibleWith, depth: 1)
  .similar("wireless accessories", "embedding", 5)
  .all

for item in related
  print(item.name + " — " + str(item._similarity_score))
end

Traversal + .similar() always uses exact client-side cosine over the reachable vertices (HNSW pushdown does not apply to graph FOR-heads).

Model.graph_rag() — seed-and-expand in one eager call:

class CompatibleWith < Model
  edge from: "products", to: "products"
end

class Product < Model
  vector_index "embedding", dimension: 1536, metric: "cosine"

  before_save fn() {
    this.embedding = embed(this.name + ". " + this.description)
  }
end

context = Product.graph_rag("running headphones with long battery", {
  "via": CompatibleWith,
  "direction": "any",
  "depth": 1,
  "seed_k": 3,
  "limit": 8
})

for product in context
  print(product.name)
  print("  score: " + str(product._similarity_score))
  print("  seed:  " + str(product._graph_seed))
  print("  hops:  " + str(product._graph_hops))
end

answer = llm_generate(
  "Recommend only from the list. Mention names and prices.",
  build_product_context(context) + "\n\nQuestion: running headphones"
)
Option Default Description
via — Required. Edge model class (must declare edge from:, to:)
direction "out" "out", "in", or "any"
depth 1 Int n (1..n) or [min, max] array
field "embedding" Vector field covered by vector_index
seed_k 5 ANN seeds from the collection index
limit 10 Final result cap after expand + re-rank
vector — Query vector literal — skips the embedding API call

Each result carries _similarity_score (re-rank score), _graph_seed (true for direct ANN hits), and _graph_hops (0 for seeds, 1 for expanded neighbors in v1).

Finder Methods

Find records by specific field values:

# Find by exact field match
user = User.find_by("email", "alice@example.com");

# Find with ordering (first by field value)
user = User.first_by("name", "Alice");

# Find or create - returns existing or creates new
user = User.find_or_create_by("email", "new@example.com");
user = User.find_or_create_by("email", "new@example.com", { "name": "New User" });

Dynamic Finder Methods

Automatically generated finders for any field combination:

# Single field finder
user = User.find_by_email("alice@example.com");

# Two-field finder (AND logic)
user = User.find_by_email_and_active("alice@example.com", true);

# Three+ field combinations
post = Post.find_by_title_and_published_and_author_id("Hello", true, 123);

These methods return the first matching record or null if not found. A dynamic finder is find_by for the fields named after find_by_: the same query, so it follows a SQL connection, an STI subclass's type scope, and grouped(), and a field segment that is not an identifier is refused. A static method of that name, when the class defines one, is what runs. The call stays on the VM, in an action and in a script.

Aggregations

Calculate sums, averages, min, max on query results. Each returns a QueryBuilder; chain .first for the value:

# Sum
total = User.where("age > @a", { "a": 18 }).sum("balance").first

# Average
avg = User.avg("score").first

# Minimum
min_score = User.min("score").first

# Maximum
max_score = User.max("views").first

# Group by aggregation (legacy 3-arg form, unchanged)
by_country = User.group_by("country", "sum", "balance");
# Returns: [{ group: "US", result: 1000 }, { group: "FR", result: 500 }, ...]

Current limitation: .sum, .avg, .min and .max come back nil — SoliDB rejects the query they generate. Until that is fixed, compute them with aggregate, which works and returns all of them in one round-trip:

stats = User.where("age > @a", { "a": 18 })
  .aggregate({ "total": ["sum", "balance"], "avg": ["avg", "score"],
               "lo": ["min", "score"], "hi": ["max", "score"] })
  .first
stats["total"]   # the sum; stats["avg"], stats["lo"], stats["hi"]

median, stddev, variance and count_distinct are not affected.

Rich grouped aggregation

The newer form groups on one or more fields and computes several named aggregates at once, with having for post-group filtering:

rows = Order
  .where({ "status": "paid" })
  .group_by(["country", "plan"])
  .aggregate({ "total": ["sum", "amount"], "n": ["count"] })
  .having("total > @min", { "min": 1000 })
  .order("total", "desc")
  .all
# => [{ "country": "FR", "plan": "pro", "total": 5300, "n": 12 }, ...]

User.group_by("role").all           # 1-arg form: implicit count per group ("n")
Order.aggregate({ "n": ["count"] }).first   # ungrouped: one row
Order.median("amount").first        # also: stddev / variance / count_distinct

Aggregate functions: sum, avg, min, max, count, count_distinct, median, stddev, variance (no PERCENTILE — SolidB has no such function). The full treatment — having security notes, soft-delete behavior, the window-function escape hatch — lives in Analytics & Columnar Stores.

Pluck and Exists

Quick queries for specific data:

# Get array of single field values
names = User.where("active = @a", { "a": true }).pluck("name");
# Returns: ["Alice", "Bob", "Charlie"]

# Get multiple fields as hashes — self-describing, and the projection runs
# in the database: only the named fields travel over the wire
users = User.pluck("name", "email");
# Returns: [{ name: "Alice", email: "alice@example.com" }, ...]

# Symbols work wherever a field name is expected — same query, Rails-style
users = User.pluck(:name, :email).all
posts = Post.order(:created_at, :desc).limit(10).all

# Check if records exist: `.exists` builds the query, `.first` runs it
exists = User.where("role = @r", { "r": "admin" }).exists.first
# Returns: true or false

Vector / Similarity Search

Rank results by semantic relevance using .similar():

# Basic semantic search (uses default "embedding" field, top 10)
results = Post
    .where("published == true")
    .similar("how to deploy a web app")
    .all

# Custom embedding field and result count
results = Product
    .where("active == true")
    .similar("red running shoes", "title_embedding", 5)
    .all

# Each result gets a _similarity_score
for product in results
    print(product.name + " (" + str(product._similarity_score) + ")")
end

Requires SOLI_EMBEDDING_API_KEY environment variable. See database docs for configuration.

Index pushdown (vector_index)

Declare a vector_index on the embedding field and .similar() pushes the search down to the database's HNSW index (approximate nearest neighbor) instead of computing cosine similarity client-side:

class Article < Model
  vector_index "embedding", dimension: 1536, metric: "cosine"
end

Article.similar("query text", "embedding", 5)          # ANN via the HNSW index
Article.similar([0.1, 0.2, ...], "embedding", 5)       # vector literal — no embedding call
Article.similar("q", "embedding", 5, { "exact": true })  # force exact client-side cosine

ANN results are approximate, and chained where filters are applied after candidate selection (4×k candidates, capped at 400) — so fewer than k rows may return. Without a vector_index declaration, .similar() keeps the historical client-side path, unchanged. Full details, plus fulltext (Model.search, _search_score) and geo (near / within, _distance) search and the index DSL, live in Search: Vector, Fulltext & Geo.

Instance Methods

Methods available on model instances:

user = User.find("user_id");

# Update fields and persist
user.name = "New Name";
user.update();

# Atomic increment/decrement (CAS via `_rev` on SoliDB; one UPDATE on SQL)
user.increment("view_count");      # +1
user.increment("view_count", 5);   # +5
user.decrement("stock");           # -1

# Update timestamp only
user.touch();  # Updates _updated_at

# Refresh from database
user.reload();

Dirty tracking

Model instances track which attributes changed since they were loaded from (or last persisted to) the database:

user = User.find(id)
user.changed?                 # false — freshly loaded
user.name = "New Name"

user.changed?                 # true
user.changed                  # ["name"]  (sorted attribute names)
user.changes                  # { "name": ["Old Name", "New Name"] }
user.attribute_was("name")    # "Old Name"

user.save()
user.changed?                 # false — baseline reset
user.previous_changes         # { "name": ["Old Name", "New Name"] }

Semantics worth knowing:

  • New records report every attribute as changed — User.new({"name": "A"}) has changes == { "name": [null, "A"] }, and after create the record's previous_changes covers all inserted attributes (including id), matching Rails.
  • Failed persists keep the record dirty. A validation or DB error on save/update leaves changed? true and previous_changes untouched.
  • reload() resets the baseline and clears previous_changes; atomic increment/decrement, soft delete(), and restore() keep their written field clean.
  • Tracking is value-based. Reassigning an attribute to an equal value is not a change. Conversely, mutating a nested Hash/Array in place (user.tags.push("x")) is invisible to tracking — reassign the attribute (user.tags = updated_tags) to record it.
  • There are no dynamic per-attribute methods (name_was); use attribute_was("name"). A database column literally named changed shadows the method (field reads win), like any other field/method collision.

How increment / decrement stay atomic under concurrency

increment and decrement are not plain read-modify-writes on the in-memory instance. How atomicity is achieved depends on the backend:

  • SoliDB drives an optimistic compare-and-swap loop (below).
  • Postgres, MySQL, and SQLite do the arithmetic inside one UPDATE (jsonb_set / JSON_SET / json_set over the current value), so the row's own lock serializes concurrent bumps. There is no retry loop and no contention error on these adapters — and no _rev, which SQL document tables do not have. A column-aware model increments the real column the same way (SET col = COALESCE(col, 0) + ?), and a non-numeric column is refused by name. A missing field (or a NULL column) counts as 0, so nothing needs backfilling.

On SoliDB each call:

  1. Re-fetch the document to read the current field value and its _rev.
  2. Compute current + delta (or current - delta).
  3. PUT the new value with an If-Match: <rev> header.
  4. If another writer modified the document in between, the DB returns 409 Conflict and the loop retries (up to 10 attempts) by re-fetching.

On success the in-memory instance's field and _rev are refreshed, so any follow-up call observes the same state the DB now holds. Concurrent increments cannot lose updates: every successful PUT was the unique continuation of the rev it read.

If the document is being hit by many writers at once, increment may return an error like "increment failed: Atomic update of users.view_count failed after 10 attempts (too much contention)" instead of silently dropping the update. Callers can retry, queue the work, or back off as they prefer.

Bulk attribute updates: .save(hash) and .update(hash)

Both .save() and .update() accept an optional hash of attributes that are applied to the instance before the persist pipeline runs. This collapses the common "set multiple fields, then save" pattern into a single call:

# Instead of:
user.name = "Alice";
user.email = "alice@example.com";
user.role = "admin";
user.save();

# Write:
user.save({
  "name": "Alice",
  "email": "alice@example.com",
  "role": "admin"
});

The hash is merged onto the instance — keys you don't pass keep their current value, keys you do pass overwrite. Validations run after the merge, so errors surface on .errors the same way as individual field assignments:

# Partial update — only `price` changes, `name` is preserved
p = Product.find(id);
p.update({ "price": 99.00 });

# Mix field assignment with hash — pre-assigned fields fall back when hash
# omits them, hash wins on conflict.
p = Product.new();
p.name = "Widget";            # will survive
p.save({ "price": 12.50 });   # name stays "Widget", price becomes 12.50

Framework-internal fields (_key, _id, _rev, _errors, etc.) are silently skipped when they appear in the hash — you can't overwrite them via bulk update. A non-hash argument raises: expected a Hash of attributes, got <type>.

.update(hash) is effectively sugar for .save(hash) on an existing record (requires _key to be set); the two share the exact same validation and DB write path.

Scopes

Define reusable query scopes. Inside the closure this is bound to a fresh QueryBuilder for the model; the closure returns a (possibly refined) QueryBuilder. Accessing the scope name on the class invokes the closure:

class User < Model
  scope("active", fn() { this.where("active = @a", { "a": true }) })
  scope("recent", fn() { this.order("created_at", "desc").limit(10) })
end

# Use scopes — `User.active` invokes the closure and returns a QueryBuilder
# you can chain further:
let active_users = User.active.all
let top_ten     = User.recent.where("verified = @v", { "v": true }).all

Scopes compose: User.active.recent chains both closures' refinements. See Metaprogramming for the underlying mechanism.

Soft Delete

Mark records as deleted without removing them:

class Post < Model
  soft_delete
end

# Delete sets deleted_at timestamp
post.delete()

# Restore clears deleted_at
post.restore()

# Query without deleted records (default behavior)
posts = Post.where("doc.published == true").all

# Include soft-deleted records — the parentheses are required
everything = Post.with_deleted().all

# Query only deleted records
deleted = Post.only_deleted().all

Post.with_deleted without parentheses is the function itself, not a query: .all on it raises Cannot access property 'all' on Function.

Current limitation: the soft-delete filter is applied to the rows of a built query — Post.where(...).all, Post.order(...).all, Post.limit(...).all, Post.where(...).first. A bare Post.all, every .count (with or without where), and find_by still include soft-deleted rows. Until that is fixed, filter explicitly where it matters: Post.where("doc.deleted_at == null").count.

Interactions with other features: a soft delete() does not run dependent: cascades (children survive, so restore() has nothing to un-do), and it keeps dirty tracking clean for deleted_at. A soft-deleting child with a counter_cache: decrements its parent's counter, and restore() increments it back.

Timeseries Models

Declare a model as timeseries with the timeseries DSL. The collection is created with the SolidB timeseries type — optimized for append-only, time-indexed data (metrics, logs, telemetry):

class Metric < Model
  timeseries retention: "30d"     # bare `timeseries` (no options) also works
end

class Reading < Model
  timeseries retention: "90d", timestamp: "recorded_at"
end
  • retention: — optional retention window; used by prune when called without an argument.
  • timestamp: — the field time_bucket buckets on. Defaults to the server-set _created_at.

Insert-Only

Timeseries records are insert-only, mirroring the database's own rules. Documents get UUIDv7 keys, so _key order is insertion-time order:

Metric.create({ "device": "srv1", "value": 0.42 })

m.update({ "value": 1 })
# => raises: "Metric is a timeseries model: records are insert-only.
#    update is not supported — use prune() for retention."

Blocked: static update / upsert, instance update / save on an existing record / increment / decrement, and update_all. Allowed: delete and delete_all.

Don't set _key yourself on a timeseries model. prune relies on the UUIDv7 key ordering — documents inserted with a caller-supplied _key are never pruned.

Bucketed Aggregation (time_bucket)

time_bucket(interval, aggregates?) groups rows into fixed time buckets and computes per-bucket aggregates. Chain it after where(...) filters and finish with .all:

rows = Metric.where("device = @d", { "d": "srv1" })
  .time_bucket("5m", { "avg": "value", "max": "value" })
  .all
# => [{ "bucket": "2026-07-05T10:00:00+00:00", "avg": 0.41, "max": 0.9 }, ...]

rows = Metric.time_bucket("1d").all                  # bare form: count per bucket
# => [{ "bucket": "...", "count": 42 }, ...]

rows = Metric.time_bucket("1h", avg: "value").all    # keyword style works too
  • Interval units: s, m, h, d (the database's TIME_BUCKET contract).
  • Aggregates: sum / avg / min / max take a field name; count takes true ({ "count": true }). With no aggregates you get a count per bucket.
  • Buckets fall on the declared timestamp: field (default _created_at).
  • Rows come back as plain hashes — bucket (an RFC3339 string) plus your aggregate aliases — sorted by bucket.

Retention (prune)

prune deletes rows older than a cutoff and returns the number deleted:

deleted = Metric.prune("30d")                    # duration cutoff (units: s/m/h/d/w)
deleted = Metric.prune("2026-06-01T00:00:00Z")   # explicit RFC3339 cutoff
deleted = Metric.prune                           # uses the declared retention:

There is no auto-prune scheduler. Register a recurring cron job whose handler calls prune:

Cron.schedule("prune_metrics", Cron.daily_at("03:00"), "PruneMetricsJob", {})
# ...and PruneMetricsJob.perform is a one-liner: Metric.prune

Migrations and Continuous Aggregates

Dev auto-create provisions the timeseries type for you; the explicit migration form is:

def up(db: Any)
  db.create_collection("metrics", "timeseries")
end

db.prune_collection("metrics", "2026-01-01T00:00:00Z") is also available on the migration db handle for one-off cleanups. For continuous aggregates (downsampling on write), SolidB streams are the raw-SDBQL escape hatch — db.query("CREATE STREAM ...") in a migration. See Migrations.

Translated Fields

translate "title", "body" in a model's body keeps one value per locale for those fields: the default locale's in the column, the others in a translated_fields hash of the same document. record.title reads and writes the request's locale, falling back to the column. where_translated / order_translated query them as a reader in the locale sees them (order("title") on a translated field sorts the translation, ignoring case and accents), and {"locale": "fr"} on a form field edits one locale. See Translated model fields.

class Article < Model
  translate "title", "body"
end

Encrypted Attributes

Encrypt sensitive fields at rest with encrypts. Values are encrypted on create/save/update and decrypted transparently on load, using AES-256-GCM:

class User < Model
  encrypts(:ssn, :api_token)
end

u = User.create({ "ssn": "123-45-6789", "email": "a@b.com" });
# stored ciphertext in the DB; in memory it's plaintext:
User.find(u._key).ssn  # => "123-45-6789"

Works on SoliDB document collections, SQL document tables (_key + doc), and column-aware models:

class User < Model
  table "users"          # `ssn` must be a string/text column
  encrypts(:ssn)
end

Ciphertext is stored in that column; create / save / find decrypt so the instance always sees plaintext. Boot fails if the column is missing or not text (encrypted values are base64).

The encryption key comes from the SOLI_ENCRYPTION_KEY environment variable — set it to a long, high-entropy secret (e.g. Crypto.random_hex(32)) and keep it out of source control.

Encrypted columns can't be queried by value. AES-GCM uses a random nonce, so the same plaintext encrypts to different ciphertext every time — User.where("ssn = @s", { "s": "123-45-6789" }) will never match. Encrypt only fields you store and read, not ones you filter on.

A field written before encrypts was added (legacy plaintext) is returned as-is on load rather than erroring. Low-level/transaction writes that bypass create/save aren't auto-encrypted — use Crypto.encrypt directly there.

encrypts builds on the standalone Crypto.encrypt(plaintext, key?) / Crypto.decrypt(ciphertext, key?) builtins, which you can also use on their own (key defaults to SOLI_ENCRYPTION_KEY).

Files take "encrypted": true on uploader / has_*_attached instead — see Encrypted attachments.

Audit Log

Who changed what, and when — as a concern a model includes.

soli generate audit           # app/models/concerns/audited.sl, app/models/audit.sl, a migration
soli generate audit --chain   # the same, with the entries chained by hash
soli db:migrate up
class Invoice < Model
  include Audited
end

invoice.update({"total": 120})
invoice.audits.last.changes     # {"total": [100, 120]}

Every create, update and delete of the model writes an Audit entry:

Field
action "create", "update" or "delete"
record_type, record_key the model's class name and the record's key
changes {field: [old, new]} — on a create every field as [nil, value], on a delete every field as [value, nil]
at Unix seconds
actor_type, actor_key, actor_label the signed-in user of the request (req["current_user"]: its class, key and email), or "system" outside a request — a job, a script, a migration
request_id, ip the request's X-Request-Id header and remote address, when there is a request

Reading:

invoice.audits                       # this record's history, oldest first
Audit.by_actor(user)                 # what someone did, newest first
Audit.between(from_unix, to_unix)    # a period, oldest first
Audit.purge_before(unix)             # retention, when you decide on one; returns how many

Both files are plain Soli over callbacks, dirty tracking and concerns, and yours to edit — what an entry holds is Audit.record, who the actor is Audit.actor.

Secrets stay out

Fields declared with encrypts and password_digest are logged as changed with their values withheld ({"iban": ["[redacted]", "[redacted]"]}). Add your own per model, or leave fields out of the log altogether:

class Invoice < Model
  include Audited
  encrypts(:iban)

  static def audit_redacted
    ["secret_note"]
  end

  static def audit_ignored
    ["views"]              # a change to these alone writes no entry
  end
end

Model.encrypted_attributes is the list of a model's encrypts fields.

A tamper-evident log

With --chain, each entry carries a sequence number and a hash over its content and the previous entry's hash (Crypto.ledger_hash), so editing, removing or inserting an entry breaks every hash after it:

Audit.verify    # nil while the log is intact, else the seq of the first broken entry

It costs a read per entry, and writers queue on the tail of the log: two requests that read the same tail ask for the same seq, the unique index refuses one, and that one retries (up to eight times, then raises). Choose it for a log you must be able to defend, not for a busy table. Someone who can rewrite the whole table can rewrite the whole chain — publish or store the latest entry_hash elsewhere if that is your threat. purge_before removes the head of the chain; archive before you purge.

What the chain proves is yours to decide. With AUDIT_CHAIN_KEY (32+ characters, set before the first entry) the hashes are keyed: without it, someone who can write to the table can edit an entry and redo every hash after it, and verify sees an intact chain. And removing the newest entries leaves a shorter chain that is intact — keep Audit.head ({seq, entry_hash}) somewhere the database's writers cannot reach, and hand it to Audit.verify(head), which then reports the missing tail.

What is not logged

  • Writes that skip callbacks: update_all, delete_all, increment / decrement, insert_all, raw queries.
  • A change made by mutating a nested Hash or Array in place — reassign the attribute (see Dirty tracking).
  • The entry is written after the change, in its own write: if it fails, the change stands and the error is raised. Wrap both in Model.transaction on a SQL database if they must succeed or fail together.

Relationship Accessors

Access related records directly from instances:

user = User.find("user_id");

# has_many returns a chainable QueryBuilder, not an array.
# Each terminal call (.all, .count, .delete_all, iteration, ...)
# runs a query against the foreign-key filter at that moment.
posts = user.posts;

# Access has_one relation
profile = user.profile;

# Access belongs_to relation
author = post.user;

Writing through associations

has_many accessors (including polymorphic as: inverses) accept writes — the foreign key, and the polymorphic type when applicable, are stamped automatically:

# Create a child through the relation — FK (and type) auto-set:
post = author.posts.create({"title": "seeded"})
post._errors                # null on success, error array on validation failure

# Adopt an existing (or unpersisted) record — sets the FK and saves:
author.posts << loose_post
author.posts << [draft_a, draft_b]

# Polymorphic inverses stamp both halves of the reference:
customer.comments << Comment.create({"message": "bla"})
comment = customer.comments.create({"message": "bla"})
comment.commentable_id      # customer._key
comment.commentable_type    # "Customer"

Semantics:

  • Both writers persist through the regular save path — validations, before_/after_save/create/update callbacks, counter caches, and dirty tracking all apply. .create returns the instance (_errors carries validation failures, like Model.create); a failing << raises so the push can't silently no-op.
  • The association seed wins over caller-supplied values — passing a different commentable_id to customer.comments.create is overridden.
  • The owner must be persisted (<</.create on an unpersisted owner raises); << expects model instances (or an array of them), not raw keys.
  • On HABTM relations << inserts a join row, and on through: relations it creates the join record — both documented in their sections. .create on a through: relation raises (create the record and push it instead).

has_many is Enumerable AND chainable

The has_many accessor behaves like an array (iteration, indexing, len, each, map, filter, ...) and like a QueryBuilder (.where, .order, .limit, .count, .delete_all, .exists, ...):

user = User.find("user_id");

# Iterate — each iteration runs the FK-filtered query once
for post in user.posts
  print(post.title);
end

# Indexing materializes the result set
first = user.posts[0];

# len() and .length / .size return the count
n = len(user.posts);
same = user.posts.length;
alt = user.posts.size;

# Array-style helpers materialize then delegate
user.posts.each(fn(p) { print(p.title) });
titles = user.posts.map(fn(p) { p.title });

# Chained query — composes onto the seed `user_id == @__rel_fk` filter
published = user.posts.where("published = @p", { "p": true }).all;
n_pub = user.posts.where("published = @p", { "p": true }).count;

# Bulk delete — one REMOVE statement, no N+1
user.posts.delete_all;
user.posts.where("draft = @d", { "d": true }).delete_all;

# Bulk update — one UPDATE statement, no N+1
user.posts.where("draft = @d", { "d": true }).update_all({ "draft": false });

# Sort / paginate before materializing
recent = user.posts.order("created_at", "desc").limit(10).all;

Notes:

  • An owner that has not been saved yet (no _key) returns a QueryBuilder whose filter never matches — count is 0, delete_all / update_all are no-ops, and iteration yields nothing.
  • If the related model uses soft_delete, soft-deleted children are filtered out of the relation (consistent with Related.where(...)). Use the static Related.with_deleted() / Related.only_deleted() to query them explicitly.
  • belongs_to and has_one still return a single instance (or nil), not a QueryBuilder.

Batch Operations

Insert or update multiple records:

# Batch create
result = User.create_many([
  { "name": "Alice", "email": "alice@example.com" },
  { "name": "Bob", "email": "bob@example.com" },
  { "name": "Charlie", "email": "charlie@example.com" }
]);
# Returns: { "created": 3, "errors": [] }

# Upsert (insert or update by ID)
User.upsert("user123", { "name": "Updated Name" });
# Updates if exists, inserts with ID if not

# Batch delete via QueryBuilder — one AQL REMOVE for the whole match.
# Useful for clearing a relation without an N+1 loop:
User.where("doc.active == false").delete_all;
post.comments.delete_all;          # via has_many relation
Model.delete_all;                  # static — wipe the whole collection

# Batch update via QueryBuilder — one AQL UPDATE for the whole match.
# Patches every matching row; skips validations and callbacks:
User.where("doc.active == false").update_all({ "archived": true });
post.comments.where("draft = @d", { "d": true }).update_all({ "draft": false });

Batch Iteration (find_each / in_batches)

The operations above are bulk writes. On the read side, .all materialises every matching row as Soli values at once, so a job over a large collection is bounded by RAM rather than by anything you chose. .each is not an escape hatch — it materialises first, then iterates.

find_each walks the whole result set one record at a time, holding only one batch in memory:

# One batch of 1000 in memory at a time, however large the collection is.
User.find_each(fn(user) {
  user.recompute_score();
});

# Any filter chain composes.
User.where("doc.active == true").find_each(fn(user) {
  user.backfill_initials();
}, { "batch_size": 500 });

in_batches (alias find_in_batches) hands the block each batch as an array, which is what you want when the work itself is bulk:

Invoice.where("doc.status == @s", { "s": "pending" }).in_batches(fn(batch) {
  Mailer.deliver_reminders(batch);
}, { "batch_size": 200 });

batch_size defaults to 1000 and is capped at 10,000 — past that the batch is large enough to be the memory problem it exists to avoid.

Paging is by key, not by offset. Each batch adds FILTER doc._key > <last key of the previous batch> and sorts by _key ascending. LIMIT offset, n would degrade as the offset grows and — worse — skip or repeat rows when the collection is written to mid-scan, which is exactly what a long correction job does to the collection it is correcting. Deleting or updating records inside the block is therefore safe: the cursor is read before the block runs.

Because the ordering is fixed and the batch size is the limit, these are refused rather than silently ignored:

Rejected Why
.order(...) Batches are ordered by _key so the cursor advances
.limit(...) The batch size is the limit
.offset(...) Batches are positioned by key, not by offset
.pluck(...) Projected rows carry no _key to position the next batch
aggregates, .group_by, .time_bucket, .exists They return a value or reshaped rows, not records
.similar(...) Results are ordered by score, which key ordering would override
inside grouped(...) Each batch needs the previous batch's rows to build the next query, so the reads cannot be coalesced

A columnar model has no _key, so it has no batch iteration either — use the columnar query / aggregate surface instead.

Both spellings work from the class and from a chain: User.find_each(...) and User.where(...).find_each(...) are the same code path. Both return null; they are traversals, not projections.

An action or a script that calls find_each, in_batches or find_in_batches runs on the tree-walking interpreter. The cursor calls the block once per batch, and a block compiled for the VM cannot be called back from that walk. Class reflection (send, class_eval, methods, and respond_to? on the class) stays on the interpreter too: the VM does not implement it.

Coalescing Reads (grouped)

A controller action that reads several unrelated things pays one network round-trip per read:

@posts    = Post.all                          # round-trip 1
@accounts = Account.where({ active: true }).count   # round-trip 2
@tags     = Tag.all                           # round-trip 3

Wrap the reads in grouped(fn() { ... }) and they are deferred and combined into a single request — one LET … RETURN […] statement that computes every subquery server-side and returns them together:

grouped(fn() {
  @posts    = Post.all
  @accounts = Account.where({ active: true }).count
  @tags     = Tag.all
})
# one round-trip for all three

Inside the block each read returns a placeholder instead of hitting the database; the queries fire as one combined statement when the block ends, and the results are then materialised. After the block you use @posts, @accounts, and @tags exactly as before — iterate them, index them, read fields, serialise them to JSON.

Strictly speaking the binding stays a thin placeholder that resolves to its value on use, rather than being replaced by one. That is invisible in normal code, but it is why a new way of consuming a value can occasionally need teaching to unwrap it — if you ever see an error naming a type that the value plainly is (cannot iterate over array), that is the shape of the bug, and it is worth reporting.

What gets coalesced

Read queries are batched: all, where(...).all / .first / .count / .exists, the aggregates (sum / avg / min / max), find, find_by, and first_by. Writes are not — create, save, update, delete run immediately even inside the block (use transaction for atomic writes).

On Cloudflare D1

On a D1 connection (soli edge build) the reads inside the block go to D1 in one batch() — one round trip from the Worker for the whole block, where each read used to cost its own:

grouped(fn() {
  per_colo = CheckIn.group_by("colo").all
  @latest  = CheckIn.order("at", "desc").limit(10).all
})
# one round trip to D1 for both

The same reads are coalesced as on SoliDB, find / find_by / first_by included, and the results are the ones they get one by one. A read the batch cannot answer in advance — one that needs another read's rows, or a table's first read on a fresh isolate, which checks that the table exists — runs on its own after the batch. If D1 refuses the batch (a statement in it fails), every read runs on its own and reports its own error. Postgres, MySQL and SQLite run the reads of a grouped block one by one.

Reading a result inside the block (auto-flush)

If you read one of the deferred results before the block ends, the queries collected so far fire immediately (an "auto-flush"), then collection resumes for the rest:

grouped(fn() {
  @posts = Post.all
  log("loaded #{@posts.length} posts") if @posts.present?  # forces a flush here
  @tags = Tag.all                                          # batched separately
})

This always returns correct data; it just means you get more than one round-trip when you interleave reads. For maximum coalescing, do the reads first and use the results after the block.

Notes

  • find on a missing id still raises RecordNotFound (→ 404) — the error surfaces when the result is read or the block ends.
  • On SoliDB a combined query is all-or-nothing: if it fails, every read in the batch fails together. On D1 a refused batch falls back to one statement per read.
  • In interactive --dev the reads are not coalesced — each runs as its own query so the dev query log stays readable (you see the natural statements instead of one combined LET … RETURN […]). Coalescing is active in production, where the single round-trip is what matters.
  • soli test coalesces. The test server runs with --dev so the query log is populated, but specs exercise the production shape deliberately — otherwise the whole coalescing path would go untested and assert_query_count would measure dev's un-coalesced number instead of the round-trips production makes. A grouped action reports one query in a spec, not one per read.

Finding reads that should be grouped

Because grouped is for reads that each run once, an N+1 scan can never point you at them: it fingerprints by query template and only fires on a repeated one. Three unrelated reads are three distinct templates with a count of one each — invisible to assert_no_n_plus_one and to the dev bar's N+1 badge.

Two tools cover that blind spot:

  • The dev bar query panel shows a N READS · N ROUND-TRIPS advisory when a request issues three or more distinct one-off reads outside any grouped block. It is amber, not red: it is a suggestion, because reads that feed each other cannot share a round-trip.

  • assert_no_ungrouped_reads(response) fails a spec on the same condition:

    test("the dashboard loads in one round-trip", fn() {
      let response = get("/dashboard")
      assert_no_ungrouped_reads(response)
      assert_query_count(response, 1)
    })
    

Neither can prove the reads are independent — User.find(id) followed by a query on user._key is genuinely two round-trips. When the reads must be sequential, that advisory is a false positive and the assertion is the wrong tool for that action.

Transactions

Execute multiple operations atomically within a database transaction:

Using a Block (Recommended)

Model.transaction runs a block inside a single database transaction. Every document write inside the block — create, save, update, delete, and key lookups via find — participates automatically. The block commits when it returns normally and rolls back (re-raising the error) if it throws:

User.transaction do
  User.create({ "name": "Alice", "age": 30 })
  User.create({ "name": "Bob", "age": 25 })
end
# Both rows commit together. If either operation — or your own `throw` —
# raises, neither row is persisted.

The block's value is returned, so you can hand back what you computed:

order = Order.transaction do
  account = Account.find(account_id)   # `find` (key lookup) sees in-transaction state
  account.balance -= amount
  account.save()
  Order.create({ "account_id": account_id, "total": amount })
end

Nested transaction calls join the outer transaction — only the outermost begins and commits/rolls back (SolidB has no savepoints), so a throw anywhere inside undoes every write in the whole nest.

Query writes go through the transaction too. Besides document operations — create, save, update, delete — a write made by a query inside the block is staged on the transaction and commits or rolls back with it: .where(...).update_all(...), .where(...).delete_all, and an @sdbql{} INSERT, UPDATE, REMOVE or UPSERT. In 2.34 and earlier these ran outside the transaction: they applied at once and survived a rollback.

Reads inside a transaction see its own writes, on SoliDB 2.10.2 and later. Query-builder reads (where, all, first, count, find_by, first_by), aggregations and @sdbql{} reads run inside the transaction and see what the block wrote before them:

Account.transaction do
  Account.create({ "owner": owner_id, "balance": 0 })
  # Counts the row above.
  existing = Account.where({ "owner": owner_id }).count
end

A uniqueness validation runs this kind of read, so the second of two records that break a uniqueness rule in one block fails its validation. Full-text, vector and geo searches and graph traversals still read committed data.

On a SoliDB older than 2.10.2 those reads are answered from the state committed before the transaction: the count above leaves the new row out, and two records that break a uniqueness rule can both pass validation and both commit. There, read a row written earlier in the block with find (a key lookup), and enforce uniqueness with a unique index.

find inside a SoliDB transaction reads through the transaction, so it sees the transaction's own inserts, updates and deletes, on SoliDB servers that serve GET …/transaction/{id}/document/{collection}/{key} (after 2.2.1). On older servers it reads the committed document.

After the Commit

after_commit { … } runs a block once the data is durable: after the outermost commit inside a transaction (never if it rolls back), at once outside one. It is the place for side effects that must not happen for data that was never stored — a cache purge, a notification, a webhook:

Order.transaction do
  order.pay
  order.save
  after_commit { Channel.broadcast("orders", {"paid": order.number}) }
end

after_commit do … end works too. Domain events use the same moment for their block handlers.

Using AQL String

# Execute a single AQL statement transactionally (auto-commits).
# The string runs through the cursor endpoint with bind variables, so the
# query parameter is never interpolated into server-side JavaScript.
result = User.transaction("
  FOR u IN users FILTER u.active == true UPDATE u WITH { last_seen: DATE_NOW() } IN users
")

Using Transaction Object (Manual Control)

# Get transaction handle for manual control
tx = User.transaction();
tx.create({ name: "Alice" });
tx.create({ name: "Bob" });
tx.commit();
# Or tx.rollback() to undo all changes

All operations within the transaction either all succeed or all fail together.

class User < Model def posts() Post.where("doc.author_id == @id", { "id": this.id }) end end


## Custom Methods

Add custom methods to your models:

```soli
class User < Model
  def is_admin() -> Bool
    this.role == "admin"
  end

  def full_name() -> String
    this.first_name + " " + this.last_name
  end
end

# Usage
user = User.find("user123");
if user.is_admin()
  print("Welcome, admin " + user.full_name());
end

Query Generation (SDBQL)

Under the hood, Model methods generate SDBQL (SoliDB Query Language) queries:

Method Generated SDBQL
User.all FOR doc IN users RETURN doc
User.where("age >= @age", {"age": 18}) FOR doc IN users FILTER doc.age >= @age RETURN doc
.order("name", "asc") ... SORT doc.name ASC RETURN doc
.order("status").order("name", "desc") ... SORT doc.status ASC, doc.name DESC RETURN doc
.limit(10).offset(20) ... LIMIT 20, 10 RETURN doc
User.count RETURN COLLECTION_COUNT("users")
User.includes("posts") FOR doc IN users LET _rel_posts = (FOR rel IN posts FILTER rel.user_id == doc._key RETURN rel) RETURN MERGE(doc, {posts: _rel_posts})
User.includes("posts", "published = @p", {"p": true}) ... FILTER rel.user_id == doc._key AND rel.published == @p RETURN rel ...
User.includes({"posts": ["title"]}) ... RETURN {title: rel.title} ...
User.select("name", "email") FOR doc IN users RETURN {name: doc.name, email: doc.email, _key: doc._key}
User.join("posts") FOR doc IN users FILTER LENGTH(FOR rel IN posts FILTER rel.user_id == doc._key LIMIT 1 RETURN 1) > 0 RETURN doc

SDBQL uses:

  • FOR doc IN collection instead of SELECT * FROM
  • FILTER expression instead of WHERE
  • SORT doc.field ASC/DESC instead of ORDER BY
  • @variable syntax for bind parameters
  • LET subqueries + MERGE for eager loading

Complete Example

# app/models/user.sl
class User < Model
  has_many("posts")      # strings and symbols both work
  has_many(:posts)       # Ruby-style symbol shorthand
  has_one("profile")

  validates("email", { "presence": true, "uniqueness": true })
  validates("name", { "presence": true, "min_length": 2 })

  before_save("normalize_email")   # strings and symbols both work
  before_save(:normalize_email)    # Ruby-style symbol shorthand

  def normalize_email()
    this.email = this.email.downcase;
  end

  def is_adult() -> Bool
    this.age >= 18
  end
end

# app/models/post.sl
class Post < Model
  belongs_to("user")     # symbols also work
  has_many("comments")

  validates("title", { "presence": true, "min_length": 3 })
end

# app/models/profile.sl
class Profile < Model
  belongs_to("user")
end

# Usage in controller
class UsersController < Controller
  def index
    # Eager load posts and profiles to avoid N+1 queries
    @users = User.includes("posts", "profile").all
  end

  def show
    @user = User.includes("posts").find(params["id"])
  end

  def active
    # Find active users who have at least one post
    @users = User.join("posts")
      .where("active = @a", { "a": true })
      .order("created_at", "desc")
      .limit(10)
      .all
  end

  def create
    @user = User.create(permit(params, { "name": true, "email": true, "age": true }))
    return render("users/new", {}, { "status": 422 }) if @user._errors

    redirect("/users/" + @user._key)
  end
end

Testing Models

See the Testing Guide for comprehensive information on testing models.

Mock Database Queries

For integration tests without a real database, use Model.mock_query_result():

describe("User queries", fn()
  before_each(fn()
    User.clear_mocks()
  end)
  
  after_each(fn()
    User.clear_mocks()
  end)
  
  test("finds user by id", fn()
    User.mock_query_result(
      "FOR doc IN users FILTER doc._key == @key RETURN doc",
      [
        {
          "_key": "123",
          "_id": "default:users/123",
          "name": "Alice",
          "email": "alice@example.com"
        }
      ]
    )
    
    user = User.find("123")
    expect(user.name).to_equal("Alice")
  end)
  
  test("includes returns correct class for relations", fn()
    # Mock the parent query
    Contact.mock_query_result(
      "FOR doc IN contacts RETURN doc",
      [
        {
          "_key": "c1",
          "_id": "default:contacts/c1",
          "name": "Bob",
          "organisation_id": "default:organisations/o1"
        }
      ]
    )
    
    # Mock the included relation query
    Organisation.mock_query_result(
      "FOR doc IN organisations FILTER doc._key IN @keys RETURN doc",
      [
        {
          "_key": "o1",
          "_id": "default:organisations/o1",
          "name": "Acme Corp"
        }
      ]
    )
    
    contact = Contact.includes("organisation").first
    org = contact.organisation
    
    # Verify the relation has the correct class (not Contact)
    expect(org.class_name).to_equal("Organisation")
    expect(org.name).to_equal("Acme Corp")
  end)
end)

Key points:

  • Model.mock_query_result(query, results) - Register mock data for an AQL query
  • Model.clear_mocks() - Remove all registered mocks
  • Include relations require mocking both the parent and related queries
  • The _id field (e.g., "default:organisations/o1") determines the correct class for included documents
describe("User model", fn()
  test("creates user with valid data", fn()
    user = User.create({
      "email": "test@example.com",
      "name": "Test User"
    });
    expect(user._errors).to_equal(null);
    expect(user.email).to_equal("test@example.com");
  end)

  test("fails validation for invalid data", fn()
    user = User.create({ "email": "" });
    expect(user._errors).not_to_equal(null);
  end)

  test("finds users with where clause", fn()
    User.create({ "name": "Alice", "age": 25 });
    User.create({ "name": "Bob", "age": 17 });

    # where() returns QueryBuilder - chain .all to get results
    adults = User.where("doc.age >= @age", { "age": 18 }).all;
    expect(len(adults)).to_equal(1);
  end)
end)

Inspecting Queries (Dev Tool)

When the server runs with --dev, every query a request executes through the Model layer is captured into a per-request stack. Read it with the dev_queries() builtin and render it however you like — typically as a debug bar at the bottom of the page.

This covers every backend. On SoliDB the entries are AQL; on the SQL adapters they are the SQL actually sent, with the bind values numbered as $1 / ? appear in the statement. That means the dev bar's DB panel and timings, the N+1 badge, assert_no_n_plus_one, and soli test --fail-on-n1 work the same on Postgres, MySQL, and SQLite. Bind values longer than 200 characters are truncated (with their real length noted) so a large document cannot flood the panel.

dev_queries()

Returns an Array<Hash> of queries executed during the current request. The stack is cleared at the start of every request.

Key Type Description
query String The statement sent to the database (AQL on SoliDB, SQL on the SQL adapters)
bind_vars Hash or null The bind variables, or null if the query had none
duration_ms Float Wall-clock time the query took, in milliseconds
replica Bool Whether it ran on a read replica — only present when a connection has read replicas

In production (without --dev), dev_queries() always returns an empty array — the executor skips logging entirely, so there's no overhead.

Example: Controller

def index
  users = User.where("doc.active == true").all;
  posts = Post.includes("author").all;

  return render("users/index", {
    "users":   users,
    "posts":   posts,
    "queries": dev_queries()
  });
end

Example: Debug bar partial

<%# app/views/shared/_dev_bar.erb %>
<% if queries.length > 0 %>
  <div class="dev-bar">
    <h3><%= queries.length %> AQL queries</h3>
    <ol>
      <% for q in queries %>
        <li>
          <code><%= q["query"] %></code>
          <% if q["bind_vars"] != null %>
            <small>binds: <%= json_stringify(q["bind_vars"]) %></small>
          <% end %>
          <span><%= q["duration_ms"] %> ms</span>
        </li>
      <% end %>
    </ol>
  </div>
<% end %>

Coverage

Logged:

  • All Model operations (Model.all, .where(), .find(), .create(), .update(), .delete, .count, eager-loaded includes, soft-delete scopes, etc.)
  • Validation lookups (uniqueness)
  • HABTM join-table operations

Not logged in v1:

  • Direct Solidb(host, db).query(...) calls
  • Mocked queries registered via register_query_mock (they short-circuit before the executor)
  • Internal session storage queries that go through SoliDBClient directly

Best Practices

  1. Keep models simple - Just extend Model, no configuration needed
  2. Use meaningful class names - They become collection names automatically
  3. Add validations - Validate data before it reaches the database
  4. Use callbacks wisely - Keep them focused and avoid heavy operations
  5. Add custom methods - Encapsulate business logic in model methods
  6. Declare relationships - Use has_many, has_one, belongs_to for associations
  7. Use includes for eager loading - Avoid N+1 queries when accessing related data
  8. Use join for filtering - When you only need to filter by existence, not preload
  9. Use migrations in production - Define indexes and schema for optimal performance

Database Migrations

Note: Collections are now automatically created when you first use a Model. You can start using your models immediately without creating migrations.

However, for production applications, we recommend using migrations to:

  • Define indexes for better query performance
  • Set collection options (e.g., key options, sharding)
  • Document your schema
  • Handle schema changes over time

See the Migrations Guide for creating collections and indexes.