surorm
A typed Python ORM and query builder for SurrealDB, built on Pydantic v2.
Status: pre-release (
0.0.x). The API is not stable yet and breaking changes should be expected between versions — there is no compatibility shim between releases.
Features
- SurrealQL-native data types —
String,Int,Float,Decimal,Boolean,Datetime,Duration,Bytes,Array[T],Set[T],Object,Json,Option[T],Range,RecordID,RecordLink[T],UUID,File. Each type both declares a field's schema and knows how to serialize/deserialize itself to/from SurrealQL. - Pydantic-backed models —
Modelsubclasses are real Pydantic v2 models (validation, mutation,model_dump(), etc. all work as expected) with automatic dirty tracking. - Immutable, chainable query builder —
Select,Create,Update,Delete,Relate,Define*,Remove,Transactionmirror SurrealQL directly. Every builder method returns a new instance, so partially-built queries can be safely reused and extended. - Repository pattern — a small
Repository[Model]generic gives youget,list_,save,update, anddeletewithout hand-writing statements for common CRUD. - Graph relations — declare edge tables with
Relationand buildRELATE ... -> ... -> ...statements directly.
Installation
pip install surorm
Requires Python 3.12+ and SurrealDB 3.x (tested against 3.2), through the surrealdb Python
SDK 2.x. SurrealDB 2.x servers are not supported; see
Upgrading from SurrealDB 2.x.
Quickstart
Define a model
from surorm import Model
from surorm.data_model import String, Int, Option
class User(Model):
__table__ = 'user'
name: String
age: Int
bio: Option[String] = None
Model extends Pydantic's BaseModel, so instances are constructed and validated the normal way:
user = User(name='Alice', age=30)
user.age = 31
user.is_dirty() # True
user.changed_fields() # {'age': 31}
user.reset_snapshot() # call after persisting to clear the dirty state
id is declared automatically on every Model (id: RecordID | None = None) — None means the
record hasn't been created yet.
Connect and run queries
from surrealdb import AsyncWsSurrealConnection
from surorm import Session
async def main():
async with AsyncWsSurrealConnection('ws://localhost:8000/rpc') as connection:
await connection.signin({'username': 'root', 'password': 'root'})
await connection.use('my_namespace', 'my_database')
session = Session(connection)
result = await session.execute(
Select(User.name, User.age).from_(User).where(User.age > 18)
)
users = result.all() # -> list[User]
Session.execute() returns a Result, which exposes:
.all()— every row, deserialized into the model class if one was inferred from the statement.first()— the first row, orNone.dicts()— raw rows as plain dicts
A failing statement raises the SDK's ServerError (for multi-statement queries, the error of the
statement that actually failed). To run several execute() calls atomically, use a transaction;
it commits when the block exits and is cancelled if the block raises. Only the task that opened
the block (and tasks it starts inside it) runs in the transaction; other tasks sharing the session
are unaffected:
async with session.transaction():
await session.execute(Create(User).set(name='Alice'))
await session.execute(Update(User).set(age=31).where(User.name == 'Alice'))
Query builder
Statements are frozen dataclasses — every method call returns a new statement, leaving the original untouched:
from surorm.statements import Select, Create, Update, Delete
Select(User.name, User.age).from_(User).where(User.age > 18).sql()
# 'SELECT name, age FROM user WHERE age > 18'
Create(User).content({'name': 'Alice', 'age': 30}).sql()
# 'CREATE user CONTENT { name: "Alice", age: 30 }'
Update(User).set(age=31).where(User.id == 'user:alice').sql()
# 'UPDATE user SET age = 31 WHERE id = user:alice'
Delete(User).where(User.age < 18).sql()
# 'DELETE user WHERE age < 18'
.where() is additive — each call appends a condition (joined with AND), it never replaces the
existing clause:
Select(User.name).from_(User).where(User.age > 18).where(User.name == 'Alice').sql()
# 'SELECT name FROM user WHERE age > 18 AND name = "Alice"'
Conditions compose with &, |, and ~:
Select('*').from_(User).where((User.age > 18) & (User.name != 'Alice')).sql()
Other builders follow the same pattern: .limit(), .start(), .order_by(), .fetch(),
.merge(), .return_('after'). By default no RETURN clause is emitted — SurrealDB's own default
(the mutated record) applies unless you opt in explicitly.
Repository
For straightforward CRUD, wrap a model in a Repository:
from surorm import Repository
class UserRepository(Repository[User]):
pass
repo = UserRepository(session)
user = await repo.save(User(name='Alice', age=30)) # CREATE (id is None)
user = await repo.update(user, age=31) # UPDATE
users = await repo.list_(age=31) # SELECT * WHERE age = 31
await repo.delete(user) # DELETE
save() dispatches automatically: id is None issues a CREATE, otherwise it diffs
changed_fields() and issues an UPDATE with only the changed fields. upsert(instance) writes the
whole instance to its id with UPSERT, creating the record if it does not exist yet.
Relations and graph traversal
SurrealDB relations are edges: separate records that live on their own table and link two other
records together with RELATE. surorm supports them in three ways — declaring the edge table,
building/executing RELATE statements, and storing direct references with RecordLink.
Declaring an edge table
Subclass Relation instead of Model. in_ and out document the endpoint types; extra fields
become properties on the edge itself:
from surorm import Relation
from surorm.data_model import Int
class Likes(Relation):
__table__ = 'likes'
in_: User
out: Post
rating: Int
Optionally define the table's schema (FROM/TO constrain which tables the edge can connect):
from surorm.statements import DefineTable
DefineTable(Likes).type('relation', from_='user', to='post').sql()
# 'DEFINE TABLE likes SCHEMALESS TYPE RELATION FROM user TO post'
Creating a relation
Build a RELATE statement directly with Relate:
from surorm.statements import Relate
Relate('likes').from_(user.id).to(post.id).sql()
# 'RELATE user:alice->likes->post:1'
Relate('likes').from_(user.id).to(post.id).set(rating=5).return_('after').sql()
# 'RELATE user:alice->likes->post:1 SET rating = 5 RETURN AFTER'
.from_() and .to() each accept multiple records, which relates every source to every target:
Relate('likes').from_(alice.id, bob.id).to(post.id).sql()
# 'RELATE [user:alice,user:bob]->likes->post:1'
.set(**fields) and .content(dict) are mutually exclusive — whichever is called last wins.
Or use Repository.relate(), which takes model instances instead of raw IDs and executes the
statement immediately:
repo = UserRepository(session)
await repo.relate(user, Likes, post, rating=5)
# RELATE user:alice->likes->post:1 SET rating = 5 RETURN AFTER
Storing a direct reference with RecordLink
For a plain "points to one other record" field (as opposed to a many-to-many edge), use
RecordLink[T] on a regular Model:
from surorm.data_model import RecordLink, String
class Post(Model):
__table__ = 'post'
title: String
author: RecordLink[User]
author holds a RecordID at rest. Add .fetch() to a Select to have SurrealDB resolve it into
the full User record instead:
Select('*').from_(Post).fetch(Post.author).sql()
# 'SELECT * FROM post FETCH author'
Schema definitions
from surorm.statements import DefineTable, DefineField, DefineIndex
DefineTable(User).schemafull(True).sql()
# 'DEFINE TABLE user SCHEMAFULL TYPE NORMAL'
DefineField('name', String).on(User).sql()
# 'DEFINE FIELD name ON TABLE user TYPE string'
DefineIndex('user_name_idx').on('user').columns('name').unique().sql()
# 'DEFINE INDEX user_name_idx ON TABLE user COLUMNS name UNIQUE'
The builders cover the SurrealDB 3.x schema clauses:
from surorm.statements import DefineDatabase, Permissions, Variable
DefineDatabase('app').strict().sql()
# 'DEFINE DATABASE app STRICT'
DefineTable(Likes).type('relation', from_=User, to=Post, enforced=True).sql()
# 'DEFINE TABLE likes SCHEMALESS TYPE RELATION FROM user TO post ENFORCED'
DefineTable(Post).permissions(Permissions(select=True, update=Post.author == Variable('auth.id'))).sql()
# 'DEFINE TABLE post SCHEMALESS TYPE NORMAL PERMISSIONS FOR select FULL FOR update WHERE author = $auth.id'
DefineField('author', RecordLink[User]).on(Post).reference(on_delete='cascade').sql()
# 'DEFINE FIELD author ON TABLE post TYPE record<user> REFERENCE ON DELETE CASCADE'
DefineField('meta', 'object').on(Post).type('object', is_flexible=True).default('{}', always=True).sql()
# 'DEFINE FIELD meta ON TABLE post TYPE object FLEXIBLE DEFAULT ALWAYS {}'
DefineIndex('post_title').on(Post).columns('title').fulltext('english', highlights=True).sql()
# 'DEFINE INDEX post_title ON TABLE post COLUMNS title FULLTEXT ANALYZER english BM25 HIGHLIGHTS'
DefineIndex('post_count').on(Post).count().sql()
# 'DEFINE INDEX post_count ON TABLE post COUNT'
DefineIndex('post_embedding').on(Post).columns('embedding').hnsw(768, dist='cosine').concurrently().sql()
# 'DEFINE INDEX post_embedding ON TABLE post COLUMNS embedding HNSW DIMENSION 768 DIST COSINE CONCURRENTLY'
DefineTable also has .drop(), .changefeed(duration, include_original=...) and
.as_select(query) (views); DefineField has .readonly(), .assert_(expr), .permissions(...)
and .computed(expr); DefineIndex has .diskann(...) (SurrealDB 3.1+). Names that are SurrealQL
reserved words are escaped with backticks automatically.
Computed fields
A field can be derived from its siblings instead of being assigned directly, via
Field(computed=..., computed_in=...). The computed lambda receives the model class and builds
an expression from its other fields (cls.field_name); computed_in picks where that expression
is evaluated:
from surorm import Field
from surorm.data_model import String, Option
class User(Model):
__table__ = 'user'
first_name: String
last_name: String
full_name: Option[String] = Field(
computed=lambda cls: cls.first_name + ' ' + cls.last_name, computed_in='orm'
)
-
computed_in='orm'— no database column. The expression is spliced into theSELECTlist at query time, soSELECT *auto-expands to include it:Select('*').from_(User).sql() # 'SELECT *, first_name + " " + last_name as full_name FROM user'
-
computed_in='surreal'— computed by SurrealDB. Restate the same expression in a migration withDefineField(...).computed(...), which SurrealDB evaluates whenever the field is read (migrations are hand-authored, so nothing derives it from the field definition). Use.value(...)instead if the result should be stored on each write, e.g. to index it — SurrealDB cannot indexCOMPUTEDfields:from surorm.data_model import Float from surorm.operators import Multiply from surorm.statements import DefineField class OrderItem(Model): __table__ = 'order_item' price: Float quantity: Float line_total: Option[Float] = Field( computed=lambda cls: Multiply(cls.price, cls.quantity), computed_in='surreal' ) DefineField('line_total', Float).on(OrderItem).computed(Multiply(OrderItem.price, OrderItem.quantity)).sql() # 'DEFINE FIELD line_total ON TABLE order_item COMPUTED price * quantity TYPE float'
Class-level access renders context-sensitively — aliased in a top-level SELECT list, bare
everywhere else — so a computed field can be used in .where() / .order_by() without referencing
a not-yet-projected alias:
Select(User.name).from_(User).where(User.full_name == 'Alice Smith').sql()
# "SELECT name FROM user WHERE first_name + \" \" + last_name = \"Alice Smith\""
Computed fields are always declared as Option[T], are read-only on instances (assigning raises
AttributeError), and are excluded from dirty tracking and changed_fields(). They can reference
plain fields and other computed fields, with one rule: a surreal-computed field cannot reference
an orm-computed one, since the latter has no backing column to read from at the database level.
Embedded documents
Nested, inline documents (no table, no id, no dirty tracking) use EmbeddedModel:
from surorm.orm import EmbeddedModel
class Address(EmbeddedModel):
city: String
zip: String
class Customer(Model):
__table__ = 'customer'
name: String
address: Address
Upgrading from SurrealDB 2.x
surorm now generates SurrealQL for SurrealDB 3.x only. Migrate the database itself with SurrealDB's tooling (Studio's migration diagnostics on 2.6.1+, then a V3-compatible export and import), and rewrite any raw 2.x SurrealQL in your own migration files. In surorm itself:
-
Removed:
Like/NotLike(SurrealDB removed~/!~; usestring::similarity::jaro(...)orstring::distance::*),F.type.thing(nowF.type.record, renderingtype::record), andDefineIndex.search()(now.fulltext(), renderingFULLTEXT ANALYZER). -
Renamed output:
F.duration.from_daysrendersduration::from_days;FLEXIBLEis rendered after the type (TYPE object FLEXIBLE) and only for object types;F.random(strategy='uuid4')rendersrand::uuid::v4(). -
Noneis written asNONE(an absent value, whichoption<T>fields accept) instead ofNULL. That includesNoneitems of typed fields written to a model (Array[Option[T]], an optional field of an embedded model).Noneinside a plain dict or list, or a write to a table given by name, is still JSONnull. Use theNulltype to writeNULLexplicitly. -
Stricter server: SurrealDB 3.x errors on unknown fields of
SCHEMAFULLtables and on queries against tables that do not exist.Repository.create()rejects unknown and computed field names before sending the query. -
Record-id keys keep their Python type.
RecordID('post', 1)ispost:1(a number key);RecordID('post', '1')is nowpost:⟨1⟩(a string key), and so is any digit-led string such as'007'. UUIDs render asu"…", lists and dicts as array and object keys. IDs read back from the server keep the type they were stored with, soRepository.get(1)andget('1')are different records. Pass anintwhere you mean a number key. -
Errors are raised for every statement. Previously only the first statement of a query was checked, so a failing operation inside a migration's transaction went unnoticed and the migration was recorded as applied.
-
session.transaction()now really is a transaction; before, statements in the block ran outside it. -
Migrations are recorded in the same transaction that applies them (and the record is removed in the one that reverses them), so a migration is never applied without being recorded.
-
ORDER BYwith a direction applies it to every column (ORDER BY name DESC, age DESC). -
COMMENTtext is now quoted, andmodel_dump()keepsRecordID/Datetimevalues typed (they are only turned into strings inmode='json'), so record links and datetimes are stored with their real types instead of as strings. -
Collection fields of surorm types (
Array[Int],Set[String],Array[Address], ...) work as model fields, sets are written as SurrealQL sets, andDefineFieldtakes the annotation directly:DefineField('tags', Array[Option[String]])rendersTYPE array<option<string>>. -
Booleanfields dump asTrue/False(they were1/0).
Known limitations:
setvalues are not understood by thesurrealdbSDK 2.x, so surorm adds the missing decoder to it on import. Raw query results return sets as (ordered, de-duplicated) lists;Set[T]model fields turn them into Python sets.- Tables and fields named after reserved words (
select,delete, ...) are escaped correctly, but SurrealDB 3.2 still fails to write records to them. Prefer other names.
Development
poetry install
poetry run pytest
poetry run ruff check .
tests/integration runs against a real SurrealDB: it starts surreal start memory itself when the
surreal binary is on PATH, or uses the server at SURORM_TEST_URL (root/root). Without either,
those tests are skipped.
Releasing to PyPI
The version lives in pyproject.toml ([project].version). Releases use Poetry.
One-time setup (create an API token at https://pypi.org/manage/account/token/):
poetry config pypi-token.pypi <your-token>
Each release:
# 1. Make sure tests and lint pass on a clean master
poetry run pytest
poetry run ruff check .
# 2. Bump the version (patch: 0.0.25 -> 0.0.26; use minor/major for bigger releases)
poetry version patch
# 3. Commit and tag the bump
git commit -am "Bump version to $(poetry version -s)"
git tag "v$(poetry version -s)"
git push && git push --tags
# 4. Build and upload (publish only uploads dist/ files for the current version)
poetry build
poetry publish
poetry publish --build combines step 4 into one command. To check the result first, upload to
TestPyPI instead:
poetry config repositories.testpypi https://test.pypi.org/legacy/
poetry config pypi-token.testpypi <your-testpypi-token>
poetry publish --build -r testpypi
Metadata
Release files for surorm 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| surorm-0.1.0.tar.gz | 49.3 kB | Without provenance | Details for surorm-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| surorm-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for surorm-0.1.0-py3-none-any.whl |
Total release size: 120.0 kB
Release files / surorm-0.1.0.tar.gz
| Download URL | surorm-0.1.0.tar.gz |
|---|---|
| Size | 49.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
7b876dc0092ef4aa6bf58625c2f07bb52df98ccabecdaef196b7f8261f2bba31
|
|
BLAKE2b-256 checksum How to use checksums |
1208a84407f1f7b77eda79de33cad4545096297de6eeaf978944edf1626aa2c3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.5.1 CPython/3.14.8 Darwin/27.0.0
|
Release files / surorm-0.1.0-py3-none-any.whl
| Download URL | surorm-0.1.0-py3-none-any.whl |
|---|---|
| Size | 70.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f81a2a2b34949b32248dd6aa088b68584eaa6c0809ee9149366b5cef8a917b87
|
|
BLAKE2b-256 checksum How to use checksums |
60fb676a896cf3f6bc50fd087b90952a8c55aab4ce4b7152c397d1545b0225d4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.5.1 CPython/3.14.8 Darwin/27.0.0
|
Security for surorm 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.