rn-forge-sqlalchemy 0.2.2__tar.gz → 0.2.3__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.2
3
+ Version: 0.2.3
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>
@@ -15,11 +15,13 @@ Classifier: Programming Language :: Python :: 3.14
15
15
  Classifier: Typing :: Typed
16
16
  Requires-Dist: rn-forge-web>=0.3.0,<0.4
17
17
  Requires-Dist: sqlalchemy[asyncio]>=2.0
18
+ Requires-Dist: alembic>=1.20.1 ; extra == 'migrations'
18
19
  Requires-Python: >=3.14
19
20
  Project-URL: Documentation, https://rn-forge.github.io/pykit/packages/rn-forge-sqlalchemy/latest/
20
21
  Project-URL: Source, https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-sqlalchemy
21
22
  Project-URL: Changelog, https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-sqlalchemy/CHANGELOG.md
22
23
  Project-URL: Issues, https://github.com/rn-forge/pykit/issues
24
+ Provides-Extra: migrations
23
25
  Description-Content-Type: text/markdown
24
26
 
25
27
  # rn-forge-sqlalchemy
@@ -40,6 +42,8 @@ opaque page token.
40
42
  | `models` | `Base` (Alembic naming convention), `UTCDateTime`, `AuditMixin` (`create_time`, `update_time`, `created_by`, `updated_by`), `VersionMixin` |
41
43
  | `concurrency` | `update_versioned` — optimistic concurrency, raising `rn_forge.web.VersionConflict` (412) |
42
44
  | `upsert` | `upsert` — create or update rows by natural key, counting created, updated and skipped |
45
+ | `sqlite` | `create_sqlite_engine` — an async SQLite engine with WAL, foreign keys, busy timeout and `synchronous` set on every connection |
46
+ | `migrate` | `run_migrations` — Alembic `upgrade` from inside the process; needs the `migrations` extra and is imported directly, not from the facade |
43
47
  | `pagination` | `keyset`, `next_page_token` — AIP-132 `orderBy` and AIP-158 tokens over a `Select` |
44
48
 
45
49
  Everything works on **PostgreSQL and SQLite**, through `AsyncSession` only.
@@ -74,6 +78,9 @@ Application code catches `rn_forge.web.VersionConflict` and passes
74
78
  No database driver is declared. Add `asyncpg` for PostgreSQL or `aiosqlite` for
75
79
  SQLite.
76
80
 
81
+ `run_migrations` needs the `migrations` extra:
82
+ `rn-forge-sqlalchemy[migrations]>=0.2.3,<0.3`.
83
+
77
84
  ## Testing
78
85
 
79
86
  ```bash
@@ -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` |
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
+ | `sqlite` | `create_sqlite_engine` — an async SQLite engine with WAL, foreign keys, busy timeout and `synchronous` set on every connection |
20
+ | `migrate` | `run_migrations` — Alembic `upgrade` from inside the process; needs the `migrations` extra and is imported directly, not from the facade |
19
21
  | `pagination` | `keyset`, `next_page_token` — AIP-132 `orderBy` and AIP-158 tokens over a `Select` |
20
22
 
21
23
  Everything works on **PostgreSQL and SQLite**, through `AsyncSession` only.
@@ -50,6 +52,9 @@ Application code catches `rn_forge.web.VersionConflict` and passes
50
52
  No database driver is declared. Add `asyncpg` for PostgreSQL or `aiosqlite` for
51
53
  SQLite.
52
54
 
55
+ `run_migrations` needs the `migrations` extra:
56
+ `rn-forge-sqlalchemy[migrations]>=0.2.3,<0.3`.
57
+
53
58
  ## Testing
54
59
 
