2 Commits
Author SHA1 Message Date
dsql a46c4b13fc fix: connect() orphan (lockstep psql-3) + await pool.release() (mysql-1)
- connect() closes an existing pool on re-connect and tears down the built pool on SELECT-1
  validation failure (sibling of psql-3).
- _Transaction now awaits pool.release() in both __aexit__ and the __aenter__ failure path,
  matching psql and aiomysql's idiom (no un-awaited _wakeup task per transaction).
- README: insert-returns-lastrowid headline precision + upsert-rowcount convention note.
verified vs real MariaDB (re-connect, 5-tx release, full suite). bump v0.1.1 -> v0.1.2

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-01 00:28:27 -04:00
dsql 2372b1ecd1 fix: transaction() releases the pooled connection when begin() fails (lockstep w/ psql-1)
same acquire-then-fail leak as psql: begin() failing after acquire leaked the conn. release
on failure. verified against MariaDB: 6 forced begin-failures no longer drain the pool.
bump v0.1.0 -> v0.1.1

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-06-30 21:04:43 -04:00
3 changed files with 39 additions and 13 deletions
+11 -5
View File
@@ -11,24 +11,26 @@ wire-compatible and share the driver, so this covers both.
`requirements.txt`: `requirements.txt`:
``` ```
mysql @ git+ssh://git@git.rethinkstudios.io/rethink-public/mysql.git@v0.1.0 mysql @ git+ssh://git@git.rethinkstudios.io/rethink-public/mysql.git@v0.1.2
``` ```
Direct: Direct:
```bash ```bash
pip install "mysql @ git+ssh://git@git.rethinkstudios.io/rethink-public/mysql.git@v0.1.0" pip install "mysql @ git+ssh://git@git.rethinkstudios.io/rethink-public/mysql.git@v0.1.2"
``` ```
Pulls `aiomysql` (which pulls `PyMySQL`). Pulls `aiomysql` (which pulls `PyMySQL`).
Drop the `@v0.1.0` suffix from the line above to install the latest unpinned. Drop the `@v0.1.2` suffix from the line above to install the latest unpinned.
## The two-layer API ## The two-layer API
**Layer 1 — friendly verbs** for simple single-table CRUD. These hide the dialect and are **Layer 1 — friendly verbs** for simple single-table CRUD. These hide the dialect and are
**identical to the `psql` lib** — same method names, signatures, return shapes — so you **signature-identical to the `psql` lib** — same method names, arguments, and return
swap psql↔mysql with zero call-site changes. *types* — so you swap psql↔mysql with zero call-site changes. One value-level difference:
`insert()` returns the new row id (`lastrowid`) here vs. the inserted rowcount in psql
(both `int`); everything else returns the same shape.
**Layer 2 — raw escape hatch** for the complex ~20% (joins, aggregates, subqueries). You **Layer 2 — raw escape hatch** for the complex ~20% (joins, aggregates, subqueries). You
write the SQL with `%s` placeholders + a params sequence; the wrapper still gives pooling, write the SQL with `%s` placeholders + a params sequence; the wrapper still gives pooling,
@@ -111,6 +113,10 @@ Layer 1 is portable — you never see these. A Layer-2 raw-SQL author does:
`fetchone` is the unified Layer-2 name in both libs (psql maps it onto asyncpg's `fetchone` is the unified Layer-2 name in both libs (psql maps it onto asyncpg's
`fetchrow` internally; here it's the native DBAPI verb). `fetchrow` internally; here it's the native DBAPI verb).
`upsert()`'s returned rowcount follows MySQL's `ON DUPLICATE KEY UPDATE` convention (1 for
an insert, 2 for an update, 0 for a no-op) — a per-row count that differs from psql's; treat
it as "affected", not "rows matched".
## Error contract — fail loud ## Error contract — fail loud
Unlike the `mongo` lib (which log-and-swallows), **this lib re-raises.** Every method Unlike the `mongo` lib (which log-and-swallows), **this lib re-raises.** Every method
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project] [project]
name = "mysql" name = "mysql"
version = "0.1.0" version = "0.1.2"
description = "async mysql/mariadb wrapper over aiomysql: two-layer API (friendly verbs + raw escape hatch), fail-loud, config-free" description = "async mysql/mariadb wrapper over aiomysql: two-layer API (friendly verbs + raw escape hatch), fail-loud, config-free"
requires-python = ">=3.10" requires-python = ">=3.10"
dependencies = [ dependencies = [
+27 -7
View File
@@ -112,17 +112,25 @@ class MysqlDB:
async def connect(self) -> "MysqlDB": async def connect(self) -> "MysqlDB":
"""build the pool and validate it with SELECT 1; fail loud on bad config """build the pool and validate it with SELECT 1; fail loud on bad config
returns self so callers can write `db = await MysqlDB(...).connect()`. returns self so callers can write `db = await MysqlDB(...).connect()`. if called
again on an already-connected instance the previous pool is closed first (no
orphaned pool); if the SELECT-1 validation fails the freshly-built pool is torn
down before re-raising, so a failed connect() never leaks a live pool.
""" """
if self._pool is not None:
await self.close()
pool = await aiomysql.create_pool(**self._config)
try: try:
self._pool = await aiomysql.create_pool(**self._config) async with pool.acquire() as conn:
async with self._pool.acquire() as conn:
async with conn.cursor() as cur: async with conn.cursor() as cur:
await cur.execute("SELECT 1") await cur.execute("SELECT 1")
await cur.fetchone() await cur.fetchone()
except _DRIVER_ERRORS: except BaseException:
log.exception("mysql.connect() failed") log.exception("mysql.connect() validation failed")
pool.close()
await pool.wait_closed()
raise raise
self._pool = pool
return self return self
async def close(self) -> None: async def close(self) -> None:
@@ -373,7 +381,15 @@ class _Transaction:
async def __aenter__(self): async def __aenter__(self):
self._conn = await self._pool.acquire() self._conn = await self._pool.acquire()
await self._conn.begin() try:
await self._conn.begin()
except BaseException:
# begin() failing after acquire would otherwise leak the pooled connection —
# __aexit__ is not called when __aenter__ raises. release it and reset so a
# failed transaction start never burns a pool slot.
await self._pool.release(self._conn)
self._conn = None
raise
return self._conn return self._conn
async def __aexit__(self, exc_type, exc, tb) -> None: async def __aexit__(self, exc_type, exc, tb) -> None:
@@ -383,7 +399,11 @@ class _Transaction:
else: else:
await self._conn.rollback() await self._conn.rollback()
finally: finally:
self._pool.release(self._conn) # aiomysql's release() returns a task (it schedules a _wakeup); await it so we
# don't leave an un-awaited task each transaction — matches psql's awaited
# release and aiomysql's own idiom. the connection is returned synchronously
# inside release() regardless, so pool accounting is never at risk.
await self._pool.release(self._conn)
def _where(conditions: Optional[Dict[str, Any]]) -> tuple: def _where(conditions: Optional[Dict[str, Any]]) -> tuple: