API Reference

This section contains the complete API documentation for QuantumEngine.

Core Classes

QuantumEngine: Multi-backend Object-Document Mapper with both sync and async support

class quantumengine.SurrealEngine(connection)[source]

Bases: object

Dynamic database accessor.

This class provides dynamic access to tables in the database without requiring predefined schemas. It allows accessing tables as attributes of the instance.

connection

The database connection to use for queries

is_async

Whether the connection is asynchronous

__getattr__(name)[source]

Get a table accessor for the given table name.

This method allows accessing tables as attributes of the instance.

Parameters:

name (str) – The name of the table

Returns:

A SchemalessTable for accessing the table

Return type:

SchemalessTable

__init__(connection)[source]

Initialize a new SurrealEngine.

Parameters:

connection (Any) – The database connection to use for queries

class quantumengine.SurrealEngineAsyncConnection(url=None, namespace=None, database=None, username=None, password=None, name=None, make_default=False, use_pool=False, pool_size=10, max_idle_time=60, connect_timeout=30, operation_timeout=30, retry_limit=3, retry_delay=1.0, retry_backoff=2.0, validate_on_borrow=True)[source]

Bases: object

Asynchronous connection manager for SurrealDB.

This class manages the asynchronous connection to a SurrealDB database, providing methods for connecting, disconnecting, and executing transactions. It also provides access to the database through the db property.

url

The URL of the SurrealDB server

namespace

The namespace to use

database

The database to use

username

The username for authentication

password

The password for authentication

client

The SurrealDB async client instance or ConnectionPoolClient

use_pool

Whether to use a connection pool

pool

The connection pool if use_pool is True

pool_size

The size of the connection pool

max_idle_time

Maximum time in seconds a connection can be idle before being closed

async __aenter__()[source]

Enter the async context manager.

Returns:

The connection instance

Return type:

SurrealEngineAsyncConnection

async __aexit__(exc_type, exc_val, exc_tb)[source]

Exit the async context manager.

Parameters:
  • exc_type (Type[BaseException] | None) – The exception type, if an exception was raised

  • exc_val (BaseException | None) – The exception value, if an exception was raised

  • exc_tb (Any | None) – The exception traceback, if an exception was raised

__init__(url=None, namespace=None, database=None, username=None, password=None, name=None, make_default=False, use_pool=False, pool_size=10, max_idle_time=60, connect_timeout=30, operation_timeout=30, retry_limit=3, retry_delay=1.0, retry_backoff=2.0, validate_on_borrow=True)[source]

Initialize a new SurrealEngineAsyncConnection.

Parameters:
  • url (str | None) – The URL of the SurrealDB server

  • namespace (str | None) – The namespace to use

  • database (str | None) – The database to use

  • username (str | None) – The username for authentication

  • password (str | None) – The password for authentication

  • name (str | None) – The name to register this connection under in the registry

  • make_default (bool) – Whether to set this connection as the default

  • use_pool (bool) – Whether to use a connection pool

  • pool_size (int) – The size of the connection pool

  • max_idle_time (int) – Maximum time in seconds a connection can be idle before being closed

  • connect_timeout (int) – Timeout in seconds for establishing a connection

  • operation_timeout (int) – Timeout in seconds for operations

  • retry_limit (int) – Maximum number of retries for failed operations

  • retry_delay (float) – Initial delay in seconds between retries

  • retry_backoff (float) – Backoff multiplier for retry delay

  • validate_on_borrow (bool) – Whether to validate connections when borrowing from the pool

async connect()[source]

Connect to the database.

This method creates a new client if one doesn’t exist. If use_pool is True, it creates a connection pool and a ConnectionPoolClient. Otherwise, it creates a direct connection to the database.

Returns:

The SurrealDB client instance or ConnectionPoolClient

Return type:

Any

property db: SurrealEngine

Get dynamic table accessor.

Returns:

A SurrealEngine instance for accessing tables dynamically

async disconnect()[source]

Disconnect from the database.

This method closes the client connection if one exists. If use_pool is True, it closes the connection pool.

async transaction(coroutines)[source]

Execute multiple operations in a transaction.

This method executes a list of coroutines within a transaction, committing the transaction if all operations succeed or canceling it if any operation fails.

Parameters:

coroutines (list) – List of coroutines to execute in the transaction

Returns:

List of results from the coroutines

Raises:

Exception – If any operation in the transaction fails

Return type:

list

class quantumengine.SurrealEngineSyncConnection(url=None, namespace=None, database=None, username=None, password=None, name=None, make_default=False)[source]

Bases: object

Synchronous connection manager for SurrealDB.

This class manages the synchronous connection to a SurrealDB database, providing methods for connecting, disconnecting, and executing transactions. It also provides access to the database through the db property.

url

The URL of the SurrealDB server

namespace

The namespace to use

database

The database to use

username

The username for authentication

password

The password for authentication

client

The SurrealDB sync client instance

__enter__()[source]

Enter the sync context manager.

Returns:

The connection instance

Return type:

SurrealEngineSyncConnection

__exit__(exc_type, exc_val, exc_tb)[source]

Exit the sync context manager.

Parameters:
  • exc_type (Type[BaseException] | None) – The exception type, if an exception was raised

  • exc_val (BaseException | None) – The exception value, if an exception was raised

  • exc_tb (Any | None) – The exception traceback, if an exception was raised

__init__(url=None, namespace=None, database=None, username=None, password=None, name=None, make_default=False)[source]

Initialize a new SurrealEngineSyncConnection.

Parameters:
  • url (str | None) – The URL of the SurrealDB server

  • namespace (str | None) – The namespace to use

  • database (str | None) – The database to use

  • username (str | None) – The username for authentication

  • password (str | None) – The password for authentication

  • name (str | None) – The name to register this connection under in the registry

  • make_default (bool) – Whether to set this connection as the default

connect()[source]

Connect to the database.

This method creates a new client if one doesn’t exist, signs in if credentials are provided, and sets the namespace and database.

Returns:

The SurrealDB client instance

Return type:

Any

property db: SurrealEngine

Get dynamic table accessor.

Returns:

A SurrealEngine instance for accessing tables dynamically

disconnect()[source]

Disconnect from the database.

This method closes the client connection if one exists.

transaction(callables)[source]

Execute multiple operations in a transaction.

This method executes a list of callables within a transaction, committing the transaction if all operations succeed or canceling it if any operation fails.

Parameters:

callables (list) – List of callables to execute in the transaction

Returns:

List of results from the callables

Raises:

Exception – If any operation in the transaction fails

Return type:

list

quantumengine.SurrealEngineConnection

alias of SurrealEngineAsyncConnection

class quantumengine.BaseSurrealEngineConnection(*args, **kwargs)[source]

Bases: Protocol

Protocol defining the interface for SurrealDB connections.

This protocol defines the common interface that both synchronous and asynchronous connections must implement.

__init__(*args, **kwargs)
property db: SurrealEngine

Get dynamic table accessor.

url: str | None
namespace: str | None
database: str | None
username: str | None
password: str | None
client: Any
quantumengine.create_connection(url=None, namespace=None, database=None, username=None, password=None, name=None, make_default=False, async_mode=True, use_pool=False, pool_size=10, max_idle_time=60, connect_timeout=30, operation_timeout=30, retry_limit=3, retry_delay=1.0, retry_backoff=2.0, validate_on_borrow=True, auto_connect=False, backend='surrealdb', **backend_kwargs)[source]

Factory function to create a connection for the specified backend.

Parameters:
  • url (str | None) – The URL of the database server (for SurrealDB) or host (for ClickHouse)

  • namespace (str | None) – The namespace to use (SurrealDB only)

  • database (str | None) – The database to use

  • username (str | None) – The username for authentication

  • password (str | None) – The password for authentication

  • name (str | None) – The name to register this connection under in the registry

  • make_default (bool) – Whether to set this connection as the default

  • async_mode (bool) – Whether to create an async or sync connection (SurrealDB only)

  • use_pool (bool) – Whether to use a connection pool (SurrealDB async_mode only)

  • pool_size (int) – The size of the connection pool

  • max_idle_time (int) – Maximum time in seconds a connection can be idle before being closed

  • connect_timeout (int) – Timeout in seconds for establishing a connection

  • operation_timeout (int) – Timeout in seconds for operations

  • retry_limit (int) – Maximum number of retries for failed operations

  • retry_delay (float) – Initial delay in seconds between retries

  • retry_backoff (float) – Backoff multiplier for retry delay

  • validate_on_borrow (bool) – Whether to validate connections when borrowing from the pool

  • auto_connect (bool) – Whether to automatically connect the connection

  • backend (str) – The backend type (‘surrealdb’, ‘clickhouse’, etc.)

  • **backend_kwargs – Additional backend-specific connection parameters

Returns:

A connection instance for the specified backend

Return type:

Any

Examples

SurrealDB connection (default):

surrealdb_conn = create_connection(
    url="ws://localhost:8000/rpc",
    namespace="test", database="test",
    username="root", password="root"
)

ClickHouse connection:

clickhouse_conn = create_connection(
    url="localhost", database="default",
    username="default", password="",
    backend="clickhouse", port=8123
)
class quantumengine.ConnectionRegistry[source]

Bases: object

Global connection registry for multi-backend support.

This class provides a centralized registry for managing database connections for multiple backends (SurrealDB, ClickHouse, etc.). It allows setting default connections per backend and registering named connections that can be retrieved throughout the application.

_default_async_connection

The default async connection to use when none is specified (legacy)

Type:

quantumengine.connection.SurrealEngineAsyncConnection | None

_default_sync_connection

The default sync connection to use when none is specified (legacy)

Type:

quantumengine.connection.SurrealEngineSyncConnection | None

_async_connections

Dictionary of named async connections (legacy)

Type:

Dict[str, quantumengine.connection.SurrealEngineAsyncConnection]

_sync_connections

Dictionary of named sync connections (legacy)

Type:

Dict[str, quantumengine.connection.SurrealEngineSyncConnection]

_backend_connections

Dictionary of backend -> {connection_name -> connection}

Type:

Dict[str, Dict[str, Any]]

_default_backend_connections

Dictionary of backend -> default_connection

Type:

Dict[str, Any]

classmethod add_async_connection(name, connection)[source]

Add a named async connection to the registry.

Parameters:
classmethod add_connection(name, connection)[source]

Add a named connection to the registry based on its type.

Parameters:
classmethod add_sync_connection(name, connection)[source]

Add a named sync connection to the registry.

Parameters:
classmethod get_async_connection(name)[source]

Get a named async connection from the registry.

Parameters:

name (str) – The name of the async connection to retrieve

Returns:

The requested async connection

Raises:

KeyError – If no async connection with the given name exists

Return type:

SurrealEngineAsyncConnection

classmethod get_connection(name, async_mode=True)[source]

Get a named connection from the registry based on the mode.

Parameters:
  • name (str) – The name of the connection to retrieve

  • async_mode (bool) – Whether to get an async or sync connection

Returns:

The requested connection of the requested type

Raises:

KeyError – If no connection of the requested type with the given name exists

Return type:

SurrealEngineAsyncConnection | SurrealEngineSyncConnection

classmethod get_connection_by_backend(name, backend='surrealdb')[source]

Get a named connection for a specific backend.

Parameters:
  • name (str) – The name of the connection

  • backend (str) – The backend type

Returns:

The requested connection

Raises:

ValueError – If the connection is not found

Return type:

Any

classmethod get_default_async_connection()[source]

Get the default async connection.

Returns:

The default async connection

Raises:

RuntimeError – If no default async connection has been set

Return type:

SurrealEngineAsyncConnection

classmethod get_default_connection(backend='surrealdb')[source]

Get the default connection for a backend.

Parameters:

backend (str) – The backend type

Returns:

The default connection for the backend

Raises:

ValueError – If no default connection is set for the backend

Return type:

Any

classmethod get_default_sync_connection()[source]

Get the default sync connection.

Returns:

The default sync connection

Raises:

RuntimeError – If no default sync connection has been set

Return type:

SurrealEngineSyncConnection

classmethod get_sync_connection(name)[source]

Get a named sync connection from the registry.

Parameters:

name (str) – The name of the sync connection to retrieve

Returns:

The requested sync connection

Raises:

KeyError – If no sync connection with the given name exists

Return type:

SurrealEngineSyncConnection

classmethod list_backends()[source]

List all registered backends.

Returns:

List of backend names

Return type:

List[str]

classmethod list_connections(backend)[source]

List all connections for a backend.

Parameters:

backend (str) – The backend type

Returns:

List of connection names for the backend

Return type:

List[str]

classmethod register(name, connection, backend='surrealdb')[source]

Register a connection for a specific backend.

Parameters:
  • name (str) – The name to register the connection under

  • connection (Any) – The connection object

  • backend (str) – The backend type (‘surrealdb’, ‘clickhouse’, etc.)

classmethod set_default(backend, connection_name)[source]

Set the default connection for a backend.

Parameters:
  • backend (str) – The backend type

  • connection_name (str) – The name of the connection to set as default

classmethod set_default_async_connection(connection)[source]

Set the default async connection.

Parameters:

connection (SurrealEngineAsyncConnection) – The async connection to set as default

classmethod set_default_connection(connection)[source]

Set the default connection based on its type.

Parameters:

connection (SurrealEngineAsyncConnection | SurrealEngineSyncConnection) – The connection to set as default

classmethod set_default_sync_connection(connection)[source]

Set the default sync connection.

Parameters:

connection (SurrealEngineSyncConnection) – The sync connection to set as default

class quantumengine.Document(**values)[source]

Bases: object

Base class for all documents.

