Fields API

This section provides the complete API reference for all field types in QuantumEngine.

Base Field

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

Bases: Generic[T]

Base class for all field types.

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

required

Whether the field is required

default

Default value for the field

name

Name of the field (set during document class creation)

db_field

Name of the field in the database

owner_document

The document class that owns this field

define_schema

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

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

Initialize a new Field.

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

  • default (Any) – Default value for the field

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

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

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

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

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

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

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

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

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

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

validate(value)[source]

Validate the field value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated value

Raises:

ValueError – If the value is invalid

Return type:

T

to_db(value, backend=None)[source]

Convert Python value to database representation.

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

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

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

Returns:

The database representation of the value

Return type:

Any

from_db(value, backend=None)[source]

Convert database value to Python representation.

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

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

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

Returns:

The Python representation of the value

Return type:

T

Scalar Fields

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

Bases: Field[str]

String field type.

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

min_length

Minimum length of the string

max_length

Maximum length of the string

regex

Regular expression pattern to match

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

Initialize a new StringField.

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

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

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

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

validate(value)[source]

Validate the string value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated string value

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

  • ValueError – If the value does not meet the constraints

Return type:

str

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

Bases: Field[int | float]

Base class for numeric fields.

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

min_value

Minimum allowed value

max_value

Maximum allowed value

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

Initialize a new NumberField.

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

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

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

validate(value)[source]

Validate the numeric value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated numeric value

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

  • ValueError – If the value does not meet the constraints

Return type:

int | float

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

Bases: NumberField

Integer field type.

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

__init__(**kwargs)[source]

Initialize a new IntField.

Parameters:

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

validate(value)[source]

Validate the integer value.

This method checks if the value is a valid integer.

Parameters:

value (Any) – The value to validate

Returns:

The validated integer value

Raises:

TypeError – If the value is not an integer

Return type:

int

to_db(value, backend=None)[source]

Convert Python value to database representation.

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

Parameters:

value (Any) – The Python value to convert

Returns:

The integer value for the database

Return type:

int | None

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

Bases: NumberField

Float field type.

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

__init__(**kwargs)[source]

Initialize a new FloatField.

Parameters:

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

validate(value)[source]

Validate the float value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated float value

Raises:

TypeError – If the value cannot be converted to a float

Return type:

float

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

Bases: Field[bool]

Boolean field type.

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

__init__(**kwargs)[source]

Initialize a new BooleanField.

Parameters:

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

validate(value)[source]

Validate the boolean value.

This method checks if the value is a valid boolean.

Parameters:

value (Any) – The value to validate

Returns:

The validated boolean value

Raises:

TypeError – If the value is not a boolean

Return type:

bool

DateTime Fields

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

Bases: Field[datetime]

DateTime field type.

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

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

Example

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

Initialize a new DateTimeField.

Parameters:

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

validate(value)[source]

Validate the datetime value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated datetime value

Raises:

TypeError – If the value cannot be converted to a datetime

Return type:

datetime

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

Bases: DateTimeField

Field for time series data.

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

Example

class SensorReading(Document):

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

class Meta:

time_series = True time_field = “timestamp”

__init__(**kwargs)[source]

Initialize a new TimeSeriesField.

Parameters:

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

validate(value)[source]

Validate the timestamp value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated timestamp value

Return type:

datetime | None

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

Bases: Field

Duration field type.

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

__init__(**kwargs)[source]

Initialize a new DurationField.

Parameters:

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

validate(value)[source]

Validate the duration value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated timedelta value

Raises:

TypeError – If the value cannot be converted to a timedelta

Return type:

timedelta | None

to_db(value)[source]

Convert Python timedelta to database representation.

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

Parameters:

value (Any) – The Python timedelta to convert

Returns:

The SurrealDB Duration object for the database

Return type:

Any | None

from_db(value)[source]

Convert database value to Python timedelta.

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

Parameters:

value (Any) – The database value to convert

Returns:

The Python timedelta object

Return type:

timedelta | None

Collection Fields

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

Bases: Field

List field type.

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

field_type

The field type for items in the list

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

Initialize a new ListField.

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

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

validate(value)[source]

Validate the list value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated list value

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

  • ValueError – If an item in the list fails validation

Return type:

List[Any] | None

to_db(value, backend=None)[source]

Convert Python list to database representation.

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

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

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

Returns:

The database representation of the list

Return type:

Any

from_db(value)[source]

Convert database list to Python representation.

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

Parameters:

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

Returns:

The Python representation of the list

Return type:

List[Any] | None

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

Bases: Field

Dict field type.

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

field_type

The field type for values in the dictionary

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

Initialize a new DictField.

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

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

validate(value)[source]

Validate the dictionary value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated dictionary value

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

  • ValueError – If a value in the dictionary fails validation

Return type:

Dict[str, Any] | None

to_db(value, backend=None)[source]

Convert Python dictionary to database representation.

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

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

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

Returns:

The database representation of the dictionary

Return type:

Any

from_db(value)[source]

Convert database dictionary to Python representation.

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

Parameters:

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

Returns:

The Python representation of the dictionary

Return type:

Dict[str, Any] | None

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

Bases: ListField

Set field type.

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

Example

class User(Document):

tags = SetField(StringField())

validate(value)[source]

Validate the list value and ensure uniqueness.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated and deduplicated list value

Return type:

List[Any] | None

to_db(value, backend=None)[source]

Convert Python list to database representation with deduplication.

Reference Fields

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

Bases: Field

Reference to another document.

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

document_type

The type of document being referenced

__init__(document_type, **kwargs)[source]

Initialize a new ReferenceField.

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

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

validate(value)[source]

Validate the reference value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated reference value

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

  • ValueError – If the referenced document is not saved

Return type:

Any

to_db(value)[source]

