ORIONIS API REFERENCE

THE ORIONIS API

Build with clarity.

Explore the building blocks of an async-first Python framework. Every module, class, and method — connected, searchable, and ready to build with.

class documentation

class SQLCompiler: (source)

Constructor: SQLCompiler(prefix)

View In Hierarchy

Translate Orionis query plans into engine-executable statements.

This is the only component, together with the connection and the dialect helpers, aware of the underlying SQL toolkit. It converts TableDefinition objects into engine table metadata (cached per compiler) and query plans into executable statements.

Static Method _betweenExpression Compile an inclusive range condition into a boolean expression.
Static Method _combineExpressions Combine clauses using left-to-right boolean grouping.
Static Method _rawElement Turn a raw SQL fragment into a bound engine element.
Static Method supportsBatchInsert Report whether an insert plan supports batch execution.
Method __init__ Initialize the compiler with an optional table name prefix.
Method _aggregateExpression Compile an aggregate clause into a projection expression.
Method _applyJoin Extend a FROM clause with a single joined table.
Method _applyOrderingAndPaging Apply ordering, limit, and offset clauses to a statement.
Method _applyUnions Combine a compiled statement with the plan union branches.
Method _bareNameForIdentifier Return the bare column name when a reference targets an identifier.
Method _basicExpression Compile a basic comparison clause into a boolean expression.
Method _buildSelect Compile a select plan, correlating it with an enclosing query.
Method _cacheKey Build the internal table cache key, disambiguating by schema.
Method _clauseExpression Compile a single where clause into a boolean expression.
Method _clauseValue Resolve the bound value of a clause, compiling nested subqueries.
Method _collectClauseColumnNames Collect the column references of a clause list, recursing groups.
Method _collectPlanColumnNames Collect every column reference touched anywhere in a select plan.
Method _columnComparison Compile a comparison between two columns of the same query.
Method _columnlessExpression Compile the clause kinds that carry no column reference.
Method _ensureRawColumns Lazily declare columns a plan references against a raw table.
Method _ensureReferencedColumns Register a stub table exposing the given referenced columns.
Method _ensureReferencedTable Register a stub for a referenced table when it is unknown.
Method _ensureSelectRawColumns Lazily declare raw columns referenced by a select plan's sources.
Method _joinCondition Fold a join's ON conditions into a single boolean expression.
Method _joinConditionExpression Compile a single ON condition into a column-to-column comparison.
Method _joinSource Build the FROM source contributed by a single join expression.
Method _physicalName Prepend the connection prefix to a logical table name.
Method _projectionElement Compile a single entry of a select projection.
Method _resolveColumn Resolve a column reference against the tables reachable in a plan.
Method _resolveSources Build the main source, the resolvable source map, and the FROM.
Method _selectProjection Build the base SELECT statement with its projection.
Method _splitQualifiedColumn Split a column reference into its table qualifier and column name.
Method _sqlColumn Translate a column definition into an engine column.
Method _sqlTable Resolve and cache the engine table for a table definition.
Method _sqlType Resolve the engine type backing a column definition.
Method _tableConstraints Build the composite, table-level constraints for a definition.
Method _whereExpression Fold a sequence of where clauses into a boolean expression.
Method compileCreateTable Compile a table definition into a CREATE TABLE statement.
Method compileDelete Compile a delete plan into an executable DELETE statement.
Method compileDropTable Compile a DROP TABLE statement for the given logical name.
Method compileInsert Compile an insert plan into an executable INSERT statement.
Method compileSelect Compile a select plan into an executable SELECT statement.
Method compileUpdate Compile an update plan into an executable UPDATE statement.
Constant _TYPE_BUILDERS Undocumented
Class Variable __slots__ Undocumented
Instance Variable _definitions Undocumented
Instance Variable _metadata Undocumented
Instance Variable _prefix Undocumented
Instance Variable _tables Undocumented
def _betweenExpression(column: ColumnElement[Any], clause: WhereClause) -> ColumnElement[bool]: (source)

