rn-forge-sqlalchemy 0.2.3__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.3
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>
@@ -39,7 +39,7 @@ opaque page token.
39
39
 
40
40
  | Module | What it holds |
41
41
  | -- | -- |
42
- | `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` |
43
43
  | `concurrency` | `update_versioned` — optimistic concurrency, raising `rn_forge.web.VersionConflict` (412) |
44
44
  | `upsert` | `upsert` — create or update rows by natural key, counting created, updated and skipped |
45
45
  | `sqlite` | `create_sqlite_engine` — an async SQLite engine with WAL, foreign keys, busy timeout and `synchronous` set on every connection |
@@ -50,15 +50,8 @@ Everything works on **PostgreSQL and SQLite**, through `AsyncSession` only.
50
50
 
51
51
  ## Where it sits
52
52
 
53
- ```text
54
- commons ──► web ──► sqlalchemy (this package)
55
- ├───► django
56
- └───► fastapi
57
- ```
58
-
59
- It depends on `rn-forge-web` and SQLAlchemy. It imports neither
60
- `rn_forge.fastapi` nor `rn_forge.django`, nor either framework;
61
- `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
62
55
  framework itself: the FastAPI guide shows the import and list endpoints.
63
56
 
64
57
  ## Installation
@@ -81,16 +74,33 @@ SQLite.
81
74
  `run_migrations` needs the `migrations` extra:
82
75
  `rn-forge-sqlalchemy[migrations]>=0.2.3,<0.3`.
83
76
 
84
- ## Testing
77
+ ## Minimum example
78
+
79
+ ```python
80
+ from sqlalchemy.orm import Mapped, mapped_column
81
+ from rn_forge.sqlalchemy import AuditMixin, Base, VersionMixin
82
+
85
83
 
86
- ```bash
87
- uv run pytest packages/rn-forge-sqlalchemy
88
- RN_FORGE_TEST_POSTGRES_DSN=postgresql+asyncpg://user:pw@localhost/db \
89
- 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)
90
89
  ```
91
90
 
92
- The default run uses SQLite. Tests marked `postgres` run only when the DSN is
93
- 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.
94
104
 
95
105
  ## Not included
96
106
 
@@ -13,7 +13,7 @@ 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
19
  | `sqlite` | `create_sqlite_engine` — an async SQLite engine with WAL, foreign keys, busy timeout and `synchronous` set on every connection |
@@ -24,15 +24,8 @@ Everything works on **PostgreSQL and SQLite**, through `AsyncSession` only.
24
24
 
25
25
  ## Where it sits
26
26
 
27
- ```text
28
- commons ──► web ──► sqlalchemy (this package)
29
- ├───► django
30
- └───► fastapi
31
- ```
32
-
33
- It depends on `rn-forge-web` and SQLAlchemy. It imports neither
34
- `rn_forge.fastapi` nor `rn_forge.django`, nor either framework;
35
- `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
36
29
  framework itself: the FastAPI guide shows the import and list endpoints.
37
30
 
38
31
  ## Installation
@@ -55,16 +48,33 @@ SQLite.
55
48
  `run_migrations` needs the `migrations` extra:
56
49
  `rn-forge-sqlalchemy[migrations]>=0.2.3,<0.3`.
57
50
 
58
- ## Testing
51
+ ## Minimum example
52
+
53
+ ```python
54
+ from sqlalchemy.orm import Mapped, mapped_column
55
+ from rn_forge.sqlalchemy import AuditMixin, Base, VersionMixin
56
+
59
57
 
60
- ```bash
61
- uv run pytest packages/rn-forge-sqlalchemy
62
- RN_FORGE_TEST_POSTGRES_DSN=postgresql+asyncpg://user:pw@localhost/db \
63
- 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)
64
63
  ```
65
64
 
66
- The default run uses SQLite. Tests marked `postgres` run only when the DSN is
67
- 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.
68
78
 
69
79
  ## Not included
70
80
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rn-forge-sqlalchemy"
3
- version = "0.2.3"
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"
@@ -92,7 +92,7 @@ dev = [
92
92
  "pytest-asyncio>=1.3.0",
93
93
  "pytest-cov>=7.1.0",
94
94
  "pytest-randomly>=4.1.0",
95
- "rn-forge-fastapi[transfer]>=0.4.0,<0.5",
95
+ "rn-forge-fastapi[transfer]>=0.4.0,<0.6",
96
96
  "ruff>=0.15.21",
97
97
  ]
98
98
  docs = [
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rn-forge-sqlalchemy"
3
- version = "0.2.3"
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
  authors = [{ name = "Rohit Narayanan", email = "rohit.nn@gmail.com" }]
@@ -85,7 +85,7 @@ dev = [
85
85
  "pytest-asyncio>=1.3.0",
86
86
  "pytest-cov>=7.1.0",
87
87
  "pytest-randomly>=4.1.0",
88
- "rn-forge-fastapi[transfer]>=0.4.0,<0.5",
88
+ "rn-forge-fastapi[transfer]>=0.4.0,<0.6",
89
89
  "ruff>=0.15.21",
90
90
  ]
91
91
  docs = [
@@ -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]