Metadata-Version: 2.4
Name: vs-db
Version: 0.3.1
Summary: Async database layer for Viveka Sutra — SQLAlchemy sessions, transactions, and base repository
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship made available under
              the License, as indicated by a copyright notice that is included in
              or attached to the work (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and derivative works thereof.
        
              "Contribution" shall mean, as submitted to the Licensor for inclusion
              in the Work by the copyright owner or by an individual or Legal Entity
              authorized to submit on behalf of the copyright owner. For the purposes
              of this definition, "submitted" means any form of electronic, verbal,
              or written communication sent to the Licensor or its representatives,
              including but not limited to communication on electronic mailing lists,
              source code control systems, and issue tracking systems that are managed
              by, or on behalf of, the Licensor for the purpose of discussing and
              improving the Work, but excluding communication that is conspicuously
              marked or designated in writing by the copyright owner as "Not a
              Contribution."
        
              "Contributor" shall mean Licensor and any Legal Entity on behalf of
              whom a Contribution has been received by the Licensor and incorporated
              within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by the combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a cross-claim
              or counterclaim in a lawsuit) alleging that the Work or any
              Contribution embodied within the Work constitutes direct or
              contributory patent infringement, then any patent licenses granted to
              You under this License for that Work shall terminate as of the date
              such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or Derivative
                  Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" file as part of its distribution,
                  You must include a readable copy of the attribution notices
                  contained within such NOTICE file, in at least one of the
                  following places: within a NOTICE text file distributed as part
                  of the Derivative Works; within the Source form or documentation,
                  if provided along with the Derivative Works; or, within a display
                  generated by the Derivative Works, if and wherever such
                  third-party notices normally appear. The contents of the NOTICE
                  file are for informational purposes only and do not modify the
                  License. You may add Your own attribution notices within
                  Derivative Works that You distribute, alongside or as an addendum
                  to the NOTICE text from the Work, provided that such additional
                  attribution notices cannot be construed as modifying the License.
        
              You may add Your own license statement for Your modifications and
              may provide additional grant of rights to use, modify, and distribute
              Your modifications.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any conditions of TITLE,
              NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
              PURPOSE. You are solely responsible for determining the
              appropriateness of using or reproducing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or exemplary damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or all other
              commercial damages or losses), even if such Contributor has been
              advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           Copyright 2026 VivekaSutra. All rights reserved.
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
           implied. See the License for the specific language governing
           permissions and limitations under the License.
        
Project-URL: Homepage, https://vivekasutra.com/
Project-URL: Source, https://github.com/vivekasutra/viveka-mula
Keywords: sqlalchemy,async,database,orm,transaction,repository,viveka,vs
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Database
Classifier: Framework :: AsyncIO
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: sqlalchemy[asyncio]<2.1,>=2.0
Requires-Dist: greenlet>=3.0
Requires-Dist: vs-common>=0.2.0
Provides-Extra: mysql
Requires-Dist: aiomysql>=0.2; extra == "mysql"
Provides-Extra: postgres
Requires-Dist: asyncpg>=0.29; extra == "postgres"
Provides-Extra: sqlite
Requires-Dist: aiosqlite>=0.20; extra == "sqlite"
Provides-Extra: starlette
Requires-Dist: starlette>=0.27; extra == "starlette"
Provides-Extra: dev
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: aiomysql>=0.2; extra == "dev"
Dynamic: license-file

# 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:

```python
# 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`:

```python
# 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

```bash
pip install vs-db
```

Install with your database driver:

```bash
pip install vs-db[mysql]      # MySQL / MariaDB
pip install vs-db[postgres]   # PostgreSQL
pip install vs-db[sqlite]     # SQLite
```

Install the Starlette middleware support:

```bash
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:

```python
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.

```python
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:

```python
class ScheduledTaskRepo(VsDbRepo[ScheduledTask]):
    def __init__(self):
        super().__init__(ScheduledTask, data_source="scheduler")
```

Or select one for an individual transaction:

```python
@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:

```python
@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:

```python
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.

```python
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`).

```python
# 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**

```python
VsDbSessionFactory(
    config,
    entities=["my_app.entity"],
    db_upgrade=["my_app.versions"],   # scanned for @db_install classes
)
```

```ini
[database]
url     = mysql+aiomysql://user:pass@localhost/mydb
version = 1.1.0
```

**Step 3 — Call `populate_data()` at startup after `create_tables()`**

```python
await db.create_tables()
await db.populate_data()
```

**How it works:**