Compile an inclusive range condition into a boolean expression.

Parameters
column:ColumnElementColumn the range applies to.
clause:WhereClauseRange condition carrying exactly two boundary values.
Returns
ColumnElementBoolean expression for the range.
Raises
QueryExceptionIf the clause does not carry exactly two boundaries.
def _combineExpressions(compile_clause: Callable[..., ColumnElement[bool]], sources: SourceMap, default: SqlSource, clauses: Sequence[WhereClause] | Sequence[JoinCondition]) -> ColumnElement[bool] | None: (source)

Combine clauses using left-to-right boolean grouping.

Parameters
compile_clause:CallableFunction that translates one clause into a boolean expression.
sources:SourceMapSources available while resolving clause references.
default:SqlSourceSource used for unqualified column references.
clauses:Sequence of WhereClause or JoinConditionClauses to combine in their declared order.
Returns
ColumnElement or NoneCombined boolean expression, or None for an empty sequence.
def _rawElement(raw: RawExpression) -> ColumnElement[Any]: (source)

Turn a raw SQL fragment into a bound engine element.

Every value travels as a bound parameter, so the driver escapes it and the fragment cannot be used to smuggle literals. A raw fragment carrying an alias is compiled as a labeled column so it stays addressable when the query is used as a derived table.

Parameters
raw:RawExpressionFragment, its named bindings, and its optional alias.
Returns
ColumnElementTextual element ready to be embedded in a statement.
def supportsBatchInsert(plan: InsertPlan) -> bool: (source)

Report whether an insert plan supports batch execution.

Parameters
plan:InsertPlanInsert plan whose rows are checked for a shared parameter shape.
Returns
boolWhether the rows can be sent as one batch without SQL expressions.
def __init__(self, prefix: str = ''): (source)

Initialize the compiler with an optional table name prefix.

Parameters
prefix:str, optionalPrefix prepended to every physical table name.
Returns
NoneThis method does not return a value.
def _aggregateExpression(self, sources: SourceMap, default: SqlSource, aggregate: AggregateClause) -> ColumnElement[Any]: (source)

Compile an aggregate clause into a projection expression.

Parameters
sources:SourceMapTable sources reachable by qualified column references.
default:SqlSourceSource an unqualified column reference resolves against.
aggregate:AggregateClauseAggregate projection description.
Returns
ColumnElementAggregate expression such as COUNT(*) or MAX(col).
Raises
QueryExceptionIf a non-count aggregate targets "*".
def _applyJoin(self, from_clause: SqlSource, sources: SourceMap, join: JoinExpression) -> tuple[SqlSource, str, SqlSource]: (source)

Extend a FROM clause with a single joined table.

Parameters
from_clause:SqlSourceFROM clause assembled so far.
sources:SourceMapTable sources already reachable by qualified references.
join:JoinExpressionJoin description to compile.
Returns
tuple of (SqlSource, str, SqlSource)The extended FROM clause, the identifier the joined table is reachable by, and the joined source itself.
Raises
QueryExceptionIf the join type is not supported, or its ON conditions cannot be resolved.
def _applyOrderingAndPaging(self, sources: SourceMap, default: SqlSource, statement: Select[Any], plan: SelectPlan) -> Select[Any]: (source)

Apply ordering, limit, and offset clauses to a statement.

Parameters
sources:SourceMapTable sources reachable by qualified column references.
default:SqlSourceSource an unqualified column reference resolves against.
statement:SelectStatement being assembled.
plan:SelectPlanEngine-agnostic select description.
Returns
SelectStatement with ordering and pagination applied.
def _applyUnions(self, statement: Select[Any], plan: SelectPlan) -> CompoundSelect: (source)

Combine a compiled statement with the plan union branches.

Consecutive branches of the same kind form one flat compound. Mixed operators retain left-to-right semantics through derived tables, which also keeps the SQL valid on SQLite.

Parameters
statement:SelectStatement compiled from the owning plan.
plan:SelectPlanEngine-agnostic select description carrying the unions.
Returns
CompoundSelectCompound statement combining every branch.
def _bareNameForIdentifier(self, name: str, identifier: str) -> str | None: (source)

Return the bare column name when a reference targets an identifier.

Parameters
name:strColumn reference, optionally qualified as "table.column".
identifier:strAlias or logical table name being checked against.
Returns
str or NoneThe bare column name when unqualified or matching identifier, otherwise None.
def _basicExpression(self, column: ColumnElement[Any], clause: WhereClause) -> ColumnElement[bool]: (source)

Compile a basic comparison clause into a boolean expression.

NULL comparisons with equality operators are transparently promoted to IS NULL / IS NOT NULL.

Parameters
column:ColumnElementColumn the comparison applies to.
clause:WhereClauseBasic condition to compile.
Returns
ColumnElementBoolean expression for the comparison.
Raises
QueryExceptionIf the operator is not supported.
def _buildSelect(self, plan: SelectPlan, outer_sources: SourceMap) -> Select[Any]: (source)

Compile a select plan, correlating it with an enclosing query.

Parameters
plan:SelectPlanEngine-agnostic select description.
outer_sources:SourceMapTable sources of the enclosing query, so a subquery can reference outer columns and be correlated by the engine.
Returns
SelectExecutable SELECT statement.
Raises
QueryExceptionIf the plan references unknown columns or invalid clauses.
def _cacheKey(self, physical: str, schema: str | None) -> str: (source)

Build the internal table cache key, disambiguating by schema.

Parameters
physical:strPhysical table name including the connection prefix.
schema:str or NoneDatabase schema owning the table, or None for the default.
Returns
strCache key unique per physical name and schema.
def _clauseExpression(self, sources: SourceMap, default: SqlSource, clause: WhereClause) -> ColumnElement[bool]: (source)

Compile a single where clause into a boolean expression.

Parameters
sources:SourceMapTable sources reachable by qualified column references.
default:SqlSourceSource an unqualified column reference resolves against.
clause:WhereClauseCondition to compile.
Returns
ColumnElementBoolean expression for the clause.
Raises
QueryExceptionIf the clause uses an unsupported operator or shape.
def _clauseValue(self, sources: SourceMap, value: Any) -> Any: (source)

Resolve the bound value of a clause, compiling nested subqueries.

Parameters
sources:SourceMapTable sources of the enclosing query, used to correlate a subquery with the columns it references from outside.
value:AnyRaw clause value taken from the plan.
Returns
AnyThe value untouched, or the compiled subquery statement.
def _collectClauseColumnNames(self, clauses: Sequence[WhereClause], names: set[str]): (source)

Collect the column references of a clause list, recursing groups.

Parameters
clauses:Sequence of WhereClauseConditions to inspect.
names:set of strAccumulator receiving every referenced column name.
Returns
NoneThis method does not return a value.
def _collectPlanColumnNames(self, plan: SelectPlan) -> set[str]: (source)

Collect every column reference touched anywhere in a select plan.

Parameters
plan:SelectPlanEngine-agnostic select description.
Returns
set of strEvery column name referenced by the plan, qualified or not.
def _columnComparison(self, sources: SourceMap, default: SqlSource, column: ColumnElement[Any], clause: WhereClause) -> ColumnElement[bool]: (source)

Compile a comparison between two columns of the same query.

Parameters
sources:SourceMapTable sources reachable by qualified column references.
default:SqlSourceSource an unqualified column reference resolves against.
column:ColumnElementLeft-hand column of the comparison.
clause:WhereClauseCondition carrying the right-hand column reference.
Returns
ColumnElementBoolean expression comparing both columns.
Raises
QueryExceptionIf the operator is not supported.
def _columnlessExpression(self, sources: SourceMap, default: SqlSource, clause: WhereClause) -> ColumnElement[bool] | None: (source)

