rn-forge-sqlalchemy 0.2.4__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.4
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
@@ -42,6 +49,8 @@ opaque page token.
42
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` |
@@ -68,8 +77,9 @@ dependencies = [
68
77
  Application code catches `rn_forge.web.VersionConflict` and passes
69
78
  `rn_forge.web` pagination terms, so declare `rn-forge-web` as well.
70
79
 
71
- No database driver is declared. Add `asyncpg` for PostgreSQL or `aiosqlite` for
72
- 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`.
73
83
 
74
84
  `run_migrations` needs the `migrations` extra:
75
85
  `rn-forge-sqlalchemy[migrations]>=0.2.3,<0.3`.
@@ -16,6 +16,8 @@ opaque page token.
16
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` |
@@ -42,8 +44,9 @@ dependencies = [
42
44
  Application code catches `rn_forge.web.VersionConflict` and passes
43
45
  `rn_forge.web` pagination terms, so declare `rn-forge-web` as well.
44
46
 
45
- No database driver is declared. Add `asyncpg` for PostgreSQL or `aiosqlite` for
46
- 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`.
47
50
 
48
51
  `run_migrations` needs the `migrations` extra:
49
52
  `rn-forge-sqlalchemy[migrations]>=0.2.3,<0.3`.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rn-forge-sqlalchemy"
3
- version = "0.2.4"
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
98
  "rn-forge-fastapi[transfer]>=0.4.0,<0.6",
96
- "ruff>=0.15.21",
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.4"
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
90
  "rn-forge-fastapi[transfer]>=0.4.0,<0.6",
89
- "ruff>=0.15.21",
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()
@@ -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)