Convert Python reference to database representation.

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

Parameters:

value (Any) – The Python reference to convert

Returns:

The database representation of the reference

Raises:

ValueError – If the referenced document is not saved

Return type:

str | None

from_db(value, dereference=False)[source]

Convert database reference to Python representation.

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

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

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

Returns:

The Python representation of the reference

Return type:

Any

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

Bases: Field

Field representing a relation between documents.

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

to_document

The type of document being related to

__init__(to_document, **kwargs)[source]

Initialize a new RelationField.

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

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

validate(value)[source]

Validate the relation value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated relation value

Raises:

TypeError – If the value is not a valid relation

Return type:

Any

to_db(value)[source]

Convert Python relation to database representation.

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

Parameters:

value (Any) – The Python relation to convert

Returns:

The database representation of the relation

Raises:

ValueError – If the related document is not saved

Return type:

str | None

from_db(value, dereference=False)[source]

Convert database relation to Python representation.

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

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

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

Returns:

The Python representation of the relation

Return type:

Any

Get documents related through this relation field.

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

Parameters:

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

Returns:

List of related documents

Raises:

ValueError – If the instance is not saved

Return type:

List[Any]

Get documents related through this relation field synchronously.

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

Parameters:

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

Returns:

List of related documents

Raises:

ValueError – If the instance is not saved

Return type:

List[Any]

Geometry Fields

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

Bases: Field

Field for handling geometric data in SurrealDB.

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

required

Whether the field is required. Defaults to False.

Type:

bool

Example

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

Initialize a GeometryField.

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

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

validate(value)[source]

Validate geometry data.

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

Parameters:

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

Returns:

The validated geometry data.

Return type:

dict

Raises:

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

ID Fields

class quantumengine.fields.id.RecordIDField(**kwargs)[source]

Bases: Field

RecordID field type.

This field type stores record IDs and provides validation and conversion between Python values and SurrealDB record ID format.

A RecordID consists of a table name and a unique identifier, formatted as table:id. This field can accept a string in this format, or a tuple/list with the table name and ID.

Example

>>> class Reference(Document):
...     target = RecordIDField()
__init__(**kwargs)[source]

Initialize a new RecordIDField.

Parameters:

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

validate(value)[source]

Validate the record ID.

This method checks if the value is a valid record ID.

Parameters:

value (Any) – The value to validate

Returns:

The validated record ID

Raises:
  • TypeError – If the value cannot be converted to a record ID

  • ValueError – If the record ID format is invalid

Return type:

str | None

to_db(value)[source]

Convert Python value to database representation.

This method converts a Python value to a record ID for storage in the database.

Parameters:

value (Any) – The Python value to convert

Returns:

The record ID for the database

Return type:

str | None

from_db(value)[source]

Convert database value to Python representation.

This method converts a record ID from the database to a Python representation.

Parameters:

value (Any) – The database value to convert

Returns:

The Python representation of the record ID

Return type:

str | None

Specialized Fields

BytesField

class quantumengine.fields.BytesField(**kwargs)[source]

Bases: Field

Bytes field type.

This field type stores binary data as byte arrays and provides validation and conversion between Python bytes objects and SurrealDB bytes format.

__init__(**kwargs)[source]

Initialize a new BytesField.

Parameters:

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

validate(value)[source]

Validate the bytes value.

This method checks if the value is a valid bytes object or can be converted to bytes.

Parameters:

value (Any) – The value to validate

Returns:

The validated bytes value

Raises:

TypeError – If the value cannot be converted to bytes

Return type:

bytes | None

to_db(value)[source]

Convert Python bytes to database representation.

This method converts a Python bytes object to a SurrealDB bytes format for storage in the database.

Parameters:

value (Any) – The Python bytes to convert

Returns:

The SurrealDB bytes format for the database

Return type:

str | None

from_db(value)[source]

Convert database value to Python bytes.

This method converts a SurrealDB bytes format from the database to a Python bytes object.

Parameters:

value (Any) – The database value to convert

Returns:

The Python bytes object

Return type:

bytes | None

RegexField

class quantumengine.fields.RegexField(**kwargs)[source]

Bases: Field

Regular expression field type.

This field type stores regular expressions and provides validation and conversion between Python regex objects and SurrealDB regex format.

__init__(**kwargs)[source]

Initialize a new RegexField.

Parameters:

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

validate(value)[source]

Validate the regex value.

This method checks if the value is a valid regex pattern or can be compiled into a regex pattern.

Parameters:

value (Any) – The value to validate

Returns:

The validated regex pattern

Raises:
  • TypeError – If the value cannot be converted to a regex pattern

  • ValueError – If the regex pattern is invalid

Return type:

Pattern | None

to_db(value)[source]

Convert Python regex to database representation.

This method converts a Python regex pattern to a SurrealDB regex format for storage in the database.

Parameters:

value (Any) – The Python regex pattern to convert

Returns:

The SurrealDB regex format for the database

Return type:

str | None

from_db(value)[source]

Convert database value to Python regex.

This method converts a SurrealDB regex format from the database to a Python regex pattern.

Parameters:

value (Any) – The database value to convert

Returns:

The Python regex pattern

Return type:

Pattern | None

DecimalField

class quantumengine.fields.DecimalField(**kwargs)[source]

Bases: NumberField

Decimal field type.

This field type stores decimal values with arbitrary precision using Python’s Decimal class. It provides validation to ensure the value is a valid decimal.

__init__(**kwargs)[source]

Initialize a new DecimalField.

Parameters:

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

validate(value)[source]

Validate the decimal value.

This method checks if the value is a valid decimal or can be converted to a decimal.

Parameters:

value (Any) – The value to validate

Returns:

The validated decimal value

Raises:

TypeError – If the value cannot be converted to a decimal

Return type:

Decimal | None

UUIDField