This class provides the foundation for all document models in the ORM. It includes methods for CRUD operations, validation, and serialization.

The Document class uses a Meta inner class to configure behavior:

Example

>>> class User(Document):
...     username = StringField(required=True)
...     email = EmailField(required=True)
...     age = IntField(min_value=0)
...
...     class Meta:
...         collection = "users"          # Collection/table name
...         backend = "surrealdb"         # Backend to use
...         indexes = [                   # Index definitions
...             {"name": "idx_username", "fields": ["username"], "unique": True},
...             {"name": "idx_email", "fields": ["email"], "unique": True}
...         ]
...         strict = True                 # Strict field validation
Meta Options:
collection (str): The name of the collection/table in the database.

Defaults to the lowercase class name.

table_name (str): Alternative to ‘collection’, used by some backends.

Defaults to the value of ‘collection’.

backend (str): The database backend to use (“surrealdb” or “clickhouse”).

Defaults to “surrealdb”.

indexes (list): List of index definitions. Each index is a dict with:
  • name (str): Index name

  • fields (list): List of field names to index

  • unique (bool): Whether the index is unique (optional)

  • type (str): Index type for backend-specific indexes (optional)

id_field (str): Name of the ID field. Defaults to “id”.

strict (bool): Whether to raise errors for unknown fields.

Defaults to True.

objects

QuerySetDescriptor for querying documents of this class

_data

Dictionary of field values

_changed_fields

List of field names that have been changed

_fields

Dictionary of fields for this document class (class attribute)

_fields_ordered

List of field names in order of definition (class attribute)

_meta

Dictionary of metadata for this document class (class attribute)

__getattr__(name)[source]

Get a field value.

This method is called when an attribute is not found through normal lookup. It checks if the attribute is a field and returns its value if it is.

Parameters:

name (str) – Name of the attribute to get

Returns:

The field value

Raises:

AttributeError – If the attribute is not a field

Return type:

Any

__init__(**values)[source]

Initialize a new Document.

Parameters:

**values (Any) – Field values to set on the document

Raises:

AttributeError – If strict mode is enabled and an unknown field is provided

__setattr__(name, value)[source]

Set a field value.

This method is called when an attribute is set. It checks if the attribute is a field and validates the value if it is.

Parameters:
  • name (str) – Name of the attribute to set

  • value (Any) – Value to set

async classmethod bulk_create(documents, batch_size=1000, validate=True, return_documents=True, connection=None)[source]

Create multiple documents in batches.

Parameters:
  • documents (List[Any]) – List of documents to create

  • batch_size (int) – Number of documents per batch

  • validate (bool) – Whether to validate documents before creation

  • return_documents (bool) – Whether to return created documents

Returns:

List of created documents if return_documents=True, else count of created documents

Return type:

List[Any] | int

classmethod bulk_create_sync(documents, batch_size=1000, validate=True, return_documents=True, connection=None)[source]

Create multiple documents in a single operation synchronously.

This method creates multiple documents in a single operation, processing them in batches for better performance. It can optionally validate the documents and return the created documents.

Parameters:
  • documents (List[Any]) – List of Document instances to create

  • batch_size (int) – Number of documents per batch (default: 1000)

  • validate (bool) – Whether to validate documents (default: True)

  • return_documents (bool) – Whether to return created documents (default: True)

  • connection (Any | None) – The database connection to use (optional)

Returns:

List of created documents with their IDs set if return_documents=True, otherwise returns the count of created documents

Return type:

List[Any] | int

async classmethod create_index(index_name, fields, unique=False, search=False, analyzer=None, comment=None, connection=None)[source]

Create an index on the document’s collection asynchronously.

Parameters:
  • index_name (str) – Name of the index

  • fields (List[str]) – List of field names to include in the index

  • unique (bool) – Whether the index should enforce uniqueness

  • search (bool) – Whether the index is a search index

  • analyzer (str | None) – Analyzer to use for search indexes

  • comment (str | None) – Optional comment for the index

  • connection (Any | None) – Optional connection to use

classmethod create_index_sync(index_name, fields, unique=False, search=False, analyzer=None, comment=None, connection=None)[source]

Create an index on the document’s collection synchronously.

Parameters:
  • index_name (str) – Name of the index

  • fields (List[str]) – List of field names to include in the index

  • unique (bool) – Whether the index should enforce uniqueness

  • search (bool) – Whether the index is a search index

  • analyzer (str | None) – Analyzer to use for search indexes

  • comment (str | None) – Optional comment for the index

  • connection (Any | None) – Optional connection to use

async classmethod create_indexes(connection=None)[source]

Create all indexes defined for this document class asynchronously.

This method creates indexes defined in the Meta class and also creates indexes for fields marked as indexed.

Parameters:

connection (Any | None) – Optional connection to use

classmethod create_indexes_sync(connection=None)[source]

Create all indexes defined for this document class synchronously.

This method creates indexes defined in the Meta class and also creates indexes for fields marked as indexed.

Parameters:

connection (Any | None) – Optional connection to use

classmethod create_materialized_view(name, query, refresh_interval=None, aggregations=None, select_fields=None, **kwargs)[source]

Create a materialized view based on a query.

This method creates a materialized view in SurrealDB based on a query. Materialized views are precomputed views of data that can be used to improve query performance for frequently accessed aggregated data.

Parameters:
  • name (str) – The name of the materialized view

  • query (QuerySet) – The query that defines the materialized view

  • refresh_interval (str) – The interval at which the view is refreshed (e.g., “1h”, “30m”)

  • aggregations – Dictionary of field names and aggregation functions

  • select_fields – List of fields to select (if None, selects all fields)

  • **kwargs – Additional keyword arguments to pass to the MaterializedView constructor

Returns:

A MaterializedView instance

async classmethod create_table(connection=None, schemafull=True)[source]

Create the table for this document class asynchronously.

Parameters:
  • connection (Any | None) – Optional connection to use

  • schemafull (bool) – Whether to create a SCHEMAFULL table (default: True)

classmethod create_table_sync(connection=None, schemafull=True)[source]

Create the table for this document class synchronously.

async delete(connection=None)[source]

Delete the document from the database asynchronously.

This method deletes the document from the database.

Parameters:

connection (Any | None) – The database connection to use (optional)

Returns:

True if the document was deleted

Raises:

ValueError – If the document doesn’t have an ID

Return type:

bool

async delete_relation_to(relation_name, target_instance=None, connection=None)[source]

Delete a relation to another document asynchronously.

This method deletes a relation from this document to another document. If target_instance is not provided, it deletes all relations with the specified name from this document.

Parameters:
  • relation_name (str) – Name of the relation

  • target_instance (Any | None) – The document instance the relation is to (optional)

  • connection (Any | None) – The database connection to use (optional)

Returns:

Number of deleted relations

Return type:

int

delete_relation_to_sync(relation_name, target_instance=None, connection=None)[source]

Delete a relation to another document synchronously.

This method deletes a relation from this document to another document. If target_instance is not provided, it deletes all relations with the specified name from this document.

Parameters:
  • relation_name (str) – Name of the relation

  • target_instance (Any | None) – The document instance the relation is to (optional)

  • connection (Any | None) – The database connection to use (optional)

Returns:

Number of deleted relations

Return type:

int

delete_sync(connection=None)[source]

Delete the document from the database synchronously.

This method deletes the document from the database.

Parameters:

connection (Any | None) – The database connection to use (optional)

Returns:

True if the document was deleted

Raises:

ValueError – If the document doesn’t have an ID

Return type:

bool

async classmethod drop_table(connection=None, if_exists=True)[source]

Drop the table for this document class asynchronously.

Parameters:
  • connection (Any | None) – Optional connection to use

  • if_exists (bool) – Whether to use IF EXISTS clause to avoid errors if table doesn’t exist

classmethod drop_table_sync(connection=None, if_exists=True)[source]

Drop the table for this document class synchronously.

Parameters:
  • connection (Any | None) – Optional connection to use

  • if_exists (bool) – Whether to use IF EXISTS clause to avoid errors if table doesn’t exist

async fetch_relation(relation_name, target_document=None, relation_document=None, connection=None, **filters)[source]

Fetch related documents asynchronously.

This method fetches documents related to this document through the specified relation.

Parameters:
  • relation_name (str) – Name of the relation

  • target_document (Type | None) – The document class of the target documents (optional)

  • relation_document (Type | None) – The document class representing the relation (optional)

  • connection (Any | None) – The database connection to use (optional)

  • **filters (Any) – Filters to apply to the related documents

Returns:

List of related documents, relation documents, or relation records

Return type:

List[Any]

fetch_relation_sync(relation_name, target_document=None, relation_document=None, connection=None, **filters)[source]

Fetch related documents synchronously.

This method fetches documents related to this document through the specified relation.

Parameters:
  • relation_name (str) – Name of the relation

  • target_document (Type | None) – The document class of the target documents (optional)

  • relation_document (Type | None) – The document class representing the relation (optional)

  • connection (Any | None) – The database connection to use (optional)

  • **filters (Any) – Filters to apply to the related documents

Returns:

List of related documents, relation documents, or relation records

Return type:

List[Any]

classmethod from_db(data, dereference=False)[source]

Create a document instance from database data.

Parameters:
  • data (Any) – Data from the database (dictionary, string, RecordID, etc.)

  • dereference (bool) – Whether to dereference references (default: False)

Returns:

A new document instance

Return type:

Document

async classmethod get(id, dereference=False, dereference_depth=1, **kwargs)[source]

Get a document by ID with optional dereferencing using FETCH.

This method retrieves a document by ID and optionally resolves references using SurrealDB’s FETCH clause for efficient reference resolution.

Parameters:
  • id (str | int | RecordID) – The ID of the document to retrieve

  • dereference (bool) – Whether to resolve references (default: False)

  • dereference_depth (int) – Maximum depth of reference resolution (default: 1)

  • **kwargs (Any) – Additional arguments to pass to the get method

Returns:

The document instance with optionally resolved references

Return type:

T

classmethod get_sync(id, dereference=False, dereference_depth=1, **kwargs)[source]

Get a document by ID with optional dereferencing synchronously using FETCH.

This method retrieves a document by ID and optionally resolves references using SurrealDB’s FETCH clause for efficient reference resolution.

Parameters:
  • id (str | int | RecordID) – The ID of the document to retrieve

  • dereference (bool) – Whether to resolve references (default: False)

  • dereference_depth (int) – Maximum depth of reference resolution (default: 1)

  • **kwargs (Any) – Additional arguments to pass to the get method

Returns:

The document instance with optionally resolved references

Return type:

T

property id: str | int | RecordID | None

Get the document ID.

Returns:

The document ID (string, RecordID, or None)

objects

Descriptor that provides QuerySet access through Document.objects.

This class is a descriptor that provides access to a QuerySet through the Document.objects attribute. It allows querying documents of a specific document class using the Document.objects attribute.

owner

The document class that owns this descriptor

connection

The database connection to use for queries

async refresh(connection=None)[source]

Refresh the document from the database asynchronously.

This method refreshes the document’s data from the database.

Parameters:

connection (Any | None) – The database connection to use (optional)

Returns:

The refreshed document instance

Raises:

ValueError – If the document doesn’t have an ID

Return type:

Document

refresh_sync(connection=None)[source]

Refresh the document from the database synchronously.

This method refreshes the document’s data from the database.

Parameters:

connection (Any | None) – The database connection to use (optional)

Returns:

The refreshed document instance

Raises:

ValueError – If the document doesn’t have an ID

Return type:

Document

async relate_to(relation_name, target_instance, connection=None, **attrs)[source]

Create a relation to another document asynchronously.

This method creates a relation from this document to another document.

Parameters:
  • relation_name (str) – Name of the relation

  • target_instance (Any) – The document instance to relate to

  • connection (Any | None) – The database connection to use (optional)

  • **attrs (Any) – Attributes to set on the relation

Returns:

The created relation record or None if creation failed

Return type:

Any | None

relate_to_sync(relation_name, target_instance, connection=None, **attrs)[source]

Create a relation to another document synchronously.

This method creates a relation from this document to another document.

Parameters:
  • relation_name (str) – Name of the relation

  • target_instance (Any) – The document instance to relate to

  • connection (Any | None) – The database connection to use (optional)

  • **attrs (Any) – Attributes to set on the relation

Returns:

The created relation record or None if creation failed

Return type:

Any | None

classmethod relates(relation_name)[source]

Get a RelationQuerySet for a specific relation.

This method returns a function that creates a RelationQuerySet for the specified relation name. The function can be called with an optional connection parameter.

Parameters:

relation_name (str) – Name of the relation

Returns:

Function that creates a RelationQuerySet

Return type:

callable

async resolve_references(depth=1)[source]

Resolve all references in this document using FETCH.

This method uses SurrealDB’s FETCH clause to efficiently resolve references instead of making individual queries for each reference.

Parameters:

depth (int) – Maximum depth of reference resolution (default: 1)

Returns:

The document instance with resolved references

Return type:

Document

resolve_references_sync(depth=1)[source]

Resolve all references in this document synchronously using FETCH.

This method uses SurrealDB’s FETCH clause to efficiently resolve references instead of making individual queries for each reference.

Parameters:

depth (int) – Maximum depth of reference resolution (default: 1)

Returns:

The document instance with resolved references

Return type:

Document

async resolve_relation(relation_name, target_document_class=None, relation_document=None, connection=None)[source]

Resolve related documents from a relation fetch result asynchronously.

This method resolves related documents from a relation fetch result. It fetches the relation data and then resolves each related document.

