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:

Any

abstractmethod validate_connection(connection)[source]

Validate a connection.

Parameters:

connection (Any) – The connection to validate

Returns:

True if the connection is valid, False otherwise

Return type:

bool

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:

Any

abstractmethod return_connection(connection)[source]

Return a connection to the pool.

Parameters:

connection (Any) – The connection to return

abstractmethod close()[source]

Close the pool and all connections.

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:

SurrealEngineSyncConnection

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:

bool

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:
Return type:

SurrealEngineSyncConnection

return_connection(connection)[source]

Return a connection to the pool.

Parameters:

connection (SurrealEngineSyncConnection) – The connection to return (SurrealEngineSyncConnection)

close()[source]

Close the pool and all connections.

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:

SurrealEngineAsyncConnection

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:

bool

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:
Return type:

SurrealEngineAsyncConnection

async return_connection(connection)[source]

Return a connection to the pool.

Parameters:

connection (SurrealEngineAsyncConnection) – The connection to return (SurrealEngineAsyncConnection)

async close()[source]

Close the pool and all connections.

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.

on_event(event_type, connection, **kwargs)[source]

Handle a connection event.

Parameters:
  • event_type (str) – The type of event

  • connection (Any) – The connection that emitted the event

  • **kwargs – Additional event data

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

__init__()[source]

Initialize a new ConnectionEventEmitter.

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

emit_event(event_type, connection, **kwargs)[source]

Emit a connection event.

Parameters:
  • event_type (str) – The type of event

  • connection (Any) – The connection that emitted the event

  • **kwargs – Additional event data

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

__init__()[source]

Initialize a new OperationQueue.

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.

queue_operation(operation, args=None, kwargs=None)[source]

Queue a synchronous operation.

Parameters:
  • operation (Callable) – The operation to queue

  • args (List) – The positional arguments for the operation

  • kwargs (Dict) – The keyword arguments for the operation

queue_async_operation(operation, args=None, kwargs=None)[source]

Queue an asynchronous operation.

Parameters:
  • operation (Callable) – The operation to queue

  • args (List) – The positional arguments for the operation

  • kwargs (Dict) – The keyword arguments for the operation

execute_queued_operations()[source]

Execute all queued synchronous operations.

async execute_queued_async_operations()[source]

Execute all queued asynchronous operations.

wait_for_reconnection(timeout=None)[source]

Wait for reconnection to complete.

Parameters:

timeout (float | None) – Maximum time to wait in seconds

Returns:

True if reconnection completed, False if timed out

Return type:

bool

async wait_for_async_reconnection(timeout=None)[source]

Wait for reconnection to complete asynchronously.

Parameters:

timeout (float | None) – Maximum time to wait in seconds

Returns:

True if reconnection completed, False if timed out

Return type:

bool

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

__init__(max_attempts=10, initial_delay=1.0, max_delay=60.0, backoff_factor=2.0)[source]

Initialize a new ReconnectionStrategy.

Parameters:
  • max_attempts (int) – Maximum number of reconnection attempts

  • initial_delay (float) – Initial delay in seconds between reconnection attempts

  • max_delay (float) – Maximum delay in seconds between reconnection attempts

  • backoff_factor (float) – Backoff multiplier for reconnection delay

get_delay(attempt)[source]

Get the delay for a reconnection attempt.

Parameters:

attempt (int) – The reconnection attempt number (0-based)

Returns:

The delay in seconds for the reconnection attempt

Return type:

float

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.

Parameters:
  • retry_limit (int) – Maximum number of retries

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

  • retry_backoff (float) – Backoff multiplier for retry delay

get_retry_delay(attempt)[source]

Get the delay for a retry attempt.

Parameters:

attempt (int) – The retry attempt number (0-based)

Returns:

The delay in seconds for the retry attempt

Return type:

float

should_retry(attempt, exception)[source]

Determine whether to retry an operation.

Parameters:
  • attempt (int) – The retry attempt number (0-based)

  • exception (Exception) – The exception that caused the operation to fail

Returns:

True if the operation should be retried, False otherwise

Return type:

bool

execute_with_retry(operation)[source]

Execute an operation with retry.

Parameters:

operation (Callable[[], Any]) – The operation to execute

Returns:

The result of the operation

Raises:

Exception – If the operation fails after all retries

Return type:

Any

async execute_with_retry_async(operation)[source]

Execute an asynchronous operation with retry.

Parameters:

operation (Callable[[], Any]) – The asynchronous operation to execute

Returns:

The result of the operation

Raises:

Exception – If the operation fails after all retries

Return type:

Any

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&param2=value2 (maps to ws://) - wss://user:pass@host:port/namespace/database?param1=value1&param2=value2 - ws://user:pass@host:port/namespace/database?param1=value1&param2=value2 - http://user:pass@host:port/namespace/database?param1=value1&param2=value2 - https://user:pass@host:port/namespace/database?param1=value1&param2=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:

Dict[str, Any]

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.

url: str | None
namespace: str | None
database: str | None
username: str | None
password: str | None
client: Any
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

async create(collection, data)[source]

Create a new record in the database.

Parameters:
  • collection (str) – The collection to create the record in

  • data (Dict[str, Any]) – The data to create the record with

Returns:

The created record

Return type:

Any

async update(id, data)[source]

Update an existing record in the database.

Parameters:
  • id (str) – The ID of the record to update

  • data (Dict[str, Any]) – The data to update the record with

Returns:

The updated record

Return type:

Any

async delete(id)[source]

Delete a record from the database.

Parameters:

id (str) – The ID of the record to delete

Returns:

The result of the delete operation

Return type:

Any

async select(id)[source]

Select a record from the database.

Parameters:

id (str) – The ID of the record to select

Returns:

The selected record

Return type:

Any

async query(query)[source]

Execute a query against the database.

Parameters:

query (str) – The query to execute

Returns:

The result of the query

Return type:

Any

async insert(collection, data)[source]

Insert multiple records into the database.

Parameters:
  • collection (str) – The collection to insert the records into

  • data (List[Dict[str, Any]]) – The data to insert

Returns:

The inserted records

Return type:

Any

async signin(credentials)[source]

Sign in to the database.

Parameters:

credentials (Dict[str, str]) – The credentials to sign in with

Returns:

The result of the sign-in operation

Return type:

Any

async use(namespace, database)[source]

Use a specific namespace and database.

Parameters:
  • namespace (str) – The namespace to use

  • database (str) – The database to use

Returns:

The result of the use operation

Return type:

Any

async close()[source]

Close the connection pool.

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)

Type:

quantumengine.connection.SurrealEngineAsyncConnection | None

_default_sync_connection

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

Type:

quantumengine.connection.SurrealEngineSyncConnection | None

_async_connections

Dictionary of named async connections (legacy)

Type:

Dict[str, quantumengine.connection.SurrealEngineAsyncConnection]

_sync_connections

Dictionary of named sync connections (legacy)

Type:

Dict[str, quantumengine.connection.SurrealEngineSyncConnection]

_backend_connections

Dictionary of backend -> {connection_name -> connection}

Type:

Dict[str, Dict[str, Any]]

_default_backend_connections

Dictionary of backend -> default_connection

Type:

Dict[str, Any]

classmethod 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:

SurrealEngineAsyncConnection

classmethod get_default_sync_connection()[source]

Get the default sync connection.

Returns:

The default sync connection

Raises:

RuntimeError – If no default sync connection has been set

Return type:

SurrealEngineSyncConnection

classmethod add_async_connection(name, connection)[source]

Add a named async connection to the registry.

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

Add a named sync connection to the registry.

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

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

Parameters:
classmethod get_async_connection(name)[source]

Get a named async connection from the registry.

Parameters:

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

Returns:

The requested async connection

Raises:

KeyError – If no async connection with the given name exists

Return type:

SurrealEngineAsyncConnection

classmethod get_sync_connection(name)[source]

Get a named sync connection from the registry.

Parameters:

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

Returns:

The requested sync connection

Raises:

KeyError – If no sync connection with the given name exists

Return type:

SurrealEngineSyncConnection

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

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

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

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

Returns:

The requested connection of the requested type

Raises:

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

Return type:

SurrealEngineAsyncConnection | SurrealEngineSyncConnection

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

Register a connection for a specific backend.

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

  • connection (Any) – The connection object

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

classmethod set_default(backend, connection_name)[source]

Set the default connection for a backend.

Parameters:
  • backend (str) – The backend type

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

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

Get the default connection for a backend.

Parameters:

backend (str) – The backend type

Returns:

The default connection for the backend

Raises:

ValueError – If no default connection is set for the backend

Return type:

Any

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

Get a named connection for a specific backend.

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

  • backend (str) – The backend type

Returns:

The requested connection

Raises:

ValueError – If the connection is not found

Return type:

Any

classmethod list_backends()[source]

List all registered backends.

Returns:

List of backend names

Return type:

List[str]

classmethod list_connections(backend)[source]

List all connections for a backend.

Parameters:

backend (str) – The backend type

Returns:

List of connection names for the backend

Return type:

List[str]

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:

SurrealEngineAsyncConnection

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

Exit the async context manager.

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

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

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

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:

Any

async disconnect()[source]

Disconnect from the database.

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

async transaction(coroutines)[source]

Execute multiple operations in a transaction.

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

Parameters:

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

Returns:

List of results from the coroutines

Raises:

Exception – If any operation in the transaction fails

Return type:

list

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:

Any

Examples

SurrealDB connection (default):

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

ClickHouse connection:

clickhouse_conn = create_connection(
    url="localhost", database="default",
    username="default", password="",
    backend="clickhouse", port=8123
)
class quantumengine.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

__enter__()[source]

Enter the sync context manager.

Returns:

The connection instance

Return type:

SurrealEngineSyncConnection

__exit__(exc_type, exc_val, exc_tb)[source]

Exit the sync context manager.

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

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

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

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:

Any

disconnect()[source]

Disconnect from the database.

This method closes the client connection if one exists.

transaction(callables)[source]

Execute multiple operations in a transaction.

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

Parameters:

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

Returns:

List of results from the callables

Raises:

Exception – If any operation in the transaction fails

Return type:

list

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 insert(table_name, data)[source]

Insert a single document.

Parameters:
  • table_name (str) – The table name

  • data (Dict[str, Any]) – The document data to insert

Returns:

The inserted document with any generated fields

Return type:

Dict[str, Any]

async insert_many(table_name, data)[source]

Insert multiple documents efficiently.

Parameters:
  • table_name (str) – The table name

  • data (List[Dict[str, Any]]) – List of documents to insert

Returns:

List of inserted documents

Return type:

List[Dict[str, Any]]

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 name

  • conditions (List[str]) – List of condition strings

  • fields (List[str] | None) – List of fields to return (None for all)

  • limit (int | None) – Maximum number of results

  • offset (int | None) – Number of results to skip (START in SurrealDB)

  • order_by (List[tuple[str, str]] | None) – List of (field, direction) tuples

Returns:

List of matching documents

Return type:

List[Dict[str, Any]]

async select_by_ids(table_name, ids)[source]

Select documents by their IDs using direct record access.

Parameters:
  • table_name (str) – The table name

  • ids (List[Any]) – List of IDs to select

Returns:

List of matching documents

Return type:

List[Dict[str, Any]]

async count(table_name, conditions)[source]

Count documents matching conditions.

Parameters:
  • table_name (str) – The table name

  • conditions (List[str]) – List of condition strings

Returns:

Number of matching documents

Return type:

int

async update(table_name, conditions, data)[source]

Update documents matching conditions.

Parameters:
  • table_name (str) – The table name

  • conditions (List[str]) – List of condition strings

  • data (Dict[str, Any]) – The fields to update

Returns:

List of updated documents

Return type:

List[Dict[str, Any]]

async delete(table_name, conditions)[source]

Delete documents matching conditions.

Parameters:
  • table_name (str) – The table name

  • conditions (List[str]) – List of condition strings

Returns:

Number of deleted documents

Return type:

int

async drop_table(table_name, if_exists=True)[source]

Drop a table using SurrealDB’s REMOVE TABLE statement.

Parameters:
  • table_name (str) – The table name to drop

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

async execute_raw(query, params=None)[source]

Execute a raw SurrealQL query.

Parameters:
  • query (str) – The raw SurrealQL query string

  • params (Dict[str, Any] | None) – Optional query parameters (not used - SurrealDB handles this)

Returns:

Query result

Return type:

Any

build_condition(field, operator, value)[source]

Build a condition string for SurrealQL.

Parameters:
  • field (str) – The field name

  • operator (str) – The operator (=, !=, >, <, >=, <=, ~, !~, etc.)

  • value (Any) – The value to compare against

Returns:

A condition string in SurrealQL

Return type:

str

get_field_type(field)[source]

Get the SurrealDB field type for a SurrealEngine field.

Parameters:

field (Any) – A SurrealEngine field instance

Returns:

The corresponding SurrealDB field type

Return type:

str

format_value(value, field_type=None)[source]

Format a value for SurrealQL.

Parameters:
  • value (Any) – The value to format

  • field_type (str | None) – Optional field type hint

Returns:

The formatted value as a string for SurrealQL

Return type:

str

async begin_transaction()[source]

Begin a transaction.

Returns:

Transaction object (SurrealDB client for now)

Return type:

Any

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

supports_transactions()[source]

SurrealDB supports transactions within query batches.

supports_references()[source]

SurrealDB supports references between records.

supports_graph_relations()[source]

SurrealDB has native graph relation support.

supports_direct_record_access()[source]

SurrealDB supports direct record access syntax.

supports_explain()[source]

SurrealDB supports EXPLAIN queries.

supports_indexes()[source]

SurrealDB supports indexes.

SurrealDB supports full-text search.

supports_bulk_operations()[source]

SurrealDB supports bulk operations.

get_optimized_methods()[source]

Get SurrealDB-specific optimization methods.

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:
  • from_table (str) – Source table name

  • from_id (str) – Source document ID

  • relation_name (str) – Name of the relation

  • to_table (str) – Target table name

  • to_id (str) – Target document ID

  • attributes (Dict[str, Any] | None) – Optional attributes for the relation

Returns:

The created relation record

Return type:

Dict[str, Any] | None

async delete_relation(from_table, from_id, relation_name, to_table=None, to_id=None)[source]

Delete relations using SurrealDB’s DELETE statement.

Parameters:
  • from_table (str) – Source table name

  • from_id (str) – Source document ID

  • relation_name (str) – Name of the relation

  • to_table (str | None) – Target table name (optional)

  • to_id (str | None) – Target document ID (optional)

Returns:

Number of relations deleted

Return type:

int

async query_relations(from_table, from_id, relation_name, direction='out')[source]

Query relations using SurrealDB’s graph traversal.

Parameters:
  • from_table (str) – Source table name

  • from_id (str) – Source document ID

  • relation_name (str) – Name of the relation

  • direction (str) – Direction of relations (‘out’, ‘in’, ‘both’)

Returns:

List of related documents

Return type:

List[Dict[str, Any]]

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

async drop_materialized_view(materialized_document_class)[source]

Drop a SurrealDB materialized view.

Parameters:

materialized_document_class (Type) – The MaterializedDocument class

async refresh_materialized_view(materialized_document_class)[source]

Refresh a SurrealDB materialized view.

Note: SurrealDB materialized views update automatically when data changes. This is a no-op for SurrealDB.

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 insert(table_name, data)[source]

Insert a single document.

Parameters:
  • table_name (str) – The table name

  • data (Dict[str, Any]) – The document data to insert

Returns:

The inserted document with generated id if not provided

Return type:

Dict[str, Any]

async insert_many(table_name, data)[source]

Insert multiple documents efficiently.

Parameters:
  • table_name (str) – The table name

  • data (List[Dict[str, Any]]) – List of documents to insert

Returns:

List of inserted documents

Return type:

List[Dict[str, Any]]

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 name

  • conditions (List[str]) – List of condition strings

  • fields (List[str] | None) – List of fields to return (None for all)

  • 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

Returns:

List of matching documents

Return type:

List[Dict[str, Any]]

async count(table_name, conditions)[source]

Count documents matching conditions.

Parameters:
  • table_name (str) – The table name

  • conditions (List[str]) – List of condition strings

Returns:

Number of matching documents

Return type:

int

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.

Parameters:
  • table_name (str) – The table name

  • conditions (List[str]) – List of condition strings

  • data (Dict[str, Any]) – The fields to update

