rn-forge-sqlalchemy 0.2.3__tar.gz → 0.2.5__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.5
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>
@@ -16,12 +16,19 @@ Classifier: Typing :: Typed
16
16
  Requires-Dist: rn-forge-web>=0.3.0,<0.4
17
17
  Requires-Dist: sqlalchemy[asyncio]>=2.0
18
18
  Requires-Dist: alembic>=1.20.1 ; extra == 'migrations'
19
+ Requires-Dist: asyncpg>=0.32.0 ; extra == 'postgres'
20
+ Requires-Dist: aiosqlite>=0.22.1 ; extra == 'sqlite'
21
+ Requires-Dist: pytest>=9.1.1 ; extra == 'testing'
22
+ Requires-Dist: pytest-asyncio>=1.4.1.post1 ; extra == 'testing'
19
23
  Requires-Python: >=3.14
20
24
  Project-URL: Documentation, https://rn-forge.github.io/pykit/packages/rn-forge-sqlalchemy/latest/
21
25
  Project-URL: Source, https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-sqlalchemy
22
26
  Project-URL: Changelog, https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-sqlalchemy/CHANGELOG.md
23
27
  Project-URL: Issues, https://github.com/rn-forge/pykit/issues
24
28
  Provides-Extra: migrations
29
+ Provides-Extra: postgres
30
+ Provides-Extra: sqlite
31
+ Provides-Extra: testing
25
32
  Description-Content-Type: text/markdown
26
33
 
27
34
  # rn-forge-sqlalchemy
@@ -39,9 +46,11 @@ opaque page token.
39
46
 
40
47
  | Module | What it holds |
41
48
  | -- | -- |
42
- | `models` | `Base` (Alembic naming convention), `UTCDateTime`, `AuditMixin` (`create_time`, `update_time`, `created_by`, `updated_by`), `VersionMixin` |
49
+ | `models` | `Base` (Alembic naming convention), `UTCDateTime`, `AuditMixin` (`create_time`, `update_time`, `created_by`, `updated_by`), `VersionMixin`, `SoftDeleteMixin`, `live`, `soft_delete`, `undelete` |
43
50
  | `concurrency` | `update_versioned` — optimistic concurrency, raising `rn_forge.web.VersionConflict` (412) |
44
51
  | `upsert` | `upsert` — create or update rows by natural key, counting created, updated and skipped |
52
+ | `postgres` | `create_postgres_engine` — an async PostgreSQL engine (asyncpg) with UTC sessions, pool settings and an optional statement timeout and application name |
53
+ | `testing` | `postgres_schema` — a pytest plugin whose fixture gives each test its own PostgreSQL schema; needs the `testing` and `postgres` extras and is loaded with `pytest_plugins`, not imported from the facade |
45
54
  | `sqlite` | `create_sqlite_engine` — an async SQLite engine with WAL, foreign keys, busy timeout and `synchronous` set on every connection |
46
55
  | `migrate` | `run_migrations` — Alembic `upgrade` from inside the process; needs the `migrations` extra and is imported directly, not from the facade |
47
56
  | `pagination` | `keyset`, `next_page_token` — AIP-132 `orderBy` and AIP-158 tokens over a `Select` |
@@ -50,15 +59,8 @@ Everything works on **PostgreSQL and SQLite**, through `AsyncSession` only.
50
59
 
51
60
  ## Where it sits
52
61
 
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
62
+ It depends on `rn-forge-web` and SQLAlchemy and imports no web framework or
63
+ framework package; `task lint` proves it. An application wires it to its
62
64
  framework itself: the FastAPI guide shows the import and list endpoints.
63
65
 
64
66
  ## Installation
