|
| 1 | +"""SQLite / database compatibility helpers. |
| 2 | +
|
| 3 | +SQLAlchemy's ``.returning()`` on DELETE/UPDATE statements, and raw SQL ``RETURNING`` |
| 4 | +clauses, both require SQLite >= 3.35.0 (released 2021-03-12). This module exposes |
| 5 | +a runtime flag and ready-to-use helpers so every call site can fall back gracefully |
| 6 | +to a SELECT-then-DELETE pattern when running on an older SQLite build. |
| 7 | +""" |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import sqlite3 |
| 11 | +from typing import Optional, TypeVar |
| 12 | + |
| 13 | +from sqlmodel import Session, SQLModel, select |
| 14 | + |
| 15 | +# Both SQLAlchemy's .returning() and raw-SQL RETURNING require SQLite >= 3.35.0 |
| 16 | +SQLITE_SUPPORTS_RETURNING: bool = ( |
| 17 | + tuple(int(x) for x in sqlite3.sqlite_version.split(".")) >= (3, 35, 0) |
| 18 | +) |
| 19 | + |
| 20 | +_ModelT = TypeVar("_ModelT", bound=SQLModel) |
| 21 | + |
| 22 | + |
| 23 | +def exec_delete_returning_first( |
| 24 | + db: Session, |
| 25 | + delete_stmt, |
| 26 | + model_cls: type[_ModelT], |
| 27 | +) -> Optional[_ModelT]: |
| 28 | + """Execute ``DELETE … RETURNING`` and return the first deleted row as a model instance. |
| 29 | +
|
| 30 | + Falls back to SELECT + DELETE within the same transaction on SQLite < 3.35. |
| 31 | + """ |
| 32 | + if SQLITE_SUPPORTS_RETURNING: |
| 33 | + row = db.exec(delete_stmt.returning(*model_cls.__table__.columns)).first() |
| 34 | + if row is None: |
| 35 | + return None |
| 36 | + return model_cls.model_validate(dict(row._mapping)) |
| 37 | + # Fallback: fetch the row first, then delete it. |
| 38 | + existing = db.exec(select(model_cls).where(delete_stmt.whereclause)).first() |
| 39 | + if existing is None: |
| 40 | + return None |
| 41 | + db.exec(delete_stmt) |
| 42 | + return existing |
| 43 | + |
| 44 | + |
| 45 | +def exec_delete_returning_all( |
| 46 | + db: Session, |
| 47 | + delete_stmt, |
| 48 | + model_cls: type[_ModelT], |
| 49 | +) -> list[_ModelT]: |
| 50 | + """Execute ``DELETE … RETURNING`` and return all deleted rows as model instances. |
| 51 | +
|
| 52 | + Falls back to SELECT + DELETE within the same transaction on SQLite < 3.35. |
| 53 | + """ |
| 54 | + if SQLITE_SUPPORTS_RETURNING: |
| 55 | + rows = db.exec(delete_stmt.returning(*model_cls.__table__.columns)).all() |
| 56 | + return [model_cls.model_validate(dict(row._mapping)) for row in rows] |
| 57 | + # Fallback: fetch all matching rows first, then delete them. |
| 58 | + existing = db.exec(select(model_cls).where(delete_stmt.whereclause)).all() |
| 59 | + if not existing: |
| 60 | + return [] |
| 61 | + db.exec(delete_stmt) |
| 62 | + return existing |
0 commit comments