Parameters:
  • relation_name (str) – Name of the relation to resolve

  • target_document_class (Type | None) – Class of the target document (optional)

  • relation_document (Type | None) – The document class representing the relation (optional)

  • connection (Any | None) – Database connection to use (optional)

Returns:

List of resolved document instances

Return type:

List[Any]

resolve_relation_sync(relation_name, target_document_class=None, relation_document=None, connection=None)[source]

Resolve related documents from a relation fetch result synchronously.

This method resolves related documents from a relation fetch result. It fetches the relation data and then resolves each related document.

Parameters:
  • relation_name (str) – Name of the relation to resolve

  • target_document_class (Type | None) – Class of the target document (optional)

  • relation_document (Type | None) – The document class representing the relation (optional)

  • connection (Any | None) – Database connection to use (optional)

Returns:

List of resolved document instances

Return type:

List[Any]

async save(connection=None)[source]

Save the document to the database asynchronously.

This method saves the document to the database, either creating a new document or updating an existing one based on whether the document has an ID.

Parameters:

connection (Any | None) – The database connection to use (optional, deprecated for multi-backend)

Returns:

The saved document instance

Raises:

ValidationError – If the document fails validation

Return type:

T

save_sync(connection=None)[source]

Save the document to the database synchronously.

This method saves the document to the database, either creating a new document or updating an existing one based on whether the document has an ID.

Parameters:

connection (Any | None) – The database connection to use (optional)

Returns:

The saved document instance

Raises:

ValidationError – If the document fails validation

Return type:

T

classmethod to_dataclass()[source]

Convert the document class to a dataclass.

This method creates a dataclass based on the document’s fields. It uses the field names, types, and whether they are required. Required fields have no default value, making them required during initialization. Non-required fields use None as default if they don’t define one. A __post_init__ method is added to validate all fields after initialization.

Returns:

A dataclass type based on the document’s fields

to_db()[source]

Convert the document to a database-friendly dictionary.

This method converts the document to a dictionary suitable for storage in the database. It applies field-specific conversions and includes only non-None values unless the field is required.

Returns:

Dictionary of field values for the database

Return type:

Dict[str, str | int | float | bool | None | Dict[str, Any] | List[Any]]

to_dict()[source]

Convert the document to a dictionary.

This method converts the document to a dictionary containing all field values including the document ID. It ensures that RecordID objects are properly converted to strings for JSON serialization. It also recursively converts embedded documents to dictionaries.

Returns:

Dictionary of field values including ID

Return type:

Dict[str, str | int | float | bool | None | Dict[str, Any] | List[Any]]

async traverse_path(path_spec, target_document=None, connection=None, **filters)[source]

Traverse a path in the graph asynchronously.

This method traverses a path in the graph starting from this document. The path_spec is a string like “->[watched]->->[acted_in]->” which describes a path through the graph.

Parameters:
  • path_spec (str) – String describing the path to traverse

  • target_document (Type | None) – The document class to return instances of (optional)

  • connection (Any | None) – The database connection to use (optional)

  • **filters (Any) – Filters to apply to the results

Returns:

List of documents or path results

Raises:

ValueError – If the document is not saved

Return type:

List[Any]

traverse_path_sync(path_spec, target_document=None, connection=None, **filters)[source]

Traverse a path in the graph synchronously.

This method traverses a path in the graph starting from this document. The path_spec is a string like “->[watched]->->[acted_in]->” which describes a path through the graph.

Parameters:
  • path_spec (str) – String describing the path to traverse

  • target_document (Type | None) – The document class to return instances of (optional)

  • connection (Any | None) – The database connection to use (optional)

  • **filters (Any) – Filters to apply to the results

Returns:

List of documents or path results

Raises:

ValueError – If the document is not saved

Return type:

List[Any]

async update_relation_to(relation_name, target_instance, connection=None, **attrs)[source]

Update a relation to another document asynchronously.

This method updates a relation from this document to another document.

Parameters:
  • relation_name (str) – Name of the relation

  • target_instance (Any) – The document instance the relation is to

  • connection (Any | None) – The database connection to use (optional)

  • **attrs (Any) – Attributes to update on the relation

Returns:

The updated relation record or None if update failed

Return type:

Any | None

update_relation_to_sync(relation_name, target_instance, connection=None, **attrs)[source]

Update a relation to another document synchronously.

This method updates a relation from this document to another document.

Parameters:
  • relation_name (str) – Name of the relation

  • target_instance (Any) – The document instance the relation is to

  • connection (Any | None) – The database connection to use (optional)

  • **attrs (Any) – Attributes to update on the relation

Returns:

The updated relation record or None if update failed

Return type:

Any | None

validate()[source]

Validate all fields.

This method validates all fields in the document against their validation rules.

Raises:

ValidationError – If a field fails validation

class quantumengine.RelationDocument(**values)[source]

Bases: Document

A Document that represents a relationship between two documents.

RelationDocuments should be used to model relationships with additional attributes. They can be used with Document.relates(), Document.fetch_relation(), and Document.resolve_relation().

class Meta[source]

Bases: object

Meta options for RelationDocument.

abstract = True
async classmethod create_relation(from_instance, to_instance, **attrs)[source]

Create a relation between two instances asynchronously.

This method creates a relation between two document instances and returns a RelationDocument instance representing the relationship.

Parameters:
  • from_instance (Any) – The instance to create the relation from

  • to_instance (Any) – The instance to create the relation to

  • **attrs (Any) – Attributes to set on the relation

Returns:

A RelationDocument instance representing the relationship

Raises:

ValueError – If either instance is not saved

Return type:

RelationDocument

classmethod create_relation_sync(from_instance, to_instance, **attrs)[source]

Create a relation between two instances synchronously.

This method creates a relation between two document instances and returns a RelationDocument instance representing the relationship.

Parameters:
  • from_instance (Any) – The instance to create the relation from

  • to_instance (Any) – The instance to create the relation to

  • **attrs (Any) – Attributes to set on the relation

Returns:

A RelationDocument instance representing the relationship

Raises:

ValueError – If either instance is not saved

Return type:

RelationDocument

classmethod find_by_in_document(in_doc, **additional_filters)[source]

Query RelationDocument by in_document field.

Parameters:
  • in_doc – The document instance or ID to filter by

  • **additional_filters – Additional filters to apply

Returns:

QuerySet filtered by in_document

classmethod find_by_in_document_sync(in_doc, **additional_filters)[source]

Query RelationDocument by in_document field synchronously.

Parameters:
  • in_doc – The document instance or ID to filter by

  • **additional_filters – Additional filters to apply

Returns:

QuerySet filtered by in_document

classmethod get_relation_name()[source]

Get the name of the relation.

By default, this is the lowercase name of the class. Override this method to customize the relation name.

Returns:

The name of the relation

Return type:

str

classmethod relates(from_document=None, to_document=None)[source]

Get a RelationQuerySet for this relation.

This method returns a function that creates a RelationQuerySet for this relation. The function can be called with an optional connection parameter.

Parameters:
  • from_document (Type | None) – The document class the relation is from (optional)

  • to_document (Type | None) – The document class the relation is to (optional)

Returns:

Function that creates a RelationQuerySet

Return type:

callable

async resolve_out(connection=None)[source]

Resolve the out_document field asynchronously.

This method resolves the out_document field if it’s currently just an ID reference. If the out_document is already a document instance, it returns it directly.

Parameters:

connection – Database connection to use (optional)

Returns:

The resolved out_document instance

resolve_out_sync(connection=None)[source]

Resolve the out_document field synchronously.

This method resolves the out_document field if it’s currently just an ID reference. If the out_document is already a document instance, it returns it directly.

Parameters:

connection – Database connection to use (optional)

Returns:

The resolved out_document instance

exception quantumengine.DoesNotExist[source]

Bases: QuantumEngineError

Raised when a document does not exist in the database.

This exception is raised when attempting to retrieve a document that does not exist in the database, such as when using the get() method with a query that matches no documents.

exception quantumengine.MultipleObjectsReturned[source]

Bases: QuantumEngineError

Raised when multiple documents are returned when only one was expected.

This exception is raised when a query that is expected to return a single document returns multiple documents, such as when using the get() method with a query that matches multiple documents.

exception quantumengine.ValidationError(message, errors=None, field_name=None)[source]

Bases: QuantumEngineError

Raised when document validation fails.

This exception is raised when a document fails validation, such as when a required field is missing or a field value is of the wrong type.

errors

Dictionary of validation errors by field

field_name

Name of the field that failed validation, if applicable

__init__(message, errors=None, field_name=None)[source]

Initialize a ValidationError.

Parameters:
  • message (str) – The error message

  • errors (Dict[str, Any] | None) – Dictionary of validation errors by field

  • field_name (str | None) – Name of the field that failed validation, if applicable

class quantumengine.Field(required=False, default=None, db_field=None, define_schema=False, indexed=False, unique=False, search=False, analyzer=None, index_with=None, materialized=None, indexes=None, help_text=None)[source]

Bases: Generic[T]

Base class for all field types.

This class provides the foundation for all field types in the document model. It includes methods for validation and conversion between Python and database representations.

required

Whether the field is required

default

Default value for the field

name

Name of the field (set during document class creation)

db_field

Name of the field in the database

owner_document

The document class that owns this field

define_schema

Whether to define this field in the schema (even for SCHEMALESS tables)

__init__(required=False, default=None, db_field=None, define_schema=False, indexed=False, unique=False, search=False, analyzer=None, index_with=None, materialized=None, indexes=None, help_text=None)[source]

Initialize a new Field.

Parameters:
  • required (bool) – Whether the field is required

  • default (Any) – Default value for the field

  • db_field (str | None) – Name of the field in the database (defaults to the field name)

  • define_schema (bool) – Whether to define this field in the schema (even for SCHEMALESS tables)

  • indexed (bool) – Whether the field should be indexed

  • unique (bool) – Whether the index should enforce uniqueness

  • search (bool) – Whether the index is a search index

  • analyzer (str | None) – Analyzer to use for search indexes

  • index_with (List[str] | None) – List of other field names to include in the index

  • materialized (str | None) – ClickHouse materialized column expression

  • help_text (str | None) – Human-readable description of what this field represents

  • indexes (List[Dict[str, Any]] | None) – List of index specifications for advanced indexing

from_db(value, backend=None)[source]

Convert database value to Python representation.

This method converts a value from the database to a Python value. Subclasses should override this method to provide type-specific conversion.

Parameters:
  • value (Any) – The database value to convert

  • backend (str | None) – The backend type (‘surrealdb’, ‘clickhouse’, etc.)

Returns:

The Python representation of the value

Return type:

T

to_db(value, backend=None)[source]

Convert Python value to database representation.

This method converts a Python value to a representation that can be stored in the database. Subclasses should override this method to provide type-specific conversion.

Parameters:
  • value (Any) – The Python value to convert

  • backend (str | None) – The backend type (‘surrealdb’, ‘clickhouse’, etc.)

Returns:

The database representation of the value

Return type:

Any

validate(value)[source]

Validate the field value.

This method checks if the value is valid for this field type. Subclasses should override this method to provide type-specific validation.

Parameters:

value (Any) – The value to validate

Returns:

The validated value

Raises:

ValueError – If the value is invalid

Return type:

T

class quantumengine.StringField(min_length=None, max_length=None, regex=None, choices=None, **kwargs)[source]

Bases: Field[str]

String field type.

This field type stores string values and provides validation for minimum length, maximum length, and regex pattern matching.

min_length

Minimum length of the string

max_length

Maximum length of the string

regex

Regular expression pattern to match

__init__(min_length=None, max_length=None, regex=None, choices=None, **kwargs)[source]

Initialize a new StringField.

Parameters:
  • min_length (int | None) – Minimum length of the string

  • max_length (int | None) – Maximum length of the string

  • regex (str | None) – Regular expression pattern to match

  • **kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the string value.

This method checks if the value is a valid string and meets the constraints for minimum length, maximum length, and regex pattern.

Parameters:

value (Any) – The value to validate

Returns:

The validated string value

Raises:
  • TypeError – If the value is not a string

  • ValueError – If the value does not meet the constraints

Return type:

str

class quantumengine.NumberField(min_value=None, max_value=None, **kwargs)[source]

Bases: Field[int | float]

Base class for numeric fields.

This field type is the base class for all numeric field types. It provides validation for minimum and maximum values.

min_value

Minimum allowed value

max_value

Maximum allowed value

__init__(min_value=None, max_value=None, **kwargs)[source]

Initialize a new NumberField.

Parameters:
  • min_value (int | float | None) – Minimum allowed value

  • max_value (int | float | None) – Maximum allowed value

  • **kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the numeric value.

This method checks if the value is a valid number and meets the constraints for minimum and maximum values.

Parameters:

value (Any) – The value to validate

Returns:

The validated numeric value

Raises:
  • TypeError – If the value is not a number

  • ValueError – If the value does not meet the constraints

Return type:

int | float

class quantumengine.IntField(**kwargs)[source]

Bases: NumberField

Integer field type.

This field type stores integer values and provides validation to ensure the value is an integer.

__init__(**kwargs)[source]

Initialize a new IntField.

Parameters:

**kwargs (Any) – Additional arguments to pass to the parent class

to_db(value, backend=None)[source]

Convert Python value to database representation.

This method converts a Python value to an integer for storage in the database.

Parameters:

value (Any) – The Python value to convert

Returns:

The integer value for the database

Return type:

int | None

validate(value)[source]

Validate the integer value.

This method checks if the value is a valid integer.

Parameters:

value (Any) – The value to validate

Returns:

The validated integer value

Raises:

TypeError – If the value is not an integer

Return type:

int

class quantumengine.FloatField(**kwargs)[source]

Bases: NumberField

Float field type.

This field type stores floating-point values and provides validation to ensure the value can be converted to a float.

__init__(**kwargs)[source]

Initialize a new FloatField.

Parameters:

**kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the float value.

This method checks if the value can be converted to a float.

Parameters:

value (Any) – The value to validate

Returns:

The validated float value

Raises:

TypeError – If the value cannot be converted to a float

Return type:

float

class quantumengine.BooleanField(**kwargs)[source]

Bases: Field[bool]

Boolean field type.

This field type stores boolean values and provides validation to ensure the value is a boolean.

__init__(**kwargs)[source]

Initialize a new BooleanField.

Parameters:

**kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the boolean value.

This method checks if the value is a valid boolean.

Parameters:

value (Any) – The value to validate

Returns:

The validated boolean value

Raises:

TypeError – If the value is not a boolean

Return type:

bool

class quantumengine.DateTimeField(**kwargs)[source]

Bases: Field[datetime]

DateTime field type.

This field type stores datetime values and provides validation and conversion between Python datetime objects and SurrealDB datetime format.

SurrealDB v2.0.0+ requires datetime values to have a d prefix or be cast as <datetime>. This field handles the conversion automatically, so you can use standard Python datetime objects in your code.

Example

>>> class Event(Document):
...     created_at = DateTimeField(default=datetime.datetime.now)
...     scheduled_for = DateTimeField()
>>>
>>> # Python datetime objects are automatically converted to SurrealDB format
>>> event = Event(scheduled_for=datetime.datetime.now() + datetime.timedelta(days=7))
>>> await event.save()
__init__(**kwargs)[source]

Initialize a new DateTimeField.

Parameters:

**kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the datetime value.

This method checks if the value is a valid datetime or can be converted to a datetime from an ISO format string.

Parameters:

value (Any) – The value to validate

Returns:

The validated datetime value

Raises:

TypeError – If the value cannot be converted to a datetime

Return type:

datetime

class quantumengine.ListField(field_type=None, **kwargs)[source]

Bases: Field

List field type.

This field type stores lists of values and provides validation and conversion for the items in the list. The items can be of a specific field type, which is used to validate and convert each item.

field_type

The field type for items in the list

__init__(field_type=None, **kwargs)[source]

Initialize a new ListField.

Parameters:
  • field_type (Field | None) – The field type for items in the list

  • **kwargs (Any) – Additional arguments to pass to the parent class

from_db(value)[source]

Convert database list to Python representation.

This method converts a database list to a Python representation by converting each item using the field_type if provided.

Parameters:

value (List[Any] | None) – The database list to convert

Returns:

The Python representation of the list

Return type:

List[Any] | None

to_db(value, backend=None)[source]

Convert Python list to database representation.

This method converts a Python list to a database representation by converting each item using the field_type if provided. For ClickHouse, lists are converted to JSON strings.

Parameters:
  • value (List[Any] | None) – The Python list to convert

  • backend (str | None) – The backend name for backend-specific serialization

Returns:

The database representation of the list

Return type:

Any

validate(value)[source]

Validate the list value.

This method checks if the value is a valid list and validates each item in the list using the field_type if provided.

Parameters:

value (Any) – The value to validate

Returns:

The validated list value

Raises:
  • TypeError – If the value is not a list

  • ValueError – If an item in the list fails validation

Return type:

List[Any] | None

class quantumengine.DictField(field_type=None, **kwargs)[source]

Bases: Field

Dict field type.

This field type stores dictionaries of values and provides validation and conversion for the values in the dictionary. The values can be of a specific field type, which is used to validate and convert each value.

field_type

The field type for values in the dictionary

__init__(field_type=None, **kwargs)[source]

Initialize a new DictField.

Parameters:
  • field_type (Field | None) – The field type for values in the dictionary

  • **kwargs (Any) – Additional arguments to pass to the parent class

from_db(value)[source]

Convert database dictionary to Python representation.

This method converts a database dictionary to a Python representation by converting each value using the field_type if provided.

Parameters:

value (Dict[str, Any] | None) – The database dictionary to convert

Returns:

The Python representation of the dictionary

Return type:

Dict[str, Any] | None

to_db(value, backend=None)[source]

Convert Python dictionary to database representation.

This method converts a Python dictionary to a database representation by converting each value using the field_type if provided. For ClickHouse, dictionaries are converted to JSON strings.

Parameters:
  • value (Dict[str, Any] | None) – The Python dictionary to convert

  • backend (str | None) – The backend name for backend-specific serialization

Returns:

The database representation of the dictionary

Return type:

Any

validate(value)[source]

Validate the dictionary value.

This method checks if the value is a valid dictionary and validates each value in the dictionary using the field_type if provided.

Parameters:

value (Any) – The value to validate

Returns:

The validated dictionary value

Raises:
  • TypeError – If the value is not a dictionary

  • ValueError – If a value in the dictionary fails validation

Return type:

Dict[str, Any] | None

class quantumengine.ReferenceField(document_type, **kwargs)[source]

Bases: Field

Reference to another document.

This field type stores references to other documents in the database. It can accept a document instance, an ID string, or a dictionary with an ID.

document_type

The type of document being referenced

__init__(document_type, **kwargs)[source]

Initialize a new ReferenceField.

Parameters:
  • document_type (Type) – The type of document being referenced

  • **kwargs (Any) – Additional arguments to pass to the parent class

from_db(value, dereference=False)[source]

Convert database reference to Python representation.

This method converts a database reference to a Python representation. If the value is already a resolved document (from FETCH), return it as is. If dereference is False, it returns the string reference as is. If dereference is True but value is still a string, fetch the referenced document.

Parameters:
  • value (Any) – The database reference to convert

  • dereference (bool) – Whether to dereference the reference (default: False)

Returns:

The Python representation of the reference

Return type:

Any

to_db(value)[source]

Convert Python reference to database representation.

This method converts a Python reference (document instance, ID string, dictionary with an ID, or RecordID object) to a database representation.

Parameters:

value (Any) – The Python reference to convert

Returns:

The database representation of the reference

Raises:

ValueError – If the referenced document is not saved

Return type:

str | None

validate(value)[source]

Validate the reference value.

This method checks if the value is a valid reference to another document. It accepts a document instance, an ID string, a dictionary with an ID, or a RecordID object.

Parameters:

value (Any) – The value to validate

Returns:

The validated reference value

Raises:
  • TypeError – If the value is not a valid reference

  • ValueError – If the referenced document is not saved

Return type:

Any

class quantumengine.RelationField(to_document, **kwargs)[source]

Bases: Field

Field representing a relation between documents.

This field type stores relations between documents in the database. It can accept a document instance, an ID string, or a dictionary with an ID.

to_document

The type of document being related to

__init__(to_document, **kwargs)[source]

Initialize a new RelationField.

Parameters:
  • to_document (Type) – The type of document being related to

  • **kwargs (Any) – Additional arguments to pass to the parent class

from_db(value, dereference=False)[source]

Convert database relation to Python representation.

This method converts a database relation to a Python representation. If the value is already a resolved document (from FETCH), return it as is. If dereference is False, it returns the string reference as is. If dereference is True but value is still a string, fetch the related document.

Parameters:
  • value (Any) – The database relation to convert

  • dereference (bool) – Whether to dereference the relation (default: False)

Returns:

The Python representation of the relation

Return type:

Any

Get documents related through this relation field.

This method retrieves documents related to the given instance through this relation field. It uses the RelationQuerySet to get related documents.

Parameters:

instance (Any) – The instance to get related documents for

Returns:

List of related documents

Raises:

ValueError – If the instance is not saved

Return type:

List[Any]

Get documents related through this relation field synchronously.

This method retrieves documents related to the given instance through this relation field. It uses the RelationQuerySet to get related documents.

Parameters:

instance (Any) – The instance to get related documents for

Returns:

List of related documents

Raises:

ValueError – If the instance is not saved

Return type:

List[Any]

to_db(value)[source]

Convert Python relation to database representation.

This method converts a Python relation (document instance, ID string, or dictionary with an ID) to a database representation.

Parameters:

value (Any) – The Python relation to convert

Returns:

The database representation of the relation

Raises:

ValueError – If the related document is not saved

Return type:

str | None

validate(value)[source]

Validate the relation value.

This method checks if the value is a valid relation to another document. It accepts a document instance, an ID string, or a dictionary with an ID.

Parameters:

value (Any) – The value to validate

Returns:

The validated relation value

Raises:

TypeError – If the value is not a valid relation

Return type:

Any

class quantumengine.GeometryField(required=False, **kwargs)[source]

Bases: Field

Field for handling geometric data in SurrealDB.

This field validates and processes geometric data according to SurrealDB’s geometry specification. It supports various geometry types including Point, LineString, Polygon, MultiPoint, MultiLineString, and MultiPolygon.

required

Whether the field is required. Defaults to False.

Type:

bool

Example

>>> class Location(Document):
...     point = GeometryField()
>>>
>>> # Using GeometryPoint for precise coordinate handling
>>> from quantumengine.geometry import GeometryPoint
>>> loc = Location(point=GeometryPoint([-122.4194, 37.7749]))
__init__(required=False, **kwargs)[source]

Initialize a GeometryField.

Parameters:
  • required (bool, optional) – Whether this field is required. Defaults to False.

  • **kwargs – Additional field options to be passed to the parent Field class.

validate(value)[source]

Validate geometry data.

Ensures the geometry data follows SurrealDB’s expected format with proper structure and coordinates. Does not modify the numeric values to preserve SurrealDB’s native geometry handling.

Parameters:

value – The geometry value to validate. Can be a GeometryPoint object or a dict with ‘type’ and ‘coordinates’ fields.

Returns:

The validated geometry data.

Return type:

dict

Raises:

ValidationError – If the geometry data is invalid or improperly formatted.

class quantumengine.QuerySet(document_class, connection=None)[source]

Bases: BaseQuerySet, Generic[T]

Query builder for SurrealDB with generic type safety.

This class provides a query builder for document classes with a predefined schema. It extends BaseQuerySet to provide methods for querying and manipulating documents of a specific document class.

Type Parameters:

T: The document class type that this QuerySet operates on

document_class

The document class to query

connection

The database connection to use for queries

__init__(document_class, connection=None)[source]

Initialize a new QuerySet.

Parameters:
  • document_class (Type[T]) – The document class to query

  • connection (Any) – The database connection to use for queries (optional, will use document’s backend if None)

async all(dereference=False)[source]

Execute the query and return all results asynchronously.

This method builds and executes the query, then converts the results to instances of the document class. Includes automatic retry on transient failures.

Parameters:

dereference (bool) – Whether to dereference references (default: False)

Returns:

List of document instances

Return type:

List[T]

all_sync(dereference=False)[source]

Execute the query and return all results synchronously.

This method builds and executes the query, then converts the results to instances of the document class. Includes automatic retry on transient failures.

Parameters:

dereference (bool) – Whether to dereference references (default: False)

Returns:

List of document instances

Return type:

List[T]

async bulk_create(documents, batch_size=1000, validate=True, return_documents=True)[source]

Create multiple documents in a single operation asynchronously.

This method creates multiple documents in a single operation, processing them in batches for better performance. It can optionally validate the documents and return the created documents.

Parameters:
  • documents (List[T]) – List of Document instances to create

  • batch_size (int) – Number of documents per batch (default: 1000)

  • validate (bool) – Whether to validate documents (default: True)

  • return_documents (bool) – Whether to return created documents (default: True)

Returns:

List of created documents with their IDs set if return_documents=True, otherwise returns the count of created documents

Return type:

List[T] | int

bulk_create_sync(documents, batch_size=1000, validate=True, return_documents=True)[source]

Create multiple documents in a single operation synchronously.

This method creates multiple documents in a single operation, processing them in batches for better performance. It can optionally validate the documents and return the created documents.

Parameters:
  • documents (List[T]) – List of Document instances to create

  • batch_size (int) – Number of documents per batch (default: 1000)

  • validate (bool) – Whether to validate documents (default: True)

  • return_documents (bool) – Whether to return created documents (default: True)

Returns:

List of created documents with their IDs set if return_documents=True, otherwise returns the count of created documents

Return type:

List[T] | int

async count()[source]

Count documents matching the query asynchronously.

This method builds and executes a count query to count the number of documents matching the query. Includes automatic retry on transient failures.

Returns:

Number of matching documents

Return type:

int

count_sync()[source]

Count documents matching the query synchronously.

This method builds and executes a count query to count the number of documents matching the query. Includes automatic retry on transient failures.

Returns:

Number of matching documents

Return type:

int

async create(**kwargs)[source]

Create a new document asynchronously.

This method creates a new document with the given field values. Includes automatic retry on transient failures.

Parameters:

**kwargs (Any) – Field names and values for the new document

Returns:

The created document

Return type:

T

create_sync(**kwargs)[source]

Create a new document synchronously.

This method creates a new document with the given field values. Includes automatic retry on transient failures.

Parameters:

**kwargs (Any) – Field names and values for the new document

Returns:

The created document

Return type:

T

async delete()[source]

Delete documents matching the query asynchronously with performance optimizations.

This method deletes documents matching the query. Uses direct record access for bulk ID operations for better performance.

Returns:

Number of deleted documents

Return type:

int

delete_sync()[source]

Delete documents matching the query synchronously with performance optimizations.

This method deletes documents matching the query. Uses direct record access for bulk ID operations for better performance.

Returns:

Number of deleted documents

Return type:

int

async explain()[source]

Get query execution plan for performance analysis.

This method appends EXPLAIN to the query to show how the database will execute it, helping identify performance bottlenecks.

Returns:

List of execution plan steps with details

Return type:

