Skip to content

Add transaction support#5

Open
erikgaas wants to merge 4 commits intomainfrom
feat/transactions
Open

Add transaction support#5
erikgaas wants to merge 4 commits intomainfrom
feat/transactions

Conversation

@erikgaas
Copy link

Changes

  • Database.transaction() context manager — acquires a single connection from the pool, starts a transaction, and uses a contextvars.ContextVar to route all queries through it. Existing code (db.t.table.insert(...), db.q(...), etc.) automatically participates in the transaction with no changes needed.

  • Fix _ColsGetter.__call__ — was referencing self.tbl.columns which doesn't exist on Table. Changed to self.tbl.cols.

Usage

async with db.transaction():
    await db.t.credit.update(...)
    await db.execute('UPDATE usage SET billed=true ...')
    # if either fails, both roll back

How it works

A contextvars.ContextVar (_txn_conn) holds the active transaction connection. Database.__getattr__ checks it before falling back to self.conn:

def __getattr__(self, k): return getattr(_txn_conn.get() or self.conn, k)

This means zero changes to calling code — everything just works inside an async with db.transaction() block.

Tests

  • Rollback test: insert + raise → verify count unchanged
  • Commit test: insert → verify count increased → cleanup

- Add Database.transaction() context manager using contextvars
- All existing db.t.* calls automatically participate in active transaction
- Fix _ColsGetter.__call__: .columns -> .cols
@erikgaas erikgaas requested a review from comhar February 12, 2026 22:42
def __dir__(self): return list(self.tbl.cols)
def __repr__(self): return ", ".join(dir(self))
def __call__(self): return [_Col(self.tbl.name,o.name) for o in self.tbl.columns]
def __call__(self): return [_Col(self.tbl.name, c) for c in self.tbl.cols]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bugfix. .columns returns a dict. cols returns a list of the names.

@erikgaas erikgaas changed the title Add transaction support and fix _ColsGetter.__call__ Add transaction support Feb 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant