Skip to content

Table and type definitions

Model, Schema, and the compiler share a backend independent table representation: TableDefinition. Integer, String, and the other types are ColumnDefinition objects; structured constraints complete the physical schema. This reference covers public metadata. The type catalog contains all 39 logical types, their 40 factories, constructors, arguments, and examples; modifiers explain every fluent operation.

from orionis.database.schema.column import Column
from orionis.orm import Model
from orionis.orm.schema import TableDefinition
from orionis.orm.schema.constraints import TableIndex, UniqueConstraint
class ProjectsV1Schema:
table_definition = TableDefinition(
name="projects",
columns={
"id": Column.id(),
"name": Column.string("name", 120),
"slug": Column.string("slug", 160),
},
primary_key="id",
unique_constraints=(UniqueConstraint(("slug",), name="uq_project_slug"),),
indexes=(TableIndex(("name",), name="ix_project_name"),),
)
class Project(Model):
table_definition = ProjectsV1Schema.table_definition
timestamps = False
fillable = ("name", "slug")

The definition executes no DDL. A migration must call await Schema.createFromDefinition(ProjectsV1Schema.table_definition); Project can be used once its table exists. Preserve V1 and introduce a new definition for future changes to keep history reproducible. Model definitions explain how inline columns and explicit metadata are integrated.

A dataclass with frozen=True, slots=True, eq=False. Fields accept positional or keyword arguments in this order. Frozen prevents field reassignment but does not deeply freeze the columns dictionary or its ColumnDefinition values: do not mutate a version used by historical migrations.

name: str

Logical name without the connection prefix. Required.

columns: dict[str, ColumnDefinition] = field(default_factory=dict)

A fresh, initially empty name → ColumnDefinition dictionary. Insertion order determines column order. The dictionary key is the SQL name used by the compiler.

primary_key: str = 'id'

Single key name, default id. This neither creates a missing column nor marks an arbitrary definition as primary by itself: declare primary() on the column, or use composite_primary_key for a composite constraint.

schema: str | None = None

Owning SQL schema; None uses the default. This does not create the schema automatically.

comment: str | None = None

Table comment or None; storage is backend dependent.

composite_primary_key: tuple[str, ...] | None = None

Ordered tuple or None; translated to PrimaryKeyConstraint. Takes precedence over the simple key representation for the schema. This does not turn Model.primary_key into a supported tuple.

unique_constraints: tuple[UniqueConstraint, ...] = ()

Tuple of UniqueConstraint values, default (). Supports simple or composite constraints with optional names.

foreign_keys: tuple[CompositeForeignKey, ...] = ()

Tuple of CompositeForeignKey values, default (). Aligns local and referenced columns by position.

indexes: tuple[TableIndex, ...] = ()

Tuple of TableIndex values, default (). Retains each index column order, name, and uniqueness.

columnNames() -> tuple[str, ...]

columnNames returns an ordered name tuple; hasColumn checks membership and returns bool. Both read metadata and do not inspect the database.

hasColumn(name: str) -> bool

columnNames returns an ordered name tuple; hasColumn checks membership and returns bool. Both read metadata and do not inspect the database.

definition = ProjectsV1Schema.table_definition
names = definition.columnNames()
contains_slug = definition.hasColumn("slug")

These are frozen/slotted dataclasses with no SQL access. Required arguments have no default; optional defaults appear in the signatures. There is no comprehensive early validation of lengths, columns, or server compatibility. Supply nonempty tuples, existing columns, and equal counts of local and referenced columns.

UniqueConstraint(columns: tuple[str, ...], name: str | None = None)

columns identifies jointly unique columns; name leaves naming to the backend when None.

TableIndex(columns: tuple[str, ...], name: str | None = None, unique: bool = False)

columns preserves order; name=None produces ix_<logical_table>_<columns>; unique requests uniqueness.

CompositeForeignKey(columns: tuple[str, ...], ref_table: str, ref_columns: tuple[str, ...], name: str | None = None)

ref_table accepts schema.table. columns and ref_columns align by position. No ondelete, onupdate, or deferrable arguments exist.

ForeignReference(table: str, column: str)

Contains a single column reference. Its constructor stores values; parse validates table.column syntax.

ForeignReference.parse(reference: str) -> ForeignReference
ForeignReference.qualified() -> str
from orionis.orm.schema.constraints import ForeignReference
reference = ForeignReference.parse("users.id")
assert reference.table == "users"
assert reference.column == "id"
assert reference.qualified() == "users.id"

parse is a classmethod requiring exactly two nonempty segments; schema.table.column, incomplete strings, or nonstrings raise ValueError. qualified is an instance method returning table.column. Use CompositeForeignKey for schema qualified targets.

The articles table must exist with a compatible UNIQUE or PRIMARY KEY over (tenant_id, id). Enable foreign keys on SQLite to enforce references.

from orionis.database.schema.column import Column
from orionis.orm.schema import TableDefinition
from orionis.orm.schema.constraints import CompositeForeignKey
TRANSLATIONS_V1 = TableDefinition(
name="article_translations",
columns={
"tenant_id": Column.integer("tenant_id"),
"article_id": Column.integer("article_id"),
"locale": Column.string("locale", 10),
"title": Column.string("title", 120),
},
composite_primary_key=("tenant_id", "article_id", "locale"),
foreign_keys=(
CompositeForeignKey(
columns=("tenant_id", "article_id"),
ref_table="articles",
ref_columns=("tenant_id", "id"),
name="fk_translation_article",
),
),
)

A frozen=True/slots=True dataclass. Its constructor accepts all fields below, positionally or by keyword, with the displayed defaults. ColumnDefinition copies each option onto its own attributes; prefer concrete constructors from the catalog.

length: int | None = None

Text/binary length.

precision: int | None = None

Numeric precision.

scale: int | None = None

Decimal scale.

decimal_return_scale: int | None = None

Scale for Decimal conversion.

as_decimal: bool = True

Decimal conversion; public type constructors call this asdecimal. Float/Double change it to False.

enum_values: tuple[str, ...] = ()

Enum string members.

enum_name: str | None = None

Enum type name; constructors call this name.

native_enum: bool = True

Request native ENUM.

validate_strings: bool = False

Enum string validation.

create_constraint: bool = False

CHECK for emulated booleans/enums.

constraint_name: str | None = None

Boolean CHECK name.

timezone: bool = False

Date/time timezone support where available.

collation: str | None = None

Text collation.

as_uuid: bool = True

Convert to uuid.UUID objects.

native_uuid: bool = True

Native UUID representation where available.

item_type: ColumnDefinition | None = None

ARRAY element type; retained but has no SQL builder.

dimensions: int | None = None

ARRAY dimensions; retained but not materializable.

as_tuple: bool = False

ARRAY results as tuples; retained without SQL support.

zero_indexes: bool = False

ARRAY index conversion; retained without SQL support.

none_as_null: bool = False

JSON None as SQL NULL instead of JSON null.

native: bool = True

Native INTERVAL where available.

second_precision: int | None = None

INTERVAL second precision.

day_precision: int | None = None

INTERVAL day precision.

protocol: int = 5

Pickle protocol; the literal default is 5.

pickler: object | None = None

Custom pickler retained; SQLCompiler does not forward it.

comparator: Callable[[object, object], bool] | None = None

Comparator retained; SQLCompiler does not use it. No concrete type constructor exposes it.

impl: object | None = None

Custom binary implementation retained; SQLCompiler does not forward it.

from orionis.orm.schema.column import ColumnDefinition, ColumnOptions
from orionis.orm import ColumnType
column = ColumnDefinition(
ColumnType.STRING,
ColumnOptions(length=120),
).nullable()
column.name = "title"

In addition to the options above, available properties are name (initially empty string), column_type (required ColumnType), is_primary/is_nullable/is_unique/has_index/is_auto_increment (False), comment_text (None), foreign_ref (None or ForeignReference), and default_value (a private absence sentinel). Use hasDefault rather than comparing that sentinel. Configure these properties through fluent methods. These metadata expose neither business data validation nor direct backend access.

A StrEnum with 39 identifiers. Values are logical metadata, not a promise of available native storage. ARRAY, MATCH_TYPE, NUMERIC_COMMON, and SCHEMA_TYPE translation is not registered; creating tables with them raises QueryException.

MemberValue
BIG_INTEGERbig_integer
BOOLEANboolean
DATEdate
DATETIMEdatetime
DOUBLEdouble
ENUMenum
FLOATfloat
INTEGERinteger
INTERVALinterval
LARGE_BINARYlarge_binary
MATCH_TYPEmatch_type
NUMERICnumeric
NUMERIC_COMMONnumeric_common
PICKLE_TYPEpickle_type
SCHEMA_TYPEschema_type
SMALL_INTEGERsmall_integer
STRINGstring
TEXTtext
TIMEtime
UNICODEunicode
UNICODE_TEXTunicode_text
UUIDuuid
ARRAYarray
BIGINTbigint
BINARYbinary
BLOBblob
CHARchar
CLOBclob
DECIMALdecimal
DOUBLE_PRECISIONdouble_precision
INTint
JSONjson
NCHARnchar
NVARCHARnvarchar
REALreal
SMALLINTsmallint
TIMESTAMPtimestamp
VARBINARYvarbinary
VARCHARvarchar

DefinitionBucket() is an implementation accumulator, not an alternative table creation API. Its public containers columns={}, primary_columns=[], unique_constraints=[], foreign_keys=[], indexes=[], and kwargs={} group definitions while Schema processes a blueprint. Schema._createTable has a reserved prefix and is not public facade API. Use the five documented Schema operations to create tables.