List[Dict[str, Any]]

Example

plan = await User.objects.filter(age__lt=18).explain() print(f”Query will use: {plan[0][‘operation’]}”)

Raises:

NotImplementedError – If backend doesn’t support EXPLAIN queries

explain_sync()[source]

Get query execution plan for performance analysis synchronously.

Returns:

List of execution plan steps with details

Return type:

List[Dict[str, Any]]

async get(dereference=False, **kwargs)[source]

Get a single document matching the query asynchronously.

This method applies filters and ensures that exactly one document is returned.

Parameters:
  • dereference (bool) – Whether to dereference references (default: False)

  • **kwargs (Any) – Field names and values to filter by

Returns:

The matching document

Raises:
Return type:

T

get_sync(dereference=False, **kwargs)[source]

Get a single document matching the query synchronously.

This method applies filters and ensures that exactly one document is returned.

Parameters:
  • dereference (bool) – Whether to dereference references (default: False)

  • **kwargs (Any) – Field names and values to filter by

Returns:

The matching document

Raises:
Return type:

T

async join(field_name, target_fields=None, dereference=True, dereference_depth=1)[source]

Perform a JOIN-like operation on a reference field using FETCH.

This method performs a JOIN-like operation on a reference field by using SurrealDB’s FETCH clause to efficiently resolve references in a single query.

Parameters:
  • field_name (str) – The name of the reference field to join on

  • target_fields (List[str] | None) – Optional list of fields to select from the target document

  • dereference (bool) – Whether to dereference references in the joined documents (default: True)

  • dereference_depth (int) – Maximum depth of reference resolution (default: 1)

Returns:

List of documents with joined data

Raises:

ValueError – If the field is not a ReferenceField

Return type:

List[Any]

join_sync(field_name, target_fields=None, dereference=True, dereference_depth=1)[source]

Perform a JOIN-like operation on a reference field synchronously using FETCH.

This method performs a JOIN-like operation on a reference field by using SurrealDB’s FETCH clause to efficiently resolve references in a single query.

Parameters:
  • field_name (str) – The name of the reference field to join on

  • target_fields (List[str] | None) – Optional list of fields to select from the target document

  • dereference (bool) – Whether to dereference references in the joined documents (default: True)

  • dereference_depth (int) – Maximum depth of reference resolution (default: 1)

Returns:

List of documents with joined data

Raises:

ValueError – If the field is not a ReferenceField

Return type:

List[Any]

suggest_indexes()[source]

Suggest indexes based on current query patterns.

Analyzes the current query conditions and suggests optimal indexes that could improve performance.

Returns:

List of suggested DEFINE INDEX statements

Return type:

List[str]

Example

>>> suggestions = User.objects.filter(age__lt=18, city="NYC").suggest_indexes()
>>> for suggestion in suggestions:
...     print(f"Consider: {suggestion}")
async update(**kwargs)[source]

Update documents matching the query asynchronously with performance optimizations.

This method updates documents matching the query with the given field values. Uses direct record access for bulk ID operations for better performance.

Parameters:

**kwargs (Any) – Field names and values to update

Returns:

List of updated documents

Return type:

List[T]

update_sync(**kwargs)[source]

Update documents matching the query synchronously with performance optimizations.

This method updates documents matching the query with the given field values. Uses direct record access for bulk ID operations for better performance.

Parameters:

**kwargs (Any) – Field names and values to update

Returns:

List of updated documents

Return type:

List[T]

class quantumengine.RelationQuerySet(from_document, connection, relation=None)[source]

Bases: object

Query set specifically for graph relations.

This class provides methods for querying and manipulating graph relations between documents in the database. It allows creating, retrieving, updating, and deleting relations between documents.

from_document

The document class the relation is from

connection

The database connection to use for queries

relation

The name of the relation

query_parts

List of query parts

__init__(from_document, connection, relation=None)[source]

Initialize a new RelationQuerySet.

Parameters:
  • from_document (Type) – The document class the relation is from

  • connection (Any) – The database connection to use for queries

  • relation (str | None) – The name of the relation

async delete_relation(from_instance, to_instance=None)[source]

Delete a relation asynchronously.

This method deletes a relation between two document instances in the database. If to_instance is not provided, it deletes all relations from from_instance.

Parameters:
  • from_instance (Any) – The instance the relation is from

  • to_instance (Any | None) – The instance the relation is to (optional)

Returns:

Number of deleted relations

Raises:

ValueError – If from_instance is not saved, if to_instance is provided but not saved, or if no relation name is specified

Return type:

int

delete_relation_sync(from_instance, to_instance=None)[source]

Delete a relation synchronously.

This method deletes a relation between two document instances in the database. If to_instance is not provided, it deletes all relations from from_instance.

Parameters:
  • from_instance (Any) – The instance the relation is from

  • to_instance (Any | None) – The instance the relation is to (optional)

Returns:

Number of deleted relations

Raises:

ValueError – If from_instance is not saved, if to_instance is provided but not saved, or if no relation name is specified

Return type:

int

Get related documents asynchronously.

This method retrieves documents related to the given instance through the specified relation. It can return either the target documents or the relation records themselves.

Parameters:
  • instance (Any) – The instance to get related documents for

  • target_document (Type | None) – The document class of the target documents (optional)

  • **filters (Any) – Filters to apply to the related documents

Returns:

List of related documents or relation records

Raises:

ValueError – If the instance is not saved or if no relation name is specified

Return type:

List[Any]

Get related documents synchronously.

This method retrieves documents related to the given instance through the specified relation. It can return either the target documents or the relation records themselves.

Parameters:
  • instance (Any) – The instance to get related documents for

  • target_document (Type | None) – The document class of the target documents (optional)

  • **filters (Any) – Filters to apply to the related documents

Returns:

List of related documents or relation records

Raises:

ValueError – If the instance is not saved or if no relation name is specified

Return type:

List[Any]

async relate(from_instance, to_instance, **attrs)[source]

Create a relation between two instances asynchronously.

This method creates a relation between two document instances in the database. It constructs a RELATE query with the given relation name and attributes.

Parameters:
  • from_instance (Any) – The instance to create the relation from

  • to_instance (Any) – The instance to create the relation to

  • **attrs (Any) – Attributes to set on the relation

Returns:

The created relation record or None if creation failed

Raises:

ValueError – If either instance is not saved or if no relation name is specified

Return type:

Any | None

relate_sync(from_instance, to_instance, **attrs)[source]

Create a relation between two instances synchronously.

This method creates a relation between two document instances in the database. It constructs a RELATE query with the given relation name and attributes.

Parameters:
  • from_instance (Any) – The instance to create the relation from

  • to_instance (Any) – The instance to create the relation to

  • **attrs (Any) – Attributes to set on the relation

Returns:

The created relation record or None if creation failed

Raises:

ValueError – If either instance is not saved or if no relation name is specified

Return type:

Any | None

async update_relation(from_instance, to_instance, **attrs)[source]

Update an existing relation asynchronously.

This method updates an existing relation between two document instances in the database. If the relation doesn’t exist, it creates it.

Parameters:
  • from_instance (Any) – The instance the relation is from

  • to_instance (Any) – The instance the relation is to

  • **attrs (Any) – Attributes to update on the relation

Returns:

The updated relation record or None if update failed

Raises:

ValueError – If either instance is not saved or if no relation name is specified

Return type:

Any | None

update_relation_sync(from_instance, to_instance, **attrs)[source]

Update an existing relation synchronously.

This method updates an existing relation between two document instances in the database. If the relation doesn’t exist, it creates it.

Parameters:
  • from_instance (Any) – The instance the relation is from

  • to_instance (Any) – The instance the relation is to

  • **attrs (Any) – Attributes to update on the relation

Returns:

The updated relation record or None if update failed

Raises:

ValueError – If either instance is not saved or if no relation name is specified

Return type:

Any | None

class quantumengine.Q(**kwargs)[source]

Bases: object

Query expression builder for complex queries.

This class allows building complex query expressions that can be used with filter() and objects() methods.

Example

# Complex AND/OR queries query = Q(age__gt=18) & Q(active=True) users = User.objects.filter(query)

# Complex queries with objects() query = Q(department=”engineering”) | Q(department=”sales”) users = User.objects(query)

__and__(other)[source]

Combine with another Q object using AND.

__init__(**kwargs)[source]

Initialize a query expression.

Parameters:

**kwargs – Field filters to include in the query

__invert__()[source]

Negate this query using NOT.

__or__(other)[source]

Combine with another Q object using OR.

classmethod raw(query_string)[source]

Create a raw query expression.

Parameters:

query_string (str) – Raw SurrealQL WHERE clause

Returns:

Q object with raw query

Return type:

Q

to_conditions()[source]

Convert this Q object to a list of conditions.

Returns:

List of (field, operator, value) tuples

Return type:

List[tuple]

to_where_clause()[source]

Convert this Q object to a WHERE clause string.

Returns:

WHERE clause string for SurrealQL

Return type:

str

class quantumengine.QueryExpression(where=None)[source]

Bases: object

Higher-level query expression that can include fetch, grouping, etc.

This class provides a more comprehensive query building interface that includes not just WHERE conditions but also FETCH, GROUP BY, etc.

__init__(where=None)[source]

Initialize a query expression.

Parameters:

where (Q | None) – Q object for WHERE clause conditions

apply_to_queryset(queryset)[source]

Apply this expression to a queryset.

Parameters:

queryset – BaseQuerySet to apply expression to

Returns:

Modified queryset

fetch(*fields)[source]

Add FETCH clause to resolve references.

Parameters:

*fields (str) – Field names to fetch

Returns:

Self for method chaining

Return type:

QueryExpression

group_by(*fields)[source]

Add GROUP BY clause.

Parameters:

*fields (str) – Field names to group by

Returns:

Self for method chaining

Return type:

QueryExpression

limit(value)[source]

Add LIMIT clause.

Parameters:

value (int) – Maximum number of results

Returns:

Self for method chaining

Return type:

QueryExpression

order_by(field, direction='ASC')[source]

Add ORDER BY clause.

Parameters:
  • field (str) – Field name to order by

  • direction (str) – ‘ASC’ or ‘DESC’

Returns:

Self for method chaining

Return type:

QueryExpression

start(value)[source]

Add START clause for pagination.

Parameters:

value (int) – Number of results to skip

Returns:

Self for method chaining

Return type:

QueryExpression

class quantumengine.DurationField(**kwargs)[source]

Bases: Field

Duration field type.

This field type stores durations of time and provides validation and conversion between Python timedelta objects and SurrealDB duration strings.

__init__(**kwargs)[source]

Initialize a new DurationField.

Parameters:

**kwargs (Any) – Additional arguments to pass to the parent class

from_db(value)[source]

Convert database value to Python timedelta.

This method converts a SurrealDB duration string from the database to a Python timedelta object.

Parameters:

value (Any) – The database value to convert

Returns:

The Python timedelta object

Return type:

timedelta | None

to_db(value)[source]

Convert Python timedelta to database representation.

This method converts a Python timedelta object to a SurrealDB Duration object for storage in the database.

Parameters:

value (Any) – The Python timedelta to convert

Returns:

The SurrealDB Duration object for the database

Return type:

Any | None

validate(value)[source]

Validate the duration value.

This method checks if the value is a valid timedelta or can be converted to a timedelta from a string.

Parameters:

value (Any) – The value to validate

Returns:

The validated timedelta value

Raises:

TypeError – If the value cannot be converted to a timedelta

Return type:

timedelta | None

class quantumengine.OptionField(field_type, **kwargs)[source]

Bases: Field

Option field type.

This field type makes a field optional and guarantees it to be either None or a value of the specified type.

field_type

The field type for the value when not None

__init__(field_type, **kwargs)[source]

Initialize a new OptionField.

Parameters:
  • field_type (Field) – The field type for the value when not None

  • **kwargs (Any) – Additional arguments to pass to the parent class

from_db(value)[source]

Convert database value to Python representation.

This method converts a database value to a Python representation using the field_type’s from_db method if the value is not None.

Parameters:

value (Any) – The database value to convert

Returns:

The Python representation of the value

Return type:

Any

to_db(value)[source]

Convert Python value to database representation.

This method converts a Python value to a database representation using the field_type’s to_db method if the value is not None.

Parameters:

value (Any) – The Python value to convert

Returns:

The database representation of the value

Return type:

Any

validate(value)[source]

Validate the option value.

This method checks if the value is None or a valid value for the field_type.

Parameters:

value (Any) – The value to validate

Returns:

The validated value

Raises:

ValueError – If the value is not None and fails validation for field_type

Return type:

Any

class quantumengine.LiteralField(allowed_values, **kwargs)[source]

Bases: Field

Field for union/enum-like values.

Allows a field to accept multiple different types or specific values, similar to a union or enum type in other languages.

Example

class Product(Document):

status = LiteralField([“active”, “discontinued”, “out_of_stock”]) id_or_name = LiteralField([IntField(), StringField()])

__init__(allowed_values, **kwargs)[source]

Initialize a new LiteralField.

Parameters:
  • allowed_values (List[Any]) – List of allowed values or field types

  • **kwargs (Any) – Additional arguments to pass to the parent class

from_db(value)[source]

Convert database value to Python representation.

This method converts a database value to a Python representation by using the appropriate field type if the value is not a literal.

Parameters:

value (Any) – The database value to convert

Returns:

The Python representation of the value

Return type:

Any

to_db(value)[source]

Convert Python value to database representation.

This method converts a Python value to a database representation by using the appropriate field type if the value is not a literal.

Parameters:

value (Any) – The Python value to convert

Returns:

The database representation of the value

Return type:

Any

