vs-db
Async database layer for Python — built on SQLAlchemy async. Designed to feel like Spring JPA: define your entity, extend a repo, annotate with @transactional, and never manually manage a session again.
The Problem It Solves
Without vs-db, every async database operation requires you to manually manage sessions, transactions, commits, and rollbacks:
# Without vs-db — repeated in every service method
async def create_user(name: str, email: str):
async with async_session() as session:
async with session.begin():
user = User(name=name, email=email)
session.add(user)
await session.flush()
await session.refresh(user)
return user
With vs-db:
# With vs-db — session managed automatically
@transactional
async def create_user(self, name: str, email: str) -> User:
return await self.create(User(name=name, email=email))
The middleware opens the session at the start of each request, commits on a success response, rolls back on an error response or exception, and closes it — all without you writing a single line of session management code.
Installation
pip install vs-db
Install with your database driver:
pip install vs-db[mysql] # MySQL / MariaDB
pip install vs-db[postgres] # PostgreSQL
pip install vs-db[sqlite] # SQLite
Install the Starlette middleware support:
pip install vs-db[starlette]
How It All Fits Together
Application Startup
└── VsDbSessionFactory(config) # create engine + session factory once
Per Request (via middleware)
└── VsDbMiddleware
├── creates AsyncSession
├── stores in ContextVar # available everywhere in the request
├── commits on a success response (status < 400)
├── rolls back on an error response or exception
└── closes session
(transaction_scope="call": no request session — each outermost
@transactional call opens, commits and releases its own)
Your Code
└── @transactional on service/repo methods
├── pulls session from ContextVar (REQUIRED)
└── or opens its own (REQUIRES_NEW / background tasks)
└── self.db on VsDbRepo / VsDbSessionAware classes
└── reads the same ContextVar — never stored on the object,
so shared services and repos are safe under concurrency
Application Startup
Initialise once before handling any request. Pass entities to tell the factory which packages contain your @entity classes — it scans and imports them automatically so they are registered before any table creation or query:
from vs_common.config.vs_ini_config import VsIniConfig
from vs_db.session.vs_db_session_factory import VsDbSessionFactory
config = VsIniConfig("config.ini")
db = VsDbSessionFactory(config, entities=["my_service.models", "my_service.audit"])
This mirrors Spring's @EntityScan — entity classes are discovered at startup regardless of whether you use create_tables() or an external migration tool like Alembic.
Multiple data sources
Register named data sources when one process needs more than one SQL database. Mark the default explicitly; code that does not name a source continues to use it.
from vs_db import VsDataSource
application_db = VsDataSource.register(
"application",
application_config,
entities=["my_app.entity"],
default=True,
)
scheduler_db = VsDataSource.register(
"scheduler",
scheduler_config,
entities=["vs_scheduler.entity"],
)
Bind a repository to a source once:
class ScheduledTaskRepo(VsDbRepo[ScheduledTask]):
def __init__(self):
super().__init__(ScheduledTask, data_source="scheduler")
Or select one for an individual transaction:
@transactional(data_source="scheduler")
async def claim_task(self):
...
Resolution is explicit annotation, then the repository's data_source, then the
default. Transactions on different sources are independent; committing one database
does not atomically commit another.
Entities may also declare their source. This is useful when factories do not receive an
entities package list:
@entity("vs_scheduled_task", data_source="scheduler")
class ScheduledTask(VsDbBase):
...
create_tables() creates only the tables assigned to that factory. Database install
steps support the same optional argument: @db_install("1.0", data_source="scheduler").
At shutdown, dispose all registered engines:
await VsDataSource.close_all()
Auto Table Creation & Schema Validation (v0.1.1)
Call create_tables() at startup to automatically create all tables registered via @entity. If a table already exists, it is skipped — but the schema is validated against the entity definition and any drift is logged as a warning.
await db.create_tables()
Example warnings when entity and DB table are out of sync:
WARNING [User] Table 'users' is missing columns: {'first_name', 'last_name'}
WARNING [User] Table 'users' has extra columns not in entity: {'full_name'}
No columns are added or removed automatically — create_tables() only creates missing tables. Use a migration tool (e.g. Alembic) for schema changes on existing tables.
Data Versioning — @db_install & populate_data()
For seeding and managing initial data across application versions. This is separate from schema migrations (Alembic) — it handles the data that must exist before your application starts.
The library maintains a vs_db_version table to track the applied data version. On startup, populate_data() compares the version in your config against the DB and runs the required upgrade or downgrade steps in order.
Step 1 — Define version classes
Each class handles one version's data changes. The version string defines the execution order — any depth works (1.0, 1.0.0, 2.1.3).
# my_app/versions/v1_0_0.py
from vs_db.version.vs_base_version import VsBaseVersion
from vs_db.version.vs_db_install import db_install
from vs_db.decorator.vs_db_decorator import transactional
@db_install(version="1.0.0")
class V1_0_0(VsBaseVersion):
@transactional
async def upgrade(self) -> None:
await self.db.execute(text(
"INSERT INTO roles (name) VALUES ('admin'), ('user')"
))
@transactional
async def downgrade(self) -> None:
await self.db.execute(text("DELETE FROM roles"))
@db_install(version="1.1.0")
class V1_1_0(VsBaseVersion):
@transactional
async def upgrade(self) -> None:
await self.db.execute(text(
"INSERT INTO settings (key, value) VALUES ('theme', 'light')"
))
@transactional
async def downgrade(self) -> None:
await self.db.execute(text("DELETE FROM settings WHERE key = 'theme'"))
VsBaseVersion is session-aware, so self.db inside a @transactional upgrade / downgrade is the session of the install step that is running. There is no need to declare a db attribute on the class.
Step 2 — Register packages and set target version in config
VsDbSessionFactory(
config,
entities=["my_app.entity"],
db_upgrade=["my_app.versions"], # scanned for @db_install classes
)
[database]
url = mysql+aiomysql://user:pass@localhost/mydb
version = 1.1.0
Step 3 — Call populate_data() at startup after create_tables()
await db.create_tables()
await db.populate_data()
How it works:
populate_data()readsdatabase.versionfrom config (the target).- Reads the latest entry from
vs_db_versiontable (the current DB state). - If DB version < config version → runs
upgrade()for each missing version in ascending order. - If DB version > config version → runs
downgrade()for each excess version in descending order. - If versions match → no-op.
- Each step runs in its own transaction. If a step fails, it stops and the successfully completed steps remain committed.
- After each step, the
vs_db_versiontable is updated with the new current version.
Upgrade sequence example:
DB is at 1.0.0, config says 1.2.0:
Running upgrade → 1.1.0 ... ✓
Running upgrade → 1.2.0 ... ✓
Downgrade sequence example:
DB is at 1.2.0, config says 1.0.0:
Running downgrade → 1.2.0 ... (now at 1.1.0) ✓
Running downgrade → 1.1.0 ... (now at 1.0.0) ✓
config.ini:
[database]
url = mysql+aiomysql://user:pass@localhost/mydb
pool_size = 10
max_overflow = 20
echo = false
| Key | Default | Description |
|---|---|---|
database.url |
— | Required. Database connection URL including driver |
database.pool_size |
10 |
Number of persistent connections kept open |
database.max_overflow |
20 |
Extra connections allowed when pool is exhausted |
database.echo |
false |
SQLAlchemy's own statement log. Shows the SQL only — values are hidden unless hide_parameters is off |
database.hide_parameters |
true |
Keep parameter values out of error messages and query logs. Set false on a development machine only |
database.connection_hold_warning_seconds |
5 |
Log a warning when one transaction keeps a connection out of the pool this long. 0 turns it off |
database.version |
— | Target data version for populate_data(). If not set, populate_data() is a no-op |
Max concurrent connections = pool_size + max_overflow. Connections are pre-pinged before use (pool_pre_ping=True) so stale connections are replaced transparently.
Query Logging — Ids Only
A SQL statement's parameters are the data itself: names, emails, password hashes, API tokens. vs-db never writes them to a log by default.
What is logged, on the vs_db.sql logger:
| Level | When | Content |
|---|---|---|
DEBUG |
Every statement | SQL + parameters, masked |
ERROR |
A statement fails | Exception type + SQL + parameters, masked |
There is no switch in vs-db for the statement log — it follows your application's logging configuration. Set the vs_db.sql logger (or the root logger) to DEBUG to see every statement; leave it at INFO and only failures are logged. With DEBUG off the log line is never built, so it costs nothing.
Masking. A parameter's value is shown only when it belongs to a primary-key or foreign-key column. Everything else is printed as ***:
INSERT INTO users (id, tenant_id, name, email, password_hash) VALUES (%s, %s, %s, %s, %s)
| params: id=42, tenant_id=7, name=***, email=***, password_hash=***
SELECT ... FROM users WHERE users.tenant_id = %s AND users.email = %s
| params: tenant_id_1=7, email_1=***
Statement failed (IntegrityError): INSERT INTO users (...) VALUES (...)
| params: id=42, tenant_id=7, name=***, email=***, password_hash=***
Ids tell you which row and tenant a statement touched, which is what you need to debug; the row's contents stay out of the log.
How a parameter is recognised as an id:
- ORM and Core statements — by structure, not by name: the parameter must be compared with, or assigned to, a column declared as a primary key or with a
ForeignKey. A column merely namedsession_idornational_idis masked unless it really is a key. - Raw
text()SQL — there is no structure to inspect, so a parameter is shown only if its name is exactly the name of a key column on one of your entities (:id,:tenant_id). Anything else is masked. - Driver-level strings (
exec_driver_sql) — all parameters are hidden.
Long values are truncated, IN lists show the first 10 items, and bulk inserts show the first 3 rows.
Things to know:
- SQLAlchemy exceptions no longer include a
[parameters: ...]section; they read[SQL parameters hidden due to hide_parameters=True]. The maskedERRORline above is where to look instead. - The database's own error text is not rewritten. MySQL's
Duplicate entry 'bob@x.com' for key 'email'still contains the one colliding value. - A failed statement is logged at
ERROReven if your code catches the exception and carries on (for example a handled duplicate-key error). - The one exception is a table-existence check. On MySQL, SQLAlchemy asks whether a table exists by running
DESCRIBE, which fails when it does not. FailedDESCRIBE/SHOWstatements are logged atDEBUG, socreate_tables()on a fresh database does not fill the log with errors. - Do not use a secret as a primary or foreign key. A table keyed by the token itself would have that token shown.
database.hide_parameters = falseturns all masking off — in SQLAlchemy's messages, inecho, and in thevs_db.sqllog — and logs a warning at startup. It exists for local debugging only.
Example URLs for other databases:
# PostgreSQL
url = postgresql+asyncpg://user:pass@localhost/mydb
# SQLite
url = sqlite+aiosqlite:///./app.db
Middleware
Register once with your Starlette / FastAPI app:
from vs_db.middleware.vs_db_middleware import VsDbMiddleware
app.add_middleware(VsDbMiddleware)
What it does per request automatically:
| Step | Action |
|---|---|
| Before handler | Creates AsyncSession, stores in ContextVar |
| After handler — response status below 400 | Commits transaction |
| After handler — response status 400 or above | Rolls back transaction |
| After handler — unhandled exception | Rolls back transaction |
| After commit | Flushes any deferred @cache_evict patterns |
| Finally | Closes session and clears ContextVar |
You write zero session management code anywhere in your services or repos.
Connections and slow calls
A session takes a connection from the pool at its first query and gives it back only when the transaction commits or rolls back. In the default mode that is the end of the request. If the handler then waits on something slow, the connection sits idle the whole time:
conversation = await conversation_repo.get_by_id(conversation_id) # connection taken here
answer = await llm.complete(conversation.messages) # 10 s — connection still held
await message_repo.create(Message(...))
# connection returned when the request ends
The pool has pool_size + max_overflow connections (30 by default), so the ceiling on such requests is the pool size divided by how long each one holds a connection:
| Request shape | Connection held | Max requests / second |
|---|---|---|
| 50 ms of database work, no slow call | ~50 ms | ~600 |
| 50 ms of database work, then a 10 s LLM call | ~10 s | 3 |
Beyond that ceiling, requests queue for a connection and fail with a pool timeout. There are two ways to avoid it.
1. Commit before the slow call. VsTransactionManager.commit() commits the work so far and returns the connection. The next query in the same request quietly takes one again:
conversation = await conversation_repo.get_by_id(conversation_id)
await VsTransactionManager.commit() # connection goes back to the pool
answer = await llm.complete(conversation.messages) # holding nothing
await message_repo.create(Message(...)) # takes a connection again
Call it from the handler, between service calls — not from inside a @transactional method. Work done before it is committed and will not be rolled back if the request later fails.
2. Use per-call transactions. With transaction_scope="call" the middleware opens no request-wide session at all:
app.add_middleware(VsDbMiddleware, transaction_scope="call")
Each outermost @transactional method then opens its own session, commits, and returns its connection as soon as it finishes — the same way background tasks and scripts already work. Nothing is held while the handler waits.
"request" (default) |
"call" |
|
|---|---|---|
| Transaction boundary | The whole request | Each outermost @transactional call |
| Connection held | First query → end of request | Only while a @transactional call runs |
| A failed request | Everything is rolled back | Calls that already finished stay committed |
commit_on_status |
Applies | Not used — there is no request transaction |
| Changing a loaded entity in the handler | Saved by the final commit | Not saved — pass it to repo.update() |
Sync @transactional methods |
Work | Raise — they need an existing session |
What to change when you switch an app to "call":
- Group work that must succeed or fail together in one
@transactionalservice method. Two separate calls from a handler are two separate transactions. - Save changes explicitly. An entity returned by a finished call is no longer tracked; modifying it in the handler does nothing until you pass it to
update(). - Avoid many small calls from the handler. Each outermost call checks out a connection and commits, about two extra round trips. One service method wrapping them pays that once.
Finding the requests that hold connections. vs-db logs a warning whenever a connection is returned after being held longer than database.connection_hold_warning_seconds (default 5):
Database connection held for 12.3s (warning threshold 5s) | data_source=default. ...
Those warnings tell you which workloads need one of the two fixes above, before the pool actually runs out.
Error responses roll back
A request is all-or-nothing: if it ends in an error, nothing it wrote is kept.
@router.post("/projects/{project_id}/members")
async def add_member(project_id: int, body: AddMember, user=Depends(current_user)):
await member_repo.create(Member(project_id=project_id, user_id=body.user_id))
project = await project_repo.get_by_id(project_id)
if project.owner_id != user.id:
raise HTTPException(status_code=403, detail="Not your project") # member row is rolled back
The middleware decides by status code, not by whether an exception reached it. FastAPI and Starlette convert HTTPException — and anything caught by an @app.exception_handler — into an ordinary response before the middleware sees it, so "no exception" does not mean "success". This covers all of:
raise HTTPException(status_code=4xx / 5xx)return JSONResponse(..., status_code=4xx / 5xx)- an exception turned into an error response by a registered exception handler
When a request is rolled back, its queued cache evictions are dropped too, since nothing changed.
Keeping a write on a failed request. Some writes must survive the error — a failed-login counter before a 401, an audit record of a rejected action. Put those in a REQUIRES_NEW method, which commits independently of the request:
@transactional(propagation=Propagation.REQUIRES_NEW)
async def record_failed_login(self, email: str) -> None:
await self.attempt_repo.create(LoginAttempt(email=email, ok=False))
Changing the rule. Pass commit_on_status, a function that receives the status code and returns True to commit:
# Commit on client errors too; roll back only on 5xx.
app.add_middleware(VsDbMiddleware, commit_on_status=lambda status: status < 500)
Changed from earlier versions. The middleware used to commit whenever the handler did not let an exception escape, which included every
HTTPException. Handlers that relied on a write being kept alongside a 4xx response needREQUIRES_NEWorcommit_on_status.
Defining Entities
from sqlalchemy.orm import Mapped, mapped_column
from vs_db.base.vs_db_base import VsDbBase
from vs_db.decorator.vs_db_decorator import entity
@entity("users")
class User(VsDbBase):
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
name: Mapped[str]
email: Mapped[str]
@entity("table_name") replaces the boilerplate __tablename__ class attribute and registers the model with SQLAlchemy's metadata automatically.
Mixins
Mixins are fully opt-in. Add only what you need:
from vs_db.base.vs_audit_mixin import AuditMixin
from vs_db.base.vs_soft_delete_mixin import SoftDeleteMixin
from vs_db.base.vs_version_mixin import VersionMixin
@entity("users")
class User(VsDbBase, AuditMixin, SoftDeleteMixin, VersionMixin):
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
name: Mapped[str]
email: Mapped[str]
AuditMixin
Adds created_at and updated_at. Both are set automatically via SQLAlchemy event hooks — you never touch them.
user.created_at # set on INSERT
user.updated_at # updated on every UPDATE
Without AuditMixin you would add these columns to every model and wire up event listeners or override save() in every repo. With the mixin: just inherit it.
SoftDeleteMixin
Adds a deleted_at column. Call repo.soft_delete(id) instead of repo.delete(id) to mark a record deleted without removing it from the database.
user.is_deleted # True if deleted_at is set, False otherwise
Useful for audit trails, recovery scenarios, and compliance requirements where hard deletes are not acceptable.
VersionMixin
Adds a version column for optimistic locking. SQLAlchemy auto-increments version on every update. If two concurrent transactions read the same record and both try to update it, the second one raises StaleDataError — preventing silent data overwrites.
# Concurrent update scenario:
# Transaction A reads user (version=1), Transaction B reads user (version=1)
# Transaction A updates → version becomes 2, commits
# Transaction B tries to update → raises StaleDataError (version mismatch)
Without VersionMixin you would write custom version-check logic in every update path. With the mixin: SQLAlchemy handles it entirely.
Repository
Extend VsDbRepo[T] for your entity. You get all CRUD and query methods for free:
from vs_db.base.vs_db_repo import VsDbRepo
from vs_db.decorator.vs_db_decorator import transactional
class UserRepo(VsDbRepo[User]):
def __init__(self):
super().__init__(User)
@transactional(read_only=True)
async def find_by_email(self, email: str) -> User | None:
return await self.find_by_field(User.email, email)
@transactional
async def find_active(self) -> list[User]:
return await self.find_all_by_field(User.is_deleted, False)
For queries the built-in methods don't cover, use self.db — the AsyncSession of the current request or task:
@transactional(read_only=True)
async def find_recent(self, limit: int = 10) -> list[User]:
result = await self.db.execute(
select(User).order_by(User.created_at.desc()).limit(limit)
)
return list(result.scalars().all())
A repo instance can be created once and shared by every request: self.db is resolved per request, not stored on the repo. See Using self.db in Your Own Classes.
Built-in Methods
| Method | Description |
|---|---|
create(entity) |
Insert and return with generated ID |
insert_all(entities) |
Bulk insert |
get_by_id(id) |
Fetch by primary key |
get_all(skip, limit) |
Offset-based list |
get_page(page, page_size) |
Returns Page[T] with total and page metadata |
update(entity) |
Merge and flush |
delete(id) |
Hard delete by primary key |
soft_delete(id) |
Sets deleted_at — requires SoftDeleteMixin |
exists(id) |
Returns True / False |
count() |
Total row count |
find_by_field(field, value) |
First result matching field |
find_all_by_field(field, value) |
All results matching field |
upsert(entity, conflict_fields, update_fields=None) |
Insert, or update the one row matching conflict_fields — all databases |
Upsert
saved = await user_repo.upsert(
User(email="bob@x.com", name="Bob"),
conflict_fields=["email"],
)
upsert looks up the row whose conflict_fields equal the values on entity. If one exists it is updated; if not, entity is inserted. It always returns the persistent row, which on an update is not the object you passed in — use the return value.
conflict_fields decides which row is updated, and nothing else does.
- They must identify a single row: use the primary key or the columns of a unique index. If they match more than one row,
ValueErroris raised. - Unknown column names, or an empty list, raise
ValueError. - If the insert collides on a different unique key, the
IntegrityErroris raised. The row that owns that key is never overwritten:
# No user 99, but bob@x.com belongs to user 7.
await user_repo.upsert(User(id=99, email="bob@x.com", name="Eve"), conflict_fields=["id"])
# → IntegrityError. User 7 is untouched, and the surrounding transaction is still usable.
- A conflict value of
Nonecan never match, so the entity is inserted. This is howconflict_fields=["id"]behaves for a new entity with an auto-generated id.
What gets written on an update
| Column | Behaviour |
|---|---|
Columns you set on entity |
Copied to the stored row |
| Columns you did not set | Left as they are — never reset to NULL or a default |
A column set explicitly to None |
Cleared, e.g. deleted_at=None to restore a soft-deleted row |
| Primary key, the conflict fields | Never changed |
created_at (AuditMixin) |
Kept from the row's first insert; updated_at moves |
version (VersionMixin) |
Incremented automatically |
Pass update_fields to copy only specific columns, whatever else is set on the entity:
await user_repo.upsert(
User(email="bob@x.com", name="Bob", last_login=now),
conflict_fields=["email"],
update_fields=["last_login"], # name is used for an insert, ignored on update
)
Optimistic locking. With VersionMixin, an entity that carries a version different from the stored row raises StaleDataError — the copy you hold is out of date. An entity with no version set skips this check and simply updates.
Concurrency. If two transactions upsert the same new key at once, one inserts and the other's insert fails on the unique key; the second then re-reads the row and updates it instead. This relies on the conflict fields being backed by a real unique index.
Changed from earlier versions.
upsertused to be a single MySQLINSERT ... ON DUPLICATE KEY UPDATE, which ignoredconflict_fields, fired on any unique key, overwrote every column and bypassedVersionMixin. It now costs one extraSELECT, works on MySQL, PostgreSQL and SQLite, and no longer resets columns you leave unset.
Pagination
page = await repo.get_page(page=2, page_size=20)
page.items # List[User] for page 2
page.total # total rows across all pages
page.pages # total number of pages
page.page # current page number
page.page_size # page size used
@transactional
The core decorator. Annotate any async method on a service or repo — session management happens automatically.
from vs_db.decorator.vs_db_decorator import transactional
@transactional
async def save_order(self, order: Order) -> Order:
return await self.repo.create(order)
How it works:
- If a session is already in
ContextVar(i.e. a request is active), it reuses it and wraps the call in a savepoint — a nested transaction that rolls back independently if the method raises. Methods markedread_only=Trueskip the savepoint. - If no session exists (background task, script, test), it opens a standalone session, commits on success, and rolls back on exception.
This mirrors Spring's @Transactional(propagation = REQUIRED) behaviour exactly.
Using self.db in Your Own Classes — VsDbSessionAware
VsDbRepo subclasses and VsBaseVersion subclasses already have a safe self.db. For any other class that needs the session — a service, a store, a hand-written repo — inherit from VsDbSessionAware:
from vs_db.base.vs_db_session_aware import VsDbSessionAware
from vs_db.decorator.vs_db_decorator import transactional
class ReportService(VsDbSessionAware):
@transactional
async def monthly_totals(self, month: str) -> list:
result = await self.db.execute(text("SELECT ..."), {"month": month})
return result.all()
self.db is a property, not a stored attribute. Every read returns the session of the current request or asyncio task, looked up from the ContextVar that @transactional and VsDbMiddleware manage. Outside a transaction it raises RuntimeError instead of returning a stale session.
Why this matters. Services are normally created once and shared by every request. If the session were stored on the instance, concurrent requests would overwrite each other's:
- Request A sets
self.db = sessionA, then pauses at anawait. - Request B sets
self.db = sessionBon the same object. - Request A resumes and reads
self.db— it now getssessionB.
A then reads B's uncommitted data, and A's writes commit or roll back with B's request. VsDbSessionAware makes this impossible because nothing is stored on the object.
Deprecated: a plain db attribute. Older classes declare self.db = None in __init__ and rely on @transactional to assign the session. This still works, but it has the problem above, and a warning naming the class is logged the first time one of its @transactional methods runs:
class ReportService: # ⚠ deprecated — not safe when shared
def __init__(self):
self.db = None
To migrate, add VsDbSessionAware as a base class. The self.db = None line can stay or go — assignments are ignored — and method bodies need no changes. Assigning self.db from @transactional will be removed in a future version.
A class that uses @transactional but never touches self.db — for example a service that only calls repos — needs no base class and gets no warning.
If you would rather not use self.db at all, VsTransactionManager.get_session() returns the same task-local session from anywhere.
Propagation
from vs_db.decorator.vs_db_decorator import Propagation
@transactional(propagation=Propagation.REQUIRES_NEW)
async def write_audit_log(self, action: str) -> None:
await self.audit_repo.create(AuditLog(action=action))
| Value | Behaviour |
|---|---|
REQUIRED (default) |
Reuses existing session; opens new one if none exists |
REQUIRES_NEW |
Always opens a new independent session; suspends the current one |
Use REQUIRES_NEW when you need a method to commit independently — e.g. audit logging that must persist even if the outer transaction rolls back.
Isolation
from vs_db.decorator.vs_db_decorator import Isolation
@transactional(isolation=Isolation.REPEATABLE_READ)
async def transfer(self, from_id: int, to_id: int, amount: float) -> None:
...
@transactional(isolation=Isolation.SERIALIZABLE)
async def allocate_seat(self, flight_id: int, seat: str) -> bool:
...
| Value | Behaviour |
|---|---|
DEFAULT |
Database default (typically READ COMMITTED) |
READ_COMMITTED |
Sees only committed rows — prevents dirty reads |
REPEATABLE_READ |
Same snapshot throughout the transaction — prevents non-repeatable reads |
SERIALIZABLE |
Fully isolated — prevents phantom reads; use for financial or inventory operations |
A requested level is either in force or the call fails — it is never silently ignored.
A database fixes a transaction's isolation level when the transaction starts and refuses to change it afterwards (MySQL: TRANSACTION ISOLATION can't be set while a transaction is in progress). What @transactional(isolation=...) does therefore depends on the transaction the method ends up in:
| Situation | Result |
|---|---|
| The method opens its own session (worker, script) | Level applied to that transaction |
propagation=REQUIRES_NEW |
Level applied to the new transaction |
| It joins a session whose transaction has not run a query yet | Level applied — to the whole transaction from then on, not only this method |
| It joins a transaction already running at the same level | Runs normally |
| It joins a transaction already running at a different level, or at the database default | Raises IsolationLevelError; the method body does not run |
The last row is the one to know about. Under VsDbMiddleware, a method called after the request has already queried the database cannot be given a different level:
@router.post("/flights/{flight_id}/seats/{seat}")
async def book(flight_id: int, seat: str, user=Depends(current_user)):
flight = await flight_repo.get_by_id(flight_id) # the request's transaction starts here
await booking_service.allocate_seat(flight_id, seat) # asks for SERIALIZABLE → IsolationLevelError
Running allocate_seat at the default level instead would let two simultaneous requests both see the seat as free and both book it, with nothing to show for it — so the call fails loudly. Two ways to fix the handler:
# 1. Give the critical section its own transaction at the level it needs.
@transactional(isolation=Isolation.SERIALIZABLE, propagation=Propagation.REQUIRES_NEW)
async def allocate_seat(self, flight_id: int, seat: str) -> bool: ...
# 2. Or make it the first database work of the request, so the level is set in time.
await booking_service.allocate_seat(flight_id, seat)
flight = await flight_repo.get_by_id(flight_id)
With option 1 the method commits independently and cannot see writes the outer request has not committed yet. With option 2 the whole request runs at the stricter level, which means more locking for that request.
Levels must match exactly. A method asking for READ_COMMITTED inside a SERIALIZABLE transaction also raises: the levels differ in what a query can see, not only in how strict they are, so one cannot stand in for another.
After VsTransactionManager.commit() the next query starts a new transaction, and a level can be requested again.
Changed from earlier versions.
isolationused to be ignored whenever the method joined an existing session, which under the middleware was every call. Methods that relied on it were running at the database default.
Read-Only Methods — read_only
@transactional(read_only=True)
async def find_recent(self, limit: int = 10) -> list[User]:
result = await self.db.execute(
select(User).order_by(User.created_at.desc()).limit(limit)
)
return list(result.scalars().all())
What a savepoint is for. When a @transactional method joins an existing transaction, it runs inside a savepoint — a bookmark the database can roll back to. If the method fails and its caller catches the exception and carries on, only that method's writes are undone, and the caller's transaction stays clean:
@transactional
async def place_order(self, order):
await self.order_repo.create(order)
try:
await self.loyalty_service.add_points(order) # writes 3 rows, fails on the 3rd
except LoyaltyError:
pass # the 2 loyalty rows already written are rolled back; the order is kept
That protection costs two extra statements per call (SAVEPOINT before, RELEASE SAVEPOINT after). A method that only reads has nothing to undo, so for it the savepoint is pure cost. read_only=True says so, and the method then joins the transaction directly.
Without read_only |
With read_only=True |
|
|---|---|---|
| Statements sent for one query | 3 | 1 |
| Simple lookup, local MySQL | 0.34 ms | 0.18 ms |
Lookup answered from memory (get_by_id on a loaded row) |
2 statements | 0 statements |
The saving is two database round trips per call, so it grows with network latency and with the number of repo calls in a request.
Built-in repo reads are already read-only. get_by_id, get_all, get_page, find_by_field, find_all_by_field, exists and count need no change in your code. Add read_only=True to your own query methods.
Writes are rejected. A read-only method has no savepoint, so a write inside it could not be undone on its own. Any INSERT, UPDATE, DELETE or DDL statement issued while it runs raises ReadOnlyTransactionError — whether it comes from the ORM, from raw text() SQL, or from another method it calls:
@transactional(read_only=True)
async def get_and_touch(self, user_id: int):
user = await self.get_by_id(user_id)
user.last_seen = now()
await self.db.flush() # → ReadOnlyTransactionError
Treat that error as a bug to fix, not something to catch: remove read_only=True, or move the write out. After a rejected write the surrounding transaction can only be rolled back.
Rules:
- The default is unchanged: without
read_only, a method gets a savepoint. Forgetting the flag costs speed, never safety. - A
REQUIRES_NEWmethod called from a read-only method may write. It runs in its own transaction, which is useful for audit records of reads. - Writes the caller queued before the call (
session.add(x)with no flush yet) are flushed before the read-only method starts, so they are not mistaken for its own. - When the method opens its own session (a worker or script), there was never a savepoint, so nothing is saved — but writes are still rejected, so the method behaves the same everywhere.
- The check covers the read-only method's own session only. Writes made through another session — another data source, or a session opened by hand — are not restricted.
SELECT ... FOR UPDATEis allowed; it locks rows but does not change them.- Sync
@transactionalmethods never use a savepoint, soread_onlyhas no effect on them.
PostgreSQL note. On PostgreSQL a failed statement aborts the whole transaction unless it ran inside a savepoint. A failing query in a read-only method therefore leaves the caller's transaction unusable, where previously the caller could catch the error and continue. MySQL and SQLite are not affected.
Keeping Writes When an Exception Is Raised — no_rollback_for
By default every exception rolls back the method's writes. Some exceptions are intentional business outcomes rather than failures — a declined payment, an exceeded quota — where you want to raise and keep what was written. List those in no_rollback_for:
class PaymentDeclined(Exception):
pass
@transactional(no_rollback_for=(PaymentDeclined,))
async def charge(self, order_id: int, amount: Decimal) -> None:
await self.attempt_repo.create(PaymentAttempt(order_id=order_id, status="started"))
result = await gateway.charge(amount)
if not result.ok:
await self.attempt_repo.create(PaymentAttempt(order_id=order_id, status="declined"))
raise PaymentDeclined(result.reason) # both attempt rows are kept
Rules:
- The exception is always re-raised.
no_rollback_foronly decides what happens to the writes. - Subclasses match:
no_rollback_for=(PaymentDeclined,)also coversclass CardExpired(PaymentDeclined). - A single class is accepted as well as a tuple:
no_rollback_for=PaymentDeclined. - Any exception not listed still rolls back, exactly as before.
- If committing the kept writes fails, the transaction is rolled back and the commit error is raised instead, with the original exception as its
__cause__.
What "kept" means depends on who owns the transaction:
| Situation | Effect of a no_rollback_for exception |
|---|---|
| No session yet (worker, script, background task) | The method's session is committed, then the exception is re-raised |
propagation=REQUIRES_NEW |
The new session is committed independently of any outer transaction |
Joining an existing session (VsDbMiddleware request, or an outer @transactional) |
Only the method's savepoint is released — nothing is committed yet |
The last row matters: when the method joins an existing transaction, the outer owner still decides. If the exception keeps propagating and reaches VsDbMiddleware or an outer @transactional that doesn't list it, the whole transaction rolls back and the kept writes go with it. The same happens under VsDbMiddleware if the exception is turned into an error response (status 400 or above). To keep them in that case, either:
- catch the exception before it reaches the owner, or
- list it in the outer method's
no_rollback_fortoo, or - write the record you must keep in a
REQUIRES_NEWmethod, which commits on its own:
@transactional(propagation=Propagation.REQUIRES_NEW)
async def record_attempt(self, attempt: PaymentAttempt) -> None:
await self.attempt_repo.create(attempt) # committed immediately, survives any outer rollback
no_rollback_for applies to async methods only. A sync @transactional method never owns a transaction, so the parameter has no effect there.
rollback_on
rollback_on does not change what rolls back — every exception not in no_rollback_for rolls back regardless. It only selects which exceptions are logged at ERROR level when a session the method owns is rolled back. It defaults to (Exception,), i.e. log everything.
@transactional(rollback_on=(SQLAlchemyError,)) # log DB errors only; all exceptions still roll back
async def process(self, data: dict) -> None:
...
Without @transactional — Manual Session Usage
You do not have to use @transactional at all. If you prefer explicit control, access the session directly from ContextVar and manage the transaction yourself.
Direct session access
When the middleware is active (inside a request), the session is always available:
from vs_db.context.db_context import get_session
from sqlalchemy import select
async def custom_query() -> list[User]:
session = get_session()
result = await session.execute(
select(User).where(User.status == "active").order_by(User.created_at.desc())
)
return list(result.scalars().all())
Use this when you need a raw SQLAlchemy query that does not fit the base repo methods.
Manual transaction control via VsTransactionManager
from vs_db.transaction.vs_transaction_manager import VsTransactionManager
session = VsTransactionManager.get_session() # session from ContextVar
VsTransactionManager.is_active() # True if session is in context
await VsTransactionManager.commit() # commit current transaction
await VsTransactionManager.rollback() # rollback current transaction
Full manual example — equivalent to @transactional but written explicitly:
from vs_db.transaction.vs_transaction_manager import VsTransactionManager
from vs_db.context.db_context import get_session
async def transfer(from_id: int, to_id: int, amount: float) -> None:
session = get_session()
try:
sender = await session.get(Account, from_id)
receiver = await session.get(Account, to_id)
sender.balance -= amount
receiver.balance += amount
await session.flush()
await VsTransactionManager.commit()
except Exception:
await VsTransactionManager.rollback()
raise
Mixing manual and annotated code
You can mix both freely. Methods with @transactional reuse whatever session is already in ContextVar — so calling an annotated repo method from manually managed code works without any changes:
async def process(user_id: int) -> None:
session = get_session() # get session directly
user = await session.get(User, user_id) # raw query
user.status = "processing"
await session.flush()
await order_repo.cancel_pending(user_id) # @transactional method — reuses same session
await VsTransactionManager.commit() # one commit covers everything
Background Tasks and Scripts
Outside a request (scheduled jobs, CLI scripts, workers), there is no middleware to open a session. Use an unmanaged session:
from vs_db.transaction.vs_transaction_manager import VsTransactionManager
async def run_nightly_sync():
await VsTransactionManager.open_unmanaged_session()
try:
repo = UserRepo()
users = await repo.get_all()
# process users ...
await VsTransactionManager.commit()
except Exception:
await VsTransactionManager.rollback()
raise
finally:
await VsTransactionManager.close_unmanaged_session()
@transactional methods called inside this block reuse the session exactly as they would in a request.
Full Example
from sqlalchemy.orm import Mapped, mapped_column
from vs_db.base.vs_db_base import VsDbBase
from vs_db.base.vs_audit_mixin import AuditMixin
from vs_db.base.vs_soft_delete_mixin import SoftDeleteMixin
from vs_db.base.vs_db_repo import VsDbRepo
from vs_db.decorator.vs_db_decorator import entity, transactional, Propagation
@entity("orders")
class Order(VsDbBase, AuditMixin, SoftDeleteMixin):
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
user_id: Mapped[int]
total: Mapped[float]
status: Mapped[str]
@entity("audit_logs")
class AuditLog(VsDbBase, AuditMixin):
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
action: Mapped[str]
user_id: Mapped[int]
class OrderRepo(VsDbRepo[Order]):
def __init__(self):
super().__init__(Order)
@transactional
async def find_by_user(self, user_id: int) -> list[Order]:
return await self.find_all_by_field(Order.user_id, user_id)
class AuditRepo(VsDbRepo[AuditLog]):
def __init__(self):
super().__init__(AuditLog)
class OrderService:
def __init__(self):
self.order_repo = OrderRepo()
self.audit_repo = AuditRepo()
@transactional
async def place_order(self, user_id: int, total: float) -> Order:
order = await self.order_repo.create(Order(user_id=user_id, total=total, status="pending"))
await self._log(user_id, f"order:{order.id}:placed")
return order
@transactional
async def cancel_order(self, order_id: int, user_id: int) -> bool:
result = await self.order_repo.soft_delete(order_id)
await self._log(user_id, f"order:{order_id}:cancelled")
return result
@transactional(propagation=Propagation.REQUIRES_NEW)
async def _log(self, user_id: int, action: str) -> None:
# REQUIRES_NEW: audit log commits independently even if outer tx rolls back
await self.audit_repo.create(AuditLog(action=action, user_id=user_id))
What vs-db eliminated here:
- No
async with session.begin()anywhere - No manual
session.add()/session.commit()/session.rollback() - No
created_at/updated_atfield management - No
deleted_atlogic for soft delete - Audit log independence handled by one annotation —
REQUIRES_NEW - No session stored on
OrderServiceor the repos — one instance of each can serve every concurrent request
Running the Tests
The suite runs against a real MySQL database that it creates and drops tables in. Tell it which one, in either of two ways:
export VS_DB_TEST_DATABASE_URL="mysql+aiomysql://user:password@localhost:3306/test1"
or copy tests/config.ini to tests/config.local.ini and put your URL there. That file is git-ignored; tests/config.ini itself is a template and must not contain real credentials.
Then:
./run_tests.sh
Without a configured database, the tests that need one fail with a message saying how to set it up; the rest still run.
Changelog
See CHANGELOG.md for what changed in each version, including the breaking changes in 0.3.0.
Metadata
Release files for vs-db 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| vs_db-0.3.0.tar.gz | 89.2 kB | Without provenance | Details for vs_db-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| vs_db-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for vs_db-0.3.0-py3-none-any.whl |
Total release size: 141.7 kB
Release files / vs_db-0.3.0.tar.gz
| Download URL | vs_db-0.3.0.tar.gz |
|---|---|
| Size | 89.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
4698a83c7ccce5c7be8f29d2a57f73f567e586e7343b45616b722133d7a03d9e
|
|
BLAKE2b-256 checksum How to use checksums |
e9e21e6a3d5e75e515a537eeeda1f83459667280db4dacf10c36af065dff5c0b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.15
|
Release files / vs_db-0.3.0-py3-none-any.whl
| Download URL | vs_db-0.3.0-py3-none-any.whl |
|---|---|
| Size | 52.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
34b14fcb9178c4bd51c91196f49dfd053512306f05feababf4c72c8cf054f86f
|
|
BLAKE2b-256 checksum How to use checksums |
6568cc21043a99222a079c94539f8517dc143af26e0187635090740cff26c7f7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.15
|
Security for vs-db 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.