class quantumengine.fields.UUIDField(**kwargs)[source]

Bases: Field

UUID field type.

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

Example

>>> class User(Document):
...     id = UUIDField(default=uuid.uuid4)
__init__(**kwargs)[source]

Initialize a new UUIDField.

Parameters:

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

validate(value)[source]

Validate the UUID value.

This method checks if the value is a valid UUID or can be converted to a UUID.

Parameters:

value (Any) – The value to validate

Returns:

The validated UUID value

Raises:
  • TypeError – If the value cannot be converted to a UUID

  • ValueError – If the UUID format is invalid

Return type:

UUID | None

to_db(value)[source]

Convert Python UUID to database representation.

This method converts a Python UUID object to a string for storage in the database.

Parameters:

value (Any) – The Python UUID to convert

Returns:

The string representation for the database

Return type:

str | None

from_db(value)[source]

Convert database value to Python UUID.

This method converts a value from the database to a Python UUID object.

Parameters:

value (Any) – The database value to convert

Returns:

The Python UUID object

Return type:

UUID | None

LiteralField

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

Bases: Field

Field for union/enum-like values.

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

Example

class Product(Document):

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

__init__(allowed_values, **kwargs)[source]

Initialize a new LiteralField.

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

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

validate(value)[source]

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

Parameters:

value (Any) – The value to validate

Returns:

The validated value

Raises:

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

Return type:

Any

to_db(value)[source]

Convert Python value to database representation.

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

Parameters:

value (Any) – The Python value to convert

Returns:

The database representation of the value

Return type:

Any

from_db(value)[source]

Convert database value to Python representation.

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

Parameters:

value (Any) – The database value to convert

Returns:

The Python representation of the value

Return type:

Any

EmailField

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

Bases: StringField

Email field type.

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

Example

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

Initialize a new EmailField.

Parameters:

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

validate(value)[source]

Validate the email address.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated email address

Raises:

ValueError – If the email address is invalid

Return type:

str | None

URLField

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

Bases: StringField

URL field type.

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

Example

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

Initialize a new URLField.

Parameters:

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

validate(value)[source]

Validate the URL.

This method checks if the value is a valid URL.

Parameters:

value (Any) – The value to validate

Returns:

The validated URL

Raises:

ValueError – If the URL is invalid

Return type:

str | None

IPAddressField

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

Bases: StringField

IP address field type.

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

Example

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

Initialize a new IPAddressField.

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

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

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

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

validate(value)[source]

Validate the IP address.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated IP address

Raises:

ValueError – If the IP address is invalid

Return type:

str | None

SlugField

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

Bases: StringField

Slug field type.

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

Example

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

Initialize a new SlugField.

Parameters:

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

validate(value)[source]

Validate the slug.

This method checks if the value is a valid slug.

Parameters:

value (Any) – The value to validate

Returns:

The validated slug

Raises:

ValueError – If the slug is invalid

Return type:

str | None

ChoiceField

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

Bases: Field

Choice field type.

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

Example

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

Initialize a new ChoiceField.

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

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

validate(value)[source]

Validate the choice value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated choice value

Raises:

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

Return type:

str | None

Additional Fields

OptionField

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

Bases: Field

Option field type.

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

field_type

The field type for the value when not None

__init__(field_type, **kwargs)[source]

Initialize a new OptionField.

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

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

validate(value)[source]

Validate the option value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated value

Raises:

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

Return type:

Any

to_db(value)[source]

Convert Python value to database representation.

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

Parameters:

value (Any) – The Python value to convert

Returns:

The database representation of the value

Return type:

Any

from_db(value)[source]

Convert database value to Python representation.

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

Parameters:

value (Any) – The database value to convert

Returns:

The Python representation of the value

Return type:

Any

FutureField

class quantumengine.fields.FutureField(computation_expression, **kwargs)[source]

Bases: Field

Field for future (computed) values.

This field type represents a computed value in SurrealDB that is calculated at query time rather than stored in the database. It uses SurrealDB’s <future> syntax to define a computation expression.

computation_expression

The SurrealDB expression to compute the value

__init__(computation_expression, **kwargs)[source]

Initialize a new FutureField.

Parameters:
  • computation_expression (str) – The SurrealDB expression to compute the value

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

to_db(value)[source]

Convert to SurrealDB future syntax.

This method returns the SurrealDB <future> syntax with the computation expression, regardless of the input value.

Parameters:

value (Any) – The input value (ignored)

Returns:

The SurrealDB future syntax string

Return type:

str

TableField

class quantumengine.fields.TableField(**kwargs)[source]

Bases: Field

Table field type.

This field type stores table names and provides validation and conversion between Python strings and SurrealDB table format.

Example

```python class Schema(Document):

table_name = TableField() fields = DictField()

```

__init__(**kwargs)[source]

Initialize a new TableField.

Parameters:

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

validate(value)[source]

Validate the table name.

This method checks if the value is a valid table name.

Parameters:

value (Any) – The value to validate

Returns:

The validated table name

Raises:
Return type:

str | None

to_db(value)[source]

Convert Python string to database representation.

This method converts a Python string to a table name for storage in the database.

Parameters:

value (Any) – The Python string to convert

Returns:

The table name for the database

Return type:

str | None

RangeField

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

Bases: Field

Field for storing ranges of values.

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

Example

class PriceRange(Document):

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

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

Initialize a new RangeField.

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

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

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

validate(value)[source]

Validate the range value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated range value

Raises:

ValidationError – If the value is not a valid range

Return type:

Dict[str, Any] | None

to_db(value)[source]

Convert Python range to database representation.

Parameters:

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

Returns:

The database representation of the range

Return type:

Dict[str, Any] | None

from_db(value)[source]

Convert database range to Python representation.

Parameters:

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

Returns:

The Python representation of the range

