rn-forge-sqlalchemy 0.2.2__tar.gz → 0.2.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rn-forge-sqlalchemy
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: Async SQLAlchemy models, upsert and keyset pagination over rn-forge-web
5
5
  Author: Rohit Narayanan
6
6
  Author-email: Rohit Narayanan <rohit.nn@gmail.com>
@@ -15,11 +15,13 @@ Classifier: Programming Language :: Python :: 3.14
15
15
  Classifier: Typing :: Typed
16
16
  Requires-Dist: rn-forge-web>=0.3.0,<0.4
17
17
  Requires-Dist: sqlalchemy[asyncio]>=2.0
18
+ Requires-Dist: alembic>=1.20.1 ; extra == 'migrations'
18
19
  Requires-Python: >=3.14
19
20
  Project-URL: Documentation, https://rn-forge.github.io/pykit/packages/rn-forge-sqlalchemy/latest/
20
21
  Project-URL: Source, https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-sqlalchemy
21
22
  Project-URL: Changelog, https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-sqlalchemy/CHANGELOG.md
22
23
  Project-URL: Issues, https://github.com/rn-forge/pykit/issues
24
+ Provides-Extra: migrations
23
25
  Description-Content-Type: text/markdown
24
26
 
25
27
  # rn-forge-sqlalchemy
@@ -37,24 +39,19 @@ opaque page token.
37
39
 
38
40
  | Module | What it holds |
39
41
  | -- | -- |
40
- | `models` | `Base` (Alembic naming convention), `UTCDateTime`, `AuditMixin` (`create_time`, `update_time`, `created_by`, `updated_by`), `VersionMixin` |
42
+ | `models` | `Base` (Alembic naming convention), `UTCDateTime`, `AuditMixin` (`create_time`, `update_time`, `created_by`, `updated_by`), `VersionMixin`, `SoftDeleteMixin`, `live`, `soft_delete`, `undelete` |
41
43
  | `concurrency` | `update_versioned` — optimistic concurrency, raising `rn_forge.web.VersionConflict` (412) |
42
44
  | `upsert` | `upsert` — create or update rows by natural key, counting created, updated and skipped |
45
+ | `sqlite` | `create_sqlite_engine` — an async SQLite engine with WAL, foreign keys, busy timeout and `synchronous` set on every connection |
46
+ | `migrate` | `run_migrations` — Alembic `upgrade` from inside the process; needs the `migrations` extra and is imported directly, not from the facade |
43
47
  | `pagination` | `keyset`, `next_page_token` — AIP-132 `orderBy` and AIP-158 tokens over a `Select` |
44
48
 
45
49
  Everything works on **PostgreSQL and SQLite**, through `AsyncSession` only.
46
50
 
47
51
  ## Where it sits
48
52
 
49
- ```text
50
- commons ──► web ──► sqlalchemy (this package)
51
- ├───► django
52
- └───► fastapi
53
- ```
54
-
55
- It depends on `rn-forge-web` and SQLAlchemy. It imports neither
56
- `rn_forge.fastapi` nor `rn_forge.django`, nor either framework;
57
- `uv run lint-imports` proves it. An application wires this package to its
53
+ It depends on `rn-forge-web` and SQLAlchemy and imports no web framework or
54
+ framework package; `task lint` proves it. An application wires it to its
58
55
  framework itself: the FastAPI guide shows the import and list endpoints.
59
56
 
60
57
  ## Installation
@@ -74,16 +71,36 @@ Application code catches `rn_forge.web.VersionConflict` and passes
74
71
  No database driver is declared. Add `asyncpg` for PostgreSQL or `aiosqlite` for
75
72
  SQLite.
76
73
 