55
60
  ```bash
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rn-forge-sqlalchemy"
3
- version = "0.2.2"
3
+ version = "0.2.3"
4
4
  description = "Async SQLAlchemy models, upsert and keyset pagination over rn-forge-web"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -24,6 +24,9 @@ dependencies = [
24
24
  name = "Rohit Narayanan"
25
25
  email = "rohit.nn@gmail.com"
26
26
 
27
+ [project.optional-dependencies]
28
+ migrations = ["alembic>=1.20.1"]
29
+
27
30
  [project.urls]
28
31
  Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-sqlalchemy/latest/"
29
32
  Source = "https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-sqlalchemy"
@@ -31,11 +34,19 @@ Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-sqlal
31
34
  Issues = "https://github.com/rn-forge/pykit/issues"
32
35
 
33
36
  [build-system]
34
- requires = ["uv_build>=0.11.28,<0.12.0"]
37
+ requires = ["uv_build>=0.13.7,<0.14.0"]
35
38
  build-backend = "uv_build"
36
39
 
40
+ [tool.pyright]
41
+ typeCheckingMode = "strict"
42
+ reportMissingTypeStubs = false
43
+ reportUnnecessaryTypeIgnoreComment = "error"
44
+ venv = ".venv"
45
+ venvPath = "../.."
46
+
37
47
  [tool.uv.build-backend]
38
48
  module-name = "rn_forge.sqlalchemy"
49
+ source-exclude = ["**/.DS_Store"]
39
50
 
40
51
  [tool.uv.sources.rn-forge-commons]
41
52
  workspace = true
@@ -56,13 +67,24 @@ markers = [
56
67
  "postgres: needs a PostgreSQL DSN in RN_FORGE_TEST_POSTGRES_DSN",
57
68
  ]
58
69
 
59
- [tool.workspace-ci.postgres]
60
- env = "RN_FORGE_TEST_POSTGRES_DSN"
70
+ [tool.workspace-ci.integration.postgres]
71
+ image = "postgres:17"
72
+ ports = ["5432:5432"]
73
+ health-cmd = "pg_isready -U ci"
74
+
75
+ [tool.workspace-ci.integration.postgres.env]
76
+ POSTGRES_USER = "ci"
77
+ POSTGRES_PASSWORD = "ci"
78
+ POSTGRES_DB = "ci"
79
+
80
+ [tool.workspace-ci.integration.postgres.expose]
81
+ RN_FORGE_TEST_POSTGRES_DSN = "postgresql://ci:ci@localhost:5432/ci"
61
82
 
62
83
  [dependency-groups]
63
84
  dev = [
64
85
  "aiosqlite>=0.21",
65
- "assertpy>=1.1",
86
+ "alembic>=1.20.1",
87
+ "assertpy>=2.35",
66
88
  "asyncpg>=0.30",
67
89
  "httpx>=0.28.1",
68
90
  "pyright>=1.1.411",
@@ -0,0 +1,96 @@
1
+ [project]
2
+ name = "rn-forge-sqlalchemy"
3
+ version = "0.2.3"
4
+ description = "Async SQLAlchemy models, upsert and keyset pagination over rn-forge-web"
5
+ readme = "README.md"
6
+ authors = [{ name = "Rohit Narayanan", email = "rohit.nn@gmail.com" }]
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Intended Audience :: Developers",
12
+ "Operating System :: OS Independent",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3 :: Only",
15
+ "Programming Language :: Python :: 3.14",
16
+ "Typing :: Typed",
17
+ ]
18
+ requires-python = ">=3.14"
19
+ # Internal requirements are version ranges (ADR-0004).
20
+ #
21
+ # No database driver is declared: the application picks one (`asyncpg`,
22
+ # `aiosqlite`). `rn-forge-commons` arrives through `rn-forge-web`.
23
+ dependencies = ["rn-forge-web>=0.3.0,<0.4", "sqlalchemy[asyncio]>=2.0"]
24
+
25
+ [project.optional-dependencies]
26
+ migrations = ["alembic>=1.20.1"]
27
+
28
+ [project.urls]
29
+ Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-sqlalchemy/latest/"
30
+ Source = "https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-sqlalchemy"
31
+ Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-sqlalchemy/CHANGELOG.md"
32
+ Issues = "https://github.com/rn-forge/pykit/issues"
33
+
34
+ [build-system]
35
+ requires = ["uv_build>=0.13.7,<0.14.0"]
36
+ build-backend = "uv_build"
37
+
38
+ [tool.pyright]
39
+ typeCheckingMode = "strict"
40
+ reportMissingTypeStubs = false
41
+ reportUnnecessaryTypeIgnoreComment = "error"
42
+ venv = ".venv"
43
+ venvPath = "../.."
44
+
45
+ [tool.uv.build-backend]
46
+ module-name = "rn_forge.sqlalchemy"
47
+ source-exclude = ["**/.DS_Store"]
48
+
49
+ [tool.uv.sources]
50
+ rn-forge-commons = { workspace = true }
51
+ rn-forge-web = { workspace = true }
52
+ rn-forge-fastapi = { workspace = true }
53
+ rn-forge-sqlalchemy = { workspace = true }
54
+
55
+ [tool.pytest.ini_options]
56
+ addopts = "-ra --import-mode=importlib"
57
+ markers = [
58
+ "unit: fast isolated tests",
59
+ "postgres: needs a PostgreSQL DSN in RN_FORGE_TEST_POSTGRES_DSN",
60
+ ]
61
+
62
+ [tool.workspace-ci.integration.postgres]
63
+ image = "postgres:17"
64
+ ports = ["5432:5432"]
65
+ health-cmd = "pg_isready -U ci"
66
+
67
+ [tool.workspace-ci.integration.postgres.env]
68
+ POSTGRES_USER = "ci"
69
+ POSTGRES_PASSWORD = "ci"
70
+ POSTGRES_DB = "ci"
71
+
72
+ [tool.workspace-ci.integration.postgres.expose]
73
+ # The `postgres`-marked tests read this DSN and skip without it.
74
+ RN_FORGE_TEST_POSTGRES_DSN = "postgresql://ci:ci@localhost:5432/ci"
75
+
76
+ [dependency-groups]
77
+ dev = [
78
+ "aiosqlite>=0.21",
79
+ "alembic>=1.20.1",
80
+ "assertpy>=2.35",
81
+ "asyncpg>=0.30",
82
+ "httpx>=0.28.1",
83
+ "pyright>=1.1.411",
84
+ "pytest>=9.1.1",
85
+ "pytest-asyncio>=1.3.0",
86
+ "pytest-cov>=7.1.0",
87
+ "pytest-randomly>=4.1.0",
88
+ "rn-forge-fastapi[transfer]>=0.4.0,<0.5",
89
+ "ruff>=0.15.21",
90
+ ]
91
+ docs = [
92
+ "mkdocs>=1.6.1",
93
+ "mkdocs-material>=9.7.6",
94
+ "mkdocstrings[python]>=1.0.6",
95
+ "rn-forge-sqlalchemy",
96
+ ]
@@ -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.sqlite import create_sqlite_engine
16
17
  from rn_forge.sqlalchemy.upsert import UpsertCounts, upsert
17
18
 
18
19
  __all__ = [
@@ -23,6 +24,7 @@ __all__ = [
23
24
  "UTCDateTime",
24
25
  "UpsertCounts",
25
26
  "VersionMixin",
27
+ "create_sqlite_engine",
26
28
  "keyset",
27
29
  "live",
28
30
  "next_page_token",
@@ -0,0 +1,43 @@
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)
@@ -0,0 +1,86 @@
1
+ """An async SQLite engine with its pragmas set on every connection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from sqlalchemy import event
9
+ from sqlalchemy.engine import URL
10
+ from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
11
+ from sqlalchemy.pool import StaticPool
12
+
13
+ __all__ = ["create_sqlite_engine"]
14
+
15
+ _MEMORY = ":memory:"
16
+ _SYNCHRONOUS = frozenset({"OFF", "NORMAL", "FULL", "EXTRA"})
17
+
18
+
19
+ def create_sqlite_engine(
20
+ path: str | Path,
21
+ *,
22
+ wal: bool = True,
23
+ busy_timeout_ms: int = 5000,
24
+ foreign_keys: bool = True,
25
+ synchronous: str = "NORMAL",
26
+ ) -> AsyncEngine:
27
+ """Create an ``AsyncEngine`` on a SQLite file with pragmas set per connection.
28
+
29
+ The parent directory of *path* is created. Every new connection runs
30
+ ``busy_timeout``, then ``journal_mode=WAL`` when *wal* is true,
31
+ ``synchronous``, and ``foreign_keys=ON`` when *foreign_keys* is true. A false
32
+ flag leaves that pragma at SQLite's default. No tables are created.
33
+
34
+ The exact string ``":memory:"`` opens an in-memory database: no directory is
35
+ created, WAL is not enabled, and a ``StaticPool`` makes every session share
36
+ one connection. ``Path(":memory:")`` is an ordinary file named ``:memory:``.
37
+
38
+ Args:
39
+ path: The database file, or the string ``":memory:"``.
40
+ wal: Enable write-ahead logging.
41
+ busy_timeout_ms: Milliseconds a connection waits on a locked database.
42
+ foreign_keys: Enforce foreign-key constraints.
43
+ synchronous: ``OFF``, ``NORMAL``, ``FULL`` or ``EXTRA``, in any case.
44
+
45
+ Returns:
46
+ The engine, using the ``sqlite+aiosqlite`` driver.
47
+
48
+ Raises:
49
+ ValueError: *synchronous* is not one of the allowed values.
50
+ ValueError: *busy_timeout_ms* cannot be converted to an integer.
51
+ """
52
+ level = synchronous.upper()
53
+ if level not in _SYNCHRONOUS:
54
+ allowed = ", ".join(sorted(_SYNCHRONOUS))
55
+ raise ValueError(f"synchronous must be one of {allowed}, got {synchronous!r}")
56
+ timeout = int(busy_timeout_ms)
57
+
58
+ in_memory = isinstance(path, str) and path == _MEMORY
59
+ # PRAGMA values cannot be bound parameters, so they are validated above.
60
+ # busy_timeout goes first so the caller's value also covers journal_mode,
61
+ # whose first switch to WAL needs an exclusive lock.
62
+ pragmas = [f"PRAGMA busy_timeout={timeout}"]
63
+ if wal and not in_memory:
64
+ pragmas.append("PRAGMA journal_mode=WAL")
65
+ pragmas.append(f"PRAGMA synchronous={level}")
66
+ if foreign_keys:
67
+ pragmas.append("PRAGMA foreign_keys=ON")
68
+
69
+ kwargs: dict[str, Any] = {}
70
+ if in_memory:
71
+ kwargs["poolclass"] = StaticPool
72
+ else:
73
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
74
+ url = URL.create("sqlite+aiosqlite", database=str(path))
75
+ engine = create_async_engine(url, **kwargs)
76
+
77
+ @event.listens_for(engine.sync_engine, "connect")
78
+ def _set_pragmas(dbapi_connection: Any, _record: Any) -> None:
79
+ cursor = dbapi_connection.cursor()
80
+ try:
81
+ for pragma in pragmas:
82
+ cursor.execute(pragma)
83
+ finally:
84
+ cursor.close()
85
+
86
+ return engine
@@ -1,77 +0,0 @@
1
- [project]
2
- name = "rn-forge-sqlalchemy"
3
- version = "0.2.2"
4
- description = "Async SQLAlchemy models, upsert and keyset pagination over rn-forge-web"
5
- readme = "README.md"
6
- authors = [{ name = "Rohit Narayanan", email = "rohit.nn@gmail.com" }]
7
- license = "MIT"
8
- license-files = ["LICENSE"]
9
- classifiers = [
10
- "Development Status :: 3 - Alpha",
11
- "Intended Audience :: Developers",
12
- "Operating System :: OS Independent",
13
- "Programming Language :: Python :: 3",
14
- "Programming Language :: Python :: 3 :: Only",
15
- "Programming Language :: Python :: 3.14",
16
- "Typing :: Typed",
17
- ]
18
- requires-python = ">=3.14"
19
- # Internal requirements are version ranges (ADR-0004).
20
- #
21
- # No database driver is declared: the application picks one (`asyncpg`,
22
- # `aiosqlite`). `rn-forge-commons` arrives through `rn-forge-web`.
23
- dependencies = [
24
- "rn-forge-web>=0.3.0,<0.4",
25
- "sqlalchemy[asyncio]>=2.0",
26
- ]
27
-
28
- [project.urls]
29
- Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-sqlalchemy/latest/"
30
- Source = "https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-sqlalchemy"
31
- Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-sqlalchemy/CHANGELOG.md"
32
- Issues = "https://github.com/rn-forge/pykit/issues"
33
-
34
- [build-system]
35
- requires = ["uv_build>=0.11.28,<0.12.0"]
36
- build-backend = "uv_build"
37
-
38
- [tool.uv.build-backend]
39
- module-name = "rn_forge.sqlalchemy"
40
-
41
- [tool.uv.sources]
42
- rn-forge-commons = { workspace = true }
43
- rn-forge-web = { workspace = true }
44
- rn-forge-fastapi = { workspace = true }
45
- rn-forge-sqlalchemy = { workspace = true }
46
-
47
- [tool.pytest.ini_options]
48
- addopts = "-ra --import-mode=importlib"
49
- markers = [
50
- "unit: fast isolated tests",
51
- "postgres: needs a PostgreSQL DSN in RN_FORGE_TEST_POSTGRES_DSN",
52
- ]
53
-
54
- [tool.workspace-ci.postgres]
55
- # The `postgres`-marked tests read this DSN and skip without it.
56
- env = "RN_FORGE_TEST_POSTGRES_DSN"
57
-
58
- [dependency-groups]
59
- dev = [
60
- "aiosqlite>=0.21",
61
- "assertpy>=1.1",
62
- "asyncpg>=0.30",
63
- "httpx>=0.28.1",
64
- "pyright>=1.1.411",
65
- "pytest>=9.1.1",
66
- "pytest-asyncio>=1.3.0",
67
- "pytest-cov>=7.1.0",
68
- "pytest-randomly>=4.1.0",
69
- "rn-forge-fastapi[transfer]>=0.4.0,<0.5",
70
- "ruff>=0.15.21",
71
- ]
72
- docs = [
73
- "mkdocs>=1.6.1",
74
- "mkdocs-material>=9.7.6",
75
- "mkdocstrings[python]>=1.0.6",
76
- "rn-forge-sqlalchemy",
77
- ]