Return type:

Dict[str, Any] | None

ClickHouse-Specific Fields

ClickHouse-specific field types for QuantumORM.

This module contains field types that are optimized for or specific to ClickHouse backend.

class quantumengine.fields.clickhouse.LowCardinalityField(base_type='String', **kwargs)[source]

Bases: StringField

ClickHouse LowCardinality field for enum-like string values.

LowCardinality is a ClickHouse optimization for string columns with a small number of distinct values (typically < 10,000). It uses dictionary encoding to reduce memory usage and improve query performance.

This field automatically maps to LowCardinality(String) in ClickHouse and falls back to regular String type in other backends.

Example

>>> class MarketplaceData(Document):
...     seller_name = LowCardinalityField(required=True)
...     marketplace = LowCardinalityField(choices=['Amazon', 'eBay', 'Walmart'])
...
...     class Meta:
...         backend = 'clickhouse'
__init__(base_type='String', **kwargs)[source]

Initialize a new LowCardinalityField.

Parameters:
  • base_type (str) – The base ClickHouse type to wrap with LowCardinality (default: ‘String’)

  • **kwargs (Any) – Additional arguments passed to StringField

get_clickhouse_type()[source]

Get the ClickHouse-specific field type.

Returns:

The ClickHouse field type definition

Return type:

str

get_surrealdb_type()[source]

Get the SurrealDB fallback field type.

Returns:

The SurrealDB field type definition

Return type:

str

class quantumengine.fields.clickhouse.FixedStringField(length, **kwargs)[source]

Bases: StringField

ClickHouse FixedString field for fixed-length strings.

FixedString is a ClickHouse type for strings of exactly N bytes. It’s more memory-efficient than String for fixed-length data like country codes, currency codes, etc.

Example

>>> class MarketplaceData(Document):
...     currency_code = FixedStringField(length=3)  # USD, EUR, etc.
...     country_code = FixedStringField(length=2)   # US, CA, etc.
__init__(length, **kwargs)[source]

Initialize a new FixedStringField.

Parameters:
  • length (int) – The exact length in bytes for the string

  • **kwargs (Any) – Additional arguments passed to StringField

validate(value)[source]

Validate the fixed string value.

Ensures the string is exactly the specified length.

Parameters:

value (Any) – The value to validate

Returns:

The validated string value

Raises:

ValueError – If the string length doesn’t match exactly

Return type:

str

get_clickhouse_type()[source]

Get the ClickHouse-specific field type.

Returns:

The ClickHouse field type definition

Return type:

str

get_surrealdb_type()[source]

Get the SurrealDB fallback field type.

Returns:

The SurrealDB field type definition

Return type:

str

class quantumengine.fields.clickhouse.EnumField(values, **kwargs)[source]

Bases: Field[str]

ClickHouse Enum field for predefined string values.

Enum fields in ClickHouse are stored as integers internally but presented as strings. They’re more efficient than LowCardinality for small sets of values that rarely change.

Example

>>> class MarketplaceData(Document):
...     status = EnumField(values={
...         'active': 1,
...         'inactive': 2,
...         'discontinued': 3
...     })
__init__(values, **kwargs)[source]

Initialize a new EnumField.

Parameters:
  • values (Dict[str, int]) – Dictionary mapping string values to integer codes

  • **kwargs (Any) – Additional arguments passed to Field

validate(value)[source]

Validate the enum value.

Parameters:

value (Any) – The value to validate

Returns:

The validated enum value

Raises:

ValueError – If the value is not in the enum

Return type:

str

get_clickhouse_type()[source]

Get the ClickHouse-specific field type.

Returns:

The ClickHouse field type definition

Return type:

str

get_surrealdb_type()[source]

Get the SurrealDB fallback field type.

Returns:

The SurrealDB field type definition

Return type:

str

class quantumengine.fields.clickhouse.CompressionMixin(codec=None, **kwargs)[source]

Bases: object

Mixin class to add compression codec support to fields.

This mixin can be used with string fields to add ClickHouse compression codec support.

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

Initialize compression settings.

Parameters:
  • codec (str | None) – ClickHouse compression codec (e.g., ‘ZSTD(3)’, ‘LZ4’, ‘NONE’)

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

get_compression_suffix()[source]

Get the compression codec suffix for ClickHouse.

Returns:

The codec suffix to append to field type

Return type:

str

class quantumengine.fields.clickhouse.CompressedStringField(codec=None, **kwargs)[source]

Bases: CompressionMixin, StringField

String field with ClickHouse compression codec support.

Useful for large text fields like URLs, descriptions, etc.

Example

>>> class MarketplaceData(Document):
...     ad_page_url = CompressedStringField(codec="ZSTD(3)")
...     product_description = CompressedStringField(codec="LZ4")
get_clickhouse_type()[source]

Get the ClickHouse-specific field type with compression.

Returns:

The ClickHouse field type definition with codec

Return type:

str

class quantumengine.fields.clickhouse.CompressedLowCardinalityField(codec=None, **kwargs)[source]

Bases: CompressionMixin, LowCardinalityField

LowCardinality field with ClickHouse compression codec support.

Example

>>> class MarketplaceData(Document):
...     category = CompressedLowCardinalityField(codec="LZ4")
get_clickhouse_type()[source]

Get the ClickHouse-specific field type with compression.

Returns:

The ClickHouse field type definition with codec

Return type:

str

class quantumengine.fields.clickhouse.ArrayField(element_field, codec=None, **kwargs)[source]

Bases: Field

ClickHouse Array field with support for nested types and optimizations.

ClickHouse arrays can contain any type including LowCardinality, Nullable, and other complex types. This field provides full ClickHouse array support with automatic type detection and optimization.

Example