validate(value)[source]

Validate that the value is one of the allowed values or types.

Parameters:

value (Any) – The value to validate

Returns:

The validated value

Raises:

ValidationError – If the value is not one of the allowed values or types

Return type:

Any

class quantumengine.RangeField(min_type, max_type=None, **kwargs)[source]

Bases: Field

Field for storing ranges of values.

This field type stores ranges of values with minimum and maximum bounds. It supports various types for the bounds, such as numbers, strings, and dates.

Example

class PriceRange(Document):

price_range = RangeField(min_type=FloatField(), max_type=FloatField()) age_range = RangeField(min_type=IntField(), max_type=IntField())

__init__(min_type, max_type=None, **kwargs)[source]

Initialize a new RangeField.

Parameters:
  • min_type (Field) – The field type for the minimum value

  • max_type (Field) – The field type for the maximum value (defaults to same as min_type)

  • **kwargs (Any) – Additional arguments to pass to the parent class

from_db(value)[source]

Convert database range to Python representation.

Parameters:

value (Dict[str, Any] | None) – The database range to convert

Returns:

The Python representation of the range

Return type:

Dict[str, Any] | None

to_db(value)[source]

Convert Python range to database representation.

Parameters:

value (Dict[str, Any] | None) – The Python range to convert

Returns:

The database representation of the range

Return type:

Dict[str, Any] | None

validate(value)[source]

Validate the range value.

This method checks if the value is a valid range with minimum and maximum values that can be validated by the respective field types.

Parameters:

value (Any) – The value to validate

Returns:

The validated range value

Raises:

ValidationError – If the value is not a valid range

Return type:

Dict[str, Any] | None

class quantumengine.SetField(field_type=None, **kwargs)[source]

Bases: ListField

Set field type.

This field type stores sets of unique values and provides validation and conversion for the items in the set. Values are automatically deduplicated.

Example

class User(Document):

tags = SetField(StringField())

to_db(value, backend=None)[source]

Convert Python list to database representation with deduplication.

validate(value)[source]

Validate the list value and ensure uniqueness.

This method checks if the value is a valid list and validates each item in the list using the field_type if provided. It also ensures that all items in the list are unique.

Parameters:

value (Any) – The value to validate

Returns:

The validated and deduplicated list value

Return type:

List[Any] | None

class quantumengine.TimeSeriesField(**kwargs)[source]

Bases: DateTimeField

Field for time series data.

This field type extends DateTimeField and adds support for time series data. It can be used to store timestamps for time series data and supports additional metadata for time series operations.

Example

class SensorReading(Document):

timestamp = TimeSeriesField(index=True) value = FloatField()

class Meta:

time_series = True time_field = “timestamp”

__init__(**kwargs)[source]

Initialize a new TimeSeriesField.

Parameters:

**kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the timestamp value.

This method checks if the value is a valid timestamp for time series data.

Parameters:

value (Any) – The value to validate

Returns:

The validated timestamp value

Return type:

datetime | None

class quantumengine.EmailField(**kwargs)[source]

Bases: StringField

Email field type.

This field type stores email addresses and provides validation to ensure the value is a valid email address.

Example

>>> class User(Document):
...     email = EmailField(required=True)
__init__(**kwargs)[source]

Initialize a new EmailField.

Parameters:

**kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the email address.

This method checks if the value is a valid email address.

Parameters:

value (Any) – The value to validate

Returns:

The validated email address

Raises:

ValueError – If the email address is invalid

Return type:

str | None

class quantumengine.URLField(**kwargs)[source]

Bases: StringField

URL field type.

This field type stores URLs and provides validation to ensure the value is a valid URL.

Example

>>> class Website(Document):
...     url = URLField(required=True)
__init__(**kwargs)[source]

Initialize a new URLField.

Parameters:

**kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the URL.

This method checks if the value is a valid URL.

Parameters:

value (Any) – The value to validate

Returns:

The validated URL

Raises:

ValueError – If the URL is invalid

Return type:

str | None

class quantumengine.IPAddressField(ipv4_only=False, ipv6_only=False, version=None, **kwargs)[source]

Bases: StringField

IP address field type.

This field type stores IP addresses and provides validation to ensure the value is a valid IPv4 or IPv6 address.

Example

>>> class Server(Document):
...     ip_address = IPAddressField(required=True)
...     ip_v4 = IPAddressField(ipv4_only=True)
...     ip_v6 = IPAddressField(ipv6_only=True)
__init__(ipv4_only=False, ipv6_only=False, version=None, **kwargs)[source]

Initialize a new IPAddressField.

Parameters:
  • ipv4_only (bool) – Whether to only allow IPv4 addresses

  • ipv6_only (bool) – Whether to only allow IPv6 addresses

  • version (str) – IP version to validate (‘ipv4’, ‘ipv6’, or ‘both’)

  • **kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the IP address.

This method checks if the value is a valid IP address.

Parameters:

value (Any) – The value to validate

Returns:

The validated IP address

Raises:

ValueError – If the IP address is invalid

Return type:

str | None

class quantumengine.SlugField(**kwargs)[source]

Bases: StringField

Slug field type.

This field type stores slugs (URL-friendly strings) and provides validation to ensure the value is a valid slug.

Example

>>> class Article(Document):
...     slug = SlugField(required=True)
__init__(**kwargs)[source]

Initialize a new SlugField.

Parameters:

**kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the slug.

This method checks if the value is a valid slug.

Parameters:

value (Any) – The value to validate

Returns:

The validated slug

Raises:

ValueError – If the slug is invalid

Return type:

str | None

class quantumengine.ChoiceField(choices, **kwargs)[source]

Bases: Field

Choice field type.

This field type stores values from a predefined set of choices and provides validation to ensure the value is one of the allowed choices.

Example

>>> class Product(Document):
...     status = ChoiceField(choices=['active', 'inactive', 'discontinued'])
__init__(choices, **kwargs)[source]

Initialize a new ChoiceField.

Parameters:
  • choices (List[str | tuple]) – List of allowed choices. Each choice can be a string or a tuple of (value, display_name).

  • **kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the choice value.

This method checks if the value is one of the allowed choices.

Parameters:

value (Any) – The value to validate

Returns:

The validated choice value

Raises:

ValueError – If the value is not one of the allowed choices

Return type:

str | None

class quantumengine.MaterializedView(name, query, refresh_interval=None, document_class=None, aggregations=None, select_fields=None)[source]

Bases: object

Materialized view for SurrealDB.

This class represents a materialized view in SurrealDB, which is a precomputed view of data that can be used to improve query performance for frequently accessed aggregated data.

name

The name of the materialized view

query

The query that defines the materialized view

refresh_interval

The interval at which the view is refreshed

document_class

The document class that the view is based on

aggregations

Dictionary of field names and aggregation functions

select_fields

List of fields to select (if None, selects all fields)

__init__(name, query, refresh_interval=None, document_class=None, aggregations=None, select_fields=None)[source]

Initialize a new MaterializedView.

Parameters:
  • name (str) – The name of the materialized view

  • query (QuerySet) – The query that defines the materialized view

  • refresh_interval (str) – The interval at which the view is refreshed (e.g., “1h”, “30m”)

  • document_class (Type['Document']) – The document class that the view is based on

  • aggregations (Dict[str, Aggregation]) – Dictionary of field names and aggregation functions

  • select_fields (List[str]) – List of fields to select (if None, selects all fields)

async create(connection=None)[source]

Create the materialized view in the database.

Parameters:

connection – The database connection to use (optional)

create_sync(connection=None)[source]

Create the materialized view in the database synchronously.

Parameters:

connection – The database connection to use (optional)

async drop(connection=None)[source]

Drop the materialized view from the database.

Parameters:

connection – The database connection to use (optional)

drop_sync(connection=None)[source]

Drop the materialized view from the database synchronously.

Parameters:

connection – The database connection to use (optional)

async execute_raw_query(connection=None)[source]

Execute a raw query against the materialized view.

This is a workaround for the “no decoder for tag” error that can occur when querying materialized views using the objects property.

Parameters:

connection – The database connection to use (optional)

Returns:

The query results

execute_raw_query_sync(connection=None)[source]

Execute a raw query against the materialized view synchronously.

This is a workaround for the “no decoder for tag” error that can occur when querying materialized views using the objects property.

Parameters:

connection – The database connection to use (optional)

Returns:

The query results

property objects: QuerySet

Get a QuerySet for querying the materialized view.

Returns:

A QuerySet for querying the materialized view

async refresh(connection=None)[source]

Manually refresh the materialized view.

Note: SurrealDB materialized views are automatically updated when underlying data changes. This method might not work as expected.

Parameters:

connection – The database connection to use (optional)

refresh_sync(connection=None)[source]

Manually refresh the materialized view.

Note: SurrealDB materialized views are automatically updated when underlying data changes. This method might not work as expected.

Parameters:

connection – The database connection to use (optional)

class quantumengine.MaterializedDocument(**values)[source]

Bases: Document

Base class for materialized documents (views).

MaterializedDocument provides a Document-like interface for creating and querying materialized views across different backends.

async classmethod create_view()[source]

Create the materialized view in the database.

async delete()[source]

MaterializedDocuments are read-only.

async classmethod drop_view()[source]

Drop the materialized view from the database.

async classmethod refresh_view()[source]

Refresh the materialized view (backend-specific behavior).

async save(**kwargs)[source]

MaterializedDocuments are read-only.

class quantumengine.MaterializedField(source=None, aggregate=None, transform=None, **kwargs)[source]

Bases: Field

Field for materialized documents with aggregation support.

__init__(source=None, aggregate=None, transform=None, **kwargs)[source]

Initialize a materialized field.

Parameters:
  • source (str | None) – Source field name from the base document

  • aggregate (AggregateFunction | None) – Aggregation function to apply

  • transform (FieldTransform | Callable | None) – Transformation to apply to the source field

  • **kwargs – Additional field arguments

class quantumengine.AggregationPipeline(query_set)[source]

Bases: object

Pipeline for building and executing aggregation queries.

This class provides a fluent interface for building complex aggregation pipelines with multiple stages, similar to MongoDB’s aggregation framework.

__init__(query_set)[source]

Initialize a new AggregationPipeline.

Parameters:

query_set (QuerySet) – The QuerySet to build the pipeline from

build_query()[source]

Build the SurrealQL query from the pipeline stages.

Returns:

The SurrealQL query string

async execute(connection=None)[source]

Execute the pipeline and return results.

Parameters:

connection – Optional connection to use

Returns:

The query results

execute_sync(connection=None)[source]

Execute the pipeline synchronously.

Parameters:

connection – Optional connection to use

Returns:

The query results

group(by_fields=None, **aggregations)[source]

Group by fields and apply aggregations.

Parameters:
  • by_fields – Field or list of fields to group by

  • **aggregations – Named aggregation functions to apply

Returns:

The pipeline instance for method chaining

limit(count)[source]

Limit number of results.

Parameters:

count – Maximum number of results to return

Returns:

The pipeline instance for method chaining

project(**fields)[source]

Select or compute fields to include in output.

Parameters:

**fields – Field mappings for projection

Returns:

The pipeline instance for method chaining

skip(count)[source]

Skip number of results.

Parameters:

count – Number of results to skip

Returns:

The pipeline instance for method chaining

sort(**fields)[source]

Sort results by fields.

Parameters:

**fields – Field names and sort directions (‘ASC’ or ‘DESC’)

Returns:

The pipeline instance for method chaining

with_index(index)[source]

Use the specified index for the query.

Parameters:

index – Name of the index to use

Returns:

The pipeline instance for method chaining

class quantumengine.Aggregation(field=None)[source]

Bases: object

Base class for aggregation functions.

This class represents an aggregation function that can be used in a materialized view. Subclasses should implement the __str__ method to return the SurrealQL representation of the aggregation function.

__init__(field=None)[source]

Initialize a new Aggregation.

Parameters:

field (str) – The field to aggregate (optional)

__str__()[source]

Return the SurrealQL representation of the aggregation function.

class quantumengine.Count(field=None)[source]

Bases: Aggregation

Count aggregation function.

This class represents the count() aggregation function in SurrealQL.

__str__()[source]

Return the SurrealQL representation of the count function.

class quantumengine.Mean(field=None)[source]

Bases: Aggregation

Mean aggregation function.

This class represents the math::mean() aggregation function in SurrealQL.

__str__()[source]

Return the SurrealQL representation of the mean function.

class quantumengine.Sum(field=None)[source]

Bases: Aggregation

Sum aggregation function.

This class represents the math::sum() aggregation function in SurrealQL.

__str__()[source]

Return the SurrealQL representation of the sum function.

class quantumengine.Min(field=None)[source]

Bases: Aggregation

Min aggregation function.

This class represents the math::min() aggregation function in SurrealQL.

__str__()[source]

Return the SurrealQL representation of the min function.

class quantumengine.Max(field=None)[source]

Bases: Aggregation

Max aggregation function.

This class represents the math::max() aggregation function in SurrealQL.

__str__()[source]

Return the SurrealQL representation of the max function.

class quantumengine.ArrayCollect(field=None)[source]

Bases: Aggregation

Array collect aggregation function.

This class represents the array::collect() aggregation function in SurrealQL.

__str__()[source]

Return the SurrealQL representation of the array collect function.

class quantumengine.Median(field=None)[source]

Bases: Aggregation

Median aggregation function.

This class represents the math::median() aggregation function in SurrealQL.

__str__()[source]

Return the SurrealQL representation of the median function.

class quantumengine.StdDev(field=None)[source]

Bases: Aggregation

Standard deviation aggregation function.

This class represents the math::stddev() aggregation function in SurrealQL.

