AsyncDatabase¶
- class nextorm.async_database.AsyncDatabase[source]¶
Bases:
objectAsync counterpart to
Database.All I/O methods are coroutines. Use
await db.bind(...)etc.Parameters¶
- entities:
Explicit list of entity classes to include. When omitted, all registered
Entitysubclasses are used.
- async load_lazy_field(entity, field_name)[source]¶
Asynchronously load a single lazy field and cache the result on the entity.
This must be used for lazy fields when the entity was loaded via
AsyncDatabase; synchronous access raisesRuntimeError:article = await db.aselect(Article).fetch_one() body = await db.load_lazy_field(article, "body") # or equivalently: body = await db.load_lazy_field(article, "body") # cached on second call
- property entities: dict[str, type[Entity]]¶
Return
{entity_name: entity_class}for all entities in this DB.
- async bind(provider, *args, **kwargs)[source]¶
Bind the database to a named async provider and open a connection.
Parameters¶
- provider:
Registered provider name:
"sqlite","postgres", or"mariadb".- args / kwargs:
Connection arguments forwarded to the async provider (e.g. the database path for aiosqlite, or the DSN for PostgreSQL).
Example:
db = AsyncDatabase(entities=[User]) await db.bind("sqlite", ":memory:") await db.generate_mapping(create_tables=True)
- async generate_mapping(*, create_tables=False, validate_relations=True)[source]¶
Build the internal schema and optionally create database tables.
Async counterpart of
generate_mapping().Parameters¶
- create_tables:
When
True, executeCREATE TABLEDDL for every entity in the schema.- validate_relations:
When
True, every declaredSet[T]relation is validated. Seegenerate_mapping()for details.
- property schema: dict[str, Table]¶
Return a copy of the current table schema (populated by
generate_mapping()).
- aselect(entity_class)[source]¶
Return an
AsyncQuerySetfor entity_class.generate_mapping()must have been called first.Example:
users = await db.aselect(User).filter(User.active == True).fetch_all()
- Parameters:
entity_class (type[ET])
- Return type:
- async asave(entity)[source]¶
Insert or update entity asynchronously.
Async counterpart of
save(). PKs that areNonetrigger anINSERT; a set PK triggers anUPDATE. The entity’s lifecycle hooks are called in both cases.Example:
async with db_session: u = User(name="alice", age=30) await db.asave(u) print(u.id) # assigned by DB
- Parameters:
entity (Entity)
- Return type:
None
- async ainsert(entity)[source]¶
Always INSERT entity asynchronously, even when its primary key is already set.
Async counterpart of
insert().- Parameters:
entity (Entity)
- Return type:
None
- async adelete_instance(entity)[source]¶
Delete entity from the database asynchronously.
Async counterpart of
delete_instance(). RaisesValueErrorwhen the entity has not been saved (PK isNone).- Parameters:
entity (Entity)
- Return type:
None
- async acommit()[source]¶
Flush pending changes then commit the current database transaction.
Calls
aflush()first so all pending inserts/updates are written, then finalises the underlying connection’s transaction (PonyORM-style integrated flush).- Return type:
None
- async arollback()[source]¶
Roll back the current database transaction and clear the session cache.
Discards uncommitted work on the active connection and wipes the identity map of the current
db_session().- Return type:
None
- async aflush()[source]¶
Write all pending dirty and new objects in the current session to the DB.
Iterates the current
db_session()cache and callsasave()on every object that has been scheduled for INSERT or marked dirty.When called outside a session this is a no-op.
- Return type:
None
- get_connection()[source]¶
Return the raw underlying async connection object.
The type depends on the active provider (e.g.
aiosqlite.Connectionfor async SQLite). Use this as an escape hatch for provider-specific features.- Return type:
- async execute(sql, *args)[source]¶
Execute arbitrary SQL asynchronously and return the number of affected rows.
args are bound as positional parameters:
await db.execute("DELETE FROM session WHERE expires_at < ?", cutoff)
- async select_raw(sql, *args)[source]¶
Execute a raw SELECT asynchronously and return results as dicts.
Column names are taken from the cursor description:
rows = await db.select_raw( "SELECT u.name, COUNT(o.id) AS cnt " "FROM user u LEFT JOIN order o ON o.user_id = u.id " "GROUP BY u.id" )
- property local_stats: dict[str, QueryStat]¶
Per-database query statistics since the last
clear_local_stats()call.Returns a snapshot copy keyed by SQL string. Each value is a
QueryStatwithcount,sum_time,min_time,max_time, andavg_timeattributes.
- merge_local_stats()[source]¶
Merge per-database stats into the module-level
global_stats.Call this periodically (e.g. at the end of a request) to accumulate statistics across multiple
AsyncDatabaseinstances.- Return type:
None
- class nextorm.async_database.AsyncQuerySet[source]¶
Bases:
GenericAsync counterpart to
QuerySet.All terminal methods (
fetch_all,fetch_one, etc.) are coroutines.- __init__(entity_class, table, db, builder)[source]¶
- Parameters:
entity_class (type[T])
table (Table)
db (AsyncDatabase)
builder (SQLBuilder)
- Return type:
None
- filter(*conditions)[source]¶
Async counterpart of
filter().- Parameters:
conditions (SqlNode)
- Return type:
- order_by(*items)[source]¶
Async counterpart of
order_by().- Parameters:
items (OrderItem)
- Return type:
- async fetch_all()[source]¶
Async counterpart of
fetch_all().- Return type:
list[T]
- async fetch_one()[source]¶
Async counterpart of
fetch_one().- Return type:
T | None
- async get_or_raise()[source]¶
Async
get_or_raise().- Return type:
T
- without_distinct()[source]¶
Disable
SELECT DISTINCT(reverses a previousdistinct()call).- Return type:
- for_update(*, skip_locked=False)[source]¶
Append
FOR UPDATE [SKIP LOCKED].- Parameters:
skip_locked (bool)
- Return type:
- page(pagenum, pagesize=10)[source]¶
Return a page of results (1-based page numbers).
- Parameters:
- Return type:
- where(predicate)[source]¶
Narrow results using a lambda predicate (same semantics as QuerySet.where).
- Parameters:
predicate (Any)
- Return type:
- async group_concat(attr, sep=',')[source]¶
Return the concatenation of all non-NULL values of attr.
Uses
GROUP_CONCAT(col, sep)on SQLite / MariaDB andSTRING_AGG(col::text, sep)on PostgreSQL. ReturnsNonewhen no rows match or all values are NULL.
- get_sql()[source]¶
Return the SQL string that
fetch_all()would execute.- Return type:
- async ashow(width=120, *, file=None)[source]¶
Async counterpart of
show().Fetches all rows asynchronously and renders them as a plain-text table to file (default:
sys.stdout).Parameters¶
- width:
Maximum total table width in characters.
- file:
Output stream; defaults to
sys.stdout.
Public API summary
Bind the database to a named async provider and open a connection. |
|
Explicitly add entity classes to this database. |
|
Build the internal schema and optionally create database tables. |
|
Return an |
|
Insert or update entity asynchronously. |
|
Always INSERT entity asynchronously, even when its primary key is already set. |
|
|
Delete entity from the database asynchronously. |
Flush pending changes then commit the current database transaction. |
|
Roll back the current database transaction and clear the session cache. |
|
Write all pending dirty and new objects in the current session to the DB. |
|
Execute arbitrary SQL asynchronously and return the number of affected rows. |
|
Execute a raw SELECT asynchronously and return results as dicts. |
|
Close the async connection (if open). |
|
Return a copy of the current table schema (populated by |
|
Return |
|
The last SQL string sent to the database. |
|
Per-database query statistics since the last |
|
Reset per-database query statistics. |
|
Merge per-database stats into the module-level |
|
Return the raw underlying async connection object. |