Skip to main content

Crate somnia

Crate somnia 

Source
Expand description

§somnia — Type-safe SurrealDB ORM

use somnia::{SomniaClient, SurrealRecord, Thing};
use serde::{Deserialize, Serialize};

#[derive(SurrealRecord, Serialize, Deserialize)]
#[table("asset")]
struct Asset {
    #[field(thing)]
    id: Thing<Asset>,
    name: String,
    #[field(name = "content_type")]
    content_type: Option<String>,
    file_size: Option<i64>,
}

async fn example() -> Result<(), SomniaError> {
    let db = SomniaClient::connect("ws://localhost:8000", "root", "root", "ns", "db").await?;

    // Typed column accessors are generated by the derive macro:
    let videos: Vec<Asset> = db.query(
        &Asset::table()
            .select(Asset::all())
            .filter(Asset::name().eq("video/mp4".to_string()))
            .filter(Asset::file_size().gt(1024 * 1024))
            .limit(10)
    ).await?;

    let db = db;
    Ok(())
}

Re-exports§

pub use auth::Credentials;
pub use connection::SomniaClient;
pub use live::Action;
pub use live::LiveQueryStream;
pub use live::Notification;
pub use migrate::MigrationStatus;
pub use migrate::Migrator;

Modules§

auth
Authentication credentials for SomniaClient.
connection
live
Live queries: a typed notification stream over LIVE SELECT.
migrate
Diesel-style migration runner for SurrealDB.

Structs§

Batch
Concatenates SurrealQL statements with ; separators. The store’s typical pattern is a mutation followed by a SELECT that re-projects the row.
Closure
A SurrealQL anonymous function (closure), e.g. |$x: int| -> int $x * 2. As a DynExpr it nests anywhere an expression is taken — a SET value, a DEFINE PARAM/LET value, or an argument to a higher-order function (array::map($xs, |$x: int| $x * 2)).
Column
A typed reference to a record field — e.g. Post::title() yields a Column<Post, String>. Generated by #[derive(SurrealRecord)] and used to build type-checked filters (.eq(...), .gt(...), …) and projections.
ColumnMeta
ColumnSet
Select-all (*) column list. Generated by #[derive(SurrealRecord)].
Create
CREATE <target> [CONTENT … | SET …] [RETURN …].
DefineAnalyzer
DEFINE ANALYZER <name> TOKENIZERS <toks> FILTERS <filters> — a full-text tokenizer + filter pipeline (referenced by a SEARCH index).
DefineEvent
DEFINE EVENT <name> ON TABLE <table> WHEN <cond> THEN <block> — a trigger that fires on CREATE/UPDATE/DELETE. $event, $before, $after, $value are available inside when/then.
DefineFunction
DEFINE FUNCTION fn::<name>(<args>) -> <ret> { <body> } — a user-defined SurrealQL function. The fn:: prefix is added automatically.
DefineIndex
Builds a DEFINE INDEX statement — plain, composite, UNIQUE, full-text (SEARCH), or vector (HNSW/MTREE) indexes.
DefineParam
DEFINE PARAM $<name> VALUE <value> — a database-scoped parameter. The $ prefix is added automatically.
Delete
A DELETE <target> [WHERE …] [RETURN …] builder.
For
Builds a FOR $<var> IN <array> { <body> } loop. The loop variable $<var> is bound inside the body; push one or more statements as the body.
Func
A SurrealQL function call name(args…).
Grouped
Wraps an expression in parentheses: (<expr>). Use to force grouping/precedence.
Ident
An untyped identifier (column or field path) for building filter expressions where a typed Column accessor is unavailable (e.g. record-link fields the derive doesn’t expose, or tenant.slug paths). Mirrors Column’s operators.
IfExpr
A SurrealQL IF <cond> THEN <expr> [ELSE IF <cond> THEN <expr>]… [ELSE <expr>] END expression. As a DynExpr it nests anywhere an expression is taken — a SET value, a SELECT projection, a RETURN, or a WHERE.
Insert
An INSERT INTO <table> … builder. Records are serialized inline as object literals; rendering requires T: serde::Serialize.
KnnExpr
K-nearest-neighbour operator <field> <|k[,opt]|> <vector>. With no option it uses the field’s vector index (<|k|>); opt carries either a brute-force distance metric (<|k,EUCLIDEAN|>) or an HNSW search size (<|k,40|>). Usually built via the VectorSearch builder.
LetVar
Builds a LET $var = <expr> statement for session-scoped variables. The variable is available in subsequent queries within the same session.
Literal
MatchesExpr
Full-text match <left> @@ <right> (SurrealQL’s MATCHES), requiring a SEARCH index on the field. With a match reference it renders @{n}@, which lets search::score(n) / search::highlight(…, n) pull relevance and highlights for that predicate. Usually built via Column::matches or the Search builder.
NoneLit
SurrealDB’s NONE.
Param
A named SurrealQL parameter $name. In inline mode renders as a literal; in param mode (to_surrealql_with_params) renders as $name and collects the value. Use when you want to reference the same value in multiple places or give params meaningful names.
Path
A graph-traversal expression — e.g. ->wrote->post, <-wrote<-user, or a multi-hop chain with an optional .field/.* accessor at the end.
Projection
A single SELECT-list entry. Either a bare expression or <expr> AS <alias>.
Raw
A verbatim SurrealQL fragment. Use for expressions somnia does not model as typed nodes (e.g. IF x != NONE THEN … END, lambdas, tenant.slug).
RecordLink
Builds a SurrealDB record link type::record('table', <key>). The key is any literal value (typically the bare UUID/string id of the related row).
Relate
Builds a graph edge statement RELATE a -> edge -> b for an edge type E. For edges that carry their own fields, see RelateEdge.
RelateEdge
Build a RELATE query with edge content.
Search
A full-text SELECT over a SEARCH-indexed field, reached from Table::search. Renders SELECT … FROM <table> WHERE field @@ 'query', and — once a match reference is set — can project search::score(n) and order by relevance.
Select
A SELECT statement builder: projections, WHERE, ORDER BY, LIMIT, START, FETCH, GROUP BY/GROUP ALL, count(), and the modifiers VALUE/OMIT/SPLIT/WITH/TIMEOUT/EXPLAIN.
Table
Entry point to the query builder for a record type T — the value returned by the derived T::table(). Each method starts a statement builder.
Thing
A typed SurrealDB record ID. Thing<Asset>asset:xyz.
Transaction
Wraps statements in a SurrealDB transaction — BEGIN TRANSACTION; … ; COMMIT TRANSACTION;. Either every statement applies or none do: SurrealDB rolls the whole block back if any statement errors, and cancel terminates with CANCEL TRANSACTION to roll back explicitly. Unlike Batch (a plain ;-joined sequence), a transaction is atomic.
Update
An UPDATE/UPSERT builder: SET / MERGE / CONTENT, an optional WHERE, and RETURN. Built via Table::update or Table::upsert.
VectorSearch
A vector K-nearest-neighbour SELECT, reached from Table::nearest. Renders SELECT … FROM <table> WHERE field <|k,ef|> [vector], optionally projecting / ordering by the computed vector::distance::knn(). By default it uses the field’s HNSW index with ef = k; call distance for a brute-force scan or ef to tune recall.