Returns:

List of documents that will be updated

Return type:

List[Dict[str, Any]]

async delete(table_name, conditions)[source]

Delete documents matching conditions.

Note: ClickHouse uses ALTER TABLE DELETE which is asynchronous.

Parameters:
  • table_name (str) – The table name

  • conditions (List[str]) – List of condition strings

Returns:

Number of documents that will be deleted

Return type:

int

async drop_table(table_name, if_exists=True)[source]

Drop a table using ClickHouse’s DROP TABLE statement.

Parameters:
  • table_name (str) – The table name to drop

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

async execute_raw(query, params=None)[source]

Execute a raw query.

Parameters:
  • query (str) – The raw query string

  • params (Dict[str, Any] | None) – Optional query parameters

Returns:

Query result

Return type:

Any

build_condition(field, operator, value)[source]

Build a condition string for ClickHouse SQL.

Parameters:
  • field (str) – The field name

  • operator (str) – The operator

  • value (Any) – The value to compare against

Returns:

A condition string in ClickHouse SQL

Return type:

str

get_field_type(field)[source]

Get the ClickHouse field type for a QuantumORM field.

Parameters:

field (Any) – A QuantumORM field instance

Returns:

The corresponding ClickHouse field type

Return type:

str

format_value(value, field_type=None)[source]

Format a value for ClickHouse SQL.

Parameters:
  • value (Any) – The value to format

  • field_type (str | None) – Optional field type hint

Returns:

The formatted value as a string

Return type:

str

async begin_transaction()[source]

Begin a transaction.

Note: ClickHouse has limited transaction support.

async commit_transaction(transaction)[source]

Commit a transaction.

Note: No-op for ClickHouse.

async rollback_transaction(transaction)[source]

Rollback a transaction.

Note: No-op for ClickHouse.

supports_transactions()[source]

ClickHouse has limited transaction support.

supports_references()[source]

ClickHouse doesn’t support references between tables.

supports_graph_relations()[source]

ClickHouse doesn’t support graph relations.

supports_direct_record_access()[source]

ClickHouse doesn’t support direct record access syntax.

supports_explain()[source]

ClickHouse supports EXPLAIN queries.

supports_indexes()[source]

ClickHouse supports indexes.

ClickHouse has limited full-text search support.

supports_bulk_operations()[source]

ClickHouse excels at bulk operations.

get_optimized_methods()[source]

Get ClickHouse-specific optimization methods.

async create_materialized_view(materialized_document_class)[source]

Create a ClickHouse materialized view.

Parameters:

materialized_document_class (Type) – The MaterializedDocument class

async drop_materialized_view(materialized_document_class)[source]

Drop a ClickHouse materialized view.

Parameters:

materialized_document_class (Type) – The MaterializedDocument class

async refresh_materialized_view(materialized_document_class)[source]

Refresh a ClickHouse materialized view.

Note: ClickHouse materialized views update automatically as data arrives. This is a no-op for ClickHouse.

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 insert(table_name, data)[source]

Insert a single document.

Parameters:
  • table_name (str) – The table/collection name

  • data (Dict[str, Any]) – The document data to insert

Returns:

The inserted document with any generated fields (e.g., id)

Return type:

Dict[str, Any]

abstractmethod async insert_many(table_name, data)[source]

Insert multiple documents.

Parameters:
  • table_name (str) – The table/collection name

  • data (List[Dict[str, Any]]) – List of documents to insert

Returns:

List of inserted documents

Return type:

List[Dict[str, Any]]

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:

List[Dict[str, Any]]

abstractmethod async count(table_name, conditions)[source]

Count documents matching conditions.

Parameters:
  • table_name (str) – The table/collection name

  • conditions (List[str]) – List of condition strings

Returns:

Number of matching documents

Return type:

int

abstractmethod async update(table_name, conditions, data)[source]

Update documents matching conditions.

Parameters:
  • table_name (str) – The table/collection name

  • conditions (List[str]) – List of condition strings

  • data (Dict[str, Any]) – The fields to update

Returns:

List of updated documents

Return type:

List[Dict[str, Any]]

abstractmethod async delete(table_name, conditions)[source]

Delete documents matching conditions.

