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
- 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:
- 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:
- 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.
- 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
- __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:
- 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.
- 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.
- 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:
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)
- _default_sync_connection¶
The default sync connection to use when none is specified (legacy)
- Type:
- _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}
- classmethod add_async_connection(name, connection)[source]¶
Add a named async connection to the registry.
- Parameters:
name (str) – The name to register the connection under
connection (SurrealEngineAsyncConnection) – The async connection to register
- classmethod add_connection(name, connection)[source]¶
Add a named connection to the registry based on its type.
- Parameters:
name (str) – The name to register the connection under
connection (SurrealEngineAsyncConnection | SurrealEngineSyncConnection) – The connection to register
- classmethod add_sync_connection(name, connection)[source]¶
Add a named sync connection to the registry.
- Parameters:
name (str) – The name to register the connection under
connection (SurrealEngineSyncConnection) – The sync connection to register
- classmethod get_async_connection(name)[source]¶
Get a named async connection from the registry.
- classmethod get_connection(name, async_mode=True)[source]¶
Get a named connection from the registry based on the mode.
- Parameters:
- Returns:
The requested connection of the requested type
- Raises:
KeyError – If no connection of the requested type with the given name exists
- Return type:
- classmethod get_connection_by_backend(name, backend='surrealdb')[source]¶
Get a named connection for a specific backend.
- Parameters:
- Returns:
The requested connection
- Raises:
ValueError – If the connection is not found
- Return type:
- 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:
- 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:
- 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:
- classmethod get_sync_connection(name)[source]¶
Get a named sync connection from the registry.
- classmethod register(name, connection, backend='surrealdb')[source]¶
Register a connection for a specific backend.
- classmethod set_default(backend, connection_name)[source]¶
Set the default connection for a backend.
- 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:
- __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.
- async classmethod bulk_create(documents, batch_size=1000, validate=True, return_documents=True, connection=None)[source]¶
Create multiple documents in batches.
- Parameters:
- Returns:
List of created documents if return_documents=True, else count of created documents
- Return type:
- 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:
- 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.
- 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:
- 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.
- 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.
- 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:
- async classmethod drop_table(connection=None, if_exists=True)[source]¶
Drop the table for this document class asynchronously.
- classmethod drop_table_sync(connection=None, if_exists=True)[source]¶
Drop the table for this document class synchronously.
- 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:
- 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:
- classmethod from_db(data, dereference=False)[source]¶
Create a document instance from database data.
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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.
- 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.
- 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:
- Returns:
List of resolved document instances
- Return type:
- 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:
- Returns:
List of resolved document instances
- Return type:
- 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.
- 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.
- 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:
- Returns:
List of documents or path results
- Raises:
ValueError – If the document is not saved
- Return type:
- 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:
- Returns:
List of documents or path results
- Raises:
ValueError – If the document is not saved
- Return type:
- 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:
- 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:
- 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().
- 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:
- Returns:
A RelationDocument instance representing the relationship
- Raises:
ValueError – If either instance is not saved
- Return type:
- 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:
- Returns:
A RelationDocument instance representing the relationship
- Raises:
ValueError – If either instance is not saved
- Return type:
- 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:
- 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.
- 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
- 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.
- 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.
- 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]¶
-
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.
- 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:
- class quantumengine.NumberField(min_value=None, max_value=None, **kwargs)[source]¶
-
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
- 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:
- 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
- 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.
- class quantumengine.BooleanField(**kwargs)[source]¶
-
Boolean field type.
This field type stores boolean values and provides validation to ensure the value is a boolean.
- class quantumengine.DateTimeField(**kwargs)[source]¶
-
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
- 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
- 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.
- 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.
- 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:
- 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
- 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.
- 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.
- 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
- 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.
- 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:
- 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
- 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.
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:
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:
- 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
- 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.
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:
- 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
- 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.
- 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.
- 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:
- Returns:
List of created documents with their IDs set if return_documents=True, otherwise returns the count of created documents
- Return type:
- 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:
- Returns:
List of created documents with their IDs set if return_documents=True, otherwise returns the count of created documents
- Return type:
- 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:
- 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:
- 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:
- 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:
- 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.
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
- 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:
- Returns:
The matching document
- Raises:
DoesNotExist – If no matching document is found
MultipleObjectsReturned – If multiple matching documents are found
- 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:
- Returns:
The matching document
- Raises:
DoesNotExist – If no matching document is found
MultipleObjectsReturned – If multiple matching documents are found
- 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:
- 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:
- suggest_indexes()[source]¶
Suggest indexes based on current query patterns.
Analyzes the current query conditions and suggests optimal indexes that could improve performance.
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.
- 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
- 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:
- 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:
- 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:
- 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:
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:
- 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:
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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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)
- __init__(**kwargs)[source]¶
Initialize a query expression.
- Parameters:
**kwargs – Field filters to include in the query
- 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:
- group_by(*fields)[source]¶
Add GROUP BY clause.
- Parameters:
*fields (str) – Field names to group by
- Returns:
Self for method chaining
- Return type:
- limit(value)[source]¶
Add LIMIT clause.
- Parameters:
value (int) – Maximum number of results
- Returns:
Self for method chaining
- Return type:
- order_by(field, direction='ASC')[source]¶
Add ORDER BY clause.
- Parameters:
- Returns:
Self for method chaining
- Return type:
- 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.
- 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.
- 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
- 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.
- 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.
- 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:
- 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()])
- 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.
- 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.
- 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:
- 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())
- 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:
- 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.
- 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”
- 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.
- 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'])
- 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
- 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.
- 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
- 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.
- class quantumengine.Count(field=None)[source]¶
Bases:
Aggregation
Count aggregation function.
This class represents the count() aggregation function in SurrealQL.
- class quantumengine.Mean(field=None)[source]¶
Bases:
Aggregation
Mean aggregation function.
This class represents the math::mean() aggregation function in SurrealQL.
- class quantumengine.Sum(field=None)[source]¶
Bases:
Aggregation
Sum aggregation function.
This class represents the math::sum() aggregation function in SurrealQL.
- class quantumengine.Min(field=None)[source]¶
Bases:
Aggregation
Min aggregation function.
This class represents the math::min() aggregation function in SurrealQL.
- class quantumengine.Max(field=None)[source]¶
Bases:
Aggregation
Max aggregation function.
This class represents the math::max() aggregation function in SurrealQL.
- class quantumengine.ArrayCollect(field=None)[source]¶
Bases:
Aggregation
Array collect aggregation function.
This class represents the array::collect() aggregation function in SurrealQL.
- class quantumengine.Median(field=None)[source]¶
Bases:
Aggregation
Median aggregation function.
This class represents the math::median() aggregation function in SurrealQL.
- class quantumengine.StdDev(field=None)[source]¶
Bases:
Aggregation
Standard deviation aggregation function.
This class represents the math::stddev() aggregation function in SurrealQL.
- class quantumengine.Variance(field=None)[source]¶
Bases:
Aggregation
Variance aggregation function.
This class represents the math::variance() aggregation function in SurrealQL.
- class quantumengine.Percentile(field=None, percentile=50)[source]¶
Bases:
Aggregation
Percentile aggregation function.
This class represents the math::percentile() aggregation function in SurrealQL.
- class quantumengine.Distinct(field=None)[source]¶
Bases:
Aggregation
Distinct aggregation function.
This class represents the array::distinct() aggregation function in SurrealQL.
- 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.
- quantumengine.get_document_classes(module_name)[source]¶
Get all Document classes defined in a module.
- async quantumengine.create_tables_from_module(module_name, connection=None, schemafull=True)[source]¶
Create tables for all Document classes in a module asynchronously.
- quantumengine.create_tables_from_module_sync(module_name, connection=None, schemafull=True)[source]¶
Create tables for all Document classes in a module synchronously.
- 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.
- quantumengine.generate_schema_statements_from_module(module_name, schemafull=True)[source]¶
Generate SurrealDB schema statements for all Document classes in a module.
- 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.
- quantumengine.generate_drop_statements_from_module(module_name)[source]¶
Generate SurrealDB DROP statements for all Document classes in a module.
- quantumengine.generate_migration_statements(old_document_class, new_document_class, schemafull=True)[source]¶
Generate migration statements between two versions of a Document class.
- Parameters:
- Returns:
A dictionary with ‘up’ and ‘down’ migration statements
- Return type:
- async quantumengine.drop_tables_from_module(module_name, connection=None)[source]¶
Drop tables for all Document classes in a module asynchronously.
- quantumengine.drop_tables_from_module_sync(module_name, connection=None)[source]¶
Drop tables for all Document classes in a module synchronously.
- class quantumengine.DataGridQueryBuilder(document_class)[source]¶
Bases:
object
Build efficient SurrealDB queries for DataGrid endpoints
- apply_search(search, search_fields)[source]¶
Apply text search across multiple fields using contains operator
- 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:
- 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
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
- _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:
- __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.
- 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.
- 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.
- classmethod from_db(data, dereference=False)[source]¶
Create a document instance from database data.
- 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.
- 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.
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- Returns:
List of resolved document instances
- Return type:
- 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:
- Returns:
List of resolved document instances
- Return type:
- 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:
- 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:
- 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:
- 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:
- 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.
- 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.
- 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:
- Returns:
List of documents or path results
- Raises:
ValueError – If the document is not saved
- Return type:
- 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:
- Returns:
List of documents or path results
- Raises:
ValueError – If the document is not saved
- Return type:
- async classmethod bulk_create(documents, batch_size=1000, validate=True, return_documents=True, connection=None)[source]¶
Create multiple documents in batches.
- Parameters:
- Returns:
List of created documents if return_documents=True, else count of created documents
- Return type:
- 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:
- 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.
- 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.
- classmethod drop_table_sync(connection=None, if_exists=True)[source]¶
Drop the table for this document class synchronously.
- 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:
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¶
- Exceptions API
- Core Exceptions Module
- Base Exception Classes
- Validation Exceptions
- Database Exceptions
- Backend-Specific Exceptions
- Document Exceptions
- Configuration Exceptions
- Field-Specific Exceptions
- Query-Specific Exceptions
- Schema Exceptions
- Security Exceptions
- Performance Exceptions
- Serialization Exceptions
- Exception Utilities
- Custom Exception Base Classes
- Exception Context Management
- Exception Reporting
- See Also