Compile the clause kinds that carry no column reference.

Covers nested groups, raw fragments, and correlated EXISTS subqueries; every other kind is left to the caller.

Parameters
sources:SourceMapTable sources reachable by qualified column references.
default:SqlSourceSource an unqualified column reference resolves against.
clause:WhereClauseCondition to compile.
Returns
ColumnElement or NoneBoolean expression, or None when the clause kind is column-based and must be handled by the caller.
def _ensureRawColumns(self, table: TableDefinition, alias: str | None, names: set[str]): (source)

Lazily declare columns a plan references against a raw table.

A schemaless TableDefinition (no declared columns, used by model-less builders such as DB.table("users")) has no upfront column list for the compiler to validate against. Every name the plan actually references for it is appended to its engine table here, before any alias gets created, since Table.alias().c memoizes on first access and would silently miss columns appended afterwards.

Parameters
table:TableDefinitionTable to inspect; a no-op unless it declares no columns.
alias:str or NoneAlias this table is referred to by inside the query.
names:set of strEvery column reference collected from the owning plan.
Returns
NoneThis method does not return a value.
def _ensureReferencedColumns(self, table_name: str, columns: Sequence[str]): (source)

Register a stub table exposing the given referenced columns.

Parameters
table_name:strLogical name of the referenced table.
columns:Sequence of strReferenced column names, each stubbed as an integer key.
Returns
NoneThis method does not return a value.
def _ensureReferencedTable(self, reference: ForeignReference): (source)

Register a stub for a referenced table when it is unknown.

The stub only carries the referenced column so foreign key DDL can resolve its target; compiling the real model later replaces the stub through extend_existing.

Parameters
reference:ForeignReferenceForeign reference to resolve.
Returns
NoneThis method does not return a value.
def _ensureSelectRawColumns(self, plan: SelectPlan): (source)

Lazily declare raw columns referenced by a select plan's sources.

Parameters
plan:SelectPlanEngine-agnostic select description.
Returns
NoneThis method does not return a value.
def _joinCondition(self, sources: SourceMap, joined_name: str, joined_source: SqlSource, join: JoinExpression) -> ColumnElement[bool]: (source)

Fold a join's ON conditions into a single boolean expression.

Parameters
sources:SourceMapTable sources reachable before this join is applied.
joined_name:strIdentifier the joined table is reachable by.
joined_source:SqlSourceThe joined table source itself.
join:JoinExpressionJoin description whose conditions are compiled.
Returns
ColumnElementCombined boolean expression for the ON clause.
Raises
QueryExceptionIf the join declares no ON conditions.
def _joinConditionExpression(self, sources: SourceMap, default: SqlSource, condition: JoinCondition) -> ColumnElement[bool]: (source)

Compile a single ON condition into a column-to-column comparison.

Parameters
sources:SourceMapTable sources reachable while resolving this condition.
default:SqlSourceSource an unqualified column reference resolves against.
condition:JoinConditionON condition to compile.
Returns
ColumnElementBoolean expression comparing both column references.
Raises
QueryExceptionIf the operator is not supported.
def _joinSource(self, join: JoinExpression) -> tuple[str, SqlSource]: (source)

Build the FROM source contributed by a single join expression.

Parameters
join:JoinExpressionJoin description to materialize.
Returns
tuple of (str, SqlSource)The identifier the joined source is reachable by, and the source itself.
Raises
QueryExceptionIf a subquery join declares no alias to be referenced by.
def _physicalName(self, name: str) -> str: (source)

Prepend the connection prefix to a logical table name.

Parameters
name:strLogical table name.
Returns
strPhysical table name including the configured prefix.
def _projectionElement(self, sources: SourceMap, default: SqlSource, entry: str | SubQueryColumn | RawExpression) -> ColumnElement[Any]: (source)