>>> class MarketplaceData(Document):
...     # Array of low cardinality strings (efficient for repeated values)
...     tags = ArrayField(LowCardinalityField())
...
...     # Array of integers
...     ratings = ArrayField(IntField())
...
...     # Array of strings with compression
...     urls = ArrayField(StringField(), codec="LZ4")
__init__(element_field, codec=None, **kwargs)[source]

Initialize a new ArrayField.

Parameters:
  • element_field (Field) – The field type for array elements

  • codec (str | None) – Optional ClickHouse compression codec for the array

  • **kwargs (Any) – Additional arguments passed to Field

validate(value)[source]

Validate the array value and all elements.

Parameters:

value (Any) – The value to validate

Returns:

The validated array value

Raises:
Return type:

List[Any] | None

get_clickhouse_type()[source]

Get the ClickHouse-specific field type.

Returns:

The ClickHouse field type definition

Return type:

str

get_surrealdb_type()[source]

Get the SurrealDB fallback field type.

Returns:

The SurrealDB field type definition

Return type:

str

Complete Fields Module

For convenience, here’s the complete fields module with all exports:

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

Base class for all field types.

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

required

Whether the field is required

default

Default value for the field

name

Name of the field (set during document class creation)

db_field

Name of the field in the database

owner_document

The document class that owns this field

define_schema

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

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

Initialize a new Field.

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

  • default (Any) – Default value for the field

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

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

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

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

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

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

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

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

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

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

from_db(value, backend=None)[source]

Convert database value to Python representation.

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

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

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

Returns:

The Python representation of the value

Return type:

T

to_db(value, backend=None)[source]

Convert Python value to database representation.

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

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

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

Returns:

The database representation of the value

Return type:

Any

validate(value)[source]

Validate the field value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated value

Raises:

ValueError – If the value is invalid

Return type:

T

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

String field type.

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

min_length

Minimum length of the string

max_length

Maximum length of the string

regex

Regular expression pattern to match

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

Initialize a new StringField.

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

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

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

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

validate(value)[source]

Validate the string value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated string value

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

  • ValueError – If the value does not meet the constraints

Return type:

str

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

Base class for numeric fields.

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

min_value

Minimum allowed value

max_value

Maximum allowed value

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

Initialize a new NumberField.

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

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

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

validate(value)[source]

Validate the numeric value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated numeric value

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

  • ValueError – If the value does not meet the constraints

Return type:

int | float

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

Integer field type.

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

__init__(**kwargs)[source]

Initialize a new IntField.

Parameters:

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

to_db(value, backend=None)[source]

Convert Python value to database representation.

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

Parameters:

value (Any) – The Python value to convert

Returns:

The integer value for the database

Return type:

int | None

validate(value)[source]

Validate the integer value.

This method checks if the value is a valid integer.

Parameters:

value (Any) – The value to validate

Returns:

The validated integer value

Raises:

TypeError – If the value is not an integer

Return type:

int

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

Float field type.

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

__init__(**kwargs)[source]

Initialize a new FloatField.

Parameters:

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

validate(value)[source]

Validate the float value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated float value

Raises:

TypeError – If the value cannot be converted to a float

Return type:

float

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

Boolean field type.

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

__init__(**kwargs)[source]

Initialize a new BooleanField.

Parameters:

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

validate(value)[source]

Validate the boolean value.

This method checks if the value is a valid boolean.

Parameters:

value (Any) – The value to validate

Returns:

The validated boolean value

Raises:

TypeError – If the value is not a boolean

Return type:

bool

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

DateTime field type.

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

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

Example

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

Initialize a new DateTimeField.

Parameters:

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

validate(value)[source]

Validate the datetime value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated datetime value

Raises:

TypeError – If the value cannot be converted to a datetime

Return type:

datetime

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

Field for time series data.

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

Example

class SensorReading(Document):

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

class Meta:

time_series = True time_field = “timestamp”

__init__(**kwargs)[source]

Initialize a new TimeSeriesField.

Parameters:

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

validate(value)[source]

Validate the timestamp value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated timestamp value

Return type:

datetime | None

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

Duration field type.

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

__init__(**kwargs)[source]

Initialize a new DurationField.

Parameters:

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

from_db(value)[source]

Convert database value to Python timedelta.

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

Parameters:

value (Any) – The database value to convert

Returns:

The Python timedelta object

Return type:

timedelta | None

to_db(value)[source]

Convert Python timedelta to database representation.

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

Parameters:

value (Any) – The Python timedelta to convert

Returns:

The SurrealDB Duration object for the database

Return type:

Any | None

validate(value)[source]

Validate the duration value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated timedelta value

Raises:

TypeError – If the value cannot be converted to a timedelta

Return type:

timedelta | None

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

List field type.

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

field_type

The field type for items in the list

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

Initialize a new ListField.

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

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

from_db(value)[source]

Convert database list to Python representation.

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

Parameters:

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

Returns:

The Python representation of the list

Return type:

List[Any] | None

to_db(value, backend=None)[source]

Convert Python list to database representation.

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

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

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

Returns:

The database representation of the list

Return type:

Any

validate(value)[source]

Validate the list value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated list value

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

  • ValueError – If an item in the list fails validation

Return type:

List[Any] | None

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

Dict field type.

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

field_type

The field type for values in the dictionary

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

Initialize a new DictField.

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

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

from_db(value)[source]

Convert database dictionary to Python representation.

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

Parameters:

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

Returns:

The Python representation of the dictionary

Return type:

Dict[str, Any] | None

to_db(value, backend=None)[source]

Convert Python dictionary to database representation.

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

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

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

Returns:

The database representation of the dictionary

Return type:

Any

validate(value)[source]

Validate the dictionary value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated dictionary value

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

  • ValueError – If a value in the dictionary fails validation

Return type:

Dict[str, Any] | None

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

Set field type.

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

Example

class User(Document):

