rn-forge-sqlalchemy 0.2.2__py3-none-any.whl
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.
- rn_forge/sqlalchemy/__init__.py +33 -0
- rn_forge/sqlalchemy/concurrency.py +64 -0
- rn_forge/sqlalchemy/models.py +160 -0
- rn_forge/sqlalchemy/pagination.py +136 -0
- rn_forge/sqlalchemy/py.typed +0 -0
- rn_forge/sqlalchemy/upsert.py +155 -0
- rn_forge_sqlalchemy-0.2.2.dist-info/METADATA +91 -0
- rn_forge_sqlalchemy-0.2.2.dist-info/RECORD +10 -0
- rn_forge_sqlalchemy-0.2.2.dist-info/WHEEL +4 -0
- rn_forge_sqlalchemy-0.2.2.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Async SQLAlchemy models, upsert and keyset pagination over :mod:`rn_forge.web`."""
|
|
2
|
+
|
|
3
|
+
from rn_forge.sqlalchemy.concurrency import update_versioned
|
|
4
|
+
from rn_forge.sqlalchemy.models import (
|
|
5
|
+
NAMING_CONVENTION,
|
|
6
|
+
AuditMixin,
|
|
7
|
+
Base,
|
|
8
|
+
SoftDeleteMixin,
|
|
9
|
+
UTCDateTime,
|
|
10
|
+
VersionMixin,
|
|
11
|
+
live,
|
|
12
|
+
soft_delete,
|
|
13
|
+
undelete,
|
|
14
|
+
)
|
|
15
|
+
from rn_forge.sqlalchemy.pagination import keyset, next_page_token
|
|
16
|
+
from rn_forge.sqlalchemy.upsert import UpsertCounts, upsert
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"NAMING_CONVENTION",
|
|
20
|
+
"AuditMixin",
|
|
21
|
+
"Base",
|
|
22
|
+
"SoftDeleteMixin",
|
|
23
|
+
"UTCDateTime",
|
|
24
|
+
"UpsertCounts",
|
|
25
|
+
"VersionMixin",
|
|
26
|
+
"keyset",
|
|
27
|
+
"live",
|
|
28
|
+
"next_page_token",
|
|
29
|
+
"soft_delete",
|
|
30
|
+
"undelete",
|
|
31
|
+
"update_versioned",
|
|
32
|
+
"upsert",
|
|
33
|
+
]
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Optimistic concurrency over a :class:`~rn_forge.sqlalchemy.VersionMixin` row."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, cast
|
|
6
|
+
|
|
7
|
+
from rn_forge.sqlalchemy.models import VersionMixin
|
|
8
|
+
from rn_forge.web import VersionConflict
|
|
9
|
+
from sqlalchemy import CursorResult, and_, inspect, select, update
|
|
10
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
11
|
+
|
|
12
|
+
__all__ = ["update_versioned"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
async def update_versioned[T: VersionMixin](
|
|
16
|
+
session: AsyncSession, obj: T, **values: Any
|
|
17
|
+
) -> T:
|
|
18
|
+
"""Update *obj*'s row only if its ``version`` is still the one *obj* holds.
|
|
19
|
+
|
|
20
|
+
Issues ``UPDATE … WHERE pk = :pk AND version = :expected`` with
|
|
21
|
+
``version = expected + 1``, then refreshes *obj*. Does not commit.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
session: The session *obj* belongs to.
|
|
25
|
+
obj: A persistent instance of a model using ``VersionMixin``.
|
|
26
|
+
**values: Column values to set.
|
|
27
|
+
|
|
28
|
+
Returns:
|
|
29
|
+
*obj*, refreshed.
|
|
30
|
+
|
|
31
|
+
Raises:
|
|
32
|
+
VersionConflict: The row exists at a different version (412).
|
|
33
|
+
LookupError: The row no longer exists.
|
|
34
|
+
"""
|
|
35
|
+
mapper = inspect(type(obj), raiseerr=True)
|
|
36
|
+
identity = mapper.primary_key_from_instance(obj)
|
|
37
|
+
same_row = and_(
|
|
38
|
+
*(col == value for col, value in zip(mapper.primary_key, identity, strict=True))
|
|
39
|
+
)
|
|
40
|
+
model: Any = type(obj)
|
|
41
|
+
expected = obj.version
|
|
42
|
+
result = cast(
|
|
43
|
+
"CursorResult[Any]",
|
|
44
|
+
await session.execute(
|
|
45
|
+
update(model)
|
|
46
|
+
.where(same_row, model.version == expected)
|
|
47
|
+
.values(**values, version=expected + 1)
|
|
48
|
+
.execution_options(synchronize_session=False)
|
|
49
|
+
),
|
|
50
|
+
)
|
|
51
|
+
if result.rowcount == 0:
|
|
52
|
+
if (
|
|
53
|
+
await session.execute(select(1).select_from(model).where(same_row))
|
|
54
|
+
).first():
|
|
55
|
+
raise VersionConflict(
|
|
56
|
+
"{} {} was modified concurrently: expected version {}",
|
|
57
|
+
type(obj).__name__,
|
|
58
|
+
identity[0] if len(identity) == 1 else identity,
|
|
59
|
+
expected,
|
|
60
|
+
error_code=412,
|
|
61
|
+
)
|
|
62
|
+
raise LookupError(f"{type(obj).__name__} {identity} no longer exists")
|
|
63
|
+
await session.refresh(obj)
|
|
64
|
+
return obj
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Declarative base, UTC timestamps and the audit and version mixins."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import UTC, datetime
|
|
6
|
+
from typing import Any, Final
|
|
7
|
+
|
|
8
|
+
from sqlalchemy import DateTime, Dialect, Integer, MetaData, Select, String
|
|
9
|
+
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
|
10
|
+
from sqlalchemy.types import TypeDecorator
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"NAMING_CONVENTION",
|
|
14
|
+
"AuditMixin",
|
|
15
|
+
"Base",
|
|
16
|
+
"SoftDeleteMixin",
|
|
17
|
+
"UTCDateTime",
|
|
18
|
+
"VersionMixin",
|
|
19
|
+
"live",
|
|
20
|
+
"soft_delete",
|
|
21
|
+
"undelete",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
NAMING_CONVENTION: Final = {
|
|
25
|
+
"ix": "ix_%(column_0_label)s",
|
|
26
|
+
"uq": "uq_%(table_name)s_%(column_0_name)s",
|
|
27
|
+
"ck": "ck_%(table_name)s_%(constraint_name)s",
|
|
28
|
+
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
|
|
29
|
+
"pk": "pk_%(table_name)s",
|
|
30
|
+
}
|
|
31
|
+
"""Constraint names Alembic can address in a migration."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Base(DeclarativeBase):
|
|
35
|
+
"""Declarative base whose metadata carries :data:`NAMING_CONVENTION`."""
|
|
36
|
+
|
|
37
|
+
metadata = MetaData(naming_convention=dict(NAMING_CONVENTION))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class UTCDateTime(TypeDecorator[datetime]):
|
|
41
|
+
"""A timezone-aware ``datetime`` stored as UTC on every dialect.
|
|
42
|
+
|
|
43
|
+
Writing a naive value raises ``ValueError``. Reading returns an aware UTC
|
|
44
|
+
value, including from SQLite, which stores no zone.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
impl = DateTime(timezone=True)
|
|
48
|
+
cache_ok = True
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def python_type(self) -> type[datetime]:
|
|
52
|
+
return datetime
|
|
53
|
+
|
|
54
|
+
def process_bind_param(
|
|
55
|
+
self, value: datetime | None, dialect: Dialect
|
|
56
|
+
) -> datetime | None:
|
|
57
|
+
if value is None:
|
|
58
|
+
return None
|
|
59
|
+
if value.tzinfo is None:
|
|
60
|
+
raise ValueError("UTCDateTime requires a timezone-aware datetime")
|
|
61
|
+
return value.astimezone(UTC)
|
|
62
|
+
|
|
63
|
+
def process_result_value(
|
|
64
|
+
self, value: datetime | None, dialect: Dialect
|
|
65
|
+
) -> datetime | None:
|
|
66
|
+
if value is None:
|
|
67
|
+
return None
|
|
68
|
+
if value.tzinfo is None:
|
|
69
|
+
return value.replace(tzinfo=UTC)
|
|
70
|
+
return value.astimezone(UTC)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _now() -> datetime:
|
|
74
|
+
return datetime.now(UTC)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class AuditMixin:
|
|
78
|
+
"""AIP-148 timestamps and the actors behind them.
|
|
79
|
+
|
|
80
|
+
``create_time`` and ``update_time`` default to the current UTC time, and
|
|
81
|
+
``update_time`` is refreshed on every ORM or Core update. ``created_by`` and
|
|
82
|
+
``updated_by`` are set by the caller; :func:`rn_forge.sqlalchemy.upsert` sets
|
|
83
|
+
all four.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
create_time: Mapped[datetime] = mapped_column(
|
|
87
|
+
UTCDateTime, default=_now, nullable=False
|
|
88
|
+
)
|
|
89
|
+
update_time: Mapped[datetime] = mapped_column(
|
|
90
|
+
UTCDateTime, default=_now, onupdate=_now, nullable=False
|
|
91
|
+
)
|
|
92
|
+
created_by: Mapped[str | None] = mapped_column(String(255), default=None)
|
|
93
|
+
updated_by: Mapped[str | None] = mapped_column(String(255), default=None)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class VersionMixin:
|
|
97
|
+
"""A ``version`` counter, starting at 1, for :func:`update_versioned`."""
|
|
98
|
+
|
|
99
|
+
version: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class SoftDeleteMixin:
|
|
103
|
+
"""A nullable, indexed ``delete_time``; ``None`` while the row is live (AIP-164).
|
|
104
|
+
|
|
105
|
+
Pair it with :class:`AuditMixin` for ``updated_by``. Nothing filters queries
|
|
106
|
+
implicitly: select live rows with :func:`live`.
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
delete_time: Mapped[datetime | None] = mapped_column(
|
|
110
|
+
UTCDateTime, default=None, index=True
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def live[T: Any](
|
|
115
|
+
stmt: Select[T], model: type[SoftDeleteMixin], *, show_deleted: bool = False
|
|
116
|
+
) -> Select[T]:
|
|
117
|
+
"""Return *stmt* restricted to live rows of *model*.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
stmt: The select to restrict.
|
|
121
|
+
model: A mapped class using :class:`SoftDeleteMixin`.
|
|
122
|
+
show_deleted: Return *stmt* unchanged, soft-deleted rows included.
|
|
123
|
+
"""
|
|
124
|
+
if show_deleted:
|
|
125
|
+
return stmt
|
|
126
|
+
return stmt.where(model.delete_time.is_(None))
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def soft_delete(
|
|
130
|
+
obj: SoftDeleteMixin, *, actor: str, now: datetime | None = None
|
|
131
|
+
) -> None:
|
|
132
|
+
"""Mark *obj* soft-deleted at *now* (default: the current UTC time).
|
|
133
|
+
|
|
134
|
+
Sets ``delete_time`` and ``updated_by``, and ``update_time`` on an
|
|
135
|
+
:class:`AuditMixin` row. Increments ``version`` on a :class:`VersionMixin`
|
|
136
|
+
row. Does not flush or commit.
|
|
137
|
+
"""
|
|
138
|
+
when = now or _now()
|
|
139
|
+
_stamp(obj, delete_time=when, actor=actor, when=when)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def undelete(obj: SoftDeleteMixin, *, actor: str, now: datetime | None = None) -> None:
|
|
143
|
+
"""Clear *obj*'s ``delete_time``, recording *actor* and *now*.
|
|
144
|
+
|
|
145
|
+
Sets ``updated_by``, ``update_time`` (an :class:`AuditMixin` row) and
|
|
146
|
+
``version`` (a :class:`VersionMixin` row) as :func:`soft_delete` does.
|
|
147
|
+
Does not flush or commit.
|
|
148
|
+
"""
|
|
149
|
+
_stamp(obj, delete_time=None, actor=actor, when=now or _now())
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _stamp(
|
|
153
|
+
obj: SoftDeleteMixin, *, delete_time: datetime | None, actor: str, when: datetime
|
|
154
|
+
) -> None:
|
|
155
|
+
obj.delete_time = delete_time
|
|
156
|
+
if isinstance(obj, AuditMixin):
|
|
157
|
+
obj.updated_by = actor
|
|
158
|
+
obj.update_time = when
|
|
159
|
+
if isinstance(obj, VersionMixin):
|
|
160
|
+
obj.version += 1
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Keyset pagination over :mod:`rn_forge.web`'s opaque page token.
|
|
2
|
+
|
|
3
|
+
``sqlakeyset`` is not adopted (checked 2026-09-23): its bookmark is its own
|
|
4
|
+
marker tuple, so adopting it would mean translating the token both ways to
|
|
5
|
+
replace a short predicate.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping, Sequence
|
|
11
|
+
from datetime import date, datetime
|
|
12
|
+
from typing import Any, cast
|
|
13
|
+
|
|
14
|
+
from rn_forge.web import (
|
|
15
|
+
Cursor,
|
|
16
|
+
InvalidCursor,
|
|
17
|
+
OrderField,
|
|
18
|
+
SortValue,
|
|
19
|
+
check_cursor_order,
|
|
20
|
+
encode_cursor,
|
|
21
|
+
format_order_by,
|
|
22
|
+
)
|
|
23
|
+
from sqlalchemy import ColumnElement, Select, and_, or_
|
|
24
|
+
|
|
25
|
+
__all__ = ["keyset", "next_page_token"]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def keyset[T: Select[Any]](
|
|
29
|
+
stmt: T,
|
|
30
|
+
*,
|
|
31
|
+
columns: Mapping[str, ColumnElement[Any]],
|
|
32
|
+
terms: Sequence[OrderField],
|
|
33
|
+
cursor: Cursor | None,
|
|
34
|
+
id_column: ColumnElement[Any],
|
|
35
|
+
) -> T:
|
|
36
|
+
"""Order *stmt* by every ``orderBy`` term and resume after *cursor*.
|
|
37
|
+
|
|
38
|
+
Rows are ordered by each term's column in turn, then by *id_column* in the
|
|
39
|
+
last term's direction (ascending with no terms), unless *id_column* is
|
|
40
|
+
already a term. Rows whose value is ``NULL`` come after those that have one,
|
|
41
|
+
in both directions, on every database. Term columns need not be unique and
|
|
42
|
+
may be nullable; *id_column* must not be.
|
|
43
|
+
|
|
44
|
+
Fetch ``page_size + 1`` rows from the result to learn whether another page
|
|
45
|
+
exists.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
stmt: The query to order and filter.
|
|
49
|
+
columns: Each allowed wire field name mapped to its column.
|
|
50
|
+
terms: The parsed ``orderBy``; pass the request's terms, empty when the
|
|
51
|
+
request gave none.
|
|
52
|
+
cursor: The decoded page token, or ``None`` for the first page.
|
|
53
|
+
id_column: The unique, non-null tiebreaker column.
|
|
54
|
+
|
|
55
|
+
Raises:
|
|
56
|
+
InvalidCursor: The token was issued for a different ``orderBy``, or its
|
|
57
|
+
values do not fit the columns.
|
|
58
|
+
"""
|
|
59
|
+
keys = [(columns[t.field], t.descending) for t in terms]
|
|
60
|
+
if not any(column is id_column for column, _ in keys):
|
|
61
|
+
keys.append((id_column, keys[-1][1] if keys else False))
|
|
62
|
+
if cursor is not None:
|
|
63
|
+
check_cursor_order(cursor, terms)
|
|
64
|
+
raw = [*cursor.sort_keys]
|
|
65
|
+
if len(raw) < len(keys):
|
|
66
|
+
raw.append(cursor.entity_id)
|
|
67
|
+
after = [_from_wire(column, value) for (column, _), value in zip(keys, raw)]
|
|
68
|
+
stmt = stmt.where(_after(keys, after, id_column))
|
|
69
|
+
ordered: list[ColumnElement[Any]] = []
|
|
70
|
+
for column, descending in keys:
|
|
71
|
+
if column is not id_column:
|
|
72
|
+
ordered.append(column.is_(None))
|
|
73
|
+
ordered.append(column.desc() if descending else column)
|
|
74
|
+
return stmt.order_by(*ordered)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _after(
|
|
78
|
+
keys: Sequence[tuple[ColumnElement[Any], bool]],
|
|
79
|
+
values: Sequence[Any],
|
|
80
|
+
id_column: ColumnElement[Any],
|
|
81
|
+
) -> ColumnElement[bool]:
|
|
82
|
+
"""The rows past *values*: for some term, every earlier one equal and it beyond."""
|
|
83
|
+
arms: list[ColumnElement[bool]] = []
|
|
84
|
+
for i, ((column, descending), value) in enumerate(zip(keys, values)):
|
|
85
|
+
if value is None:
|
|
86
|
+
if column is id_column:
|
|
87
|
+
raise InvalidCursor("Malformed page token", error_code=400)
|
|
88
|
+
continue # nothing follows inside the nulls
|
|
89
|
+
beyond = column < value if descending else column > value
|
|
90
|
+
if column is not id_column:
|
|
91
|
+
beyond = or_(beyond, column.is_(None))
|
|
92
|
+
equal = [
|
|
93
|
+
c.is_(None) if v is None else c == v
|
|
94
|
+
for (c, _), v in zip(keys[:i], values[:i])
|
|
95
|
+
]
|
|
96
|
+
arms.append(and_(*equal, beyond))
|
|
97
|
+
return or_(*arms)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def next_page_token(
|
|
101
|
+
row_values: Sequence[object], entity_id: object, terms: Sequence[OrderField]
|
|
102
|
+
) -> str:
|
|
103
|
+
"""Encode the token that resumes after the row with these values.
|
|
104
|
+
|
|
105
|
+
*row_values* is the last row's value in each term's column, one per term
|
|
106
|
+
(empty when *terms* is empty). Pass the same *terms* given to :func:`keyset`.
|
|
107
|
+
"""
|
|
108
|
+
return encode_cursor(
|
|
109
|
+
tuple(_to_wire(v) for v in row_values),
|
|
110
|
+
str(entity_id),
|
|
111
|
+
format_order_by(terms),
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _to_wire(value: object) -> SortValue:
|
|
116
|
+
if value is None or isinstance(value, str | int | float | bool):
|
|
117
|
+
return value
|
|
118
|
+
return value.isoformat() if isinstance(value, date) else str(value)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _from_wire(column: ColumnElement[Any], raw: SortValue) -> Any:
|
|
122
|
+
if raw is None:
|
|
123
|
+
return None
|
|
124
|
+
python_type: Any = column.type.python_type
|
|
125
|
+
try:
|
|
126
|
+
if python_type is datetime:
|
|
127
|
+
return datetime.fromisoformat(cast(str, raw))
|
|
128
|
+
if python_type is date:
|
|
129
|
+
return date.fromisoformat(cast(str, raw))
|
|
130
|
+
if isinstance(raw, bool) != (python_type is bool) or (
|
|
131
|
+
isinstance(raw, float) and python_type is int
|
|
132
|
+
):
|
|
133
|
+
raise TypeError(raw)
|
|
134
|
+
return python_type(raw)
|
|
135
|
+
except (ValueError, TypeError) as exc:
|
|
136
|
+
raise InvalidCursor("Malformed page token", error_code=400) from exc
|
|
File without changes
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Bulk create-or-update by natural key, on PostgreSQL and SQLite."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterator, Mapping, Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from rn_forge.sqlalchemy.models import AuditMixin, Base
|
|
11
|
+
from sqlalchemy import Table, select, tuple_
|
|
12
|
+
from sqlalchemy.dialects import postgresql, sqlite
|
|
13
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
14
|
+
|
|
15
|
+
__all__ = ["UpsertCounts", "upsert"]
|
|
16
|
+
|
|
17
|
+
# SQLite's bound-parameter limit is 999 before 3.32.
|
|
18
|
+
_MAX_PARAMETERS = 900
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class UpsertCounts:
|
|
23
|
+
"""How many input rows :func:`upsert` created, updated and left unchanged."""
|
|
24
|
+
|
|
25
|
+
created: int
|
|
26
|
+
updated: int
|
|
27
|
+
skipped: int
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
async def upsert(
|
|
31
|
+
session: AsyncSession,
|
|
32
|
+
model: type[Base],
|
|
33
|
+
rows: Sequence[Mapping[str, Any]],
|
|
34
|
+
*,
|
|
35
|
+
key: Sequence[str],
|
|
36
|
+
fields: Sequence[str],
|
|
37
|
+
actor: str,
|
|
38
|
+
) -> UpsertCounts:
|
|
39
|
+
"""Create the rows whose *key* is absent and update those whose *fields* differ.
|
|
40
|
+
|
|
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.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
session: An ``AsyncSession`` on PostgreSQL or SQLite.
|
|
50
|
+
model: A model using :class:`~rn_forge.sqlalchemy.AuditMixin`.
|
|
51
|
+
rows: One mapping per row, holding every column in *key* and *fields*.
|
|
52
|
+
key: The natural-key columns.
|
|
53
|
+
fields: The non-key columns to write.
|
|
54
|
+
actor: Stamped into ``created_by`` and ``updated_by``.
|
|
55
|
+
|
|
56
|
+
Raises:
|
|
57
|
+
ValueError: A row lacks a column, or two rows share a key.
|
|
58
|
+
TypeError: *model* does not use ``AuditMixin``.
|
|
59
|
+
NotImplementedError: The session's dialect is not PostgreSQL or SQLite.
|
|
60
|
+
"""
|
|
61
|
+
if not issubclass(model, AuditMixin):
|
|
62
|
+
raise TypeError(f"{model.__name__} must use AuditMixin")
|
|
63
|
+
columns = [*key, *fields]
|
|
64
|
+
keyed = _keyed(rows, key, columns)
|
|
65
|
+
dialect = session.get_bind().dialect.name
|
|
66
|
+
if dialect not in ("postgresql", "sqlite"):
|
|
67
|
+
raise NotImplementedError(f"upsert does not support {dialect}")
|
|
68
|
+
|
|
69
|
+
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)
|
|
72
|
+
if to_write:
|
|
73
|
+
insert = (postgresql if dialect == "postgresql" else sqlite).insert(table)
|
|
74
|
+
statement = insert.on_conflict_do_update(
|
|
75
|
+
index_elements=list(key),
|
|
76
|
+
set_={
|
|
77
|
+
name: insert.excluded[name]
|
|
78
|
+
for name in (*fields, "update_time", "updated_by")
|
|
79
|
+
},
|
|
80
|
+
)
|
|
81
|
+
await session.execute(statement, to_write)
|
|
82
|
+
return UpsertCounts(created, updated, len(keyed) - created - updated)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _keyed(
|
|
86
|
+
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]] = {}
|
|
89
|
+
for row in rows:
|
|
90
|
+
if missing := [c for c in columns if c not in row]:
|
|
91
|
+
raise ValueError(f"row lacks columns {missing}")
|
|
92
|
+
identity = tuple(row[k] for k in key)
|
|
93
|
+
if identity in keyed:
|
|
94
|
+
raise ValueError(f"duplicate key {identity}")
|
|
95
|
+
keyed[identity] = row
|
|
96
|
+
return keyed
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _changes(
|
|
100
|
+
keyed: Mapping[tuple[Any, ...], Mapping[str, Any]],
|
|
101
|
+
existing: Mapping[tuple[Any, ...], Mapping[str, Any]],
|
|
102
|
+
columns: Sequence[str],
|
|
103
|
+
fields: Sequence[str],
|
|
104
|
+
actor: str,
|
|
105
|
+
) -> tuple[list[dict[str, Any]], int, int]:
|
|
106
|
+
"""The rows to write, with how many of them are creations and updates."""
|
|
107
|
+
to_write: list[dict[str, Any]] = []
|
|
108
|
+
created = updated = 0
|
|
109
|
+
now = datetime.now(UTC)
|
|
110
|
+
for identity, row in keyed.items():
|
|
111
|
+
current = existing.get(identity)
|
|
112
|
+
if current is not None and all(row[f] == current[f] for f in fields):
|
|
113
|
+
continue
|
|
114
|
+
if current is None:
|
|
115
|
+
created += 1
|
|
116
|
+
else:
|
|
117
|
+
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
|
+
)
|
|
127
|
+
return to_write, created, updated
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
async def _existing(
|
|
131
|
+
session: AsyncSession,
|
|
132
|
+
table: Table,
|
|
133
|
+
key: Sequence[str],
|
|
134
|
+
fields: Sequence[str],
|
|
135
|
+
identities: list[tuple[Any, ...]],
|
|
136
|
+
) -> dict[tuple[Any, ...], Mapping[str, Any]]:
|
|
137
|
+
key_columns = [table.c[k] for k in key]
|
|
138
|
+
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)
|
|
150
|
+
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]
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rn-forge-sqlalchemy
|
|
3
|
+
Version: 0.2.2
|
|
4
|
+
Summary: Async SQLAlchemy models, upsert and keyset pagination over rn-forge-web
|
|
5
|
+
Author: Rohit Narayanan
|
|
6
|
+
Author-email: Rohit Narayanan <rohit.nn@gmail.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Dist: rn-forge-web>=0.3.0,<0.4
|
|
17
|
+
Requires-Dist: sqlalchemy[asyncio]>=2.0
|
|
18
|
+
Requires-Python: >=3.14
|
|
19
|
+
Project-URL: Documentation, https://rn-forge.github.io/pykit/packages/rn-forge-sqlalchemy/latest/
|
|
20
|
+
Project-URL: Source, https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-sqlalchemy
|
|
21
|
+
Project-URL: Changelog, https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-sqlalchemy/CHANGELOG.md
|
|
22
|
+
Project-URL: Issues, https://github.com/rn-forge/pykit/issues
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# rn-forge-sqlalchemy
|
|
26
|
+
|
|
27
|
+
[Documentation](https://rn-forge.github.io/pykit/packages/rn-forge-sqlalchemy/latest/)
|
|
28
|
+
·
|
|
29
|
+
[Changelog](https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-sqlalchemy/CHANGELOG.md)
|
|
30
|
+
·
|
|
31
|
+
[Source](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-sqlalchemy)
|
|
32
|
+
· [All pykit packages](https://rn-forge.github.io/pykit/)
|
|
33
|
+
|
|
34
|
+
Async SQLAlchemy building blocks that match the `rn-forge-web` wire: audit and
|
|
35
|
+
version columns, a bulk upsert for imports, and keyset pagination over web's
|
|
36
|
+
opaque page token.
|
|
37
|
+
|
|
38
|
+
| Module | What it holds |
|
|
39
|
+
| -- | -- |
|
|
40
|
+
| `models` | `Base` (Alembic naming convention), `UTCDateTime`, `AuditMixin` (`create_time`, `update_time`, `created_by`, `updated_by`), `VersionMixin` |
|
|
41
|
+
| `concurrency` | `update_versioned` — optimistic concurrency, raising `rn_forge.web.VersionConflict` (412) |
|
|
42
|
+
| `upsert` | `upsert` — create or update rows by natural key, counting created, updated and skipped |
|
|
43
|
+
| `pagination` | `keyset`, `next_page_token` — AIP-132 `orderBy` and AIP-158 tokens over a `Select` |
|
|
44
|
+
|
|
45
|
+
Everything works on **PostgreSQL and SQLite**, through `AsyncSession` only.
|
|
46
|
+
|
|
47
|
+
## Where it sits
|
|
48
|
+
|
|
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
|
|
58
|
+
framework itself: the FastAPI guide shows the import and list endpoints.
|
|
59
|
+
|
|
60
|
+
## Installation
|
|
61
|
+
|
|
62
|
+
Require the packages by version range:
|
|
63
|
+
|
|
64
|
+
```toml
|
|
65
|
+
dependencies = [
|
|
66
|
+
"rn-forge-sqlalchemy>=0.2,<0.3",
|
|
67
|
+
"rn-forge-web>=0.3,<0.4",
|
|
68
|
+
]
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Application code catches `rn_forge.web.VersionConflict` and passes
|
|
72
|
+
`rn_forge.web` pagination terms, so declare `rn-forge-web` as well.
|
|
73
|
+
|
|
74
|
+
No database driver is declared. Add `asyncpg` for PostgreSQL or `aiosqlite` for
|
|
75
|
+
SQLite.
|
|
76
|
+
|
|
77
|
+
## Testing
|
|
78
|
+
|
|
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
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
The default run uses SQLite. Tests marked `postgres` run only when the DSN is
|
|
86
|
+
set.
|
|
87
|
+
|
|
88
|
+
## Not included
|
|
89
|
+
|
|
90
|
+
The SQL idempotency store, session and unit-of-work helpers, readiness checks
|
|
91
|
+
and multi-tenant scoping wait for an application that needs them.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
rn_forge/sqlalchemy/__init__.py,sha256=g2Dr3TJ1MT83qzxpHevzSa6xS7RrNqYbPgGoqZ7OonA,738
|
|
2
|
+
rn_forge/sqlalchemy/concurrency.py,sha256=cfZB0lo_0wI6WMiy6w8ziPNCVgziNH2me95RE-Cn-og,2167
|
|
3
|
+
rn_forge/sqlalchemy/models.py,sha256=eBUvjW9hs-whlzqDYpoLga2SF41YbabRaSLoNCb48dM,4977
|
|
4
|
+
rn_forge/sqlalchemy/pagination.py,sha256=b9rMW0jpQ-z-a0t-0aOmeyuRcRykmE_yqi4mXwAysMs,4909
|
|
5
|
+
rn_forge/sqlalchemy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
rn_forge/sqlalchemy/upsert.py,sha256=3ZOHar03Lsewd5QI8IIljOZhGI_7V12gfDXn9ojdkRk,5534
|
|
7
|
+
rn_forge_sqlalchemy-0.2.2.dist-info/licenses/LICENSE,sha256=buwykOASkbZdpj0j_JmFbwNzbUiuLzOiaMQmVQt5lr8,1072
|
|
8
|
+
rn_forge_sqlalchemy-0.2.2.dist-info/WHEEL,sha256=3NO1oYsF7mANFUWVdyEQLM-zmecczWWEmmF5rEbXrWk,80
|
|
9
|
+
rn_forge_sqlalchemy-0.2.2.dist-info/METADATA,sha256=E5PZ6VcwoQu6AB2Aq3tqaZX8H9BYT_rk_tSz8B6d5_0,3480
|
|
10
|
+
rn_forge_sqlalchemy-0.2.2.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Rohit Narayanan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|