Enums§

Key
The key part of a SurrealDB record ID (the part after table:).
Order
Sort direction for ORDER BY.
Returning
How a mutating statement should return its affected rows.
SomniaError

Traits§

DynExpr
A type-erased expression that can render itself into a SurrealQL buffer. Implemented by every expression node; the common currency of the builder.
SurrealEdge
Marker for edge records.
SurrealQL
A Rust type that can be rendered as a SurrealQL literal (the right-hand side of comparisons, SET values, etc.). Implemented for the common scalar types, Option<T>, serde_json::Value, the geometry types, and Thing<T>.
SurrealRecord
A type that maps to a SurrealDB table. Normally implemented by #[derive(SurrealRecord)], which also generates the typed column accessors and the query-builder entry points (table(), all()).
SurrealSchema
Schema definition for a record type — lets the Rust type be the single source of truth for the SurrealDB schema. Implemented by #[derive(SurrealRecord)]; emits idempotent DDL and reversible up() / down() migrations.

Functions§

col
A bare column name as a projection: name.
field
<raw> AS <alias> — verbatim expression with an alias.
ident
Construct an Ident for a field name.

Type Aliases§

DynExprBox
A boxed, type-erased expression. Useful for returning a composed filter from a helper function (e.g. a shared tenant/owner predicate).

Derive Macros§

SurrealEdge
Derive SurrealEdge for an edge record, so the impl SurrealEdge { fn edge_name() … } no longer needs to be hand-written.
SurrealRecord
Derive typed SurrealDB record metadata, column accessors, and schema DDL.