- `populate_data()` reads `database.version` from config (the target).
- Reads the latest entry from `vs_db_version` table (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_version` table 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`:

```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 *named* `session_id` or `national_id` is 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 masked `ERROR` line 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 `ERROR` even 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. Failed `DESCRIBE` / `SHOW` statements are logged at `DEBUG`, so `create_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 = false` turns all masking off — in SQLAlchemy's messages, in `echo`, and in the `vs_db.sql` log — and logs a warning at startup. It exists for local debugging only.

Example URLs for other databases:

```ini
# PostgreSQL
url = postgresql+asyncpg://user:pass@localhost/mydb

# SQLite
url = sqlite+aiosqlite:///./app.db
```

### SQLite setup (automatic)

The Python SQLite drivers don't send `BEGIN` themselves. Left alone, a nested
`@transactional` (which runs in a savepoint) commits when its savepoint is
released, so an outer method that fails afterwards can't undo it.

For a SQLite URL, `VsDbSessionFactory` therefore sets up every connection itself:
it sends an explicit `BEGIN DEFERRED`, switches foreign keys on, uses WAL and waits
up to 15 seconds for a lock. MySQL and PostgreSQL are not touched. Each setting can
be changed:

```ini
[database]
sqlite_begin           = DEFERRED    # DEFERRED | IMMEDIATE | EXCLUSIVE
sqlite_foreign_keys    = true
sqlite_journal_mode    = WAL         # empty: leave the database's own mode
sqlite_busy_timeout_ms = 15000
```

**Why `DEFERRED`.** A request transaction that has only read holds no write lock,
so a `REQUIRES_NEW` method it calls (a token store, an audit log) can still write.
With `IMMEDIATE`, the first read takes the write lock and that inner write waits for
its own request until the busy timeout, then fails.

**What it gives up.** SQLite allows one writer at a time. Writers that lock with
their first statement wait their turn. But when two transactions both read and
then write at the same moment, the second can't upgrade its lock and fails at once
with "database is locked". Write before you read where you can, and use MySQL or
PostgreSQL when many requests write concurrently. `IMMEDIATE` serialises such
transactions instead, but only suits apps that never call a writing
`REQUIRES_NEW` method from a transaction that has already run a query.

Engines built by hand can use the same setup:
`install_sqlite_setup(engine.sync_engine)` from `vs_db.session.vs_sqlite`.

---

## Middleware

Register once with your Starlette / FastAPI app:

```python
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:

```python
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:

```python
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:

```python
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 `@transactional` service 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.

```python
@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:

```python
@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:

```python
# 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 need `REQUIRES_NEW` or `commit_on_status`.

---

## Defining Entities

```python
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:

```python
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.

```python
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.

```python
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.

```python
# 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:

```python
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:

```python
    @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](#using-selfdb-in-your-own-classes--vsdbsessionaware).

### 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

```python
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, `ValueError` is raised.
- Unknown column names, or an empty list, raise `ValueError`.
- If the insert collides on a *different* unique key, the `IntegrityError` is raised. The row that owns that key is never overwritten:

```python
# 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 `None` can never match, so the entity is inserted. This is how `conflict_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:

```python
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.** `upsert` used to be a single MySQL `INSERT ... ON DUPLICATE KEY UPDATE`, which ignored `conflict_fields`, fired on any unique key, overwrote every column and bypassed `VersionMixin`. It now costs one extra `SELECT`, works on MySQL, PostgreSQL and SQLite, and no longer resets columns you leave unset.

### Pagination

```python
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.

```python
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 marked [`read_only=True`](#read-only-methods--read_only) skip 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`:

```python
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:

1. Request A sets `self.db = sessionA`, then pauses at an `await`.
2. Request B sets `self.db = sessionB` on the same object.
3. Request A resumes and reads `self.db` — it now gets `sessionB`.

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:

```python
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

```python
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

```python
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:

```python
@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:

```python
# 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.** `isolation` used 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`

```python
@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:

```python
@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:

```python
@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_NEW` method 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 UPDATE` is allowed; it locks rows but does not change them.
- Sync `@transactional` methods never use a savepoint, so `read_only` has 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`:

```python
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_for` only decides what happens to the writes.
- Subclasses match: `no_rollback_for=(PaymentDeclined,)` also covers `class 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_for` too, or
- write the record you must keep in a `REQUIRES_NEW` method, which commits on its own:

```python
@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.

```python
@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:

```python
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`

```python
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:

```python
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:

```python
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:

```python
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

```python
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_at` field management
- No `deleted_at` logic for soft delete
- Audit log independence handled by one annotation — `REQUIRES_NEW`
- No session stored on `OrderService` or 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:

```bash
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:

```bash
./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](CHANGELOG.md) for what changed in each version, including the breaking changes in 0.3.0.