@@ -75,22 +77,40 @@ dependencies = [
75
77
  Application code catches `rn_forge.web.VersionConflict` and passes
76
78
  `rn_forge.web` pagination terms, so declare `rn-forge-web` as well.
77
79
 
78
- No database driver is declared. Add `asyncpg` for PostgreSQL or `aiosqlite` for
79
- SQLite.
80
+ The core install carries no database driver.
81
+ `rn-forge-sqlalchemy[postgres]>=0.2.5,<0.3` installs `asyncpg` and
82
+ `rn-forge-sqlalchemy[sqlite]>=0.2.5,<0.3` installs `aiosqlite`.
80
83
 
81
84
  `run_migrations` needs the `migrations` extra:
82
85
  `rn-forge-sqlalchemy[migrations]>=0.2.3,<0.3`.
83
86
 
84
- ## Testing
87
+ ## Minimum example
88
+
89
+ ```python
90
+ from sqlalchemy.orm import Mapped, mapped_column
91
+ from rn_forge.sqlalchemy import AuditMixin, Base, VersionMixin
92
+
85
93
 
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
94
+ class Order(AuditMixin, VersionMixin, Base):
95
+ __tablename__ = "order"
96
+
97
+ id: Mapped[str] = mapped_column(primary_key=True)
98
+ name: Mapped[str] = mapped_column(unique=True)
90
99
  ```
91
100
 
92
- The default run uses SQLite. Tests marked `postgres` run only when the DSN is
93
- set.
101
+ ## Errors
102
+
103
+ `update_versioned` raises `rn_forge.web.VersionConflict` (412) when the row is
104
+ at another version and `LookupError` when it is gone. `upsert` raises
105
+ `ValueError` for an empty key, a row missing a column or a duplicate key,
106
+ `TypeError` for a model without `AuditMixin`, and `NotImplementedError` for a
107
+ dialect other than PostgreSQL or SQLite.
108
+
109
+ ## Testing
110
+
111
+ The default test run uses SQLite. Tests marked `postgres` run when
112
+ `RN_FORGE_TEST_POSTGRES_DSN` is set;
113
+ `task ci:integration -- rn-forge-sqlalchemy` starts PostgreSQL and sets it.
94
114
 
95
115
  ## Not included
96
116
 
@@ -13,9 +13,11 @@ 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
+ | `postgres` | `create_postgres_engine` — an async PostgreSQL engine (asyncpg) with UTC sessions, pool settings and an optional statement timeout and application name |
20
+ | `testing` | `postgres_schema` — a pytest plugin whose fixture gives each test its own PostgreSQL schema; needs the `testing` and `postgres` extras and is loaded with `pytest_plugins`, not imported from the facade |
19
21
  | `sqlite` | `create_sqlite_engine` — an async SQLite engine with WAL, foreign keys, busy timeout and `synchronous` set on every connection |
20
22
  | `migrate` | `run_migrations` — Alembic `upgrade` from inside the process; needs the `migrations` extra and is imported directly, not from the facade |
21
23
  | `pagination` | `keyset`, `next_page_token` — AIP-132 `orderBy` and AIP-158 tokens over a `Select` |
@@ -24,15 +26,8 @@ Everything works on **PostgreSQL and SQLite**, through `AsyncSession` only.
24
26
 
25
27
  ## Where it sits
26
28
 
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
29
+ It depends on `rn-forge-web` and SQLAlchemy and imports no web framework or
30
+ framework package; `task lint` proves it. An application wires it to its
36
31
  framework itself: the FastAPI guide shows the import and list endpoints.
37
32
 
38
33
  ## Installation
@@ -49,22 +44,40 @@ dependencies = [
49
44
  Application code catches `rn_forge.web.VersionConflict` and passes
50
45
  `rn_forge.web` pagination terms, so declare `rn-forge-web` as well.
51
46
 
52
- No database driver is declared. Add `asyncpg` for PostgreSQL or `aiosqlite` for
53
- SQLite.
47
+ The core install carries no database driver.
48
+ `rn-forge-sqlalchemy[postgres]>=0.2.5,<0.3` installs `asyncpg` and
49
+ `rn-forge-sqlalchemy[sqlite]>=0.2.5,<0.3` installs `aiosqlite`.
54
50
 
55
51
  `run_migrations` needs the `migrations` extra:
56
52
  `rn-forge-sqlalchemy[migrations]>=0.2.3,<0.3`.
57
53
 
58
- ## Testing
54
+ ## Minimum example
55
+
56
+ ```python
57
+ from sqlalchemy.orm import Mapped, mapped_column
58
+ from rn_forge.sqlalchemy import AuditMixin, Base, VersionMixin
59
+
59
60
 
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
61
+ class Order(AuditMixin, VersionMixin, Base):
62
+ __tablename__ = "order"
63
+
64
+ id: Mapped[str] = mapped_column(primary_key=True)
65
+ name: Mapped[str] = mapped_column(unique=True)
64
66
  ```
65
67
 
66
- The default run uses SQLite. Tests marked `postgres` run only when the DSN is
67
- set.
68
+ ## Errors
69
+
70
+ `update_versioned` raises `rn_forge.web.VersionConflict` (412) when the row is
71
+ at another version and `LookupError` when it is gone. `upsert` raises
72
+ `ValueError` for an empty key, a row missing a column or a duplicate key,
73
+ `TypeError` for a model without `AuditMixin`, and `NotImplementedError` for a
74
+ dialect other than PostgreSQL or SQLite.
75
+
76
+ ## Testing
77
+
78
+ The default test run uses SQLite. Tests marked `postgres` run when
79
+ `RN_FORGE_TEST_POSTGRES_DSN` is set;
80
+ `task ci:integration -- rn-forge-sqlalchemy` starts PostgreSQL and sets it.
68
81
 
69
82
  ## Not included
70
83
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rn-forge-sqlalchemy"
3
- version = "0.2.3"
3
+ version = "0.2.5"
4
4
  description = "Async SQLAlchemy models, upsert and keyset pagination over rn-forge-web"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -26,6 +26,12 @@ email = "rohit.nn@gmail.com"
26
26
 
27
27
  [project.optional-dependencies]
28
28
  migrations = ["alembic>=1.20.1"]
29
+ postgres = ["asyncpg>=0.32.0"]
30
+ sqlite = ["aiosqlite>=0.22.1"]
31
+ testing = [
32
+ "pytest>=9.1.1",
33
+ "pytest-asyncio>=1.4.1.post1",
34
+ ]
29
35
 
30
36
  [project.urls]
31
37
  Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-sqlalchemy/latest/"
@@ -61,11 +67,8 @@ workspace = true
61
67
  workspace = true
62
68
 
63
69
  [tool.pytest.ini_options]
64
- addopts = "-ra --import-mode=importlib"
65
- markers = [
66
- "unit: fast isolated tests",
67
- "postgres: needs a PostgreSQL DSN in RN_FORGE_TEST_POSTGRES_DSN",
68
- ]
70
+ addopts = "-ra --import-mode=importlib -p rn_forge.sqlalchemy.testing"
71
+ markers = ["unit: fast isolated tests"]
69
72
 
70
73
  [tool.workspace-ci.integration.postgres]
71
74
  image = "postgres:17"
@@ -84,20 +87,20 @@ RN_FORGE_TEST_POSTGRES_DSN = "postgresql://ci:ci@localhost:5432/ci"
84
87
  dev = [
85
88
  "aiosqlite>=0.21",
86
89
  "alembic>=1.20.1",
87
- "assertpy>=2.35",
88
- "asyncpg>=0.30",
90
+ "assertpy>=2.36.0",
91
+ "asyncpg>=0.32.0",
89
92
  "httpx>=0.28.1",
90
93
  "pyright>=1.1.411",
91
- "pytest>=9.1.1",
92
- "pytest-asyncio>=1.3.0",
94
+ "pytest>=9.2.0",
95
+ "pytest-asyncio>=1.4.1.post1",
93
96
  "pytest-cov>=7.1.0",
94
97
  "pytest-randomly>=4.1.0",
95
- "rn-forge-fastapi[transfer]>=0.4.0,<0.5",
96
- "ruff>=0.15.21",
98
+ "rn-forge-fastapi[transfer]>=0.4.0,<0.6",
99
+ "ruff>=0.17.4",
97
100
  ]
98
101
  docs = [
99
102
  "mkdocs>=1.6.1",
100
- "mkdocs-material>=9.7.6",
101
- "mkdocstrings[python]>=1.0.6",
103
+ "mkdocs-material>=9.8.1",
104
+ "mkdocstrings[python]>=1.0.8",
102
105
  "rn-forge-sqlalchemy",
103
106
  ]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rn-forge-sqlalchemy"
3
- version = "0.2.3"
3
+ version = "0.2.5"
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" }]
@@ -18,12 +18,15 @@ classifiers = [
18
18
  requires-python = ">=3.14"
19
19
  # Internal requirements are version ranges (ADR-0004).
20
20
  #
21
- # No database driver is declared: the application picks one (`asyncpg`,
22
- # `aiosqlite`). `rn-forge-commons` arrives through `rn-forge-web`.
21
+ # The drivers come from the `postgres` and `sqlite` extras, so the core install
22
+ # carries none. `rn-forge-commons` arrives through `rn-forge-web`.
23
23
  dependencies = ["rn-forge-web>=0.3.0,<0.4", "sqlalchemy[asyncio]>=2.0"]
24
24
 
25
25
  [project.optional-dependencies]
26
26
  migrations = ["alembic>=1.20.1"]
27
+ postgres = ["asyncpg>=0.32.0"]
28
+ sqlite = ["aiosqlite>=0.22.1"]
29
+ testing = ["pytest>=9.1.1", "pytest-asyncio>=1.4.1.post1"]
27
30
 
28
31
  [project.urls]
29
32
  Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-sqlalchemy/latest/"
@@ -53,10 +56,9 @@ rn-forge-fastapi = { workspace = true }
53
56
  rn-forge-sqlalchemy = { workspace = true }
54
57
 
55
58
  [tool.pytest.ini_options]
56
- addopts = "-ra --import-mode=importlib"
59
+ addopts = "-ra --import-mode=importlib -p rn_forge.sqlalchemy.testing"
57
60
  markers = [
58
61
  "unit: fast isolated tests",
59
- "postgres: needs a PostgreSQL DSN in RN_FORGE_TEST_POSTGRES_DSN",
60
62
  ]
61
63
 
62
64
  [tool.workspace-ci.integration.postgres]
@@ -77,20 +79,20 @@ RN_FORGE_TEST_POSTGRES_DSN = "postgresql://ci:ci@localhost:5432/ci"
77
79
  dev = [
78
80
  "aiosqlite>=0.21",
79
81
  "alembic>=1.20.1",
80
- "assertpy>=2.35",
81
- "asyncpg>=0.30",
82
+ "assertpy>=2.36.0",
83
+ "asyncpg>=0.32.0",
82
84
  "httpx>=0.28.1",
83
85
  "pyright>=1.1.411",
84
- "pytest>=9.1.1",
85
- "pytest-asyncio>=1.3.0",
86
+ "pytest>=9.2.0",
87
+ "pytest-asyncio>=1.4.1.post1",
86
88
  "pytest-cov>=7.1.0",
87
89
  "pytest-randomly>=4.1.0",
88
- "rn-forge-fastapi[transfer]>=0.4.0,<0.5",
89
- "ruff>=0.15.21",
90
+ "rn-forge-fastapi[transfer]>=0.4.0,<0.6",
91
+ "ruff>=0.17.4",
90
92
  ]
91
93
  docs = [
92
94
  "mkdocs>=1.6.1",
93
- "mkdocs-material>=9.7.6",
94
- "mkdocstrings[python]>=1.0.6",
95
+ "mkdocs-material>=9.8.1",
96
+ "mkdocstrings[python]>=1.0.8",
95
97
  "rn-forge-sqlalchemy",
96
98
  ]
@@ -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.postgres import create_postgres_engine
16
17
  from rn_forge.sqlalchemy.sqlite import create_sqlite_engine
17
18
  from rn_forge.sqlalchemy.upsert import UpsertCounts, upsert
18
19
 
@@ -24,6 +25,7 @@ __all__ = [
24
25
  "UTCDateTime",
25
26
  "UpsertCounts",
26
27
  "VersionMixin",
28
+ "create_postgres_engine",
27
29
  "create_sqlite_engine",
28
30
  "keyset",
29
31
  "live",
@@ -0,0 +1,138 @@
1
+ """Run Alembic migrations from inside the application process."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from logging.config import fileConfig
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from alembic import command, context
11
+ from alembic.config import Config
12
+ from sqlalchemy import MetaData, make_url, pool
13
+ from sqlalchemy.engine import Connection
14
+ from sqlalchemy.ext.asyncio import async_engine_from_config
15
+
16
+ __all__ = ["run_env", "run_migrations"]
17
+
18
+
19
+ def run_env(target_metadata: MetaData | None, **configure: Any) -> None:
20
+ """Run the migrations from an Alembic ``env.py``, online only.
21
+
22
+ Replaces the whole body of ``env.py``:
23
+
24
+ ```python
25
+ from rn_forge.sqlalchemy.migrate import run_env
26
+ from myapp.db.models import Base
27
+
28
+ run_env(Base.metadata)
29
+ ```
30
+
31
+ Logging is configured from the config file only when one is set and
32
+ ``config.attributes["configure_logger"]`` is true, which it is unless
33
+ ``run_migrations`` set it. The migrations run on an async engine built from
34
+ the config's ``sqlalchemy.`` options with ``NullPool``, inside
35
+ ``asyncio.run``. ``render_as_batch`` is on for SQLite and off otherwise.
36
+
37
+ When ``config.attributes["schema"]`` is set, which ``run_migrations`` does
38
+ for its ``schema`` argument, the connection's ``search_path`` is that schema
39
+ and ``alembic_version`` is kept in it.
40
+
41
+ Args:
42
+ target_metadata: The metadata autogenerate compares against, or ``None``.
43
+ **configure: Keyword arguments for ``context.configure``; they override
44
+ the defaults above.
45
+
46
+ Raises:
47
+ NotImplementedError: Alembic is in offline mode (``--sql``).
48
+ """
49
+ config = context.config
50
+ if config.config_file_name and config.attributes.get("configure_logger", True):
51
+ fileConfig(config.config_file_name)
52
+ if context.is_offline_mode():
53
+ msg = (
54
+ "run_env runs migrations online only; "
55
+ "offline mode (alembic upgrade --sql) is not supported"
56
+ )
57
+ raise NotImplementedError(msg)
58
+
59
+ def _configure_and_run(connection: Connection) -> None:
60
+ schema = config.attributes.get("schema")
61
+ options: dict[str, Any] = {
62
+ "target_metadata": target_metadata,
63
+ "render_as_batch": connection.dialect.name == "sqlite",
64
+ }
65
+ if schema:
66
+ connection.exec_driver_sql(f'SET search_path TO "{schema}"')
67
+ # Without the commit, Alembic's transaction rolls the setting back.
68
+ connection.commit()
69
+ connection.dialect.default_schema_name = schema
70
+ options["version_table_schema"] = schema
71
+ options.update(configure)
72
+ context.configure(connection=connection, **options)
73
+ with context.begin_transaction():
74
+ context.run_migrations()
75
+
76
+ async def _online() -> None:
77
+ engine = async_engine_from_config(
78
+ config.get_section(config.config_ini_section, {}),
79
+ prefix="sqlalchemy.",
80
+ poolclass=pool.NullPool,
81
+ )
82
+ try:
83
+ async with engine.connect() as connection:
84
+ await connection.run_sync(_configure_and_run)
85
+ finally:
86
+ await engine.dispose()
87
+
88
+ asyncio.run(_online())
89
+
90
+
91
+ def run_migrations(
92
+ script_location: str | Path,
93
+ db_url: str,
94
+ *,
95
+ alembic_ini: str | Path | None = None,
96
+ revision: str = "head",
97
+ schema: str | None = None,
98
+ ) -> None:
99
+ """Upgrade the database at *db_url* to *revision*.
100
+
101
+ Blocks until the upgrade finishes. From a running event loop, call it as
102
+ ``await asyncio.to_thread(run_migrations, ...)``. A failing migration
103
+ propagates unchanged.
104
+
105
+ ``config.attributes["configure_logger"]`` is set to ``False``. The
106
+ application's logging is left alone by ``run_env``, which honours the
107
+ attribute; an ``env.py`` that calls ``fileConfig`` itself must read it.
108
+
109
+ Args:
110
+ script_location: A script directory, or a package resource such as
111
+ ``"myapp:migrations"``.
112
+ db_url: The SQLAlchemy URL handed to ``env.py`` as ``sqlalchemy.url``.
113
+ alembic_ini: An ``alembic.ini`` to start from; an empty configuration
114
+ when omitted.
115
+ revision: The target revision.
116
+ schema: A PostgreSQL schema, which must already exist, to migrate into;
117
+ ``alembic_version`` is kept in it too. The database's own default
118
+ schema when omitted.
119
+
120
+ Raises:
121
+ ValueError: *schema* is empty, or *db_url* is not a PostgreSQL URL.
122
+ """
123
+ if schema is not None:
124
+ if not schema:
125
+ msg = "schema must not be empty"
126
+ raise ValueError(msg)
127
+ backend = make_url(db_url).get_backend_name()
128
+ if backend != "postgresql":
129
+ msg = f"schema needs a PostgreSQL URL, got {backend!r}"
130
+ raise ValueError(msg)
131
+ config = Config(str(alembic_ini)) if alembic_ini is not None else Config()
132
+ # Config values pass through ConfigParser, where a bare "%" is interpolation.
133
+ config.set_main_option("script_location", str(script_location).replace("%", "%%"))
134
+ config.set_main_option("sqlalchemy.url", db_url.replace("%", "%%"))
135
+ config.attributes["configure_logger"] = False
136
+ if schema is not None:
137
+ config.attributes["schema"] = schema
138
+ command.upgrade(config, revision)
@@ -0,0 +1,111 @@
1
+ """An async PostgreSQL engine on asyncpg with UTC sessions and pool settings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ from typing import Any
7
+
8
+ from sqlalchemy.engine import URL, make_url
9
+ from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
10
+
11
+ __all__ = ["create_postgres_engine"]
12
+
13
+ _DRIVERNAMES = frozenset({"postgresql", "postgres", "postgresql+asyncpg"})
14
+
15
+
16
+ def create_postgres_engine(
17
+ url: str | URL,
18
+ *,
19
+ pool_size: int = 5,
20
+ max_overflow: int = 10,
21
+ pool_pre_ping: bool = True,
22
+ pool_recycle_s: int = 1800,
23
+ statement_timeout_ms: int | None = None,
24
+ application_name: str | None = None,
25
+ search_path: str | None = None,
26
+ prepared_statement_cache_size: int = 100,
27
+ ) -> AsyncEngine:
28
+ """Create an ``AsyncEngine`` on PostgreSQL through ``asyncpg``.
29
+
30
+ Every connection sets the session time zone to UTC, plus
31
+ ``application_name``, ``statement_timeout`` and ``search_path`` when given.
32
+ The engine does not connect and creates no tables.
33
+
34
+ Args:
35
+ url: A ``postgresql://``, ``postgres://`` or ``postgresql+asyncpg://``
36
+ URL, as a string or a SQLAlchemy ``URL``. The driver is rewritten
37
+ to ``postgresql+asyncpg``.
38
+ pool_size: Connections kept in the pool.
39
+ max_overflow: Connections allowed beyond *pool_size*.
40
+ pool_pre_ping: Test a connection before handing it out.
41
+ pool_recycle_s: Seconds after which a connection is replaced.
42
+ statement_timeout_ms: Milliseconds before the server cancels a
43
+ statement; ``None`` leaves the server default.
44
+ application_name: The ``application_name`` the server reports;
45
+ ``None`` leaves the driver default.
46
+ search_path: The schema search path every connection sets, as
47
+ PostgreSQL's comma-separated list; ``None`` leaves the server
48
+ default.
49
+ prepared_statement_cache_size: Size of both the SQLAlchemy and asyncpg
50
+ prepared-statement caches; ``0`` turns them off.
51
+
52
+ Returns:
53
+ The engine, using the ``postgresql+asyncpg`` driver.
54
+
55
+ Raises:
56
+ ValueError: *url* names a driver other than PostgreSQL with asyncpg.
57
+ ValueError: *pool_size*, *max_overflow*, *pool_recycle_s*,
58
+ *prepared_statement_cache_size* or *statement_timeout_ms* is
59
+ negative.
60
+ ValueError: *search_path* is empty.
61
+ ImportError: ``asyncpg`` is not installed.
62
+ """
63
+ parsed = make_url(url)
64
+ if parsed.drivername not in _DRIVERNAMES:
65
+ raise ValueError(
66
+ f"create_postgres_engine needs a postgresql:// URL, "
67
+ f"got {parsed.drivername!r}"
68
+ )
69
+ numbers = {
70
+ "pool_size": pool_size,
71
+ "max_overflow": max_overflow,
72
+ "pool_recycle_s": pool_recycle_s,
73
+ "prepared_statement_cache_size": prepared_statement_cache_size,
74
+ }
75
+ if statement_timeout_ms is not None:
76
+ numbers["statement_timeout_ms"] = statement_timeout_ms
77
+ for name, value in numbers.items():
78
+ if value < 0:
79
+ raise ValueError(f"{name} must be >= 0, got {value}")
80
+ if search_path == "":
81
+ raise ValueError("search_path must not be empty")
82
+ try:
83
+ importlib.import_module("asyncpg")
84
+ except ImportError as error:
85
+ raise ImportError(
86
+ "create_postgres_engine needs asyncpg; install rn-forge-sqlalchemy[postgres]"
87
+ ) from error
88
+
89
+ # asyncpg needs string values for server settings.
90
+ settings = {"timezone": "UTC"}
91
+ if application_name is not None:
92
+ settings["application_name"] = application_name
93
+ if statement_timeout_ms is not None:
94
+ settings["statement_timeout"] = str(statement_timeout_ms)
95
+ if search_path is not None:
96
+ settings["search_path"] = search_path
97
+ # SQLAlchemy's dialect reads prepared_statement_cache_size as a connect
98
+ # argument; statement_cache_size is asyncpg's own cache.
99
+ connect_args: dict[str, Any] = {
100
+ "server_settings": settings,
101
+ "prepared_statement_cache_size": prepared_statement_cache_size,
102
+ "statement_cache_size": prepared_statement_cache_size,
103
+ }
104
+ return create_async_engine(
105
+ parsed.set(drivername="postgresql+asyncpg"),
106
+ pool_size=pool_size,
107
+ max_overflow=max_overflow,
108
+ pool_pre_ping=pool_pre_ping,
109
+ pool_recycle=pool_recycle_s,
110
+ connect_args=connect_args,
111
+ )
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import importlib
5
6
  from pathlib import Path
6
7
  from typing import Any
7
8
 
@@ -48,12 +49,19 @@ def create_sqlite_engine(
48
49
  Raises:
49
50
  ValueError: *synchronous* is not one of the allowed values.
50
51
  ValueError: *busy_timeout_ms* cannot be converted to an integer.
52
+ ImportError: ``aiosqlite`` is not installed.
51
53
  """
52
54
  level = synchronous.upper()
53
55
  if level not in _SYNCHRONOUS:
54
56
  allowed = ", ".join(sorted(_SYNCHRONOUS))
55
57
  raise ValueError(f"synchronous must be one of {allowed}, got {synchronous!r}")
56
58
  timeout = int(busy_timeout_ms)
59
+ try:
60
+ importlib.import_module("aiosqlite")
61
+ except ImportError as error:
62
+ raise ImportError(
63
+ "create_sqlite_engine needs aiosqlite; install rn-forge-sqlalchemy[sqlite]"
64
+ ) from error
57
65
 
58
66
  in_memory = isinstance(path, str) and path == _MEMORY
59
67
  # PRAGMA values cannot be bound parameters, so they are validated above.
@@ -0,0 +1,88 @@
1
+ """A pytest plugin that gives each test its own PostgreSQL schema.
2
+
3
+ Load it explicitly in the root ``conftest.py``::
4
+
5
+ pytest_plugins = ["rn_forge.sqlalchemy.testing"]
6
+
7
+ It needs the ``testing`` and ``postgres`` extras. It registers the ``postgres``
8
+ marker and the ``rn_forge_postgres_dsn_env`` ini option, the name of the
9
+ environment variable that holds the DSN.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ from collections.abc import AsyncIterator
16
+ from dataclasses import dataclass
17
+ from uuid import uuid4
18
+
19
+ import pytest
20
+ import pytest_asyncio
21
+ from rn_forge.sqlalchemy.postgres import create_postgres_engine
22
+ from sqlalchemy.ext.asyncio import AsyncEngine
23
+
24
+ __all__ = ["PostgresSchema", "postgres_schema"]
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class PostgresSchema:
29
+ """A PostgreSQL schema created for one test.
30
+
31
+ Attributes:
32
+ name: The schema name, ``"t_"`` followed by 32 hexadecimal digits.
33
+ url: The DSN with the ``postgresql+asyncpg`` driver, password included.
34
+ engine: An engine whose connections use the schema as their
35
+ ``search_path``.
36
+ """
37
+
38
+ name: str
39
+ url: str
40
+ engine: AsyncEngine
41
+
42
+
43
+ def pytest_addoption(parser: pytest.Parser) -> None:
44
+ """Register the ``rn_forge_postgres_dsn_env`` ini option."""
45
+ parser.addini(
46
+ "rn_forge_postgres_dsn_env",
47
+ help="Name of the environment variable that holds the PostgreSQL DSN",
48
+ default="RN_FORGE_TEST_POSTGRES_DSN",
49
+ )
50
+
51
+
52
+ def pytest_configure(config: pytest.Config) -> None:
53
+ """Register the ``postgres`` marker."""
54
+ config.addinivalue_line(
55
+ "markers",
56
+ "postgres: needs a PostgreSQL server (DSN from rn_forge_postgres_dsn_env)",
57
+ )
58
+
59
+
60
+ @pytest_asyncio.fixture
61
+ async def postgres_schema(
62
+ request: pytest.FixtureRequest,
63
+ ) -> AsyncIterator[PostgresSchema]:
64
+ """Yield a `PostgresSchema` that exists for one test.
65
+
66
+ The test skips when the environment variable named by
67
+ ``rn_forge_postgres_dsn_env`` is unset or empty. The schema is dropped with
68
+ ``CASCADE`` after the test, whether it passed or failed.
69
+ """
70
+ variable = str(request.config.getini("rn_forge_postgres_dsn_env"))
71
+ dsn = os.environ.get(variable)
72
+ if not dsn:
73
+ pytest.skip(f"{variable} is not set")
74
+ name = "t_" + uuid4().hex
75
+ admin = create_postgres_engine(dsn)
76
+ try:
77
+ async with admin.begin() as connection:
78
+ await connection.exec_driver_sql(f'CREATE SCHEMA "{name}"')
79
+ engine = create_postgres_engine(dsn, search_path=name)
80
+ url = engine.url.render_as_string(hide_password=False)
81
+ try:
82
+ yield PostgresSchema(name, url, engine)
83
+ finally:
84
+ await engine.dispose()
85
+ finally:
86
+ async with admin.begin() as connection:
87
+ await connection.exec_driver_sql(f'DROP SCHEMA IF EXISTS "{name}" CASCADE')
88
+ await admin.dispose()
@@ -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,43 +0,0 @@
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)