tags = SetField(StringField())

to_db(value, backend=None)[source]

Convert Python list to database representation with deduplication.

validate(value)[source]

Validate the list value and ensure uniqueness.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated and deduplicated list value

Return type:

List[Any] | None

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

Reference to another document.

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

document_type

The type of document being referenced

__init__(document_type, **kwargs)[source]

Initialize a new ReferenceField.

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

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

from_db(value, dereference=False)[source]

Convert database reference to Python representation.

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

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

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

Returns:

The Python representation of the reference

Return type:

Any

to_db(value)[source]

Convert Python reference to database representation.

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

Parameters:

value (Any) – The Python reference to convert

Returns:

The database representation of the reference

Raises:

ValueError – If the referenced document is not saved

Return type:

str | None

validate(value)[source]

Validate the reference value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated reference value

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

  • ValueError – If the referenced document is not saved

Return type:

Any

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

Field representing a relation between documents.

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

to_document

The type of document being related to

__init__(to_document, **kwargs)[source]

Initialize a new RelationField.

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

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

from_db(value, dereference=False)[source]

Convert database relation to Python representation.

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

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

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

Returns:

The Python representation of the relation

Return type:

Any

Get documents related through this relation field.

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

Parameters:

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

Returns:

List of related documents

Raises:

ValueError – If the instance is not saved

Return type:

List[Any]

Get documents related through this relation field synchronously.

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

Parameters:

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

Returns:

List of related documents

Raises:

ValueError – If the instance is not saved

Return type:

List[Any]

to_db(value)[source]

Convert Python relation to database representation.

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

Parameters:

value (Any) – The Python relation to convert

Returns:

The database representation of the relation

Raises:

ValueError – If the related document is not saved

Return type:

str | None

validate(value)[source]

Validate the relation value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated relation value

Raises:

TypeError – If the value is not a valid relation

Return type:

Any

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

Field for handling geometric data in SurrealDB.

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

required

Whether the field is required. Defaults to False.

Type:

bool

Example

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

Initialize a GeometryField.

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

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

validate(value)[source]

Validate geometry data.

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

Parameters:

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

Returns:

The validated geometry data.

Return type:

dict

Raises:

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

class quantumengine.fields.RecordIDField(**kwargs)[source]

RecordID field type.

This field type stores record IDs and provides validation and conversion between Python values and SurrealDB record ID format.

A RecordID consists of a table name and a unique identifier, formatted as table:id. This field can accept a string in this format, or a tuple/list with the table name and ID.

Example

>>> class Reference(Document):
...     target = RecordIDField()
__init__(**kwargs)[source]

Initialize a new RecordIDField.

Parameters:

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

from_db(value)[source]

Convert database value to Python representation.

This method converts a record ID from the database to a Python representation.

Parameters:

value (Any) – The database value to convert

Returns:

The Python representation of the record ID

Return type:

str | None

to_db(value)[source]

Convert Python value to database representation.

This method converts a Python value to a record ID for storage in the database.

Parameters:

value (Any) – The Python value to convert

Returns:

The record ID for the database

Return type:

str | None

validate(value)[source]

Validate the record ID.

This method checks if the value is a valid record ID.

Parameters:

value (Any) – The value to validate

Returns:

The validated record ID

Raises:
  • TypeError – If the value cannot be converted to a record ID

  • ValueError – If the record ID format is invalid

Return type:

str | None

class quantumengine.fields.BytesField(**kwargs)[source]

Bytes field type.

This field type stores binary data as byte arrays and provides validation and conversion between Python bytes objects and SurrealDB bytes format.

__init__(**kwargs)[source]

Initialize a new BytesField.

Parameters:

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

from_db(value)[source]

Convert database value to Python bytes.

This method converts a SurrealDB bytes format from the database to a Python bytes object.

Parameters:

value (Any) – The database value to convert

Returns:

The Python bytes object

Return type:

bytes | None

to_db(value)[source]

Convert Python bytes to database representation.

This method converts a Python bytes object to a SurrealDB bytes format for storage in the database.

Parameters:

value (Any) – The Python bytes to convert

Returns:

The SurrealDB bytes format for the database

Return type:

str | None

validate(value)[source]

Validate the bytes value.

This method checks if the value is a valid bytes object or can be converted to bytes.

Parameters:

value (Any) – The value to validate

Returns:

The validated bytes value

Raises:

TypeError – If the value cannot be converted to bytes

Return type:

bytes | None

class quantumengine.fields.RegexField(**kwargs)[source]

Regular expression field type.

This field type stores regular expressions and provides validation and conversion between Python regex objects and SurrealDB regex format.

__init__(**kwargs)[source]

Initialize a new RegexField.

Parameters:

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

from_db(value)[source]

Convert database value to Python regex.

This method converts a SurrealDB regex format from the database to a Python regex pattern.

Parameters:

value (Any) – The database value to convert

Returns:

The Python regex pattern

Return type:

Pattern | None

to_db(value)[source]

Convert Python regex to database representation.

This method converts a Python regex pattern to a SurrealDB regex format for storage in the database.

Parameters:

value (Any) – The Python regex pattern to convert

Returns:

The SurrealDB regex format for the database

Return type:

str | None

validate(value)[source]

Validate the regex value.

This method checks if the value is a valid regex pattern or can be compiled into a regex pattern.

Parameters:

value (Any) – The value to validate

Returns:

The validated regex pattern

Raises:
  • TypeError – If the value cannot be converted to a regex pattern

  • ValueError – If the regex pattern is invalid

Return type:

Pattern | None

class quantumengine.fields.DecimalField(**kwargs)[source]

Decimal field type.

This field type stores decimal values with arbitrary precision using Python’s Decimal class. It provides validation to ensure the value is a valid decimal.

__init__(**kwargs)[source]

Initialize a new DecimalField.

