Backends API¶
This section provides the complete API reference for QuantumEngine’s backend system.
Connection Management¶
- class quantumengine.connection.ConnectionPoolBase(url, namespace=None, database=None, username=None, password=None, 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:
ABC
Base class for connection pools.
This abstract class defines the common interface and functionality for both synchronous and asynchronous connection pools.
- 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
- pool_size¶
Maximum number of connections in the pool
- max_idle_time¶
Maximum time in seconds a connection can be idle before being closed
- connect_timeout¶
Timeout in seconds for establishing a connection
- operation_timeout¶
Timeout in seconds for operations
- retry_limit¶
Maximum number of retries for failed operations
- retry_delay¶
Initial delay in seconds between retries
- retry_backoff¶
Backoff multiplier for retry delay
- validate_on_borrow¶
Whether to validate connections when borrowing from the pool
- __init__(url, namespace=None, database=None, username=None, password=None, 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 ConnectionPoolBase.
- Parameters:
url (str) – 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
pool_size (int) – Maximum number of connections in the 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
- abstractmethod create_connection()[source]¶
Create a new connection.
- Returns:
A new connection
- Return type:
- abstractmethod close_connection(connection)[source]¶
Close a connection.
- Parameters:
connection (Any) – The connection to close
- abstractmethod get_connection()[source]¶
Get a connection from the pool.
- Returns:
A connection from the pool
- Return type:
- class quantumengine.connection.SyncConnectionPool(url, namespace=None, database=None, username=None, password=None, 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:
ConnectionPoolBase
Synchronous connection pool for SurrealDB.
This class manages a pool of synchronous connections to a SurrealDB database. It handles connection creation, validation, and reuse, and provides methods for acquiring and releasing connections.
The connections returned by this pool are wrapped in SurrealEngineSyncConnection objects, which can be used with the Document class and other SurrealEngine functionality that expects a SurrealEngineSyncConnection.
- pool¶
Queue of available connections
- in_use¶
Set of connections currently in use
- lock¶
Lock for thread-safe operations
- closed¶
Whether the pool is closed
- __init__(url, namespace=None, database=None, username=None, password=None, 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 SyncConnectionPool.
- Parameters:
url (str) – 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
pool_size (int) – Maximum number of connections in the 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
- create_connection()[source]¶
Create a new connection.
- Returns:
A new connection wrapped in SurrealEngineSyncConnection
- Raises:
Exception – If the connection cannot be created
- Return type:
- validate_connection(connection)[source]¶
Validate a connection.
- Parameters:
connection (SurrealEngineSyncConnection) – The connection to validate (SurrealEngineSyncConnection)
- Returns:
True if the connection is valid, False otherwise
- Return type:
- close_connection(connection)[source]¶
Close a connection.
- Parameters:
connection (SurrealEngineSyncConnection) – The connection to close (SurrealEngineSyncConnection)
- get_connection()[source]¶
Get a connection from the pool.
- Returns:
A SurrealEngineSyncConnection from the pool
- Raises:
RuntimeError – If the pool is closed
Exception – If a connection cannot be obtained
- Return type:
- return_connection(connection)[source]¶
Return a connection to the pool.
- Parameters:
connection (SurrealEngineSyncConnection) – The connection to return (SurrealEngineSyncConnection)
- class quantumengine.connection.AsyncConnectionPool(url, namespace=None, database=None, username=None, password=None, 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:
ConnectionPoolBase
Asynchronous connection pool for SurrealDB.
This class manages a pool of asynchronous connections to a SurrealDB database. It handles connection creation, validation, and reuse, and provides methods for acquiring and releasing connections.
The connections returned by this pool are wrapped in SurrealEngineAsyncConnection objects, which can be used with the Document class and other SurrealEngine functionality that expects a SurrealEngineAsyncConnection.
- pool¶
List of available connections
- in_use¶
Dictionary of connections currently in use and their timestamps
- lock¶
Asyncio lock for thread-safe operations
- closed¶
Whether the pool is closed
- __init__(url, namespace=None, database=None, username=None, password=None, 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 AsyncConnectionPool.
- Parameters:
url (str) – 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
pool_size (int) – Maximum number of connections in the 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 create_connection()[source]¶
Create a new connection.
- Returns:
A new connection wrapped in SurrealEngineAsyncConnection
- Raises:
Exception – If the connection cannot be created
- Return type:
- async validate_connection(connection)[source]¶
Validate a connection.
- Parameters:
connection (SurrealEngineAsyncConnection) – The connection to validate (SurrealEngineAsyncConnection)
- Returns:
True if the connection is valid, False otherwise
- Return type:
- async close_connection(connection)[source]¶
Close a connection.
- Parameters:
connection (SurrealEngineAsyncConnection) – The connection to close (SurrealEngineAsyncConnection)
- async get_connection()[source]¶
Get a connection from the pool.
- Returns:
A SurrealEngineAsyncConnection from the pool
- Raises:
RuntimeError – If the pool is closed
Exception – If a connection cannot be obtained
- Return type:
- async return_connection(connection)[source]¶
Return a connection to the pool.
- Parameters:
connection (SurrealEngineAsyncConnection) – The connection to return (SurrealEngineAsyncConnection)
- class quantumengine.connection.ConnectionEvent[source]¶
Bases:
object
Event types for connection events.
This class defines the event types that can be emitted by connections.
- CONNECTED = 'connected'¶
- DISCONNECTED = 'disconnected'¶
- RECONNECTING = 'reconnecting'¶
- RECONNECTED = 'reconnected'¶
- CONNECTION_FAILED = 'connection_failed'¶
- RECONNECTION_FAILED = 'reconnection_failed'¶
- CONNECTION_CLOSED = 'connection_closed'¶
- class quantumengine.connection.ConnectionEventListener[source]¶
Bases:
object
Listener for connection events.
This class defines the interface for connection event listeners.
- class quantumengine.connection.ConnectionEventEmitter[source]¶
Bases:
object
Emitter for connection events.
This class provides methods for registering listeners and emitting events.
- listeners¶
List of registered event listeners
- add_listener(listener)[source]¶
Add a listener for connection events.
- Parameters:
listener (ConnectionEventListener) – The listener to add
- remove_listener(listener)[source]¶
Remove a listener for connection events.
- Parameters:
listener (ConnectionEventListener) – The listener to remove
- class quantumengine.connection.OperationQueue[source]¶
Bases:
object
Queue for operations during reconnection.
This class manages a queue of operations that are waiting for a connection to be reestablished. Once the connection is restored, the operations are executed in the order they were queued.
- sync_operations¶
Queue of synchronous operations
- async_operations¶
Queue of asynchronous operations
- is_reconnecting¶
Whether the connection is currently reconnecting
- reconnection_event¶
Event that is set when reconnection is complete
- async_reconnection_event¶
Asyncio event that is set when reconnection is complete
- start_reconnection()[source]¶
Start the reconnection process.
This method marks the connection as reconnecting and clears the reconnection events.
- end_reconnection()[source]¶
End the reconnection process.
This method marks the connection as no longer reconnecting and sets the reconnection events.
- class quantumengine.connection.ReconnectionStrategy(max_attempts=10, initial_delay=1.0, max_delay=60.0, backoff_factor=2.0)[source]¶
Bases:
object
Strategy for reconnecting to the database.
This class provides methods for reconnecting to the database with configurable retry limits and backoff strategies.
- max_attempts¶
Maximum number of reconnection attempts
- initial_delay¶
Initial delay in seconds between reconnection attempts
- max_delay¶
Maximum delay in seconds between reconnection attempts
- backoff_factor¶
Backoff multiplier for reconnection delay
- class quantumengine.connection.RetryStrategy(retry_limit=3, retry_delay=1.0, retry_backoff=2.0)[source]¶
Bases:
object
Strategy for retrying operations with exponential backoff.
This class provides methods for retrying operations with configurable retry limits and backoff strategies.
- retry_limit¶
Maximum number of retries
- retry_delay¶
Initial delay in seconds between retries
- retry_backoff¶
Backoff multiplier for retry delay
- __init__(retry_limit=3, retry_delay=1.0, retry_backoff=2.0)[source]¶
Initialize a new RetryStrategy.
- quantumengine.connection.parse_connection_string(connection_string)[source]¶
Parse a connection string into a dictionary of connection parameters.
Supports the following formats: - surrealdb://user:pass@host:port/namespace/database?param1=value1¶m2=value2 (maps to ws://) - wss://user:pass@host:port/namespace/database?param1=value1¶m2=value2 - ws://user:pass@host:port/namespace/database?param1=value1¶m2=value2 - http://user:pass@host:port/namespace/database?param1=value1¶m2=value2 - https://user:pass@host:port/namespace/database?param1=value1¶m2=value2
Connection string parameters: - pool_size: Maximum number of connections in the pool (default: 10) - max_idle_time: Maximum time in seconds a connection can be idle before being closed (default: 60) - connect_timeout: Timeout in seconds for establishing a connection (default: 30) - operation_timeout: Timeout in seconds for operations (default: 30) - retry_limit: Maximum number of retries for failed operations (default: 3) - retry_delay: Initial delay in seconds between retries (default: 1) - retry_backoff: Backoff multiplier for retry delay (default: 2) - validate_on_borrow: Whether to validate connections when borrowing from the pool (default: true)
- Parameters:
connection_string (str) – The connection string to parse
- Returns:
A dictionary containing the parsed connection parameters
- Raises:
ValueError – If the connection string is invalid
- Return type:
- class quantumengine.connection.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.
- property db: SurrealEngine¶
Get dynamic table accessor.
- __init__(*args, **kwargs)¶
- class quantumengine.connection.ConnectionPoolClient(pool)[source]¶
Bases:
object
Client that proxies requests to connections from a connection pool.
This class provides the same interface as the SurrealDB client but gets a connection from the pool for each operation and returns it when done.
- pool¶
The connection pool to get connections from
- __init__(pool)[source]¶
Initialize a new ConnectionPoolClient.
- Parameters:
pool (AsyncConnectionPool) – The connection pool to get connections from
- class quantumengine.connection.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 set_default_async_connection(connection)[source]¶
Set the default async connection.
- Parameters:
connection (SurrealEngineAsyncConnection) – The async 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
- 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 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_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 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_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 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 get_async_connection(name)[source]¶
Get a named async connection from the registry.
- classmethod get_sync_connection(name)[source]¶
Get a named sync 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 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 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_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:
- class quantumengine.connection.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
- __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 __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
- property db: SurrealEngine¶
Get dynamic table accessor.
- Returns:
A SurrealEngine instance for accessing tables dynamically
- 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:
- 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.
- quantumengine.connection.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.connection.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
- __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
- __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
- property db: SurrealEngine¶
Get dynamic table accessor.
- Returns:
A SurrealEngine instance for accessing tables dynamically
- 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:
- disconnect()[source]¶
Disconnect from the database.
This method closes the client connection if one exists.
Backend Configuration¶
Backend configuration and management utilities for connecting to different database systems.
Configuration Functions¶
Connection Functions¶
Backend Implementations¶
SurrealDB Backend¶
SurrealDB-specific backend implementation for multi-model database operations.
- class quantumengine.backends.surrealdb.SurrealDBBackend(connection)[source]¶
Bases:
BaseBackend
SurrealDB backend implementation.
This backend implements the BaseBackend interface for SurrealDB, providing all the core database operations using SurrealQL.
- __init__(connection)[source]¶
Initialize the SurrealDB backend.
- Parameters:
connection (Any) – SurrealEngine connection (async or sync)
- async create_table(document_class, **kwargs)[source]¶
Create a table/collection for the document class.
- Parameters:
document_class (Type) – The document class to create a table for
**kwargs – Backend-specific options: - schemafull: Whether to create a schemafull table (default: True)
- async select(table_name, conditions, fields=None, limit=None, offset=None, order_by=None)[source]¶
Select documents from a table.
- Parameters:
- Returns:
List of matching documents
- Return type:
- async select_by_ids(table_name, ids)[source]¶
Select documents by their IDs using direct record access.
- async drop_table(table_name, if_exists=True)[source]¶
Drop a table using SurrealDB’s REMOVE TABLE statement.
- async begin_transaction()[source]¶
Begin a transaction.
- Returns:
Transaction object (SurrealDB client for now)
- Return type:
- async commit_transaction(transaction)[source]¶
Commit a transaction.
- Parameters:
transaction (Any) – The transaction object
- async rollback_transaction(transaction)[source]¶
Rollback a transaction.
- Parameters:
transaction (Any) – The transaction object
- async create_relation(from_table, from_id, relation_name, to_table, to_id, attributes=None)[source]¶
Create a relation using SurrealDB’s RELATE statement.
- Parameters:
- Returns:
The created relation record
- Return type:
- async delete_relation(from_table, from_id, relation_name, to_table=None, to_id=None)[source]¶
Delete relations using SurrealDB’s DELETE statement.
- async query_relations(from_table, from_id, relation_name, direction='out')[source]¶
Query relations using SurrealDB’s graph traversal.
- async create_materialized_view(materialized_document_class)[source]¶
Create a SurrealDB materialized view using DEFINE TABLE … AS SELECT.
- Parameters:
materialized_document_class (Type) – The MaterializedDocument class
ClickHouse Backend¶
ClickHouse-specific backend implementation for analytical workloads.
- class quantumengine.backends.clickhouse.ClickHouseBackend(connection)[source]¶
Bases:
BaseBackend
ClickHouse backend implementation using clickhouse-connect.
- __init__(connection)[source]¶
Initialize the ClickHouse backend.
- Parameters:
connection (Any) – ClickHouse client connection
- async create_table(document_class, **kwargs)[source]¶
Create a table for the document class with advanced ClickHouse features.
- Parameters:
document_class (Type) – The document class to create a table for
**kwargs – Backend-specific options (override Meta settings): - engine: ClickHouse table engine (default: MergeTree) - engine_params: Parameters for the engine (e.g., [‘date_collected’] for ReplacingMergeTree) - order_by: Order by columns (default: [‘id’]) - partition_by: Partition by expression - primary_key: Primary key columns - settings: Additional table settings - ttl: TTL expression for data lifecycle
- async select(table_name, conditions, fields=None, limit=None, offset=None, order_by=None)[source]¶
Select documents from a table.
- Parameters:
- Returns:
List of matching documents
- Return type:
- async update(table_name, conditions, data)[source]¶
Update documents matching conditions.
Note: ClickHouse uses ALTER TABLE UPDATE which is asynchronous and doesn’t immediately return updated rows.
- async delete(table_name, conditions)[source]¶
Delete documents matching conditions.
Note: ClickHouse uses ALTER TABLE DELETE which is asynchronous.
- async drop_table(table_name, if_exists=True)[source]¶
Drop a table using ClickHouse’s DROP TABLE statement.
- async begin_transaction()[source]¶
Begin a transaction.
Note: ClickHouse has limited transaction support.
- async rollback_transaction(transaction)[source]¶
Rollback a transaction.
Note: No-op for ClickHouse.
- async create_materialized_view(materialized_document_class)[source]¶
Create a ClickHouse materialized view.
- Parameters:
materialized_document_class (Type) – The MaterializedDocument class
Backend Interface¶
Base Backend Classes¶
Abstract base classes that define the backend interface.
- class quantumengine.backends.base.BaseBackend(connection)[source]¶
Bases:
ABC
Abstract base class for database backends.
All database backends must implement this interface to work with QuantumEngine.
- __init__(connection)[source]¶
Initialize the backend with a connection.
- Parameters:
connection (Any) – The database connection object
- abstractmethod async create_table(document_class, **kwargs)[source]¶
Create a table/collection for the document class.
- Parameters:
document_class (Type) – The document class to create a table for
**kwargs – Backend-specific options (e.g., schemafull for SurrealDB)
- abstractmethod async select(table_name, conditions, fields=None, limit=None, offset=None, order_by=None)[source]¶
Select documents from a table.
- Parameters:
table_name (str) – The table/collection name
conditions (List[str]) – List of condition strings (already formatted by build_condition)
fields (List[str] | None) – List of fields to return (None for all fields)
limit (int | None) – Maximum number of results
offset (int | None) – Number of results to skip
order_by (List[tuple[str, str]] | None) – List of (field, direction) tuples for ordering
- Returns:
List of matching documents
- Return type:
- abstractmethod async update(table_name, conditions, data)[source]¶
Update documents matching conditions.
- abstractmethod build_condition(field, operator, value)[source]¶
Build a condition string for the backend’s query language.
- abstractmethod get_field_type(field)[source]¶
Get the database field type for a SurrealEngine field.
- abstractmethod format_value(value, field_type=None)[source]¶
Format a value for the backend’s query language.
- abstractmethod async begin_transaction()[source]¶
Begin a transaction.
- Returns:
Transaction object (backend-specific)
- Return type:
- abstractmethod async commit_transaction(transaction)[source]¶
Commit a transaction.
- Parameters:
transaction (Any) – The transaction object
- abstractmethod async rollback_transaction(transaction)[source]¶
Rollback a transaction.
- Parameters:
transaction (Any) – The transaction object
- supports_transactions()[source]¶
Check if the backend supports transactions.
- Returns:
True if transactions are supported, False otherwise
- Return type:
- supports_references()[source]¶
Check if the backend supports references/foreign keys.
- Returns:
True if references are supported, False otherwise
- Return type:
- supports_graph_relations()[source]¶
Check if the backend supports graph-style relations.
- Returns:
True if graph relations are supported, False otherwise
- Return type:
- supports_direct_record_access()[source]¶
Check if the backend supports direct record access syntax.
- Returns:
True if direct record access is supported, False otherwise
- Return type:
- supports_explain()[source]¶
Check if the backend supports EXPLAIN queries.
- Returns:
True if EXPLAIN is supported, False otherwise
- Return type:
- supports_indexes()[source]¶
Check if the backend supports indexes.
- Returns:
True if indexes are supported, False otherwise
- Return type:
- supports_full_text_search()[source]¶
Check if the backend supports full-text search.
- Returns:
True if full-text search is supported, False otherwise
- Return type:
- supports_bulk_operations()[source]¶
Check if the backend supports bulk insert/update/delete operations.
- Returns:
True if bulk operations are supported, False otherwise
- Return type:
- supports_schemas()[source]¶
Check if this backend supports strict schemas.
- Returns:
True if schemas are supported
- Return type:
- async create_relation(from_table, from_id, relation_name, to_table, to_id, attributes=None)[source]¶
Create a relation between two documents.
- Parameters:
- Returns:
The created relation record or None
- Raises:
NotImplementedError – If backend doesn’t support graph relations
- Return type:
- async delete_relation(from_table, from_id, relation_name, to_table=None, to_id=None)[source]¶
Delete relations.
- Parameters:
- Returns:
Number of relations deleted
- Raises:
NotImplementedError – If backend doesn’t support graph relations
- Return type:
- async query_relations(from_table, from_id, relation_name, direction='out')[source]¶
Query relations from a document.
- Parameters:
- Returns:
List of related documents
- Raises:
NotImplementedError – If backend doesn’t support graph relations
- Return type:
Backend Registry¶
Registry system for managing available backends.
Schema Management¶
Schema definition and management for different backends.
- quantumengine.schema.get_document_classes(module_name)[source]¶
Get all Document classes defined in a module.
- async quantumengine.schema.create_tables_from_module(module_name, connection=None, schemafull=True)[source]¶
Create tables for all Document classes in a module asynchronously.
- quantumengine.schema.create_tables_from_module_sync(module_name, connection=None, schemafull=True)[source]¶
Create tables for all Document classes in a module synchronously.
- quantumengine.schema.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.schema.generate_schema_statements_from_module(module_name, schemafull=True)[source]¶
Generate SurrealDB schema statements for all Document classes in a module.
- quantumengine.schema.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.schema.generate_drop_statements_from_module(module_name)[source]¶
Generate SurrealDB DROP statements for all Document classes in a module.
- quantumengine.schema.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.schema.drop_tables_from_module(module_name, connection=None)[source]¶
Drop tables for all Document classes in a module asynchronously.
- quantumengine.schema.drop_tables_from_module_sync(module_name, connection=None)[source]¶
Drop tables for all Document classes in a module synchronously.
Schemaless Operations¶
Support for schemaless document operations.
- class quantumengine.schemaless.SchemalessQuerySet(table_name, connection)[source]¶
Bases:
BaseQuerySet
QuerySet for schemaless operations.
This class provides a query builder for tables without a predefined schema. It extends BaseQuerySet to provide methods for querying and manipulating documents in a schemaless manner.
- table_name¶
The name of the table to query
- connection¶
The database connection to use for queries
- async all()[source]¶
Execute the query and return all results asynchronously.
This method builds and executes the query, then processes the results based on whether a matching document class is found. If a matching document class is found, the results are converted to instances of that class. Otherwise, they are converted to SimpleNamespace objects.
- all_sync()[source]¶
Execute the query and return all results synchronously.
This method builds and executes the query, then processes the results based on whether a matching document class is found. If a matching document class is found, the results are converted to instances of that class. Otherwise, they are converted to SimpleNamespace objects.
- async get(**kwargs)[source]¶
Get a single document matching the query asynchronously.
This method provides special handling for ID-based lookups, using the direct select method with RecordID. For non-ID lookups, it falls back to the base class implementation.
- Parameters:
**kwargs (Any) – Field names and values to filter by
- Returns:
The matching document
- Raises:
DoesNotExist – If no matching document is found
MultipleObjectsReturned – If multiple matching documents are found
- Return type:
- get_sync(**kwargs)[source]¶
Get a single document matching the query synchronously.
This method provides special handling for ID-based lookups, using the direct select method with RecordID. For non-ID lookups, it falls back to the base class implementation.
- Parameters:
**kwargs (Any) – Field names and values to filter by
- Returns:
The matching document
- Raises:
DoesNotExist – If no matching document is found
MultipleObjectsReturned – If multiple matching documents are found
- Return type:
- async bulk_create(documents, batch_size=1000, 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 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, 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 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:
- class quantumengine.schemaless.SchemalessTable(name, connection)[source]¶
Bases:
object
Dynamic table accessor.
This class provides access to a specific table in the database without requiring a predefined schema. It allows querying the table using the objects property or by calling the instance directly with filters.
- name¶
The name of the table
- connection¶
The database connection to use for queries
- async relate(from_id, relation, to_id, **attrs)[source]¶
Create a relation between two records asynchronously.
This method creates a relation between two records 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
- Return type:
Any | None
- relate_sync(from_id, relation, to_id, **attrs)[source]¶
Create a relation between two records synchronously.
This method creates a relation between two records 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
- Return type:
Any | None
Get related records asynchronously.
This method retrieves records related to the given record through the specified relation. It can return either the target records or the relation records themselves.
- Parameters:
- Returns:
List of related records or relation records
- Return type:
Get related records synchronously.
This method retrieves records related to the given record through the specified relation. It can return either the target records or the relation records themselves.
- Parameters:
- Returns:
List of related records or relation records
- Return type:
- async update_relation(from_id, relation, to_id, **attrs)[source]¶
Update an existing relation asynchronously.
This method updates an existing relation between two records in the database. If the relation doesn’t exist, it creates it.
- Parameters:
- Returns:
The updated relation record or None if update failed
- Return type:
Any | None
- update_relation_sync(from_id, relation, to_id, **attrs)[source]¶
Update an existing relation synchronously.
This method updates an existing relation between two records in the database. If the relation doesn’t exist, it creates it.
- Parameters:
- Returns:
The updated relation record or None if update failed
- Return type:
Any | None
- async delete_relation(from_id, relation, to_id=None)[source]¶
Delete a relation asynchronously.
This method deletes a relation between two records in the database. If to_id is not provided, it deletes all relations from from_id.
- delete_relation_sync(from_id, relation, to_id=None)[source]¶
Delete a relation synchronously.
This method deletes a relation between two records in the database. If to_id is not provided, it deletes all relations from from_id.
- async create_index(index_name, fields, unique=False, search=False, analyzer=None, comment=None)[source]¶
Create an index on this table 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
- create_index_sync(index_name, fields, unique=False, search=False, analyzer=None, comment=None)[source]¶
Create an index on this table 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
- property objects: SchemalessQuerySet¶
Get a query set for this table.
- Returns:
A SchemalessQuerySet for querying this table
- async __call__(limit=None, start=None, page=None, **kwargs)[source]¶
Query the table with filters asynchronously.
This method allows calling the table instance directly with filters to query the table. It supports pagination through limit and start parameters or the page parameter. It returns the results as SimpleNamespace objects if they aren’t already Document instances.
- Parameters:
- Returns:
List of results, either document instances or SimpleNamespace objects
- Return type:
- call_sync(limit=None, start=None, page=None, **kwargs)[source]¶
Query the table with filters synchronously.
This method allows calling the table synchronously with filters to query the table. It supports pagination through limit and start parameters or the page parameter. It returns the results as SimpleNamespace objects if they aren’t already Document instances.
- Parameters:
- Returns:
List of results, either document instances or SimpleNamespace objects
- Return type:
- async transaction(coroutines)[source]¶
Execute multiple operations in a transaction asynchronously.
This method executes a list of coroutines within a transaction, committing the transaction if all operations succeed or canceling it if any operation fails.
- transaction_sync(callables)[source]¶
Execute multiple operations in a transaction synchronously.
This method executes a list of callables within a transaction, committing the transaction if all operations succeed or canceling it if any operation fails.
- async bulk_create(documents, batch_size=1000, 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 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, 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 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:
- class quantumengine.schemaless.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
- __init__(connection)[source]¶
Initialize a new SurrealEngine.
- Parameters:
connection (Any) – The database connection to use for queries
Data Grid API¶
High-level API for data grid operations across backends.
DataGrid Query Helpers for QuantumEngine - Efficient database querying for grid data
- class quantumengine.datagrid_api.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.datagrid_api.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.datagrid_api.get_grid_data_sync(document_class, request_args, search_fields, custom_filters=None, default_sort=None)[source]¶
Synchronous version of get_grid_data
Materialized Views¶
Support for materialized views and computed documents.
Materialized views for SurrealEngine.
This module provides support for materialized views in SurrealEngine. Materialized views are precomputed views of data that can be used to improve query performance for frequently accessed aggregated data.
- class quantumengine.materialized_view.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.materialized_view.Count(field=None)[source]¶
Bases:
Aggregation
Count aggregation function.
This class represents the count() aggregation function in SurrealQL.
- class quantumengine.materialized_view.Mean(field=None)[source]¶
Bases:
Aggregation
Mean aggregation function.
This class represents the math::mean() aggregation function in SurrealQL.
- class quantumengine.materialized_view.Sum(field=None)[source]¶
Bases:
Aggregation
Sum aggregation function.
This class represents the math::sum() aggregation function in SurrealQL.
- class quantumengine.materialized_view.Min(field=None)[source]¶
Bases:
Aggregation
Min aggregation function.
This class represents the math::min() aggregation function in SurrealQL.
- class quantumengine.materialized_view.Max(field=None)[source]¶
Bases:
Aggregation
Max aggregation function.
This class represents the math::max() aggregation function in SurrealQL.
- class quantumengine.materialized_view.ArrayCollect(field=None)[source]¶
Bases:
Aggregation
Array collect aggregation function.
This class represents the array::collect() aggregation function in SurrealQL.
- class quantumengine.materialized_view.Median(field=None)[source]¶
Bases:
Aggregation
Median aggregation function.
This class represents the math::median() aggregation function in SurrealQL.
- class quantumengine.materialized_view.StdDev(field=None)[source]¶
Bases:
Aggregation
Standard deviation aggregation function.
This class represents the math::stddev() aggregation function in SurrealQL.
- class quantumengine.materialized_view.Variance(field=None)[source]¶
Bases:
Aggregation
Variance aggregation function.
This class represents the math::variance() aggregation function in SurrealQL.
- class quantumengine.materialized_view.Percentile(field=None, percentile=50)[source]¶
Bases:
Aggregation
Percentile aggregation function.
This class represents the math::percentile() aggregation function in SurrealQL.
- class quantumengine.materialized_view.Distinct(field=None)[source]¶
Bases:
Aggregation
Distinct aggregation function.
This class represents the array::distinct() aggregation function in SurrealQL.
- class quantumengine.materialized_view.GroupConcat(field=None, separator=', ')[source]¶
Bases:
Aggregation
Group concatenation aggregation function.
This class represents a custom aggregation function that concatenates values with a separator.
- class quantumengine.materialized_view.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 refresh(connection=None)[source]¶
Manually refresh the materialized view.
Note: SurrealDB materialized views are automatically updated when underlying data changes. This method might not work as expected.
- Parameters:
connection – The database connection to use (optional)
- refresh_sync(connection=None)[source]¶
Manually refresh the materialized view.
Note: SurrealDB materialized views are automatically updated when underlying data changes. This method might not work as expected.
- Parameters:
connection – The database connection to use (optional)
- property objects: QuerySet¶
Get a QuerySet for querying the materialized view.
- Returns:
A QuerySet for querying the materialized view
- 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
Materialized documents for QuantumORM.
MaterializedDocument provides a Document-like interface for creating and querying materialized views across different backends (SurrealDB, ClickHouse).
Example
- class DailySalesSummary(MaterializedDocument):
- class Meta:
source = SalesDocument backend = ‘clickhouse’
# Dimensions (grouping fields) date = DateField(source=’date_collected’, transform=ToDate) seller_name = LowCardinalityField(source=’seller_name’)
# Metrics (aggregation fields) total_sales = DecimalField(aggregate=Sum(‘offer_price’)) transaction_count = IntField(aggregate=Count()) avg_price = DecimalField(aggregate=Avg(‘offer_price’))
- class quantumengine.materialized_document.AggregateFunction(field=None)[source]¶
Bases:
object
Base class for aggregate functions.
- class quantumengine.materialized_document.Count(field=None)[source]¶
Bases:
AggregateFunction
Count aggregation.
- class quantumengine.materialized_document.Sum(field=None)[source]¶
Bases:
AggregateFunction
Sum aggregation.
- class quantumengine.materialized_document.Avg(field=None)[source]¶
Bases:
AggregateFunction
Average aggregation.
- class quantumengine.materialized_document.Min(field=None)[source]¶
Bases:
AggregateFunction
Minimum aggregation.
- class quantumengine.materialized_document.Max(field=None)[source]¶
Bases:
AggregateFunction
Maximum aggregation.
- class quantumengine.materialized_document.CountDistinct(field=None)[source]¶
Bases:
AggregateFunction
Count distinct aggregation.
- class quantumengine.materialized_document.Variance(field=None)[source]¶
Bases:
AggregateFunction
Variance aggregation.
- class quantumengine.materialized_document.StdDev(field=None)[source]¶
Bases:
AggregateFunction
Standard deviation aggregation.
- class quantumengine.materialized_document.FieldTransform(field)[source]¶
Bases:
object
Base class for field transformations.
- class quantumengine.materialized_document.ToDate(field)[source]¶
Bases:
FieldTransform
Convert to date (ClickHouse-specific).
- class quantumengine.materialized_document.ToYearMonth(field)[source]¶
Bases:
FieldTransform
Convert to YYYYMM format (ClickHouse-specific).
- class quantumengine.materialized_document.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.materialized_document.MaterializedDocumentMetaclass(name, bases, attrs)[source]¶
Bases:
DocumentMetaclass
Metaclass for MaterializedDocument classes.
- class quantumengine.materialized_document.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.
Backend Utilities¶
Connection Pooling¶
Connection pool management for efficient database connections.
Backend Detection¶
Utilities for detecting and validating backend configurations.
Backend-Specific Features¶
SurrealDB Features¶
SurrealDB-specific functionality and optimizations.
ClickHouse Features¶
ClickHouse-specific functionality and optimizations.
Migration Support¶
Tools for migrating data between backends.
Performance Monitoring¶
Backend performance monitoring and metrics.
Exception Handling¶
Backend-specific exception handling and error management.
- class quantumengine.exceptions.ConnectionError[source]¶
Bases:
QuantumEngineError
Raised when a connection to the database cannot be established.
This exception is raised when there is an issue connecting to the SurrealDB server, such as network errors, authentication failures, or server unavailability.
See Also¶
Backends - Comprehensive backends guide
Query System - Query system documentation
Fields - Field types and backend compatibility
Exceptions - Exception handling guide