Parameters:
  • table_name (str) – The table/collection name

  • conditions (List[str]) – List of condition strings

Returns:

Number of deleted documents

Return type:

int

abstractmethod async drop_table(table_name, if_exists=True)[source]

Drop a table/collection.

Parameters:
  • table_name (str) – The table/collection name to drop

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

abstractmethod async execute_raw(query, params=None)[source]

Execute a raw query.

Parameters:
  • query (str) – The raw query string

  • params (Dict[str, Any] | None) – Optional query parameters

Returns:

Query result (backend-specific)

Return type:

Any

abstractmethod build_condition(field, operator, value)[source]

Build a condition string for the backend’s query language.

Parameters:
  • field (str) – The field name

  • operator (str) – The operator (=, !=, >, <, >=, <=, in, contains, etc.)

  • value (Any) – The value to compare against

Returns:

A condition string in the backend’s query language

Return type:

str

abstractmethod get_field_type(field)[source]

Get the database field type for a SurrealEngine field.

Parameters:

field (Any) – A SurrealEngine field instance

Returns:

The corresponding database field type

Return type:

str

abstractmethod format_value(value, field_type=None)[source]

Format a value for the backend’s query language.

Parameters:
  • value (Any) – The value to format

  • field_type (str | None) – Optional field type hint

Returns:

The formatted value

Return type:

Any

abstractmethod async begin_transaction()[source]

Begin a transaction.

Returns:

Transaction object (backend-specific)

Return type:

Any

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:

bool

supports_references()[source]

Check if the backend supports references/foreign keys.

Returns:

True if references are supported, False otherwise

Return type:

bool

supports_graph_relations()[source]

Check if the backend supports graph-style relations.

Returns:

True if graph relations are supported, False otherwise

Return type:

bool

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:

bool

supports_explain()[source]

Check if the backend supports EXPLAIN queries.

Returns:

True if EXPLAIN is supported, False otherwise

Return type:

bool

supports_indexes()[source]

Check if the backend supports indexes.

Returns:

True if indexes are supported, False otherwise

Return type:

bool

Check if the backend supports full-text search.

Returns:

True if full-text search is supported, False otherwise

Return type:

bool

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:

bool

get_optimized_methods()[source]

Get backend-specific optimization methods.

Returns:

Dictionary mapping operation names to backend-specific implementations

Return type:

Dict[str, str]

supports_schemas()[source]

Check if this backend supports strict schemas.

Returns:

True if schemas are supported

Return type:

bool

get_capabilities()[source]

Get backend capabilities.

Returns:

Dictionary of capability flags

Return type:

Dict[str, bool]

async create_relation(from_table, from_id, relation_name, to_table, to_id, attributes=None)[source]

Create a relation between two documents.

Parameters:
  • from_table (str) – Source table name

  • from_id (str) – Source document ID

  • relation_name (str) – Name of the relation

  • to_table (str) – Target table name

  • to_id (str) – Target document ID

  • attributes (Dict[str, Any] | None) – Optional attributes for the relation

Returns:

The created relation record or None

Raises:

NotImplementedError – If backend doesn’t support graph relations

Return type:

Dict[str, Any] | None

async delete_relation(from_table, from_id, relation_name, to_table=None, to_id=None)[source]

Delete relations.

Parameters:
  • from_table (str) – Source table name

  • from_id (str) – Source document ID

  • relation_name (str) – Name of the relation

  • to_table (str | None) – Target table name (optional)

  • to_id (str | None) – Target document ID (optional)

Returns:

Number of relations deleted

Raises:

NotImplementedError – If backend doesn’t support graph relations

Return type:

int

async query_relations(from_table, from_id, relation_name, direction='out')[source]

Query relations from a document.

Parameters:
  • from_table (str) – Source table name

  • from_id (str) – Source document ID

  • relation_name (str) – Name of the relation

  • direction (str) – Direction of relations (‘out’, ‘in’, ‘both’)

Returns:

List of related documents

Raises:

NotImplementedError – If backend doesn’t support graph relations

Return type:

List[Dict[str, Any]]

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.

Parameters:

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

Returns:

A list of Document classes defined in the module

Return type:

List[Type[Document]]

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

