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 aDynExprit nests anywhere an expression is taken — aSETvalue, aDEFINE PARAM/LETvalue, 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 aColumn<Post, String>. Generated by#[derive(SurrealRecord)]and used to build type-checked filters (.eq(...),.gt(...), …) and projections. - Column
Meta - Column
Set - Select-all (
*) column list. Generated by#[derive(SurrealRecord)]. - Create
CREATE <target> [CONTENT … | SET …] [RETURN …].- Define
Analyzer DEFINE ANALYZER <name> TOKENIZERS <toks> FILTERS <filters>— a full-text tokenizer + filter pipeline (referenced by aSEARCHindex).- Define
Event DEFINE EVENT <name> ON TABLE <table> WHEN <cond> THEN <block>— a trigger that fires onCREATE/UPDATE/DELETE.$event,$before,$after,$valueare available insidewhen/then.- Define
Function DEFINE FUNCTION fn::<name>(<args>) -> <ret> { <body> }— a user-defined SurrealQL function. Thefn::prefix is added automatically.- Define
Index - Builds a
DEFINE INDEXstatement — plain, composite,UNIQUE, full-text (SEARCH), or vector (HNSW/MTREE) indexes. - Define
Param 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
Columnaccessor is unavailable (e.g. record-link fields the derive doesn’t expose, ortenant.slugpaths). MirrorsColumn’s operators. - IfExpr
- A SurrealQL
IF <cond> THEN <expr> [ELSE IF <cond> THEN <expr>]… [ELSE <expr>] ENDexpression. As aDynExprit nests anywhere an expression is taken — aSETvalue, aSELECTprojection, aRETURN, or aWHERE. - Insert
- An
INSERT INTO <table> …builder. Records are serialized inline as object literals; rendering requiresT: serde::Serialize. - KnnExpr
- K-nearest-neighbour operator
<field> <|k[,opt]|> <vector>. With no option it uses the field’s vector index (<|k|>);optcarries either a brute-force distance metric (<|k,EUCLIDEAN|>) or an HNSW search size (<|k,40|>). Usually built via theVectorSearchbuilder. - LetVar
- Builds a
LET $var = <expr>statement for session-scoped variables. The variable is available in subsequent queries within the same session. - Literal
- Matches
Expr - Full-text match
<left> @@ <right>(SurrealQL’sMATCHES), requiring aSEARCHindex on the field. With a match reference it renders@{n}@, which letssearch::score(n)/search::highlight(…, n)pull relevance and highlights for that predicate. Usually built viaColumn::matchesor theSearchbuilder. - 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$nameand 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). - Record
Link - 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 -> bfor an edge typeE. For edges that carry their own fields, seeRelateEdge. - Relate
Edge - Build a RELATE query with edge content.
- Search
- A full-text
SELECTover aSEARCH-indexed field, reached fromTable::search. RendersSELECT … FROM <table> WHERE field @@ 'query', and — once a matchreferenceis set — can projectsearch::score(n)and order by relevance. - Select
- A
SELECTstatement builder: projections,WHERE,ORDER BY,LIMIT,START,FETCH,GROUP BY/GROUP ALL,count(), and the modifiersVALUE/OMIT/SPLIT/WITH/TIMEOUT/EXPLAIN. - Table
- Entry point to the query builder for a record type
T— the value returned by the derivedT::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, andcancelterminates withCANCEL TRANSACTIONto roll back explicitly. UnlikeBatch(a plain;-joined sequence), a transaction is atomic. - Update
- An
UPDATE/UPSERTbuilder:SET/MERGE/CONTENT, an optionalWHERE, andRETURN. Built viaTable::updateorTable::upsert. - Vector
Search - A vector K-nearest-neighbour
SELECT, reached fromTable::nearest. RendersSELECT … FROM <table> WHERE field <|k,ef|> [vector], optionally projecting / ordering by the computedvector::distance::knn(). By default it uses the field’s HNSW index withef = k; calldistancefor a brute-force scan orefto 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.
- Somnia
Error
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.
- Surreal
Edge - Marker for edge records.
- SurrealQL
- A Rust type that can be rendered as a SurrealQL literal (the right-hand side of
comparisons,
SETvalues, etc.). Implemented for the common scalar types,Option<T>,serde_json::Value, the geometry types, andThing<T>. - Surreal
Record - 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()). - Surreal
Schema - 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 reversibleup()/down()migrations.
Functions§
- col
- A bare column name as a projection:
name. - field
<raw> AS <alias>— verbatim expression with an alias.- ident
- Construct an
Identfor a field name.
Type Aliases§
- DynExpr
Box - A boxed, type-erased expression. Useful for returning a composed filter from a helper function (e.g. a shared tenant/owner predicate).
Derive Macros§
- Surreal
Edge - Derive
SurrealEdgefor an edge record, so theimpl SurrealEdge { fn edge_name() … }no longer needs to be hand-written. - Surreal
Record - Derive typed SurrealDB record metadata, column accessors, and schema DDL.