Parameters:

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

validate(value)[source]

Validate the decimal value.

This method checks if the value is a valid decimal or can be converted to a decimal.

Parameters:

value (Any) – The value to validate

Returns:

The validated decimal value

Raises:

TypeError – If the value cannot be converted to a decimal

Return type:

Decimal | None

class quantumengine.fields.UUIDField(**kwargs)[source]

UUID field type.

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

Example

>>> class User(Document):
...     id = UUIDField(default=uuid.uuid4)
__init__(**kwargs)[source]

Initialize a new UUIDField.

Parameters:

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

from_db(value)[source]

Convert database value to Python UUID.

This method converts a value from the database to a Python UUID object.

Parameters:

value (Any) – The database value to convert

Returns:

The Python UUID object

Return type:

UUID | None

to_db(value)[source]

Convert Python UUID to database representation.

This method converts a Python UUID object to a string for storage in the database.

Parameters:

value (Any) – The Python UUID to convert

Returns:

The string representation for the database

Return type:

str | None

validate(value)[source]

Validate the UUID value.

This method checks if the value is a valid UUID or can be converted to a UUID.

Parameters:

value (Any) – The value to validate

Returns:

The validated UUID value

Raises:
  • TypeError – If the value cannot be converted to a UUID

  • ValueError – If the UUID format is invalid

Return type:

UUID | None

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

Field for union/enum-like values.

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

Example

class Product(Document):

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

__init__(allowed_values, **kwargs)[source]

Initialize a new LiteralField.

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

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

from_db(value)[source]

Convert database value to Python representation.

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

Parameters:

value (Any) – The database value to convert

Returns:

The Python representation of the value

Return type:

Any

to_db(value)[source]

Convert Python value to database representation.

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

Parameters:

value (Any) – The Python value to convert

Returns:

The database representation of the value

Return type:

Any

validate(value)[source]

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

Parameters:

value (Any) – The value to validate

Returns:

The validated value

Raises:

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

Return type:

Any

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

Email field type.

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

Example

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

Initialize a new EmailField.

Parameters:

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

validate(value)[source]

Validate the email address.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated email address

Raises:

ValueError – If the email address is invalid

Return type:

str | None

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

URL field type.

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

Example

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

Initialize a new URLField.

Parameters:

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

validate(value)[source]

Validate the URL.

This method checks if the value is a valid URL.

Parameters:

value (Any) – The value to validate

Returns:

The validated URL

Raises:

ValueError – If the URL is invalid

Return type:

str | None

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

IP address field type.

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

Example

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

Initialize a new IPAddressField.

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

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

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

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

validate(value)[source]

Validate the IP address.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated IP address

Raises:

ValueError – If the IP address is invalid

Return type:

str | None

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

Slug field type.

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

Example

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

Initialize a new SlugField.

Parameters:

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

validate(value)[source]

Validate the slug.

This method checks if the value is a valid slug.

Parameters:

value (Any) – The value to validate

Returns:

The validated slug

Raises:

ValueError – If the slug is invalid

Return type:

str | None

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

Choice field type.

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

Example

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

Initialize a new ChoiceField.

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

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

validate(value)[source]

Validate the choice value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated choice value

Raises:

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

Return type:

str | None

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

Option field type.

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

field_type

The field type for the value when not None

__init__(field_type, **kwargs)[source]

Initialize a new OptionField.

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

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

from_db(value)[source]

Convert database value to Python representation.

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

Parameters:

value (Any) – The database value to convert

Returns:

The Python representation of the value

Return type:

Any

to_db(value)[source]

Convert Python value to database representation.

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

Parameters:

value (Any) – The Python value to convert

Returns:

The database representation of the value

Return type:

Any

validate(value)[source]

Validate the option value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated value

Raises:

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

Return type:

Any

class quantumengine.fields.FutureField(computation_expression, **kwargs)[source]

Field for future (computed) values.

This field type represents a computed value in SurrealDB that is calculated at query time rather than stored in the database. It uses SurrealDB’s <future> syntax to define a computation expression.

computation_expression

The SurrealDB expression to compute the value

__init__(computation_expression, **kwargs)[source]

Initialize a new FutureField.

Parameters:
  • computation_expression (str) – The SurrealDB expression to compute the value

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

to_db(value)[source]

Convert to SurrealDB future syntax.

This method returns the SurrealDB <future> syntax with the computation expression, regardless of the input value.

Parameters:

value (Any) – The input value (ignored)

Returns:

The SurrealDB future syntax string

Return type:

str

class quantumengine.fields.TableField(**kwargs)[source]

Table field type.

This field type stores table names and provides validation and conversion between Python strings and SurrealDB table format.

Example

```python class Schema(Document):

table_name = TableField() fields = DictField()

```

__init__(**kwargs)[source]

Initialize a new TableField.

Parameters:

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

to_db(value)[source]

Convert Python string to database representation.

This method converts a Python string to a table name for storage in the database.

Parameters:

value (Any) – The Python string to convert

Returns:

The table name for the database

Return type:

str | None

validate(value)[source]

Validate the table name.

This method checks if the value is a valid table name.

Parameters:

value (Any) – The value to validate

Returns:

The validated table name

Raises:
Return type:

str | None

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

Field for storing ranges of values.

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

Example

class PriceRange(Document):

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

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

Initialize a new RangeField.

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

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

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

from_db(value)[source]

Convert database range to Python representation.

Parameters:

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

Returns:

The Python representation of the range

Return type:

Dict[str, Any] | None

to_db(value)[source]

Convert Python range to database representation.

Parameters:

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

Returns:

The database representation of the range

Return type:

Dict[str, Any] | None

validate(value)[source]

Validate the range value.

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

Parameters:

value (Any) – The value to validate

Returns:

The validated range value

Raises:

ValidationError – If the value is not a valid range

Return type:

Dict[str, Any] | None

class quantumengine.fields.LowCardinalityField(base_type='String', **kwargs)[source]

ClickHouse LowCardinality field for enum-like string values.

LowCardinality is a ClickHouse optimization for string columns with a small number of distinct values (typically < 10,000). It uses dictionary encoding to reduce memory usage and improve query performance.

This field automatically maps to LowCardinality(String) in ClickHouse and falls back to regular String type in other backends.

Example

>>> class MarketplaceData(Document):
...     seller_name = LowCardinalityField(required=True)
...     marketplace = LowCardinalityField(choices=['Amazon', 'eBay', 'Walmart'])
...
...     class Meta:
...         backend = 'clickhouse'
__init__(base_type='String', **kwargs)[source]

Initialize a new LowCardinalityField.

Parameters:
  • base_type (str) – The base ClickHouse type to wrap with LowCardinality (default: ‘String’)

  • **kwargs (Any) – Additional arguments passed to StringField

get_clickhouse_type()[source]

Get the ClickHouse-specific field type.

Returns:

The ClickHouse field type definition

Return type:

str

get_surrealdb_type()[source]

Get the SurrealDB fallback field type.

Returns:

The SurrealDB field type definition

Return type:

str

class quantumengine.fields.FixedStringField(length, **kwargs)[source]

ClickHouse FixedString field for fixed-length strings.

FixedString is a ClickHouse type for strings of exactly N bytes. It’s more memory-efficient than String for fixed-length data like country codes, currency codes, etc.

Example

>>> class MarketplaceData(Document):
...     currency_code = FixedStringField(length=3)  # USD, EUR, etc.
...     country_code = FixedStringField(length=2)   # US, CA, etc.
__init__(length, **kwargs)[source]

Initialize a new FixedStringField.

Parameters:
  • length (int) – The exact length in bytes for the string

  • **kwargs (Any) – Additional arguments passed to StringField

get_clickhouse_type()[source]

Get the ClickHouse-specific field type.

Returns:

The ClickHouse field type definition

Return type:

str

get_surrealdb_type()[source]

Get the SurrealDB fallback field type.

Returns:

The SurrealDB field type definition

Return type:

str

validate(value)[source]

Validate the fixed string value.

Ensures the string is exactly the specified length.

Parameters:

value (Any) – The value to validate

Returns:

The validated string value

Raises:

ValueError – If the string length doesn’t match exactly

Return type:

str

class quantumengine.fields.EnumField(values, **kwargs)[source]

ClickHouse Enum field for predefined string values.

Enum fields in ClickHouse are stored as integers internally but presented as strings. They’re more efficient than LowCardinality for small sets of values that rarely change.

Example

>>> class MarketplaceData(Document):
...     status = EnumField(values={
...         'active': 1,
...         'inactive': 2,
...         'discontinued': 3
...     })
__init__(values, **kwargs)[source]

Initialize a new EnumField.

Parameters:
  • values (Dict[str, int]) – Dictionary mapping string values to integer codes

  • **kwargs (Any) – Additional arguments passed to Field

get_clickhouse_type()[source]

Get the ClickHouse-specific field type.

Returns:

The ClickHouse field type definition

Return type:

str

get_surrealdb_type()[source]

Get the SurrealDB fallback field type.

Returns:

The SurrealDB field type definition

Return type:

str

validate(value)[source]

Validate the enum value.

Parameters:

value (Any) – The value to validate

Returns:

The validated enum value

Raises:

ValueError – If the value is not in the enum

Return type:

str

class quantumengine.fields.CompressedStringField(codec=None, **kwargs)[source]

String field with ClickHouse compression codec support.

Useful for large text fields like URLs, descriptions, etc.

Example

>>> class MarketplaceData(Document):
...     ad_page_url = CompressedStringField(codec="ZSTD(3)")
...     product_description = CompressedStringField(codec="LZ4")
get_clickhouse_type()[source]

Get the ClickHouse-specific field type with compression.

Returns:

The ClickHouse field type definition with codec

Return type:

str

class quantumengine.fields.CompressedLowCardinalityField(codec=None, **kwargs)[source]

LowCardinality field with ClickHouse compression codec support.

Example

>>> class MarketplaceData(Document):
...     category = CompressedLowCardinalityField(codec="LZ4")
get_clickhouse_type()[source]

Get the ClickHouse-specific field type with compression.

Returns:

The ClickHouse field type definition with codec

Return type:

str

class quantumengine.fields.ArrayField(element_field, codec=None, **kwargs)[source]

ClickHouse Array field with support for nested types and optimizations.

ClickHouse arrays can contain any type including LowCardinality, Nullable, and other complex types. This field provides full ClickHouse array support with automatic type detection and optimization.

Example

>>> class MarketplaceData(Document):
...     # Array of low cardinality strings (efficient for repeated values)
...     tags = ArrayField(LowCardinalityField())
...
...     # Array of integers
...     ratings = ArrayField(IntField())
...
...     # Array of strings with compression
...     urls = ArrayField(StringField(), codec="LZ4")
__init__(element_field, codec=None, **kwargs)[source]

Initialize a new ArrayField.

Parameters:
  • element_field (Field) – The field type for array elements

  • codec (str | None) – Optional ClickHouse compression codec for the array

  • **kwargs (Any) – Additional arguments passed to Field

get_clickhouse_type()[source]

Get the ClickHouse-specific field type.

Returns:

The ClickHouse field type definition

Return type:

str

get_surrealdb_type()[source]

Get the SurrealDB fallback field type.

Returns:

The SurrealDB field type definition

Return type:

str

validate(value)[source]

Validate the array value and all elements.

Parameters:

value (Any) – The value to validate

Returns:

The validated array value

Raises:
Return type:

List[Any] | None