__str__()[source]

Return the SurrealQL representation of the standard deviation function.

class quantumengine.Variance(field=None)[source]

Bases: Aggregation

Variance aggregation function.

This class represents the math::variance() aggregation function in SurrealQL.

__str__()[source]

Return the SurrealQL representation of the variance function.

class quantumengine.Percentile(field=None, percentile=50)[source]

Bases: Aggregation

Percentile aggregation function.

This class represents the math::percentile() aggregation function in SurrealQL.

__init__(field=None, percentile=50)[source]

Initialize a new Percentile.

Parameters:
  • field (str) – The field to aggregate (optional)

  • percentile (float) – The percentile to calculate (default: 50)

__str__()[source]

Return the SurrealQL representation of the percentile function.

class quantumengine.Distinct(field=None)[source]

Bases: Aggregation

Distinct aggregation function.

This class represents the array::distinct() aggregation function in SurrealQL.

__str__()[source]

Return the SurrealQL representation of the distinct function.

class quantumengine.GroupConcat(field=None, separator=', ')[source]

Bases: Aggregation

Group concatenation aggregation function.

This class represents a custom aggregation function that concatenates values with a separator.

__init__(field=None, separator=', ')[source]

Initialize a new GroupConcat.

Parameters:
  • field (str) – The field to aggregate (optional)

  • separator (str) – The separator to use (default: “, “)

__str__()[source]

Return the SurrealQL representation of the group concat function.

quantumengine.get_document_classes(module_name)[source]

Get all Document classes defined in a module.

Parameters:

module_name (str) – The name of the module to search

Returns:

A list of Document classes defined in the module

Return type:

List[Type[Document]]

async quantumengine.create_tables_from_module(module_name, connection=None, schemafull=True)[source]

Create tables for all Document classes in a module asynchronously.

Parameters:
  • module_name (str) – The name of the module containing Document classes

  • connection (Any | None) – Optional connection to use

  • schemafull (bool) – Whether to create SCHEMAFULL tables (default: True)

quantumengine.create_tables_from_module_sync(module_name, connection=None, schemafull=True)[source]

Create tables for all Document classes in a module synchronously.

Parameters:
  • module_name (str) – The name of the module containing Document classes

  • connection (Any | None) – Optional connection to use

  • schemafull (bool) – Whether to create SCHEMAFULL tables (default: True)

quantumengine.generate_schema_statements(document_class, schemafull=True)[source]

Generate SurrealDB schema statements for a Document class.

This function generates DEFINE TABLE and DEFINE FIELD statements for a Document class without executing them. This is useful for generating schema migration scripts.

Parameters:
  • document_class (Type[Document]) – The Document class to generate statements for

  • schemafull (bool) – Whether to generate SCHEMAFULL tables (default: True)

Returns:

A list of SurrealDB schema statements

Return type:

List[str]

quantumengine.generate_schema_statements_from_module(module_name, schemafull=True)[source]

Generate SurrealDB schema statements for all Document classes in a module.

Parameters:
  • module_name (str) – The name of the module containing Document classes

  • schemafull (bool) – Whether to generate SCHEMAFULL tables (default: True)

Returns:

A dictionary mapping class names to lists of SurrealDB schema statements

Return type:

Dict[str, List[str]]

quantumengine.generate_drop_statements(document_class)[source]

Generate SurrealDB DROP statements for a Document class.

This function generates REMOVE TABLE and REMOVE FIELD/INDEX statements for a Document class. Useful for generating down migration scripts.

Parameters:

document_class (Type[Document]) – The Document class to generate drop statements for

Returns:

A list of SurrealDB drop statements

Return type:

List[str]

quantumengine.generate_drop_statements_from_module(module_name)[source]

Generate SurrealDB DROP statements for all Document classes in a module.

Parameters:

module_name (str) – The name of the module containing Document classes

Returns:

A dictionary mapping class names to lists of SurrealDB drop statements

Return type:

Dict[str, List[str]]

quantumengine.generate_migration_statements(old_document_class, new_document_class, schemafull=True)[source]

Generate migration statements between two versions of a Document class.

Parameters:
  • old_document_class (Type[Document]) – The old version of the Document class

  • new_document_class (Type[Document]) – The new version of the Document class

  • schemafull (bool) – Whether to generate statements for SCHEMAFULL tables

Returns:

A dictionary with ‘up’ and ‘down’ migration statements

Return type:

Dict[str, List[str]]

async quantumengine.drop_tables_from_module(module_name, connection=None)[source]

Drop tables for all Document classes in a module asynchronously.

Parameters:
  • module_name (str) – The name of the module containing Document classes

  • connection (Any | None) – Optional connection to use

quantumengine.drop_tables_from_module_sync(module_name, connection=None)[source]

Drop tables for all Document classes in a module synchronously.

Parameters:
  • module_name (str) – The name of the module containing Document classes

  • connection (Any | None) – Optional connection to use

class quantumengine.DataGridQueryBuilder(document_class)[source]

Bases: object

Build efficient SurrealDB queries for DataGrid endpoints

__init__(document_class)[source]
apply_filters(filters)[source]

Apply field filters to the queryset

Parameters:

filters (Dict[str, Any]) – Dictionary of field->value filters

Apply text search across multiple fields using contains operator

Parameters:
  • search (str) – Search term

  • search_fields (List[str]) – List of fields to search in

apply_sorting(sort_field=None, sort_order='asc')[source]

Apply sorting to the queryset

Parameters:
  • sort_field (str | None) – Field to sort by

  • sort_order (str) – ‘asc’ or ‘desc’

async get_paginated_data(offset, limit)[source]

Get paginated data with total count

Parameters:
  • offset (int) – Number of records to skip

  • limit (int) – Number of records to return

Returns:

Tuple of (total_count, paginated_results)

get_paginated_data_sync(offset, limit)[source]

Synchronous version of get_paginated_data

async quantumengine.get_grid_data(document_class, request_args, search_fields, custom_filters=None, default_sort=None)[source]

Get paginated grid data using efficient SurrealDB queries

Parameters:
  • document_class – SurrealEngine document class

  • request_args (Dict[str, Any]) – Request parameters (limit, offset, search, etc.)

  • search_fields (List[str]) – List of fields to search in

  • custom_filters (Dict[str, str] | None) – Custom field filters from request

  • default_sort (str | None) – Default sorting field

Returns:

total, “rows”: rows} for BootstrapTable format

Return type:

{“total”

quantumengine.get_grid_data_sync(document_class, request_args, search_fields, custom_filters=None, default_sort=None)[source]

Synchronous version of get_grid_data

quantumengine.parse_datatables_params(request_args)[source]

Convert DataTables parameters to standard offset/limit format

quantumengine.format_datatables_response(total, rows, draw)[source]

Format response for DataTables

Document

class quantumengine.Document(**values)[source]

Bases: object

Base class for all documents.

This class provides the foundation for all document models in the ORM. It includes methods for CRUD operations, validation, and serialization.

The Document class uses a Meta inner class to configure behavior:

Example

>>> class User(Document):
...     username = StringField(required=True)
...     email = EmailField(required=True)
...     age = IntField(min_value=0)
...
...     class Meta:
...         collection = "users"          # Collection/table name
...         backend = "surrealdb"         # Backend to use
...         indexes = [                   # Index definitions
...             {"name": "idx_username", "fields": ["username"], "unique": True},
...             {"name": "idx_email", "fields": ["email"], "unique": True}
...         ]
...         strict = True                 # Strict field validation
Meta Options:
collection (str): The name of the collection/table in the database.

Defaults to the lowercase class name.

table_name (str): Alternative to ‘collection’, used by some backends.

Defaults to the value of ‘collection’.

backend (str): The database backend to use (“surrealdb” or “clickhouse”).

Defaults to “surrealdb”.

indexes (list): List of index definitions. Each index is a dict with:
  • name (str): Index name

  • fields (list): List of field names to index

  • unique (bool): Whether the index is unique (optional)

  • type (str): Index type for backend-specific indexes (optional)

id_field (str): Name of the ID field. Defaults to “id”.

strict (bool): Whether to raise errors for unknown fields.

Defaults to True.

objects

QuerySetDescriptor for querying documents of this class

_data

Dictionary of field values

Type:

Dict[str, Any]

_changed_fields

List of field names that have been changed

Type:

List[str]

_fields

Dictionary of fields for this document class (class attribute)

_fields_ordered

List of field names in order of definition (class attribute)

_meta

Dictionary of metadata for this document class (class attribute)

objects

Descriptor that provides QuerySet access through Document.objects.

This class is a descriptor that provides access to a QuerySet through the Document.objects attribute. It allows querying documents of a specific document class using the Document.objects attribute.

owner

The document class that owns this descriptor

connection

The database connection to use for queries

__init__(**values)[source]

Initialize a new Document.

Parameters:

**values (Any) – Field values to set on the document

Raises:

AttributeError – If strict mode is enabled and an unknown field is provided

__getattr__(name)[source]

Get a field value.

This method is called when an attribute is not found through normal lookup. It checks if the attribute is a field and returns its value if it is.

Parameters:

name (str) – Name of the attribute to get

Returns:

The field value

Raises:

AttributeError – If the attribute is not a field

Return type:

Any

__setattr__(name, value)[source]

Set a field value.

This method is called when an attribute is set. It checks if the attribute is a field and validates the value if it is.

Parameters:
  • name (str) – Name of the attribute to set

  • value (Any) – Value to set

property id: str | int | RecordID | None

Get the document ID.

Returns:

The document ID (string, RecordID, or None)

validate()[source]

Validate all fields.

This method validates all fields in the document against their validation rules.

Raises:

ValidationError – If a field fails validation

to_dict()[source]

Convert the document to a dictionary.

This method converts the document to a dictionary containing all field values including the document ID. It ensures that RecordID objects are properly converted to strings for JSON serialization. It also recursively converts embedded documents to dictionaries.

Returns:

Dictionary of field values including ID

Return type:

Dict[str, str | int | float | bool | None | Dict[str, Any] | List[Any]]

to_db()[source]

Convert the document to a database-friendly dictionary.

This method converts the document to a dictionary suitable for storage in the database. It applies field-specific conversions and includes only non-None values unless the field is required.

Returns:

Dictionary of field values for the database

Return type:

Dict[str, str | int | float | bool | None | Dict[str, Any] | List[Any]]

classmethod from_db(data, dereference=False)[source]

Create a document instance from database data.

Parameters:
  • data (Any) – Data from the database (dictionary, string, RecordID, etc.)

  • dereference (bool) – Whether to dereference references (default: False)

Returns:

A new document instance

Return type:

Document

async resolve_references(depth=1)[source]

Resolve all references in this document using FETCH.

This method uses SurrealDB’s FETCH clause to efficiently resolve references instead of making individual queries for each reference.

Parameters:

depth (int) – Maximum depth of reference resolution (default: 1)

Returns:

The document instance with resolved references

Return type:

Document

resolve_references_sync(depth=1)[source]

Resolve all references in this document synchronously using FETCH.

This method uses SurrealDB’s FETCH clause to efficiently resolve references instead of making individual queries for each reference.

Parameters:

depth (int) – Maximum depth of reference resolution (default: 1)

Returns:

The document instance with resolved references

Return type:

Document

async classmethod get(id, dereference=False, dereference_depth=1, **kwargs)[source]

Get a document by ID with optional dereferencing using FETCH.

This method retrieves a document by ID and optionally resolves references using SurrealDB’s FETCH clause for efficient reference resolution.

Parameters:
  • id (str | int | RecordID) – The ID of the document to retrieve

  • dereference (bool) – Whether to resolve references (default: False)

  • dereference_depth (int) – Maximum depth of reference resolution (default: 1)

  • **kwargs (Any) – Additional arguments to pass to the get method

Returns:

The document instance with optionally resolved references

Return type:

T

classmethod get_sync(id, dereference=False, dereference_depth=1, **kwargs)[source]

Get a document by ID with optional dereferencing synchronously using FETCH.

This method retrieves a document by ID and optionally resolves references using SurrealDB’s FETCH clause for efficient reference resolution.

Parameters:
  • id (str | int | RecordID) – The ID of the document to retrieve

  • dereference (bool) – Whether to resolve references (default: False)

  • dereference_depth (int) – Maximum depth of reference resolution (default: 1)

  • **kwargs (Any) – Additional arguments to pass to the get method

Returns:

The document instance with optionally resolved references

Return type:

T

async save(connection=None)[source]

Save the document to the database asynchronously.

This method saves the document to the database, either creating a new document or updating an existing one based on whether the document has an ID.

Parameters:

connection (Any | None) – The database connection to use (optional, deprecated for multi-backend)

Returns:

The saved document instance

Raises:

ValidationError – If the document fails validation

Return type:

T

save_sync(connection=None)[source]

Save the document to the database synchronously.

This method saves the document to the database, either creating a new document or updating an existing one based on whether the document has an ID.

Parameters:

connection (Any | None) – The database connection to use (optional)

Returns:

The saved document instance

Raises:

ValidationError – If the document fails validation

Return type:

T

async delete(connection=None)[source]

Delete the document from the database asynchronously.

This method deletes the document from the database.

Parameters:

connection (Any | None) – The database connection to use (optional)

Returns:

True if the document was deleted

Raises:

ValueError – If the document doesn’t have an ID

Return type:

bool

delete_sync(connection=None)[source]

Delete the document from the database synchronously.

This method deletes the document from the database.

Parameters:

connection (Any | None) – The database connection to use (optional)

Returns:

True if the document was deleted

Raises:

ValueError – If the document doesn’t have an ID

Return type:

bool

async refresh(connection=None)[source]

Refresh the document from the database asynchronously.

This method refreshes the document’s data from the database.

Parameters:

connection (Any | None) – The database connection to use (optional)

Returns:

The refreshed document instance

Raises:

ValueError – If the document doesn’t have an ID

Return type:

Document

refresh_sync(connection=None)[source]

Refresh the document from the database synchronously.

This method refreshes the document’s data from the database.

Parameters:

connection (Any | None) – The database connection to use (optional)

Returns:

The refreshed document instance

Raises:

ValueError – If the document doesn’t have an ID

Return type:

Document

classmethod relates(relation_name)[source]

Get a RelationQuerySet for a specific relation.

This method returns a function that creates a RelationQuerySet for the specified relation name. The function can be called with an optional connection parameter.

Parameters:

relation_name (str) – Name of the relation

Returns:

Function that creates a RelationQuerySet

Return type:

callable

async fetch_relation(relation_name, target_document=None, relation_document=None, connection=None, **filters)[source]

Fetch related documents asynchronously.

This method fetches documents related to this document through the specified relation.

Parameters:
  • relation_name (str) – Name of the relation

  • target_document (Type | None) – The document class of the target documents (optional)

  • relation_document (Type | None) – The document class representing the relation (optional)

  • connection (Any | None) – The database connection to use (optional)

  • **filters (Any) – Filters to apply to the related documents

Returns:

List of related documents, relation documents, or relation records

Return type:

List[Any]

fetch_relation_sync(relation_name, target_document=None, relation_document=None, connection=None, **filters)[source]

Fetch related documents synchronously.

This method fetches documents related to this document through the specified relation.

Parameters:
  • relation_name (str) – Name of the relation

  • target_document (Type | None) – The document class of the target documents (optional)

  • relation_document (Type | None) – The document class representing the relation (optional)

  • connection (Any | None) – The database connection to use (optional)

  • **filters (Any) – Filters to apply to the related documents

Returns:

List of related documents, relation documents, or relation records

Return type:

List[Any]

async resolve_relation(relation_name, target_document_class=None, relation_document=None, connection=None)[source]

Resolve related documents from a relation fetch result asynchronously.

This method resolves related documents from a relation fetch result. It fetches the relation data and then resolves each related document.

Parameters:
  • relation_name (str) – Name of the relation to resolve

  • target_document_class (Type | None) – Class of the target document (optional)

  • relation_document (Type | None) – The document class representing the relation (optional)

  • connection (Any | None) – Database connection to use (optional)

Returns:

List of resolved document instances

Return type:

List[Any]

resolve_relation_sync(relation_name, target_document_class=None, relation_document=None, connection=None)[source]

Resolve related documents from a relation fetch result synchronously.

This method resolves related documents from a relation fetch result. It fetches the relation data and then resolves each related document.

Parameters:
  • relation_name (str) – Name of the relation to resolve

  • target_document_class (Type | None) – Class of the target document (optional)

  • relation_document (Type | None) – The document class representing the relation (optional)

  • connection (Any | None) – Database connection to use (optional)

Returns:

List of resolved document instances

Return type:

List[Any]

async relate_to(relation_name, target_instance, connection=None, **attrs)[source]

Create a relation to another document asynchronously.

This method creates a relation from this document to another document.

Parameters:
  • relation_name (str) – Name of the relation

  • target_instance (Any) – The document instance to relate to

  • connection (Any | None) – The database connection to use (optional)

  • **attrs (Any) – Attributes to set on the relation

Returns:

The created relation record or None if creation failed

Return type:

Any | None

relate_to_sync(relation_name, target_instance, connection=None, **attrs)[source]

Create a relation to another document synchronously.

This method creates a relation from this document to another document.

Parameters:
  • relation_name (str) – Name of the relation

  • target_instance (Any) – The document instance to relate to

  • connection (Any | None) – The database connection to use (optional)

  • **attrs (Any) – Attributes to set on the relation

Returns:

The created relation record or None if creation failed

Return type:

Any | None

async update_relation_to(relation_name, target_instance, connection=None, **attrs)[source]

Update a relation to another document asynchronously.

This method updates a relation from this document to another document.

Parameters:
  • relation_name (str) – Name of the relation

  • target_instance (Any) – The document instance the relation is to

  • connection (Any | None) – The database connection to use (optional)

  • **attrs (Any) – Attributes to update on the relation

Returns:

The updated relation record or None if update failed

Return type:

Any | None

update_relation_to_sync(relation_name, target_instance, connection=None, **attrs)[source]

Update a relation to another document synchronously.

This method updates a relation from this document to another document.

Parameters:
  • relation_name (str) – Name of the relation

  • target_instance (Any) – The document instance the relation is to

  • connection (Any | None) – The database connection to use (optional)

  • **attrs (Any) – Attributes to update on the relation

Returns:

The updated relation record or None if update failed

Return type:

Any | None

async delete_relation_to(relation_name, target_instance=None, connection=None)[source]

Delete a relation to another document asynchronously.

This method deletes a relation from this document to another document. If target_instance is not provided, it deletes all relations with the specified name from this document.

Parameters:
  • relation_name (str) – Name of the relation

  • target_instance (Any | None) – The document instance the relation is to (optional)

  • connection (Any | None) – The database connection to use (optional)

Returns:

Number of deleted relations

Return type:

int

delete_relation_to_sync(relation_name, target_instance=None, connection=None)[source]

Delete a relation to another document synchronously.

This method deletes a relation from this document to another document. If target_instance is not provided, it deletes all relations with the specified name from this document.

Parameters:
  • relation_name (str) – Name of the relation

  • target_instance (Any | None) – The document instance the relation is to (optional)

  • connection (Any | None) – The database connection to use (optional)

Returns:

Number of deleted relations

Return type:

int

async traverse_path(path_spec, target_document=None, connection=None, **filters)[source]

Traverse a path in the graph asynchronously.

This method traverses a path in the graph starting from this document. The path_spec is a string like “->[watched]->->[acted_in]->” which describes a path through the graph.

Parameters:
  • path_spec (str) – String describing the path to traverse

  • target_document (Type | None) – The document class to return instances of (optional)

  • connection (Any | None) – The database connection to use (optional)

  • **filters (Any) – Filters to apply to the results

Returns:

List of documents or path results

Raises:

ValueError – If the document is not saved

Return type:

List[Any]

traverse_path_sync(path_spec, target_document=None, connection=None, **filters)[source]

Traverse a path in the graph synchronously.

This method traverses a path in the graph starting from this document. The path_spec is a string like “->[watched]->->[acted_in]->” which describes a path through the graph.

Parameters:
  • path_spec (str) – String describing the path to traverse

  • target_document (Type | None) – The document class to return instances of (optional)

  • connection (Any | None) – The database connection to use (optional)

  • **filters (Any) – Filters to apply to the results

Returns:

List of documents or path results

Raises:

ValueError – If the document is not saved

Return type:

List[Any]

async classmethod bulk_create(documents, batch_size=1000, validate=True, return_documents=True, connection=None)[source]

Create multiple documents in batches.

Parameters:
  • documents (List[Any]) – List of documents to create

  • batch_size (int) – Number of documents per batch

  • validate (bool) – Whether to validate documents before creation

  • return_documents (bool) – Whether to return created documents

Returns:

List of created documents if return_documents=True, else count of created documents

Return type:

List[Any] | int

classmethod bulk_create_sync(documents, batch_size=1000, validate=True, return_documents=True, connection=None)[source]

Create multiple documents in a single operation synchronously.

This method creates multiple documents in a single operation, processing them in batches for better performance. It can optionally validate the documents and return the created documents.

Parameters:
  • documents (List[Any]) – List of Document instances to create

  • batch_size (int) – Number of documents per batch (default: 1000)

  • validate (bool) – Whether to validate documents (default: True)

  • return_documents (bool) – Whether to return created documents (default: True)

  • connection (Any | None) – The database connection to use (optional)

Returns:

List of created documents with their IDs set if return_documents=True, otherwise returns the count of created documents

Return type:

List[Any] | int

async classmethod create_index(index_name, fields, unique=False, search=False, analyzer=None, comment=None, connection=None)[source]

Create an index on the document’s collection asynchronously.

Parameters:
  • index_name (str) – Name of the index

  • fields (List[str]) – List of field names to include in the index

  • unique (bool) – Whether the index should enforce uniqueness

  • search (bool) – Whether the index is a search index

  • analyzer (str | None) – Analyzer to use for search indexes

  • comment (str | None) – Optional comment for the index

  • connection (Any | None) – Optional connection to use

classmethod create_index_sync(index_name, fields, unique=False, search=False, analyzer=None, comment=None, connection=None)[source]

Create an index on the document’s collection synchronously.

Parameters:
  • index_name (str) – Name of the index

  • fields (List[str]) – List of field names to include in the index

  • unique (bool) – Whether the index should enforce uniqueness

  • search (bool) – Whether the index is a search index

  • analyzer (str | None) – Analyzer to use for search indexes

  • comment (str | None) – Optional comment for the index

  • connection (Any | None) – Optional connection to use

async classmethod create_indexes(connection=None)[source]

Create all indexes defined for this document class asynchronously.

This method creates indexes defined in the Meta class and also creates indexes for fields marked as indexed.

Parameters:

connection (Any | None) – Optional connection to use

classmethod create_indexes_sync(connection=None)[source]

Create all indexes defined for this document class synchronously.

This method creates indexes defined in the Meta class and also creates indexes for fields marked as indexed.

Parameters:

connection (Any | None) – Optional connection to use

async classmethod create_table(connection=None, schemafull=True)[source]

Create the table for this document class asynchronously.

Parameters:
  • connection (Any | None) – Optional connection to use

  • schemafull (bool) – Whether to create a SCHEMAFULL table (default: True)

classmethod create_table_sync(connection=None, schemafull=True)[source]

Create the table for this document class synchronously.

async classmethod drop_table(connection=None, if_exists=True)[source]

Drop the table for this document class asynchronously.

Parameters:
  • connection (Any | None) – Optional connection to use

  • if_exists (bool) – Whether to use IF EXISTS clause to avoid errors if table doesn’t exist

classmethod drop_table_sync(connection=None, if_exists=True)[source]

Drop the table for this document class synchronously.

Parameters:
  • connection (Any | None) – Optional connection to use

  • if_exists (bool) – Whether to use IF EXISTS clause to avoid errors if table doesn’t exist

classmethod to_dataclass()[source]

Convert the document class to a dataclass.

This method creates a dataclass based on the document’s fields. It uses the field names, types, and whether they are required. Required fields have no default value, making them required during initialization. Non-required fields use None as default if they don’t define one. A __post_init__ method is added to validate all fields after initialization.

Returns:

A dataclass type based on the document’s fields

classmethod create_materialized_view(name, query, refresh_interval=None, aggregations=None, select_fields=None, **kwargs)[source]

Create a materialized view based on a query.

This method creates a materialized view in SurrealDB based on a query. Materialized views are precomputed views of data that can be used to improve query performance for frequently accessed aggregated data.

Parameters:
  • name (str) – The name of the materialized view

  • query (QuerySet) – The query that defines the materialized view

  • refresh_interval (str) – The interval at which the view is refreshed (e.g., “1h”, “30m”)

  • aggregations – Dictionary of field names and aggregation functions

  • select_fields – List of fields to select (if None, selects all fields)

  • **kwargs – Additional keyword arguments to pass to the MaterializedView constructor

Returns:

A MaterializedView instance

Connection

quantumengine.create_connection(url=None, namespace=None, database=None, username=None, password=None, name=None, make_default=False, async_mode=True, use_pool=False, pool_size=10, max_idle_time=60, connect_timeout=30, operation_timeout=30, retry_limit=3, retry_delay=1.0, retry_backoff=2.0, validate_on_borrow=True, auto_connect=False, backend='surrealdb', **backend_kwargs)[source]

Factory function to create a connection for the specified backend.

Parameters:
  • url (str | None) – The URL of the database server (for SurrealDB) or host (for ClickHouse)

  • namespace (str | None) – The namespace to use (SurrealDB only)

  • database (str | None) – The database to use

  • username (str | None) – The username for authentication

  • password (str | None) – The password for authentication

  • name (str | None) – The name to register this connection under in the registry

  • make_default (bool) – Whether to set this connection as the default

  • async_mode (bool) – Whether to create an async or sync connection (SurrealDB only)

  • use_pool (bool) – Whether to use a connection pool (SurrealDB async_mode only)

  • pool_size (int) – The size of the connection pool

  • max_idle_time (int) – Maximum time in seconds a connection can be idle before being closed

  • connect_timeout (int) – Timeout in seconds for establishing a connection

  • operation_timeout (int) – Timeout in seconds for operations

  • retry_limit (int) – Maximum number of retries for failed operations

  • retry_delay (float) – Initial delay in seconds between retries

  • retry_backoff (float) – Backoff multiplier for retry delay

  • validate_on_borrow (bool) – Whether to validate connections when borrowing from the pool

  • auto_connect (bool) – Whether to automatically connect the connection

  • backend (str) – The backend type (‘surrealdb’, ‘clickhouse’, etc.)

  • **backend_kwargs – Additional backend-specific connection parameters

Returns:

A connection instance for the specified backend

Return type:

Any

Examples

SurrealDB connection (default):

surrealdb_conn = create_connection(
    url="ws://localhost:8000/rpc",
    namespace="test", database="test",
    username="root", password="root"
)

ClickHouse connection:

clickhouse_conn = create_connection(
    url="localhost", database="default",
    username="default", password="",
    backend="clickhouse", port=8123
)

Fields

Backends

Query System

Exceptions