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

Many-to-many relationship backed by an intermediate pivot table.

Mirrors Eloquent's BelongsToMany, with one deliberate difference: instead of compiling a single JOIN against the pivot table (which would require the SQL compiler to alias projected columns to avoid name collisions between both tables -- a feature it does not have yet), this relationship resolves in two steps:

  1. Query the pivot table for the related keys linked to the parent key(s) involved (RawQueryBuilder, since the pivot table has no model).
  2. Query the related model table with whereIn(related_key, ids), reusing the regular, fully hydrated ~orionis.orm.query.builder.ModelQueryBuilder machinery.

Composite pivot keys are out of scope: like the rest of the ORM, every key involved is a single column.

Static Method _defaultPivotTable Derive the conventional pivot table name for two model classes.
Method __init__ Bind the relationship.
Async Method _aggregate Constrain an aggregate query to the resolved pivot membership.
Async Method _currentRelatedIds Query the pivot table for the related ids currently linked.
Method _extractId Extract the related key value from a scalar or model instance.
Method _invalidatePivot Discard the resolved pivot rows and generated membership clause.
Method _normalizeIds Normalize a scalar, model, or iterable of either into id values.
Method _pivotQuery Build a model-less query targeting the pivot table.
Async Method _prepare Resolve the pivot rows once and constrain the query to their ids.
Async Method _resolvePivotMap Query the pivot table for the rows linking the captured parents.
Method addConstraints Capture the parent key used to resolve the pivot rows.
Method addEagerConstraints Capture every parent key involved in an eager-loaded batch.
Async Method attach Link the parent to the given related records via the pivot table.
Method clone Copy query clauses and pivot filters into an independent builder.
Async Method delete Delete related records linked through the pivot table.
Async Method detach Unlink the parent from the given related records.
Async Method exists Report whether at least one related row is linked.
Async Method first Execute the query and hydrate only the first linked related row.
Async Method forceDelete Permanently delete records linked through the pivot table.
Async Method get Execute the query and hydrate every linked related row.
Async Method getResults Retrieve every related row linked to the parent instance.
Method match Attach the matching related rows to each parent instance.
Async Method sync Attach exactly the given records, detaching every other one.
Async Method toggle Attach ids not currently linked, detach ids that already are.
Async Method update Update related records linked through the pivot table.
Method wherePivot Filter the pivot rows considered by this relationship query.
Class Variable __slots__ Undocumented
Instance Variable _eager_keys_empty Undocumented
Instance Variable _foreign_pivot_key Undocumented
Instance Variable _parent_key Undocumented
Instance Variable _parent_keys Undocumented
Instance Variable _pivot_constraint Undocumented
Instance Variable _pivot_wheres Undocumented
Instance Variable _prepare_lock Undocumented
Instance Variable _prepared Undocumented
Instance Variable _related_key Undocumented
Instance Variable _related_map Undocumented
Instance Variable _related_pivot_key Undocumented
Instance Variable _table Undocumented

Inherited from Relation:

Class Method noConstraints Build a relationship instance without its single-parent constraint.
Method __await__ Allow await directly on a relationship without a terminal.
Async Method getEager Execute the relationship query assembled for eager loading.
Instance Variable _parent Undocumented

Inherited from ModelQueryBuilder (via Relation):

Method __getattr__ Expose the local scopes declared by the bound model.
Method _beforeExecute Apply the global scopes and the soft delete filter once.
Method _connection Resolve the database connection for the bound model.
Method _defaultTimestampColumn Return the column latest and oldest default to.
Async Method _eagerLoad Resolve every pending eager-loaded relationship for a result set.
Method _existsColumns Return the projection used by existence probes.
Async Method _fireRetrieved Dispatch the retrieved event for freshly hydrated models.
Method _prepareUpdate Refresh the update timestamp of a mass update payload.
Method _relationErrorMessage Build the error message for an unresolvable relationship name.
Method _serializeValues Apply the model casts before values reach the database.
Async Method find Retrieve a model by its primary key.
Async Method findOrFail Retrieve a model by primary key or raise when absent.
Async Method firstOrFail Return the first matching row or raise when none exists.
Method load Eager load the given relationships; alias of withRelations.
Method onlyTrashed Restrict the query to soft deleted rows.
Async Method paginate Execute the query returning a length-aware page of results.
Async Method pluck Return one column of every matching row.
Async Method restore Restore every soft deleted row matched by the query.
Method scope Apply a local scope by name.
Async Method value Return a single column value of the first matching row.
Method withoutGlobalScope Disable one global scope for this query.
Method withoutGlobalScopes Disable several global scopes, or every one of them.
Method withoutTrashed Exclude soft deleted rows; the default behavior.
Method withRelations Eager load the given relationships alongside the query.
Method withTrashed Include soft deleted rows in the query results.
Instance Variable _connection_name Undocumented
Instance Variable _eager_loads Undocumented
Instance Variable _meta Undocumented
Instance Variable _model Undocumented
Instance Variable _scopes_applied Undocumented
Instance Variable _trashed_mode Undocumented
Instance Variable _without_scopes Undocumented

Inherited from QueryBuilderBase (via Relation, ModelQueryBuilder):

Static Method _boundaryPair Validate that a range condition carries exactly two boundaries.
Static Method _materializeValues Materialize an iterable of bound values into a tuple.
Static Method _normalizeOperator Validate and normalize a comparison operator.
Static Method _resolveJoinTable Normalize a join target into a TableDefinition.
Method _addColumnComparison Append a comparison between two columns of the query.
Method _addExists Append an EXISTS or NOT EXISTS condition.
Method _addJoin Append a join expression built from either calling convention.
Method _addMembership Append a set-membership condition backed by values or a subquery.
Method _addRaw Append a raw SQL condition to a clause list.
Method _addTyped Append a single-column condition of the given kind.
Method _addWhere Parse and append a condition to a clause list.
Method _nestedClauses Run a grouping callback and collect the conditions it declared.
Method _newQuery Create a sibling builder used for nested groups and subqueries.
Method _paginator Wrap a page of results together with its pagination metadata.
Method _resolvePlan Normalize a subquery argument into a select plan.
Method _shallowCopy Build a twin of this builder still sharing its plan.
Method addSelect Append columns to the current projection.
Method adoptConnection Bind the builder to a named connection.
Method adoptPlan Replace the plan this builder assembles.
Async Method avg Return the average value of a column among matching rows.
Async Method count Count the rows matched by the query.
Method crossJoin Add a CROSS JOIN to the query.
Method distinct Collapse duplicate rows from the query results.
Async Method doesntExist Report whether the query matches no rows.
Method forPage Limit the query to a single page of results.
Method fullJoin Add a FULL OUTER JOIN to the query.
Method groupBy Add grouping columns to the query.
Method having Add a post-grouping condition to the query.
Method havingRaw Add a raw SQL post-grouping condition.
Async Method insert Insert one or many rows into the target table.
Method join Add an INNER JOIN to the query.
Method joinSub Join a subquery as a derived table with an INNER JOIN.
Method latest Order the query by a timestamp column in descending order.
Method leftJoin Add a LEFT OUTER JOIN to the query.
Method leftJoinSub Join a subquery as a derived table with a LEFT OUTER JOIN.
Method limit Limit the number of rows returned by the query.
Method lockForUpdate Lock the selected rows against concurrent writes.
Async Method max Return the maximum value of a column among matching rows.
Async Method min Return the minimum value of a column among matching rows.
Method offset Skip the given number of rows before returning results.
Method oldest Order the query by a timestamp column in ascending order.
Method orderBy Add an ordering rule to the query.
Method orHaving Add an OR-combined post-grouping condition to the query.
Method orWhere Add an OR-combined filtering condition.
Method orWhereColumn Add an OR-combined comparison between two columns.
Method orWhereExists Add an OR-combined EXISTS condition.
Method orWhereIn Add an OR-combined set-membership condition.
Method orWhereNotExists Add an OR-combined NOT EXISTS condition.
Method orWhereNotIn Add an OR-combined set-exclusion condition.
Method orWhereNotNull Add an OR-combined IS NOT NULL condition.
Method orWhereNull Add an OR-combined IS NULL condition.
Method orWhereRaw Add an OR-combined raw SQL condition.
Method rightJoin Add a RIGHT OUTER JOIN to the query.
Method rightJoinSub Join a subquery as a derived table with a RIGHT OUTER JOIN.
Method select Restrict the query projection to the given columns.
Method selectRaw Append a raw SQL fragment to the projection.
Method selectSub Append a scalar subquery to the projection under an alias.
Method sharedLock Lock the selected rows in shared mode.
Method skip Skip the given number of rows; alias of offset.
Async Method sum Return the sum of a column among matching rows.
Method take Limit the number of rows returned; alias of limit.
Method toPlan Return the engine-agnostic plan assembled so far.
Method union Append another query's rows, collapsing duplicates.
Method unionAll Append another query's rows, keeping duplicates.
Method where Add an AND-combined filtering condition.
Method whereBetween Filter rows whose column value lies between two boundaries.
Method whereColumn Compare two columns of the query against each other.
Method whereContains Filter rows whose column value contains the given text.
Method whereEndsWith Filter rows whose column value ends with the given text.
Method whereExists Keep rows for which a correlated subquery returns any row.
Method whereILike Filter rows matching a case-insensitive SQL LIKE pattern.
Method whereIn Filter rows whose column value belongs to the given set.
Method whereLike Filter rows whose column value matches an SQL LIKE pattern.
Method whereNotBetween Filter rows whose column value lies outside two boundaries.
Method whereNotExists Keep rows for which a correlated subquery returns no row.
Method whereNotILike Filter rows not matching a case-insensitive SQL LIKE pattern.
Method whereNotIn Filter rows whose column value is outside the given set.
Method whereNotLike Filter rows whose column value does not match an SQL LIKE pattern.
Method whereNotNull Filter rows whose column value is not NULL.
Method whereNull Filter rows whose column value is NULL.
Method whereRaw Add an AND-combined raw SQL condition.
Method whereRegexpMatch Filter rows whose column value matches a regular expression.
Method whereStartsWith Filter rows whose column value starts with the given text.
Instance Variable _plan Undocumented
def _defaultPivotTable(parent_cls: type[Model], related: type[Model]) -> str: (source)

Derive the conventional pivot table name for two model classes.

Parameters
parent_cls:type of ModelParent model class.
related:type of ModelRelated model class.
Returns
strBoth class names in snake_case, alphabetically joined by "_".
def __init__(self, parent: Model, related: type[TRelated], table: str | None, foreign_pivot_key: str | None, related_pivot_key: str | None, parent_key: str | None, related_key: str | None): (source)

Bind the relationship.

Parameters
parent:ModelModel instance the relationship is accessed from.
related:type of ModelModel class the relationship targets.
table:str or NonePivot table name; defaults to both model names in snake_case, singular, joined by "_" in alphabetical order (for instance role_user).
foreign_pivot_key:str or NonePivot column referencing the parent; defaults to snake_case(ParentClass) + "_id".
related_pivot_key:str or NonePivot column referencing the related row; defaults to snake_case(RelatedClass) + "_id".
parent_key:str or NoneColumn on the parent matched against foreign_pivot_key; defaults to the parent's primary key.
related_key:str or NoneColumn on the related table matched against related_pivot_key; defaults to the related model's primary key.
Returns
NoneThis method does not return a value.
async def _aggregate(self, function: AggregateFunction, column: str) -> Any: (source)

Constrain an aggregate query to the resolved pivot membership.

Parameters
function:AggregateFunctionAggregate operation to perform.
column:strRelated-model column passed to the aggregate operation.
Returns
AnyResult returned by the query builder's aggregate operation.
async def _currentRelatedIds(self) -> list[Any]: (source)

Query the pivot table for the related ids currently linked.

Returns
listRelated ids currently linked to the parent instance.
def _extractId(self, item: Any) -> Any: (source)

Extract the related key value from a scalar or model instance.

Parameters
item:AnyRelated id, or a model instance to read the related key from.
Returns
AnyRelated id value.
def _invalidatePivot(self): (source)

Discard the resolved pivot rows and generated membership clause.

Returns
NoneThis method clears the cached pivot state in place.
def _normalizeIds(self, ids: Any) -> list[Any]: (source)

Normalize a scalar, model, or iterable of either into id values.

Parameters
ids:AnyA related id, model instance, or iterable of either.
Returns
listRelated id values.
def _pivotQuery(self) -> RawQueryBuilder: (source)

Build a model-less query targeting the pivot table.

Returns
RawQueryBuilderFresh builder bound to the pivot table and the connection the relationship runs on.
async def _prepare(self) -> bool: (source)

Resolve the pivot rows once and constrain the query to their ids.

Idempotent: repeated terminal calls on the same relationship instance reuse the first resolution instead of re-querying the pivot table.

