resource-engine-sqlalchemy 0.1.0__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.
@@ -0,0 +1,83 @@
1
+ """Idempotency records for SQLAlchemy: one row per caller and key."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from typing import override
7
+
8
+ from resource_engine.ports.idempotency import IdempotencyRecord, IdempotencyStore
9
+ from sqlalchemy import JSON, Column, DateTime, MetaData, String, Table, delete, select
10
+ from sqlalchemy.ext.asyncio import AsyncSession
11
+
12
+ DEFAULT_TABLE = "resource_engine_idempotency"
13
+
14
+
15
+ def idempotency_table(metadata: MetaData, name: str = DEFAULT_TABLE) -> Table:
16
+ """Declare the idempotency table. Its primary key ``(scope, key)`` is what
17
+ stops two racing requests with one key from both committing."""
18
+ return Table(
19
+ name,
20
+ metadata,
21
+ Column("scope", String(300), primary_key=True),
22
+ Column("key", String(255), primary_key=True),
23
+ Column("fingerprint", String(64), nullable=False),
24
+ Column("resource", String(200), nullable=False),
25
+ Column("operation", String(50), nullable=False),
26
+ Column("result", JSON, nullable=False),
27
+ Column("created_at", DateTime(timezone=True), nullable=False),
28
+ Column("expires_at", DateTime(timezone=True), nullable=False, index=True),
29
+ )
30
+
31
+
32
+ class SqlAlchemyIdempotency(IdempotencyStore):
33
+ """Idempotency records in a SQL table, in the unit of work's session."""
34
+
35
+ def __init__(self, session: AsyncSession, table: Table) -> None:
36
+ self.session = session
37
+ self.table = table
38
+
39
+ @override
40
+ async def get(self, scope: str, key: str) -> IdempotencyRecord | None:
41
+ t = self.table
42
+ row = (
43
+ (await self.session.execute(select(t).where(t.c.scope == scope, t.c.key == key)))
44
+ .mappings()
45
+ .first()
46
+ )
47
+ return IdempotencyRecord(**row) if row else None
48
+
49
+ @override
50
+ async def put(self, record: IdempotencyRecord) -> None:
51
+ t = self.table
52
+ # an expired record with the same key may still be there: replace it
53
+ await self.session.execute(
54
+ delete(t).where(
55
+ t.c.scope == record.scope,
56
+ t.c.key == record.key,
57
+ t.c.expires_at <= record.created_at,
58
+ )
59
+ )
60
+ await self.session.execute(
61
+ t.insert().values(
62
+ scope=record.scope,
63
+ key=record.key,
64
+ fingerprint=record.fingerprint,
65
+ resource=record.resource,
66
+ operation=record.operation,
67
+ result=dict(record.result),
68
+ created_at=record.created_at,
69
+ expires_at=record.expires_at,
70
+ )
71
+ )
72
+
73
+ @override
74
+ async def purge(self, before: datetime, limit: int) -> int:
75
+ t = self.table
76
+ keys = (
77
+ await self.session.execute(
78
+ select(t.c.scope, t.c.key).where(t.c.expires_at < before).limit(limit)
79
+ )
80
+ ).all()
81
+ for scope, key in keys:
82
+ await self.session.execute(delete(t).where(t.c.scope == scope, t.c.key == key))
83
+ return len(keys)
@@ -0,0 +1,74 @@
1
+ """Inbox table for idempotent consumers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from datetime import UTC, datetime
7
+ from typing import override
8
+
9
+ from resource_engine.ports.messaging import InboxStore
10
+ from sqlalchemy import Column, DateTime, MetaData, String, Table, delete, select, tuple_
11
+ from sqlalchemy.ext.asyncio import AsyncSession
12
+
13
+ DEFAULT_TABLE = "resource_engine_inbox"
14
+
15
+
16
+ def inbox_table(metadata: MetaData, name: str = DEFAULT_TABLE) -> Table:
17
+ """Declare the inbox table on your metadata (and create it with your migrations).
18
+
19
+ Rows older than the broker's maximum redelivery window can go:
20
+ ``MessagingJanitor`` deletes them.
21
+ """
22
+ return Table(
23
+ name,
24
+ metadata,
25
+ Column("consumer", String(200), primary_key=True),
26
+ Column("message_id", String(64), primary_key=True),
27
+ Column("processed_at", DateTime(timezone=True), nullable=False, index=True),
28
+ )
29
+
30
+
31
+ class SqlAlchemyInbox(InboxStore):
32
+ """The inbox in a SQL table: processed message ids per consumer, in the unit of work's
33
+ session."""
34
+
35
+ def __init__(self, session: AsyncSession, table: Table) -> None:
36
+ self.session = session
37
+ self.table = table
38
+
39
+ @override
40
+ async def processed(self, consumer: str, message_ids: Sequence[str]) -> set[str]:
41
+ if not message_ids:
42
+ return set()
43
+ stmt = select(self.table.c.message_id).where(
44
+ self.table.c.consumer == consumer, self.table.c.message_id.in_(list(message_ids))
45
+ )
46
+ return set((await self.session.scalars(stmt)).all())
47
+
48
+ @override
49
+ async def mark_processed(self, consumer: str, message_ids: Sequence[str]) -> None:
50
+ new = [i for i in message_ids if i not in await self.processed(consumer, message_ids)]
51
+ if new:
52
+ now = datetime.now(UTC)
53
+ await self.session.execute(
54
+ self.table.insert(),
55
+ [{"consumer": consumer, "message_id": i, "processed_at": now} for i in new],
56
+ )
57
+
58
+ @override
59
+ async def purge(self, before: datetime, limit: int) -> int:
60
+ t = self.table
61
+ keys = (
62
+ await self.session.execute(
63
+ select(t.c.consumer, t.c.message_id)
64
+ .where(t.c.processed_at < before)
65
+ .order_by(t.c.processed_at)
66
+ .limit(limit)
67
+ )
68
+ ).all()
69
+ if not keys:
70
+ return 0
71
+ await self.session.execute(
72
+ delete(t).where(tuple_(t.c.consumer, t.c.message_id).in_([tuple(k) for k in keys]))
73
+ )
74
+ return len(keys)
@@ -0,0 +1,68 @@
1
+ """Lease table for ``LockProvider``: one row per lock name."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import UTC, datetime, timedelta
6
+ from typing import Any, cast, override
7
+
8
+ from resource_engine.ports.locks import LockProvider
9
+ from sqlalchemy import Column, DateTime, MetaData, String, Table, delete, insert, update
10
+ from sqlalchemy.engine import CursorResult
11
+ from sqlalchemy.exc import IntegrityError
12
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
13
+
14
+ DEFAULT_TABLE = "resource_engine_locks"
15
+
16
+
17
+ def locks_table(metadata: MetaData, name: str = DEFAULT_TABLE) -> Table:
18
+ """Declare the lease table on your metadata (and create it with your migrations)."""
19
+ return Table(
20
+ name,
21
+ metadata,
22
+ Column("name", String(200), primary_key=True),
23
+ Column("owner", String(200), nullable=False),
24
+ Column("expires_at", DateTime(timezone=True), nullable=False),
25
+ )
26
+
27
+
28
+ class SqlAlchemyLocks(LockProvider):
29
+ """``LockProvider`` on a lease table, in its own short transactions.
30
+
31
+ Taking a lease is one conditional ``UPDATE`` (free, expired or ours) and,
32
+ when no row exists yet, an ``INSERT`` guarded by the primary key, so two
33
+ workers never both win. Works on any database SQLAlchemy supports.
34
+ """
35
+
36
+ def __init__(self, session_factory: async_sessionmaker[AsyncSession], table: Table) -> None:
37
+ self.session_factory = session_factory
38
+ self.table = table
39
+
40
+ @override
41
+ async def acquire(self, name: str, owner: str, ttl: timedelta) -> bool:
42
+ now = datetime.now(UTC)
43
+ t = self.table
44
+ async with self.session_factory() as session:
45
+ result = await session.execute(
46
+ update(t)
47
+ .where(t.c.name == name, (t.c.expires_at < now) | (t.c.owner == owner))
48
+ .values(owner=owner, expires_at=now + ttl)
49
+ )
50
+ if cast("CursorResult[Any]", result).rowcount == 1:
51
+ await session.commit()
52
+ return True
53
+ try:
54
+ await session.execute(
55
+ insert(t).values(name=name, owner=owner, expires_at=now + ttl)
56
+ )
57
+ await session.commit()
58
+ except IntegrityError: # held by someone else
59
+ await session.rollback()
60
+ return False
61
+ return True
62
+
63
+ @override
64
+ async def release(self, name: str, owner: str) -> None:
65
+ t = self.table
66
+ async with self.session_factory() as session:
67
+ await session.execute(delete(t).where(t.c.name == name, t.c.owner == owner))
68
+ await session.commit()
@@ -0,0 +1,214 @@
1
+ """Check that migrations upgrade databases that hold data, not only empty ones.
2
+
3
+ ```python
4
+ from alembic.config import Config
5
+ from resource_engine_sqlalchemy.migration_checks import check_upgrades
6
+
7
+ report = check_upgrades(Config("alembic.ini"), "postgresql+psycopg://.../scratch")
8
+ ```
9
+
10
+ ``check_upgrades`` walks the revisions from the first to the head, one at a
11
+ time. After each upgrade it adds rows to every table, generated from the
12
+ reflected columns (foreign keys point at existing rows), and checks that every
13
+ row added before is still there: a migration that drops, truncates or
14
+ rewrites data, or that fails on non-empty tables (a ``NOT NULL`` column
15
+ without a default, a new unique constraint), fails the check. With
16
+ ``downgrade=True`` it then goes back to the base one revision at a time, with
17
+ the data in place.
18
+
19
+ Each revision is a state a production database may be in. Once there are
20
+ releases, also start from each released revision (``start=``).
21
+
22
+ The database must be a scratch one: the check creates and drops everything.
23
+ Use the URL the application's ``env.py`` reads (``DATABASE_URL``); pass the
24
+ synchronous URL for the inspection when the application's is async.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import datetime as dt
30
+ import decimal
31
+ import os
32
+ import uuid
33
+ from collections.abc import Iterator
34
+ from dataclasses import dataclass, field
35
+ from typing import Any
36
+
37
+ from sqlalchemy import MetaData, Table, create_engine, insert, select, types
38
+ from sqlalchemy.engine import Connection
39
+
40
+ #: Tables the check leaves alone.
41
+ SKIPPED = frozenset({"alembic_version"})
42
+
43
+
44
+ @dataclass
45
+ class UpgradeReport:
46
+ """What ``check_upgrades`` did: the revisions in order, and the rows kept
47
+ per table at the head."""
48
+
49
+ revisions: list[str] = field(default_factory=list)
50
+ rows: dict[str, int] = field(default_factory=dict)
51
+ downgraded: bool = False
52
+
53
+
54
+ class DataLost(AssertionError):
55
+ """An upgrade lost rows that were there before it."""
56
+
57
+
58
+ def check_upgrades(
59
+ config: Any,
60
+ url: str,
61
+ *,
62
+ sync_url: str | None = None,
63
+ rows: int = 2,
64
+ start: str = "base",
65
+ downgrade: bool = True,
66
+ env: str = "DATABASE_URL",
67
+ ) -> UpgradeReport:
68
+ """Upgrade ``url`` revision by revision with data in every table (see the
69
+ module docstring). Raises ``DataLost`` when an upgrade loses rows, and
70
+ whatever the migration raises when it fails on data."""
71
+ from alembic import command
72
+ from alembic.script import ScriptDirectory
73
+
74
+ previous = os.environ.get(env)
75
+ os.environ[env] = url
76
+ engine = create_engine(sync_url or url)
77
+ report = UpgradeReport()
78
+ try:
79
+ script = ScriptDirectory.from_config(config)
80
+ path = [rev.revision for rev in reversed(list(script.walk_revisions("base", "heads")))]
81
+ if start != "base":
82
+ command.upgrade(config, start)
83
+ path = path[path.index(script.get_revision(start).revision) + 1 :]
84
+ kept: dict[str, set[tuple[Any, ...]]] = {}
85
+ counter = iter(range(1, 10**9))
86
+ for revision in path:
87
+ command.upgrade(config, revision)
88
+ report.revisions.append(revision)
89
+ with engine.begin() as conn:
90
+ metadata = MetaData()
91
+ metadata.reflect(conn)
92
+ _still_there(conn, metadata, kept, revision)
93
+ for table in _in_dependency_order(metadata):
94
+ added = _fill(conn, table, rows, counter)
95
+ kept.setdefault(table.name, set()).update(added)
96
+ with engine.begin() as conn:
97
+ metadata = MetaData()
98
+ metadata.reflect(conn)
99
+ for table in metadata.sorted_tables:
100
+ if table.name not in SKIPPED:
101
+ report.rows[table.name] = len(_keys(conn, table))
102
+ if downgrade:
103
+ for _ in report.revisions: # one revision at a time, data in place
104
+ command.downgrade(config, "-1")
105
+ report.downgraded = True
106
+ finally:
107
+ engine.dispose()
108
+ if previous is None:
109
+ os.environ.pop(env, None)
110
+ else:
111
+ os.environ[env] = previous
112
+ return report
113
+
114
+
115
+ def _still_there(
116
+ conn: Connection, metadata: MetaData, kept: dict[str, set[tuple[Any, ...]]], revision: str
117
+ ) -> None:
118
+ for name, keys in kept.items():
119
+ table = metadata.tables.get(name)
120
+ if table is None:
121
+ continue # dropped by the migration, on purpose
122
+ missing = keys - _keys(conn, table)
123
+ if missing:
124
+ raise DataLost(
125
+ f"after {revision}, {len(missing)} of {len(keys)} rows of {name} are gone"
126
+ )
127
+
128
+
129
+ def _keys(conn: Connection, table: Table) -> set[tuple[Any, ...]]:
130
+ columns = list(table.primary_key.columns) or list(table.columns)
131
+ return {tuple(r) for r in conn.execute(select(*columns))}
132
+
133
+
134
+ def _in_dependency_order(metadata: MetaData) -> Iterator[Table]:
135
+ for table in metadata.sorted_tables: # referenced tables first
136
+ if table.name not in SKIPPED:
137
+ yield table
138
+
139
+
140
+ def _fill(conn: Connection, table: Table, count: int, counter: Iterator[int]) -> set[Any]:
141
+ """Insert up to ``count`` generated rows; returns their keys. Each row is
142
+ its own savepoint: one a unique constraint refuses is left out."""
143
+ from sqlalchemy.exc import IntegrityError
144
+
145
+ keys: set[tuple[Any, ...]] = set()
146
+ pk = list(table.primary_key.columns) or list(table.columns)
147
+ for _ in range(count):
148
+ n = next(counter)
149
+ values: dict[str, Any] = {}
150
+ for column in table.columns:
151
+ if column.primary_key and column.autoincrement is True and _integer(column):
152
+ continue
153
+ fk = next(iter(column.foreign_keys), None)
154
+ if fk is not None:
155
+ target = None if fk.column.table is table else _pick(conn, fk.column, n)
156
+ if target is None and not column.nullable:
157
+ return keys # nothing to point at yet: leave the table empty
158
+ values[column.name] = target
159
+ continue
160
+ values[column.name] = _value(column, n)
161
+ try:
162
+ with conn.begin_nested():
163
+ result = conn.execute(insert(table).values(**values))
164
+ except IntegrityError:
165
+ continue
166
+ inserted = result.inserted_primary_key
167
+ if inserted is not None and all(v is not None for v in inserted):
168
+ keys.add(tuple(inserted))
169
+ else:
170
+ keys.add(tuple(values.get(c.name) for c in pk))
171
+ return keys
172
+
173
+
174
+ def _pick(conn: Connection, column: Any, n: int) -> Any:
175
+ """An existing value of the referenced ``column``, a different one for each ``n``."""
176
+ values = [row[0] for row in conn.execute(select(column).distinct().order_by(column))]
177
+ return values[n % len(values)] if values else None
178
+
179
+
180
+ def _integer(column: Any) -> bool:
181
+ return isinstance(column.type, types.Integer)
182
+
183
+
184
+ def _value(column: Any, n: int) -> Any:
185
+ kind = column.type
186
+ try:
187
+ python = kind.python_type
188
+ except NotImplementedError:
189
+ python = str
190
+ if isinstance(kind, types.Enum) and kind.enums:
191
+ return kind.enums[0]
192
+ if isinstance(kind, types.Boolean) or python is bool:
193
+ return False
194
+ if isinstance(kind, types.Integer) or python is int:
195
+ return n
196
+ if isinstance(kind, types.Numeric) or python in (float, decimal.Decimal):
197
+ return decimal.Decimal(n) if python is decimal.Decimal else float(n)
198
+ if isinstance(kind, types.DateTime) or python is dt.datetime:
199
+ moment = dt.datetime(2026, 1, 1, 12, 0) + dt.timedelta(seconds=n)
200
+ return moment.replace(tzinfo=dt.UTC) if getattr(kind, "timezone", False) else moment
201
+ if isinstance(kind, types.Date) or python is dt.date:
202
+ return dt.date(2026, 1, 1) + dt.timedelta(days=n)
203
+ if isinstance(kind, types.JSON) or python in (dict, list):
204
+ return {"n": n}
205
+ if isinstance(kind, types.LargeBinary) or python is bytes:
206
+ return b"x%d" % n
207
+ if isinstance(kind, types.Uuid) or python is uuid.UUID:
208
+ return uuid.UUID(int=n)
209
+ text = f"v{n}"
210
+ length = getattr(kind, "length", None)
211
+ return text[:length] if length else text
212
+
213
+
214
+ __all__ = ["DataLost", "UpgradeReport", "check_upgrades"]
@@ -0,0 +1,104 @@
1
+ """Alembic integration (``pip install resource-engine-sqlalchemy[alembic]``).
2
+
3
+ ``resource-engine db init`` writes an ``env.py`` that is three lines::
4
+
5
+ from alembic import context
6
+ from resource_engine_sqlalchemy.migrations import run_migrations
7
+ from billing.infrastructure.persistence import metadata
8
+
9
+ run_migrations(context, metadata)
10
+
11
+ ``run_migrations`` runs offline (``alembic upgrade --sql``) or online with an
12
+ async engine, from ``DATABASE_URL`` or ``sqlalchemy.url`` in ``alembic.ini``.
13
+ SQLite gets ``render_as_batch`` (it cannot ``ALTER`` most things in place) and
14
+ every database ``compare_type``, so autogenerate notices type changes.
15
+ PostgreSQL also gets ``alembic-postgresql-enum`` (in the ``[alembic]`` extra):
16
+ Alembic alone doesn't notice values added to or removed from an ``Enum``, and
17
+ leaves enum types behind when their table is dropped; with it, autogenerate
18
+ writes the ``ALTER TYPE`` statements and ``alembic check`` sees the change.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import asyncio
24
+ import os
25
+ from typing import Any
26
+
27
+ from sqlalchemy import MetaData, pool
28
+ from sqlalchemy.engine import Connection, make_url
29
+ from sqlalchemy.ext.asyncio import async_engine_from_config
30
+
31
+ #: Environment variable read before ``sqlalchemy.url`` in ``alembic.ini``.
32
+ URL_VARIABLE = "DATABASE_URL"
33
+
34
+
35
+ def database_url(context: Any) -> str:
36
+ """The database URL for Alembic: ``DATABASE_URL``, else ``sqlalchemy.url`` in alembic.ini."""
37
+ url = os.getenv(URL_VARIABLE) or context.config.get_main_option("sqlalchemy.url")
38
+ if not url:
39
+ raise RuntimeError(f"No database URL: set {URL_VARIABLE} or sqlalchemy.url in alembic.ini")
40
+ return url
41
+
42
+
43
+ def context_options(dialect_name: str) -> dict[str, Any]:
44
+ """Options for ``context.configure`` that suit the engine's tables."""
45
+ if dialect_name == "postgresql":
46
+ enable_postgresql_enums()
47
+ return {"render_as_batch": dialect_name == "sqlite", "compare_type": True}
48
+
49
+
50
+ def enable_postgresql_enums() -> bool:
51
+ """Register ``alembic-postgresql-enum`` with Alembic's autogenerate (its
52
+ import is the registration). ``False`` when it isn't installed."""
53
+ try:
54
+ import alembic_postgresql_enum # noqa: F401
55
+ except ImportError:
56
+ return False
57
+ return True
58
+
59
+
60
+ def run_migrations(context: Any, metadata: MetaData, *, url: str | None = None) -> None:
61
+ """Run Alembic for ``metadata`` (call it from ``env.py``)."""
62
+ url = url or database_url(context)
63
+ if context.is_offline_mode():
64
+ context.configure(
65
+ url=url,
66
+ target_metadata=metadata,
67
+ literal_binds=True,
68
+ dialect_opts={"paramstyle": "named"},
69
+ **context_options(make_url(url).get_backend_name()),
70
+ )
71
+ with context.begin_transaction():
72
+ context.run_migrations()
73
+ return
74
+ asyncio.run(_run_online(context, metadata, url))
75
+
76
+
77
+ async def _run_online(context: Any, metadata: MetaData, url: str) -> None:
78
+ section = dict(context.config.get_section(context.config.config_ini_section, {}))
79
+ section["sqlalchemy.url"] = url
80
+ engine = async_engine_from_config(section, prefix="sqlalchemy.", poolclass=pool.NullPool)
81
+ try:
82
+ async with engine.connect() as connection:
83
+ await connection.run_sync(_run_sync, context, metadata)
84
+ finally:
85
+ await engine.dispose()
86
+
87
+
88
+ def _run_sync(connection: Connection, context: Any, metadata: MetaData) -> None:
89
+ context.configure(
90
+ connection=connection,
91
+ target_metadata=metadata,
92
+ **context_options(connection.dialect.name),
93
+ )
94
+ with context.begin_transaction():
95
+ context.run_migrations()
96
+
97
+
98
+ __all__ = [
99
+ "URL_VARIABLE",
100
+ "context_options",
101
+ "database_url",
102
+ "enable_postgresql_enums",
103
+ "run_migrations",
104
+ ]