Compile a single entry of a select projection.

Parameters
sources:SourceMapTable sources reachable by qualified column references.
default:SqlSourceSource an unqualified column reference resolves against.
entry:str or SubQueryColumn or RawExpressionProjected column name, scalar subquery, or raw fragment.
Returns
ColumnElementEngine element for the projection entry.
def _resolveColumn(self, sources: SourceMap, default: SqlSource, name: str) -> ColumnElement[Any]: (source)

Resolve a column reference against the tables reachable in a plan.

A qualified reference such as "posts.title" is looked up in sources by its table alias or name; an unqualified reference resolves against default (the plan's main table). This is the single place that understands multiple table origins, so joins, aliases, and future table expressions never need bespoke column lookup logic elsewhere in the compiler.

Parameters
sources:SourceMapTable sources reachable by alias or logical table name.
default:SqlSourceSource an unqualified column reference resolves against.
name:strColumn reference, optionally qualified as "table.column".
Returns
ColumnElementEngine column element.
Raises
QueryExceptionIf the qualifier is unknown, or the column is not declared on the resolved table.
def _resolveSources(self, plan: SelectPlan) -> tuple[SqlSource, SourceMap, SqlSource]: (source)

Build the main source, the resolvable source map, and the FROM.

The main table and every joined table are registered under the identifier queries use to qualify their columns: the alias when present, otherwise the logical table name. This is what lets _resolveColumn find "users.id" or "posts.title" regardless of how many tables participate in the query.

Parameters
plan:SelectPlanEngine-agnostic select description.
Returns
tuple of (SqlSource, SourceMap, SqlSource)The main source (for unqualified projections), the source map keyed by alias or table name, and the compiled FROM clause (the main source joined with every configured join).
def _selectProjection(self, default: SqlSource, sources: SourceMap, plan: SelectPlan) -> Select[Any]: (source)

Build the base SELECT statement with its projection.

Parameters
default:SqlSourceSource an unqualified column reference resolves against.
sources:SourceMapTable sources reachable by qualified column references.
plan:SelectPlanEngine-agnostic select description.
Returns
SelectStatement projecting the aggregate, explicit columns, or every column of the main table.
def _splitQualifiedColumn(self, name: str) -> tuple[str | None, str]: (source)

Split a column reference into its table qualifier and column name.

Parameters
name:strColumn reference, optionally qualified as "table.column".
Returns
tuple of (str or None, str)The qualifier (None when unqualified) and the bare column name.
def _sqlColumn(self, definition: ColumnDefinition, name: str | None = None) -> SqlColumn[Any]: (source)

Translate a column definition into an engine column.

Parameters
definition:ColumnDefinitionOrionis column definition.
name:str or None, optionalAuthoritative column name from the table definition mapping.
Returns
ColumnEngine column with type and constraints applied.
Raises
QueryExceptionIf the logical column type has no registered builder.
def _sqlTable(self, definition: TableDefinition) -> Table: (source)

Resolve and cache the engine table for a table definition.

Parameters
definition:TableDefinitionOrionis table definition.
Returns
TableEngine table metadata.
def _sqlType(self, definition: ColumnDefinition) -> TypeEngine[Any]: (source)

Resolve the engine type backing a column definition.

Parameters
definition:ColumnDefinitionOrionis column definition.
Returns
TypeEngineEngine type, carrying a dialect variant when the declared type cannot auto-increment on every backend.
Raises
QueryExceptionIf the logical column type has no registered builder.
def _tableConstraints(self, definition: TableDefinition) -> list[Any]: (source)

Build the composite, table-level constraints for a definition.

Parameters
definition:TableDefinitionOrionis table definition.
Returns
list of AnySQLAlchemy schema items to attach alongside the columns.
def _whereExpression(self, sources: SourceMap, default: SqlSource, clauses: Sequence[WhereClause]) -> ColumnElement[bool] | None: (source)

Fold a sequence of where clauses into a boolean expression.

Clauses are combined left to right honoring each clause boolean connector, mirroring the semantics of fluent query builders.

Parameters
sources:SourceMapTable sources reachable by qualified column references.
default:SqlSourceSource an unqualified column reference resolves against.
clauses:Sequence of WhereClauseConditions to combine.
Returns
ColumnElement or NoneCombined boolean expression, or None without clauses.
def compileCreateTable(self, definition: TableDefinition, *, if_not_exists: bool = True) -> Executable: (source)

Compile a table definition into a CREATE TABLE statement.

Parameters
definition:TableDefinitionTable definition to materialize.
if_not_exists:bool, optionalWhether to guard the statement with IF NOT EXISTS so that an already existing table is silently kept.
Returns
ExecutableDDL statement creating the table.
def compileDelete(self, plan: DeletePlan) -> Delete: (source)

Compile a delete plan into an executable DELETE statement.

Parameters
plan:DeletePlanEngine-agnostic delete description.
Returns
DeleteExecutable DELETE statement.
def compileDropTable(self, name: str, schema: str | None = None, *, if_exists: bool = True) -> Executable: (source)

Compile a DROP TABLE statement for the given logical name.

Parameters
name:strLogical table name; the compiler prefix is applied.
schema:str or None, optionalDatabase schema owning the table, or None for the default.
if_exists:bool, optionalWhether to guard the statement with IF EXISTS so that a missing table does not raise an error.
Returns
ExecutableDDL statement dropping the table.
def compileInsert(self, plan: InsertPlan, *, parameterized: bool = False) -> Insert: (source)

Compile an insert plan into an executable INSERT statement.

Parameters
plan:InsertPlanEngine-agnostic insert description.
parameterized:bool, optionalLeave row values for executemany parameters supplied at execution.
Returns
InsertExecutable INSERT statement.
Raises
QueryExceptionIf the plan carries no rows to insert.
def compileSelect(self, plan: SelectPlan) -> Select[Any] | CompoundSelect: (source)

Compile a select plan into an executable SELECT statement.

Parameters
plan:SelectPlanEngine-agnostic select description.
Returns
Select or CompoundSelectExecutable SELECT statement; a compound statement when the plan carries unions.
Raises
QueryExceptionIf the plan references unknown columns or invalid clauses.
def compileUpdate(self, plan: UpdatePlan) -> Update: (source)

Compile an update plan into an executable UPDATE statement.

Parameters
plan:UpdatePlanEngine-agnostic update description.
Returns
UpdateExecutable UPDATE statement.
Raises
QueryExceptionIf the plan carries no values to assign.
_TYPE_BUILDERS: ClassVar[dict[ColumnType, Callable[[ColumnDefinition], TypeEngine[Any]]]] = (source)

Undocumented

Value
{ColumnType.INTEGER: (lambda _c: sqlalchemy.Integer()),
 ColumnType.BIG_INTEGER: (lambda _c: sqlalchemy.BigInteger()),
 ColumnType.SMALL_INTEGER: (lambda _c: sqlalchemy.SmallInteger()),
 ColumnType.STRING: (lambda c: sqlalchemy.String(c.length, c.collation)),
 ColumnType.TEXT: (lambda c: sqlalchemy.Text(c.length, c.collation)),
 ColumnType.UNICODE: (lambda c: sqlalchemy.Unicode(c.length, c.collation)),
 ColumnType.UNICODE_TEXT: (lambda c: sqlalchemy.UnicodeText(c.length, c.collatio↵
...
__slots__: tuple[str, ...] = (source)

Undocumented

_definitions: dict[str, TableDefinition] = (source)

Undocumented

_metadata = (source)

Undocumented

Undocumented

_tables: dict[str, Table] = (source)

Undocumented