77
- ## Testing
74
+ `run_migrations` needs the `migrations` extra:
75
+ `rn-forge-sqlalchemy[migrations]>=0.2.3,<0.3`.
76
+
77
+ ## Minimum example
78
+
79
+ ```python
80
+ from sqlalchemy.orm import Mapped, mapped_column
81
+ from rn_forge.sqlalchemy import AuditMixin, Base, VersionMixin
82
+
78
83
 
79
- ```bash
80
- uv run pytest packages/rn-forge-sqlalchemy
81
- RN_FORGE_TEST_POSTGRES_DSN=postgresql+asyncpg://user:pw@localhost/db \
82
- uv run pytest packages/rn-forge-sqlalchemy -m postgres
84
+ class Order(AuditMixin, VersionMixin, Base):
85
+ __tablename__ = "order"
86
+
87
+ id: Mapped[str] = mapped_column(primary_key=True)
88
+ name: Mapped[str] = mapped_column(unique=True)
83
89
  ```
84
90
 
85
- The default run uses SQLite. Tests marked `postgres` run only when the DSN is
86
- set.
91
+ ## Errors
92
+
93
+ `update_versioned` raises `rn_forge.web.VersionConflict` (412) when the row is
94
+ at another version and `LookupError` when it is gone. `upsert` raises
95
+ `ValueError` for an empty key, a row missing a column or a duplicate key,
96
+ `TypeError` for a model without `AuditMixin`, and `NotImplementedError` for a
97
+ dialect other than PostgreSQL or SQLite.
98
+
99
+ ## Testing
100
+
101
+ The default test run uses SQLite. Tests marked `postgres` run when
102
+ `RN_FORGE_TEST_POSTGRES_DSN` is set;
103
+ `task ci:integration -- rn-forge-sqlalchemy` starts PostgreSQL and sets it.
87
104
 
88
105
  ## Not included
89
106
 
@@ -13,24 +13,19 @@ opaque page token.
13
13
 
14
14
  | Module | What it holds |
15
15
  | -- | -- |
16
- | `models` | `Base` (Alembic naming convention), `UTCDateTime`, `AuditMixin` (`create_time`, `update_time`, `created_by`, `updated_by`), `VersionMixin` |
16
+ | `models` | `Base` (Alembic naming convention), `UTCDateTime`, `AuditMixin` (`create_time`, `update_time`, `created_by`, `updated_by`), `VersionMixin`, `SoftDeleteMixin`, `live`, `soft_delete`, `undelete` |
17
17
  | `concurrency` | `update_versioned` — optimistic concurrency, raising `rn_forge.web.VersionConflict` (412) |
18
18
  | `upsert` | `upsert` — create or update rows by natural key, counting created, updated and skipped |
19
+ | `sqlite` | `create_sqlite_engine` — an async SQLite engine with WAL, foreign keys, busy timeout and `synchronous` set on every connection |
20
+ | `migrate` | `run_migrations` — Alembic `upgrade` from inside the process; needs the `migrations` extra and is imported directly, not from the facade |
19
21
  | `pagination` | `keyset`, `next_page_token` — AIP-132 `orderBy` and AIP-158 tokens over a `Select` |
20
22
 
21
23
  Everything works on **PostgreSQL and SQLite**, through `AsyncSession` only.
22
24
 
23
25
  ## Where it sits
24
26
 
25
- ```text
26
- commons ──► web ──► sqlalchemy (this package)
27
- ├───► django
28
- └───► fastapi
29
- ```
30
-
31
- It depends on `rn-forge-web` and SQLAlchemy. It imports neither
32
- `rn_forge.fastapi` nor `rn_forge.django`, nor either framework;
33
- `uv run lint-imports` proves it. An application wires this package to its
27
+ It depends on `rn-forge-web` and SQLAlchemy and imports no web framework or
28
+ framework package; `task lint` proves it. An application wires it to its
34
29
  framework itself: the FastAPI guide shows the import and list endpoints.
35
30
 
36
31
  ## Installation
@@ -50,16 +45,36 @@ Application code catches `rn_forge.web.VersionConflict` and passes
50
45
  No database driver is declared. Add `asyncpg` for PostgreSQL or `aiosqlite` for
51
46
  SQLite.
52
47
 
53
- ## Testing
48
+ `run_migrations` needs the `migrations` extra:
49
+ `rn-forge-sqlalchemy[migrations]>=0.2.3,<0.3`.
50
+
51
+ ## Minimum example
52
+
53
+ ```python
54
+ from sqlalchemy.orm import Mapped, mapped_column
55
+ from rn_forge.sqlalchemy import AuditMixin, Base, VersionMixin
56
+
54
57
 
55
- ```bash
56
- uv run pytest packages/rn-forge-sqlalchemy
57
- RN_FORGE_TEST_POSTGRES_DSN=postgresql+asyncpg://user:pw@localhost/db \
58
- uv run pytest packages/rn-forge-sqlalchemy -m postgres
58
+ class Order(AuditMixin, VersionMixin, Base):
59
+ __tablename__ = "order"
60
+
61
+ id: Mapped[str] = mapped_column(primary_key=True)
62
+ name: Mapped[str] = mapped_column(unique=True)
59
63
  ```