Create tables for all Document classes in a module asynchronously.

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

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

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

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

Create tables for all Document classes in a module synchronously.

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

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

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

quantumengine.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.

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

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

Returns:

A list of SurrealDB schema statements

Return type:

List[str]

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

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

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

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

Returns:

A dictionary mapping class names to lists of SurrealDB schema statements

Return type:

Dict[str, List[str]]

quantumengine.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.

Parameters:

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

Returns:

A list of SurrealDB drop statements

Return type:

List[str]

quantumengine.schema.generate_drop_statements_from_module(module_name)[source]

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

Parameters:

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

Returns:

A dictionary mapping class names to lists of SurrealDB drop statements

Return type:

Dict[str, List[str]]

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

Generate migration statements between two versions of a Document class.

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

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

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

Returns:

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

Return type:

Dict[str, List[str]]

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

Drop tables for all Document classes in a module asynchronously.

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

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

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

Drop tables for all Document classes in a module synchronously.

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

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

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

__init__(table_name, connection)[source]

Initialize a new SchemalessQuerySet.

Parameters:
  • table_name (str) – The name of the table to query

  • connection (Any) – 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.

Returns:

List of results, either document instances or SimpleNamespace objects

Return type:

List[Any]

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.

Returns:

List of results, either document instances or SimpleNamespace objects

Return type:

List[Any]

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:
Return type:

Any

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:
Return type:

Any

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:
  • documents (List[Dict[str, Any]]) – List of dictionaries representing documents to create

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

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

Returns:

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

Return type:

List[Any] | int

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:
  • documents (List[Dict[str, Any]]) – List of dictionaries representing documents to create

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

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

Returns:

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

Return type:

List[Any] | int

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

__init__(name, connection)[source]

Initialize a new SchemalessTable.

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

  • connection (Any) – 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:
  • from_id (str | RecordID) – The ID of the record to create the relation from

  • relation (str) – The name of the relation

  • to_id (str | RecordID) – The ID of the record to create the relation to

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

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:
  • from_id (str | RecordID) – The ID of the record to create the relation from

  • relation (str) – The name of the relation

  • to_id (str | RecordID) – The ID of the record to create the relation to

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

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:
  • from_id (str | RecordID) – The ID of the record to get related records for

  • relation (str) – The name of the relation

  • target_table (str | None) – The name of the target table (optional)

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

Returns:

List of related records or relation records

Return type:

List[Any]

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:
  • from_id (str | RecordID) – The ID of the record to get related records for

  • relation (str) – The name of the relation

  • target_table (str | None) – The name of the target table (optional)

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

Returns:

List of related records or relation records

Return type:

List[Any]

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:
  • from_id (str | RecordID) – The ID of the record the relation is from

  • relation (str) – The name of the relation

  • to_id (str | RecordID) – The ID of the record the relation is to

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

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:
  • from_id (str | RecordID) – The ID of the record the relation is from

  • relation (str) – The name of the relation

  • to_id (str | RecordID) – The ID of the record the relation is to

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

Returns:

The updated relation record or None if update failed

Return type:

Any | None

