API Reference¶
This document provides an overview of surql's API modules. For detailed implementation, refer to the source code.
Table of Contents¶
Schema Module¶
Location: src/schema/
Defines database schemas using functional composition.
Key Files¶
fields.py¶
Field type definitions and builder functions.
Key Classes:
FieldType- Enum of SurrealDB field typesFieldDefinition- Immutable field definition model
Key Functions:
field()- Create a field definitionstring_field()- Create a string fieldint_field()- Create an integer fieldfloat_field()- Create a float fieldbool_field()- Create a boolean fielddatetime_field()- Create a datetime fieldrecord_field()- Create a record (foreign key) fieldarray_field()- Create an array fieldobject_field()- Create an object fieldcomputed_field()- Create a computed field
Example:
from surql.schema.fields import string_field, int_field
name_field = string_field('name', assertion='string::len($value) > 0')
age_field = int_field('age', assertion='$value >= 0')
table.py¶
Table schema composition and builders.
Key Classes:
TableMode- Enum for table modes (SCHEMAFULL, SCHEMALESS, DROP)IndexType- Enum for index types (UNIQUE, SEARCH, STANDARD)TableDefinition- Immutable table schema definitionIndexDefinition- Immutable index definitionEventDefinition- Immutable event/trigger definition
Key Functions:
table_schema()- Create a table schemaindex()- Create an indexunique_index()- Create a unique indexsearch_index()- Create a search indexevent()- Create an event/triggerwith_fields()- Add fields to a tablewith_indexes()- Add indexes to a tablewith_events()- Add events to a tablewith_permissions()- Add permissions to a table
Example:
from surql.schema.table import table_schema, unique_index, TableMode
schema = table_schema(
'user',
mode=TableMode.SCHEMAFULL,
fields=[...],
indexes=[unique_index('email_idx', ['email'])],
)
edge.py¶
Edge (relationship) schema definitions.
Key Classes:
EdgeDefinition- Immutable edge schema definition
Key Functions:
edge_schema()- Create an edge schema
Example:
from surql.schema.edge import edge_schema
follows = edge_schema('follows', from_table='user', to_table='user')
Migration Module¶
Location: src/migration/
Database migration generation, execution, and tracking.
Key Migration Files¶
generator.py¶
Migration file generation.
Key Functions:
create_blank_migration()- Create a blank migration file
executor.py¶
Migration execution engine.
Key Functions:
execute_migration_plan()- Execute a migration plancreate_migration_plan()- Create a migration execution planvalidate_migrations()- Validate migration files
discovery.py¶
Migration file discovery and loading.
Key Classes:
MigrationFile- Loaded migration file representation
Key Functions:
discover_migrations()- Find and load migration filesvalidate_migration_name()- Validate migration filename
history.py¶
Migration history tracking.
Key Classes:
MigrationHistory- Migration history record
Key Functions:
ensure_migration_table()- Create migration history tableget_applied_migrations()- Get list of applied migrationsrecord_migration()- Record a migration as applied
models.py¶
Migration data models.
Key Classes:
MigrationDirection- Enum for UP/DOWNMigrationState- Enum for PENDING/APPLIEDMigrationPlan- Migration execution plan
Query Module¶
Location: src/query/
Query building and ORM operations.
Key Query Files¶
crud.py¶
High-level CRUD operations.
Key Functions:
create_record()- Create a single recordcreate_records()- Create multiple recordsget_record()- Get a record by IDupdate_record()- Update entire recordmerge_record()- Partial updatedelete_record()- Delete a recorddelete_records()- Delete multiple recordsquery_records()- Query with filterscount_records()- Count records (emitscount() ... GROUP ALLfor v3)aggregate_records()- TypedSELECT ... GROUP BY | GROUP ALLreturning list-of-dicts (added in 1.5.0)exists()- Check if record existsfirst()- Get first matching recordlast()- Get last matching record
Example:
from surql.query.crud import create_record, query_records
user = await create_record('user', user_data, client=client)
users = await query_records('user', User, conditions=['age >= 18'], client=client)
functions.py¶
Pre-built SurrealQL function factories returning SurrealFn wrappers. Each factory composes with Query.set(...), Query.select([...]), and aggregate_records(select={...}).
Time:
time_now_fn()-time::now()
Math:
math_mean_fn(field),math_sum_fn(field),math_min_fn(field),math_max_fn(field)math_ceil_fn(field),math_floor_fn(field),math_round_fn(field, precision=None),math_abs_fn(field)
Strings:
string_len(field),string_concat(*parts),string_lower(field),string_upper(field)
Aggregation:
count_if(predicate=None)- renderscount()orcount(<predicate>)(v3 rejectscount(*))
See the Query UX Helpers guide for worked examples.
results.py¶
Result wrapper classes and extraction utilities for SurrealDB responses.
Result Wrappers:
QueryResult[T]- Generic result container with metadataRecordResult[T]- Single record wrapperListResult[T]- Multiple records wrapperCountResult- Aggregation result for count operationsAggregateResult- Generic aggregation resultPaginatedResult[T]- Paginated result with page metadata
Result Extraction Utilities (SurrealDB Response Format Handling):
extract_result(result)- Extract data from nested/flat SurrealDB response formatsextract_many(result)- Alias forextract_result(naming parity withextract_one/extract_scalar, added in 1.5.0)extract_one(result)- Extract first record or Noneextract_scalar(result, key, default)- Extract scalar value from aggregate querieshas_results(result)- Check if result contains any recordshas_result(result)- Alias forhas_results(added in 1.5.0)
Example:
from surql.query.results import extract_result, extract_one, extract_scalar, has_results
# Handle nested format from db.query()
result = await client.execute('SELECT * FROM user WHERE age > 18')
records = extract_result(result) # List of dicts
# Get single record
result = await client.execute('SELECT * FROM user:alice')
user = extract_one(result) # Dict or None
# Extract aggregate values
result = await client.execute('SELECT count() AS total FROM user')
count = extract_scalar(result, 'total', 0) # Scalar value
# Check if results exist
if has_results(result):
records = extract_result(result)
Why Use Extract Utilities:
SurrealDB returns responses in different formats depending on the operation:
- Nested format:
[{"result": [{"id": "...", ...}]}](fromdb.query()) - Flat format:
[{"id": "...", ...}](fromdb.select())
The extraction utilities handle both formats seamlessly, eliminating the need for custom workarounds and making code robust across SurrealDB response formats.
builder.py¶
Composable query builder.
Key Classes:
Query- Immutable query builder
Key Methods:
select()- SELECT clausefrom_table()- FROM clausewhere()- WHERE conditionorder_by()- ORDER BY clauselimit()- LIMIT clauseoffset()- OFFSET clausegroup_by()- GROUP BY clauseto_surql()- Convert to SurrealQL
Example:
from surql.query.builder import Query
query = (
Query()
.select(['name', 'email'])
.from_table('user')
.where('age >= 18')
.limit(10)
)
executor.py¶
Query execution.
Key Functions:
fetch_all()- Execute query and return all resultsfetch_one()- Execute query and return first result
expressions.py¶
Type-safe query expressions.
Key Classes:
Expression- Query expression wrapper
Connection Module¶
Location: src/connection/
Database connection management.
Key Connection Files¶
client.py¶
Async database client.
Key Classes:
DatabaseClient- Async SurrealDB client wrapperDatabaseError- Base database exceptionConnectionError- Connection error exceptionQueryError- Query execution error exception
Key Functions:
get_client()- Context manager for client lifecycle
Key Methods:
connect()- Establish connectiondisconnect()- Close connectionexecute()- Execute raw SurrealQLselect()- SELECT operationcreate()- CREATE operationupdate()- UPDATE operationmerge()- MERGE operationdelete()- DELETE operationinsert_relation()- INSERT RELATION for edges
Example:
from surql.connection.client import get_client
async with get_client(config) as client:
result = await client.execute('SELECT * FROM user')
config.py¶
Connection configuration.
Key Classes:
ConnectionConfig- Database connection configuration
context.py¶
Connection context management.
Key Functions:
get_db()- Get current database client from contextset_db()- Set database client in contextdb_context()- Context manager for scoped connections
transaction.py¶
Transaction support.
Key Classes:
Transaction- Transaction wrapper
Key Functions:
transaction()- Context manager for transactions
Example:
from surql.connection.transaction import transaction
async with transaction(client):
await client.execute('UPDATE user:alice SET credits -= 10')
await client.execute('UPDATE user:bob SET credits += 10')
Types Module¶
Location: src/types/
Type definitions and utilities.
Key Types Files¶
record_id.py¶
RecordID type for SurrealDB record identifiers with angle bracket support.
Key Classes:
RecordID- Type-safe record ID wrapper with support for complex IDs
Key Methods:
parse()- Parse from string (supports both standard and angle bracket formats)__str__()- Convert to string
Supported Formats:
- Standard format:
table:id(alphanumeric + underscores) - Angle bracket format:
table:⟨complex-id⟩(for complex record IDs)
Example:
from surql.types.record_id import RecordID
# Standard format
user_rid = RecordID(table='user', id='alice')
print(user_rid) # user:alice
# Angle bracket format
# Required for IDs with special characters (dots, hyphens, colons, etc.)
outlet_rid = RecordID.parse('outlet:⟨alaskabeacon.com⟩')
print(outlet_rid) # outlet:⟨alaskabeacon.com⟩
# Complex compound IDs
doc_rid = RecordID.parse('document:⟨alaskabeacon.com:01HQXYZ...⟩')
print(doc_rid) # document:⟨alaskabeacon.com:01HQXYZ...⟩
# Why use angle brackets:
# - Domains: outlet:⟨alaskabeacon.com⟩ (dots in domain)
# - URLs: page:⟨https://example.com/path⟩ (colons, slashes)
# - Compound keys: doc:⟨domain:ulid⟩ (multiple parts)
Complex Record ID Support:
The angle bracket format is valid SurrealDB syntax for escaping complex identifiers. This feature enables support for record IDs that contain special characters such as domain names, URLs, and compound keys.
operators.py¶
Query operators for type-safe conditions.
Key Classes:
Operator- Base operator class
Key Functions:
eq()- Equality operatorne()- Not equal operatorgt()- Greater than operatorgte()- Greater than or equal operatorlt()- Less than operatorlte()- Less than or equal operatorcontains()- String contains operatorin_list()- IN operator
surreal_fn.py¶
Raw SurrealQL function-call wrapper that renders verbatim when used as a value.
Key Classes:
SurrealFn- Immutable wrapper whose.to_surql()emits the bare function expression
Key Functions:
surql_fn(name, *args)- Build aSurrealFnfrom a function name and argumentstype_record(table, id)- Build atype::thing('table', id)record-id (the helper is namedtype_recordfor source compatibility but emitstype::thing)type_thing(table, id)- Buildtype::thing('table', id)(canonical name)
See Query UX Helpers for composition examples.
CLI Module¶
Location: src/cli/
Command-line interface implementation.
Key CLI Files¶
migrate.py¶
Migration CLI commands.
Commands:
migrate up- Apply migrationsmigrate down- Rollback migrationsmigrate status- Show migration statusmigrate history- Show migration historymigrate create- Create new migrationmigrate validate- Validate migrations
schema.py¶
Schema inspection commands.
Commands:
schema show- Show database schema
db.py¶
Database management commands.
Commands:
db init- Initialize database and create migration tracking tabledb ping- Check database connectiondb info- Show database informationdb reset- Reset database by removing all tablesdb query- Execute a raw SurrealQL querydb version- Show database version information
orchestrate.py¶
Multi-database orchestration commands.
Commands:
orchestrate deploy- Deploy migrations across environments (sequential, parallel, rolling, canary)orchestrate status- Check deployment status of environmentsorchestrate validate- Validate environment configuration and connectivity
See the CLI Reference for full options.
common.py¶
Common CLI utilities.
Key Functions:
display_info()- Display info messagedisplay_success()- Display success messagedisplay_error()- Display error messagedisplay_warning()- Display warning messagespinner()- Progress spinner context managerformat_output()- Format output as table/json/yaml
Settings¶
Location: src/settings.py
Application settings management.
Key Functions:
get_settings()- Get application settingsget_db_config()- Get database configuration from environment
Example:
from surql.settings import get_db_config
config = get_db_config() # Loads from environment variables
Usage Patterns¶
Basic CRUD¶
from surql.connection.client import get_client
from surql.connection.config import ConnectionConfig
from surql.query.crud import create_record, query_records
config = ConnectionConfig(url='ws://localhost:8000/rpc', ...)
async with get_client(config) as client:
# Create
user = await create_record('user', user_data, client=client)
# Read
users = await query_records('user', User, client=client)
# Update
await merge_record('user', 'alice', {'age': 31}, client=client)
# Delete
await delete_record('user', 'alice', client=client)
Schema Definition¶
from surql.schema.fields import string_field, int_field
from surql.schema.table import table_schema, unique_index, TableMode
schema = table_schema(
'user',
mode=TableMode.SCHEMAFULL,
fields=[
string_field('username'),
int_field('age'),
],
indexes=[
unique_index('username_idx', ['username']),
],
)
Migrations¶
from surql.migration.discovery import discover_migrations
from surql.migration.executor import create_migration_plan, execute_migration_plan
migrations = discover_migrations(Path('migrations'))
plan = await create_migration_plan(client, migrations, MigrationDirection.UP)
await execute_migration_plan(client, plan)
Type Safety¶
All public APIs use strict type hints. Use mypy for static type checking:
Further Reading¶
- Schema Definition Guide
- Migration System Guide
- Query Builder Guide
- Query UX Helpers - typed wrappers for
time::now,math::*,string::*,count_if,type_record, andaggregate_records - SurrealDB v3 Patterns - v3-required SurrealQL forms
- Upgrade Notes - 1.3.1 -> 1.4.0 -> 1.5.0 -> 1.5.1 migration guide
- CLI Reference -
migrate,schema,db,orchestratesubcommands - Examples