Returns
boolTrue when at least one related id was found.
async def _resolvePivotMap(self) -> dict[Any, list[Any]]: (source)

Query the pivot table for the rows linking the captured parents.

Returns
dictRelated ids grouped by the parent key that links to them.
def addConstraints(self): (source)

Capture the parent key used to resolve the pivot rows.

The pivot query itself is deferred to get/other terminals, since resolving it requires an awaited query the constructor cannot perform.

Returns
NoneThis method does not return a value.
def addEagerConstraints(self, models: list[Model]): (source)

Capture every parent key involved in an eager-loaded batch.

Parameters
models:list of ModelParent instances being eager loaded together.
Returns
NoneThis method does not return a value.
async def attach(self, ids: Any, attributes: dict[str, Any] | None = None) -> int: (source)

Link the parent to the given related records via the pivot table.

Parameters
ids:AnyA related id, model instance, iterable of either, or a mapping of id (or model) to per-row pivot attributes.
attributes:dict or None, optionalExtra pivot column values applied to every inserted row when ids is not already a mapping.
Returns
intNumber of pivot rows inserted.
def clone(self) -> Self: (source)

Copy query clauses and pivot filters into an independent builder.

Returns
SelfIndependent relationship builder with copied query state.
async def delete(self) -> int: (source)

Delete related records linked through the pivot table.

Returns
intNumber of linked related records deleted.
async def detach(self, ids: Any = None) -> int: (source)

Unlink the parent from the given related records.

Parameters
ids:Any, optionalA related id, model instance, or iterable of either; None detaches every related record currently linked.
Returns
intNumber of pivot rows deleted.
async def exists(self) -> bool: (source)

Report whether at least one related row is linked.

Returns
boolTrue when a linked related row exists.
async def first(self) -> TRelated | None: (source)

Execute the query and hydrate only the first linked related row.

Returns
Model or NoneFirst linked related model, or None without matches.
async def forceDelete(self) -> int: (source)

Permanently delete records linked through the pivot table.

Returns
intNumber of linked related records permanently deleted.
async def get(self) -> Collection: (source)

Execute the query and hydrate every linked related row.

Returns
CollectionCollection of hydrated related model instances.
async def getResults(self) -> Collection: (source)

Retrieve every related row linked to the parent instance.

Returns
CollectionRelated models; empty when the parent has no key or no pivot row links it to anything.
def match(self, models: list[Model], results: Collection, name: str): (source)

Attach the matching related rows to each parent instance.

Parameters
models:list of ModelParent instances being eager loaded together.
results:CollectionRelated rows produced by getEager.
name:strRelationship name the results are stored under.
Returns
NoneThis method does not return a value.
async def sync(self, ids: Iterable[Any]) -> dict[str, list[Any]]: (source)

Attach exactly the given records, detaching every other one.

Parameters
ids:IterableRelated ids or model instances that must remain attached.
Returns
dict of str to list"attached" and "detached" related id lists.
async def toggle(self, ids: Iterable[Any]) -> dict[str, list[Any]]: (source)

Attach ids not currently linked, detach ids that already are.

Parameters
ids:IterableRelated ids or model instances to toggle.
Returns
dict of str to list"attached" and "detached" related id lists.
async def update(self, values: dict[str, Any]) -> int: (source)

Update related records linked through the pivot table.

Parameters
values:dict of str to AnyColumn values to apply to the linked related records.
Returns
intNumber of related records updated.
def wherePivot(self, column: str, *args: Any) -> BelongsToManyRelation[TRelated]: (source)

Filter the pivot rows considered by this relationship query.

Parameters
column:strPivot table column name.
*args:AnyEither the bound value, or an operator followed by a value.
Returns
BelongsToManyRelationThe same relationship, enabling fluent chaining.
_foreign_pivot_key = (source)

Undocumented

_parent_key = (source)

Undocumented

_parent_keys: tuple[Any, ...] = (source)

Undocumented

_pivot_constraint: WhereClause | None = (source)

Undocumented

_pivot_wheres: list[tuple[str, tuple[Any, ...]]] = (source)

Undocumented

_prepare_lock: asyncio.Lock | None = (source)

Undocumented

_prepared: bool = (source)

Undocumented

_related_key = (source)

Undocumented

_related_map: dict[Any, list[Any]] = (source)

Undocumented

_related_pivot_key = (source)

Undocumented

Undocumented