async delete_relation(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.

Parameters:
  • from_id (str | RecordID) – The ID of the record the relation is from

  • relation (str) – The name of the relation

  • to_id (str | RecordID | None) – The ID of the record the relation is to (optional)

Returns:

Number of deleted relations

Return type:

int

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.

Parameters:
  • from_id (str | RecordID) – The ID of the record the relation is from

  • relation (str) – The name of the relation

  • to_id (str | RecordID | None) – The ID of the record the relation is to (optional)

Returns:

Number of deleted relations

Return type:

int

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:
  • limit (int | None) – Maximum number of results to return (for pagination)

  • start (int | None) – Number of results to skip (for pagination)

  • page (tuple | None) – Tuple of (page_number, page_size) for pagination

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

Returns:

List of results, either document instances or SimpleNamespace objects

Return type:

List[Any]

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:
  • limit (int | None) – Maximum number of results to return (for pagination)

  • start (int | None) – Number of results to skip (for pagination)

  • page (tuple | None) – Tuple of (page_number, page_size) for pagination

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

Returns:

List of results, either document instances or SimpleNamespace objects

Return type:

List[Any]

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.

Parameters:

coroutines (List[Callable]) – List of coroutines to execute in the transaction

Returns:

List of results from the coroutines

Raises:

Exception – If any operation in the transaction fails

Return type:

List[Any]

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.

Parameters:

callables (List[Callable]) – List of callables to execute in the transaction

Returns:

List of results from the callables

Raises:

Exception – If any operation in the transaction fails

Return type:

List[Any]

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:
  • documents (List[Dict[str, Any]]) – List of dictionaries representing documents to create

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

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

Returns:

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

Return type:

List[Any] | int

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:
  • documents (List[Dict[str, Any]]) – List of dictionaries representing documents to create

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

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

Returns:

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

Return type:

List[Any] | int

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

__getattr__(name)[source]

Get a table accessor for the given table name.

This method allows accessing tables as attributes of the instance.

Parameters:

name (str) – The name of the table

Returns:

A SchemalessTable for accessing the table

Return type:

SchemalessTable

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

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

Apply field filters to the queryset

Parameters:

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

Apply text search across multiple fields using contains operator

Parameters:
  • search (str) – Search term

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

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

Apply sorting to the queryset

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

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

async get_paginated_data(offset, limit)[source]

Get paginated data with total count

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

  • limit (int) – Number of records to return

Returns:

Tuple of (total_count, paginated_results)

get_paginated_data_sync(offset, limit)[source]

Synchronous version of get_paginated_data

async quantumengine.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:
  • document_class – SurrealEngine document class

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

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

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

  • default_sort (str | None) – Default sorting field

Returns:

total, “rows”: rows} for BootstrapTable format

Return type:

{“total”

quantumengine.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

quantumengine.datagrid_api.parse_datatables_params(request_args)[source]

Convert DataTables parameters to standard offset/limit format

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

Format response for DataTables

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.

__init__(field=None)[source]

Initialize a new Aggregation.

Parameters:

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

__str__()[source]

Return the SurrealQL representation of the aggregation function.

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

Bases: Aggregation

Count aggregation function.

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

__str__()[source]

Return the SurrealQL representation of the count function.

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

Bases: Aggregation

Mean aggregation function.

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

__str__()[source]

Return the SurrealQL representation of the mean function.

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

Bases: Aggregation

Sum aggregation function.

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

__str__()[source]

Return the SurrealQL representation of the sum function.

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

Bases: Aggregation

Min aggregation function.

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

__str__()[source]

Return the SurrealQL representation of the min function.

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

Bases: Aggregation

Max aggregation function.

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

__str__()[source]

Return the SurrealQL representation of the max function.

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

Bases: Aggregation

Array collect aggregation function.

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

__str__()[source]

Return the SurrealQL representation of the array collect function.

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

Bases: Aggregation

Median aggregation function.

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

__str__()[source]

Return the SurrealQL representation of the median function.

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

Bases: Aggregation

Standard deviation aggregation function.

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

__str__()[source]

Return the SurrealQL representation of the standard deviation function.

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

Bases: Aggregation

Variance aggregation function.

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

__str__()[source]

Return the SurrealQL representation of the variance function.

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

Bases: Aggregation

Percentile aggregation function.

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

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

Initialize a new Percentile.

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

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

__str__()[source]

Return the SurrealQL representation of the percentile function.

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

Bases: Aggregation

Distinct aggregation function.

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

__str__()[source]

Return the SurrealQL representation of the distinct function.

class quantumengine.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.

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

Initialize a new GroupConcat.

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

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

__str__()[source]

Return the SurrealQL representation of the group concat function.

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.

__init__(field=None)[source]
__str__()[source]

Return the string representation for the backend.

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.

__init__(field)[source]
__str__()[source]

Return the string representation for the backend.

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.

static __new__(mcs, name, bases, attrs)[source]

Create a new MaterializedDocument class.

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.

async classmethod create_view()[source]

Create the materialized view in the database.

async classmethod drop_view()[source]

Drop the materialized view from the database.

async classmethod refresh_view()[source]

Refresh the materialized view (backend-specific behavior).

async save(**kwargs)[source]

MaterializedDocuments are read-only.

async delete()[source]

MaterializedDocuments are read-only.

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