60
64
 
61
- The default run uses SQLite. Tests marked `postgres` run only when the DSN is
62
- set.
65
+ ## Errors
66
+
67
+ `update_versioned` raises `rn_forge.web.VersionConflict` (412) when the row is
68
+ at another version and `LookupError` when it is gone. `upsert` raises
69
+ `ValueError` for an empty key, a row missing a column or a duplicate key,
70
+ `TypeError` for a model without `AuditMixin`, and `NotImplementedError` for a
71
+ dialect other than PostgreSQL or SQLite.
72
+
73
+ ## Testing
74
+
75
+ The default test run uses SQLite. Tests marked `postgres` run when
76
+ `RN_FORGE_TEST_POSTGRES_DSN` is set;
77
+ `task ci:integration -- rn-forge-sqlalchemy` starts PostgreSQL and sets it.
63
78
 
64
79
  ## Not included
65
80
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rn-forge-sqlalchemy"
3
- version = "0.2.2"
3
+ version = "0.2.4"
4
4
  description = "Async SQLAlchemy models, upsert and keyset pagination over rn-forge-web"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -24,6 +24,9 @@ dependencies = [
24
24
  name = "Rohit Narayanan"
25
25
  email = "rohit.nn@gmail.com"
26
26
 
27
+ [project.optional-dependencies]
28
+ migrations = ["alembic>=1.20.1"]
29
+
27
30
  [project.urls]
28
31
  Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-sqlalchemy/latest/"
29
32
  Source = "https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-sqlalchemy"
@@ -31,11 +34,19 @@ Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-sqlal
31
34
  Issues = "https://github.com/rn-forge/pykit/issues"
32
35
 
33
36
  [build-system]
34
- requires = ["uv_build>=0.11.28,<0.12.0"]
37
+ requires = ["uv_build>=0.13.7,<0.14.0"]
35
38
  build-backend = "uv_build"
36
39
 
40
+ [tool.pyright]
41
+ typeCheckingMode = "strict"
42
+ reportMissingTypeStubs = false
43
+ reportUnnecessaryTypeIgnoreComment = "error"
44
+ venv = ".venv"
45
+ venvPath = "../.."
46
+
37
47
  [tool.uv.build-backend]
38
48
  module-name = "rn_forge.sqlalchemy"
49
+ source-exclude = ["**/.DS_Store"]
39
50
 
40
51
  [tool.uv.sources.rn-forge-commons]
41
52
  workspace = true
@@ -56,13 +67,24 @@ markers = [
56
67
  "postgres: needs a PostgreSQL DSN in RN_FORGE_TEST_POSTGRES_DSN",
57
68
  ]
58
69
 
59
- [tool.workspace-ci.postgres]
60
- env = "RN_FORGE_TEST_POSTGRES_DSN"
70
+ [tool.workspace-ci.integration.postgres]
71
+ image = "postgres:17"
72
+ ports = ["5432:5432"]
73
+ health-cmd = "pg_isready -U ci"
74
+
75
+ [tool.workspace-ci.integration.postgres.env]
76
+ POSTGRES_USER = "ci"
77
+ POSTGRES_PASSWORD = "ci"
78
+ POSTGRES_DB = "ci"
79
+
80
+ [tool.workspace-ci.integration.postgres.expose]
81
+ RN_FORGE_TEST_POSTGRES_DSN = "postgresql://ci:ci@localhost:5432/ci"
61
82
 
62
83
  [dependency-groups]
63
84
  dev = [
64
85
  "aiosqlite>=0.21",
65
- "assertpy>=1.1",
86
+ "alembic>=1.20.1",
87
+ "assertpy>=2.35",
66
88
  "asyncpg>=0.30",
67
89
  "httpx>=0.28.1",
68
90
  "pyright>=1.1.411",
@@ -70,7 +92,7 @@ dev = [
70
92
  "pytest-asyncio>=1.3.0",
71
93
  "pytest-cov>=7.1.0",
72
94
  "pytest-randomly>=4.1.0",
73
- "rn-forge-fastapi[transfer]>=0.4.0,<0.5",
95
+ "rn-forge-fastapi[transfer]>=0.4.0,<0.6",
74
96
  "ruff>=0.15.21",
75
97
  ]
76
98
  docs = [
@@ -0,0 +1,96 @@
1
+ [project]
2
+ name = "rn-forge-sqlalchemy"
3
+ version = "0.2.4"
4
+ description = "Async SQLAlchemy models, upsert and keyset pagination over rn-forge-web"
5
+ readme = "README.md"
6
+ authors = [{ name = "Rohit Narayanan", email = "rohit.nn@gmail.com" }]
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Intended Audience :: Developers",
12
+ "Operating System :: OS Independent",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3 :: Only",
15
+ "Programming Language :: Python :: 3.14",
16
+ "Typing :: Typed",
17
+ ]
18
+ requires-python = ">=3.14"
19
+ # Internal requirements are version ranges (ADR-0004).
20
+ #
21
+ # No database driver is declared: the application picks one (`asyncpg`,
22
+ # `aiosqlite`). `rn-forge-commons` arrives through `rn-forge-web`.
23
+ dependencies = ["rn-forge-web>=0.3.0,<0.4", "sqlalchemy[asyncio]>=2.0"]
24
+
25
+ [project.optional-dependencies]
26
+ migrations = ["alembic>=1.20.1"]
27
+
28
+ [project.urls]
29
+ Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-sqlalchemy/latest/"
30
+ Source = "https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-sqlalchemy"
31
+ Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-sqlalchemy/CHANGELOG.md"
32
+ Issues = "https://github.com/rn-forge/pykit/issues"
33
+
34
+ [build-system]
35
+ requires = ["uv_build>=0.13.7,<0.14.0"]
36
+ build-backend = "uv_build"
37
+
38
+ [tool.pyright]
39
+ typeCheckingMode = "strict"
40
+ reportMissingTypeStubs = false
41
+ reportUnnecessaryTypeIgnoreComment = "error"
42
+ venv = ".venv"
43
+ venvPath = "../.."
44
+
45
+ [tool.uv.build-backend]
46
+ module-name = "rn_forge.sqlalchemy"
47
+ source-exclude = ["**/.DS_Store"]
48
+
49
+ [tool.uv.sources]
50
+ rn-forge-commons = { workspace = true }
51
+ rn-forge-web = { workspace = true }
52
+ rn-forge-fastapi = { workspace = true }
53
+ rn-forge-sqlalchemy = { workspace = true }
54
+
55
+ [tool.pytest.ini_options]
56
+ addopts = "-ra --import-mode=importlib"
57
+ markers = [
58
+ "unit: fast isolated tests",
59
+ "postgres: needs a PostgreSQL DSN in RN_FORGE_TEST_POSTGRES_DSN",
60
+ ]
61
+
62
+ [tool.workspace-ci.integration.postgres]
63
+ image = "postgres:17"
64
+ ports = ["5432:5432"]
65
+ health-cmd = "pg_isready -U ci"
66
+
67
+ [tool.workspace-ci.integration.postgres.env]
68
+ POSTGRES_USER = "ci"
69
+ POSTGRES_PASSWORD = "ci"
70
+ POSTGRES_DB = "ci"
71
+
72
+ [tool.workspace-ci.integration.postgres.expose]
73
+ # The `postgres`-marked tests read this DSN and skip without it.
74
+ RN_FORGE_TEST_POSTGRES_DSN = "postgresql://ci:ci@localhost:5432/ci"
75
+
76
+ [dependency-groups]
77
+ dev = [
78
+ "aiosqlite>=0.21",
79
+ "alembic>=1.20.1",
80
+ "assertpy>=2.35",
81
+ "asyncpg>=0.30",
82
+ "httpx>=0.28.1",
83
+ "pyright>=1.1.411",
84
+ "pytest>=9.1.1",
85
+ "pytest-asyncio>=1.3.0",
86
+ "pytest-cov>=7.1.0",
87
+ "pytest-randomly>=4.1.0",
88
+ "rn-forge-fastapi[transfer]>=0.4.0,<0.6",
89
+ "ruff>=0.15.21",
90
+ ]
91
+ docs = [
92
+ "mkdocs>=1.6.1",
93
+ "mkdocs-material>=9.7.6",
94
+ "mkdocstrings[python]>=1.0.6",
95
+ "rn-forge-sqlalchemy",
96
+ ]
@@ -13,6 +13,7 @@ from rn_forge.sqlalchemy.models import (
13
13
  undelete,
14
14
  )
15
15
  from rn_forge.sqlalchemy.pagination import keyset, next_page_token
16
+ from rn_forge.sqlalchemy.sqlite import create_sqlite_engine
16
17
  from rn_forge.sqlalchemy.upsert import UpsertCounts, upsert
17
18
 
18
19
  __all__ = [
@@ -23,6 +24,7 @@ __all__ = [
23
24
  "UTCDateTime",
24
25
  "UpsertCounts",
25
26
  "VersionMixin",
27
+ "create_sqlite_engine",
26
28
  "keyset",
27
29
  "live",
28
30
  "next_page_token",
@@ -0,0 +1,43 @@
1
+ """Run Alembic migrations from inside the application process."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from alembic import command
8
+ from alembic.config import Config
9
+
10
+ __all__ = ["run_migrations"]
11
+
12
+
13
+ def run_migrations(
14
+ script_location: str | Path,
15
+ db_url: str,
16
+ *,
17
+ alembic_ini: str | Path | None = None,
18
+ revision: str = "head",
19
+ ) -> None:
20
+ """Upgrade the database at *db_url* to *revision*.
21
+
22
+ Blocks until the upgrade finishes. From a running event loop, call it as
23
+ ``await asyncio.to_thread(run_migrations, ...)``. A failing migration
24
+ propagates unchanged.
25
+
26
+ ``config.attributes["configure_logger"]`` is set to ``False``. The
27
+ application's ``env.py`` must read it before calling ``fileConfig`` for the
28
+ application's logging to be left alone.
29
+
30
+ Args:
31
+ script_location: A script directory, or a package resource such as
32
+ ``"myapp:migrations"``.
33
+ db_url: The SQLAlchemy URL handed to ``env.py`` as ``sqlalchemy.url``.
34
+ alembic_ini: An ``alembic.ini`` to start from; an empty configuration
35
+ when omitted.
36
+ revision: The target revision.
37
+ """
38
+ config = Config(str(alembic_ini)) if alembic_ini is not None else Config()
39
+ # Config values pass through ConfigParser, where a bare "%" is interpolation.
40
+ config.set_main_option("script_location", str(script_location).replace("%", "%%"))
41
+ config.set_main_option("sqlalchemy.url", db_url.replace("%", "%%"))
42
+ config.attributes["configure_logger"] = False
43
+ command.upgrade(config, revision)
@@ -0,0 +1,86 @@
1
+ """An async SQLite engine with its pragmas set on every connection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from sqlalchemy import event
9
+ from sqlalchemy.engine import URL
10
+ from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
11
+ from sqlalchemy.pool import StaticPool
12
+
13
+ __all__ = ["create_sqlite_engine"]
14
+
15
+ _MEMORY = ":memory:"
16
+ _SYNCHRONOUS = frozenset({"OFF", "NORMAL", "FULL", "EXTRA"})
17
+
18
+
19
+ def create_sqlite_engine(
20
+ path: str | Path,
21
+ *,
22
+ wal: bool = True,
23
+ busy_timeout_ms: int = 5000,
24
+ foreign_keys: bool = True,
25
+ synchronous: str = "NORMAL",
26
+ ) -> AsyncEngine:
27
+ """Create an ``AsyncEngine`` on a SQLite file with pragmas set per connection.
28
+
29
+ The parent directory of *path* is created. Every new connection runs
30
+ ``busy_timeout``, then ``journal_mode=WAL`` when *wal* is true,
31
+ ``synchronous``, and ``foreign_keys=ON`` when *foreign_keys* is true. A false
32
+ flag leaves that pragma at SQLite's default. No tables are created.
33
+
34
+ The exact string ``":memory:"`` opens an in-memory database: no directory is
35
+ created, WAL is not enabled, and a ``StaticPool`` makes every session share
36
+ one connection. ``Path(":memory:")`` is an ordinary file named ``:memory:``.
37
+
38
+ Args:
39
+ path: The database file, or the string ``":memory:"``.
40
+ wal: Enable write-ahead logging.
41
+ busy_timeout_ms: Milliseconds a connection waits on a locked database.
42
+ foreign_keys: Enforce foreign-key constraints.
43
+ synchronous: ``OFF``, ``NORMAL``, ``FULL`` or ``EXTRA``, in any case.
44
+
45
+ Returns:
46
+ The engine, using the ``sqlite+aiosqlite`` driver.
47
+
48
+ Raises:
49
+ ValueError: *synchronous* is not one of the allowed values.
50
+ ValueError: *busy_timeout_ms* cannot be converted to an integer.
51
+ """
52
+ level = synchronous.upper()
53
+ if level not in _SYNCHRONOUS:
54
+ allowed = ", ".join(sorted(_SYNCHRONOUS))
55
+ raise ValueError(f"synchronous must be one of {allowed}, got {synchronous!r}")
56
+ timeout = int(busy_timeout_ms)
57
+
58
+ in_memory = isinstance(path, str) and path == _MEMORY
59
+ # PRAGMA values cannot be bound parameters, so they are validated above.
60
+ # busy_timeout goes first so the caller's value also covers journal_mode,
61
+ # whose first switch to WAL needs an exclusive lock.
62
+ pragmas = [f"PRAGMA busy_timeout={timeout}"]
63
+ if wal and not in_memory:
64
+ pragmas.append("PRAGMA journal_mode=WAL")
65
+ pragmas.append(f"PRAGMA synchronous={level}")
66
+ if foreign_keys:
67
+ pragmas.append("PRAGMA foreign_keys=ON")
68
+
69
+ kwargs: dict[str, Any] = {}
70
+ if in_memory:
71
+ kwargs["poolclass"] = StaticPool
72
+ else:
73
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
74
+ url = URL.create("sqlite+aiosqlite", database=str(path))
75
+ engine = create_async_engine(url, **kwargs)
76
+
77
+ @event.listens_for(engine.sync_engine, "connect")
78
+ def _set_pragmas(dbapi_connection: Any, _record: Any) -> None:
79
+ cursor = dbapi_connection.cursor()
80
+ try:
81
+ for pragma in pragmas:
82
+ cursor.execute(pragma)
83
+ finally:
84
+ cursor.close()
85
+
86
+ return engine
@@ -2,9 +2,10 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from collections.abc import Iterator, Mapping, Sequence
5
+ from collections.abc import Mapping, Sequence
6
6
  from dataclasses import dataclass
7
7
  from datetime import UTC, datetime
8
+ from itertools import batched
8
9
  from typing import Any
9
10
 
10
11
  from rn_forge.sqlalchemy.models import AuditMixin, Base
@@ -38,12 +39,13 @@ async def upsert(
38
39
  ) -> UpsertCounts:
39
40
  """Create the rows whose *key* is absent and update those whose *fields* differ.
40
41
 
41
- The existing rows are read first, so the counts are exact. Created and
42
- updated rows are then written with one
43
- ``INSERT … ON CONFLICT (key) DO UPDATE``; ``create_time`` and ``created_by``
44
- are set on insert only, ``update_time`` and ``updated_by`` on both. Never
45
- commits: the caller's transaction decides, and rolling back after the call is
46
- a dry run. *key* must be backed by a unique constraint.
42
+ The existing rows are read first, and the counts describe that snapshot. A
43
+ writer that commits between the read and the write can make them wrong, so
44
+ serialize writers when exact counts matter. Only new and changed rows are
45
+ written, with one ``INSERT … ON CONFLICT (key) DO UPDATE``; ``create_time``
46
+ and ``created_by`` are set on insert only, ``update_time`` and ``updated_by``
47
+ on both. Never commits: the caller's transaction decides, and rolling back
48
+ after the call is a dry run. *key* must be backed by a unique constraint.
47
49
 
48
50
  Args:
49
51
  session: An ``AsyncSession`` on PostgreSQL or SQLite.
@@ -54,23 +56,46 @@ async def upsert(
54
56
  actor: Stamped into ``created_by`` and ``updated_by``.
55
57
 
56
58
  Raises:
57
- ValueError: A row lacks a column, or two rows share a key.
59
+ ValueError: *key* is empty, a row lacks a column, or two rows share a key.
58
60
  TypeError: *model* does not use ``AuditMixin``.
59
61
  NotImplementedError: The session's dialect is not PostgreSQL or SQLite.
60
62
  """
61
63
  if not issubclass(model, AuditMixin):
62
64
  raise TypeError(f"{model.__name__} must use AuditMixin")
65
+ if not key:
66
+ raise ValueError("key must not be empty")
63
67
  columns = [*key, *fields]
64
68
  keyed = _keyed(rows, key, columns)
65
69
  dialect = session.get_bind().dialect.name
66
70
  if dialect not in ("postgresql", "sqlite"):
67
71
  raise NotImplementedError(f"upsert does not support {dialect}")
72
+ del keyed
68
73
 
69
74
  table: Table = model.__table__ # pyright: ignore[reportAssignmentType]
70
- existing = await _existing(session, table, key, fields, list(keyed))
71
- to_write, created, updated = _changes(keyed, existing, columns, fields, actor)
75
+ total = len(rows)
76
+ to_write: list[dict[str, Any]] = []
77
+ created = updated = 0
78
+ now = datetime.now(UTC)
79
+ stamps = {
80
+ "create_time": now,
81
+ "created_by": actor,
82
+ "update_time": now,
83
+ "updated_by": actor,
84
+ }
85
+ for chunk in batched(rows, _MAX_PARAMETERS // len(key)):
86
+ identities = [tuple(row[k] for k in key) for row in chunk]
87
+ existing = await _existing(session, table, key, fields, identities)
88
+ changes, new, changed = _changes(chunk, identities, existing, columns, fields)
89
+ to_write.extend(changes)
90
+ created += new
91
+ updated += changed
92
+ del existing
72
93
  if to_write:
73
- insert = (postgresql if dialect == "postgresql" else sqlite).insert(table)
94
+ insert = (
95
+ (postgresql if dialect == "postgresql" else sqlite)
96
+ .insert(table)
97
+ .values(stamps)
98
+ )
74
99
  statement = insert.on_conflict_do_update(
75
100
  index_elements=list(key),
76
101
  set_={
@@ -79,35 +104,34 @@ async def upsert(
79
104
  },
80
105
  )
81
106
  await session.execute(statement, to_write)
82
- return UpsertCounts(created, updated, len(keyed) - created - updated)
107
+ return UpsertCounts(created, updated, total - created - updated)
83
108
 
84
109
 
85
110
  def _keyed(
86
111
  rows: Sequence[Mapping[str, Any]], key: Sequence[str], columns: Sequence[str]
87
- ) -> dict[tuple[Any, ...], Mapping[str, Any]]:
88
- keyed: dict[tuple[Any, ...], Mapping[str, Any]] = {}
112
+ ) -> set[tuple[Any, ...]]:
113
+ keyed: set[tuple[Any, ...]] = set()
89
114
  for row in rows:
90
115
  if missing := [c for c in columns if c not in row]:
91
116
  raise ValueError(f"row lacks columns {missing}")
92
117
  identity = tuple(row[k] for k in key)
93
118
  if identity in keyed:
94
119
  raise ValueError(f"duplicate key {identity}")
95
- keyed[identity] = row
120
+ keyed.add(identity)
96
121
  return keyed
97
122
 
98
123
 
99
124
  def _changes(
100
- keyed: Mapping[tuple[Any, ...], Mapping[str, Any]],
125
+ rows: Sequence[Mapping[str, Any]],
126
+ identities: Sequence[tuple[Any, ...]],
101
127
  existing: Mapping[tuple[Any, ...], Mapping[str, Any]],
102
128
  columns: Sequence[str],
103
129
  fields: Sequence[str],
104
- actor: str,
105
130
  ) -> tuple[list[dict[str, Any]], int, int]:
106
131
  """The rows to write, with how many of them are creations and updates."""
107
132
  to_write: list[dict[str, Any]] = []
108
133
  created = updated = 0
109
- now = datetime.now(UTC)
110
- for identity, row in keyed.items():
134
+ for identity, row in zip(identities, rows, strict=True):
111
135
  current = existing.get(identity)
112
136
  if current is not None and all(row[f] == current[f] for f in fields):
113
137
  continue
@@ -115,15 +139,7 @@ def _changes(
115
139
  created += 1
116
140
  else:
117
141
  updated += 1
118
- to_write.append(
119
- {c: row[c] for c in columns}
120
- | {
121
- "create_time": now,
122
- "created_by": actor,
123
- "update_time": now,
124
- "updated_by": actor,
125
- }
126
- )
142
+ to_write.append({c: row[c] for c in columns})
127
143
  return to_write, created, updated
128
144
 
129
145
 
@@ -136,20 +152,14 @@ async def _existing(
136
152
  ) -> dict[tuple[Any, ...], Mapping[str, Any]]:
137
153
  key_columns = [table.c[k] for k in key]
138
154
  found: dict[tuple[Any, ...], Mapping[str, Any]] = {}
139
- for chunk in _chunks(identities, _MAX_PARAMETERS // len(key)):
140
- match = (
141
- key_columns[0].in_([i[0] for i in chunk])
142
- if len(key) == 1
143
- else tuple_(*key_columns).in_(chunk)
144
- )
145
- result = await session.execute(
146
- select(*key_columns, *(table.c[f] for f in fields)).where(match)
147
- )
148
- for record in result.mappings():
149
- found[tuple(record[k] for k in key)] = dict(record)
155
+ match = (
156
+ key_columns[0].in_([i[0] for i in identities])
157
+ if len(key) == 1
158
+ else tuple_(*key_columns).in_(identities)
159
+ )
160
+ result = await session.execute(
161
+ select(*key_columns, *(table.c[f] for f in fields)).where(match)
162
+ )
163
+ for record in result.mappings():
164
+ found[tuple(record[k] for k in key)] = dict(record)
150
165
  return found
151
-
152
-
153
- def _chunks[T](items: list[T], size: int) -> Iterator[list[T]]:
154
- for start in range(0, len(items), size):
155
- yield items[start : start + size]
@@ -1,77 +0,0 @@
1
- [project]
2
- name = "rn-forge-sqlalchemy"
3
- version = "0.2.2"
4
- description = "Async SQLAlchemy models, upsert and keyset pagination over rn-forge-web"
5
- readme = "README.md"
6
- authors = [{ name = "Rohit Narayanan", email = "rohit.nn@gmail.com" }]
7
- license = "MIT"
8
- license-files = ["LICENSE"]
9
- classifiers = [
10
- "Development Status :: 3 - Alpha",
11
- "Intended Audience :: Developers",
12
- "Operating System :: OS Independent",
13
- "Programming Language :: Python :: 3",
14
- "Programming Language :: Python :: 3 :: Only",
15
- "Programming Language :: Python :: 3.14",
16
- "Typing :: Typed",
17
- ]
18
- requires-python = ">=3.14"
19
- # Internal requirements are version ranges (ADR-0004).
20
- #
21
- # No database driver is declared: the application picks one (`asyncpg`,
22
- # `aiosqlite`). `rn-forge-commons` arrives through `rn-forge-web`.
23
- dependencies = [
24
- "rn-forge-web>=0.3.0,<0.4",
25
- "sqlalchemy[asyncio]>=2.0",
26
- ]
27
-
28
- [project.urls]
29
- Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-sqlalchemy/latest/"
30
- Source = "https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-sqlalchemy"
31
- Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-sqlalchemy/CHANGELOG.md"
32
- Issues = "https://github.com/rn-forge/pykit/issues"
33
-
34
- [build-system]
35
- requires = ["uv_build>=0.11.28,<0.12.0"]
36
- build-backend = "uv_build"
37
-
38
- [tool.uv.build-backend]
39
- module-name = "rn_forge.sqlalchemy"
40
-
41
- [tool.uv.sources]
42
- rn-forge-commons = { workspace = true }
43
- rn-forge-web = { workspace = true }
44
- rn-forge-fastapi = { workspace = true }
45
- rn-forge-sqlalchemy = { workspace = true }
46
-
47
- [tool.pytest.ini_options]
48
- addopts = "-ra --import-mode=importlib"
49
- markers = [
50
- "unit: fast isolated tests",
51
- "postgres: needs a PostgreSQL DSN in RN_FORGE_TEST_POSTGRES_DSN",
52
- ]
53
-
54
- [tool.workspace-ci.postgres]
55
- # The `postgres`-marked tests read this DSN and skip without it.
56
- env = "RN_FORGE_TEST_POSTGRES_DSN"
57
-
58
- [dependency-groups]
59
- dev = [
60
- "aiosqlite>=0.21",
61
- "assertpy>=1.1",
62
- "asyncpg>=0.30",
63
- "httpx>=0.28.1",
64
- "pyright>=1.1.411",
65
- "pytest>=9.1.1",
66
- "pytest-asyncio>=1.3.0",
67
- "pytest-cov>=7.1.0",
68
- "pytest-randomly>=4.1.0",
69
- "rn-forge-fastapi[transfer]>=0.4.0,<0.5",
70
- "ruff>=0.15.21",
71
- ]
72
- docs = [
73
- "mkdocs>=1.6.1",
74
- "mkdocs-material>=9.7.6",
75
- "mkdocstrings[python]>=1.0.6",
76
- "rn-forge-sqlalchemy",
77
- ]