dap-database 0.4.1__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,40 @@
1
+ """dap-database — shared SQLAlchemy plumbing for DAP (#778 Phase 1).
2
+
3
+ URL/dialect helpers, raw engine factories (SQLite WAL / PostgreSQL), and
4
+ sync+async session factories. No ORM models, no migrations — schema
5
+ ownership stays with the consumer (``dap_engine.persistence``).
6
+ """
7
+
8
+ from dap_database.engines import (
9
+ create_async_engine_for_url,
10
+ create_postgresql_engine,
11
+ create_sqlite_engine,
12
+ )
13
+ from dap_database.sessions import (
14
+ make_async_session_factory,
15
+ make_session_factory,
16
+ session_scope,
17
+ )
18
+ from dap_database.urls import (
19
+ async_url_for,
20
+ detect_dialect,
21
+ normalize_pg_prefix,
22
+ pg_conn_string,
23
+ pg_sync_url,
24
+ redact_database_url,
25
+ )
26
+
27
+ __all__ = [
28
+ "async_url_for",
29
+ "create_async_engine_for_url",
30
+ "create_postgresql_engine",
31
+ "create_sqlite_engine",
32
+ "detect_dialect",
33
+ "make_async_session_factory",
34
+ "make_session_factory",
35
+ "normalize_pg_prefix",
36
+ "pg_conn_string",
37
+ "pg_sync_url",
38
+ "redact_database_url",
39
+ "session_scope",
40
+ ]
@@ -0,0 +1,113 @@
1
+ """Raw SQLAlchemy engine factories — SQLite (WAL mode) and PostgreSQL.
2
+
3
+ Extracted from ``dap_engine.persistence.db`` / ``dap_engine.auth.db``
4
+ (#778 Phase 1). These factories create **no schema**: ``create_all`` and
5
+ migrations stay with the consumer, which owns the ORM models. That keeps
6
+ this package importable by the CLI (and tests) without dragging in the
7
+ engine's model registry or Alembic.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from pathlib import Path
13
+
14
+ from sqlalchemy import Engine, create_engine, event
15
+ from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
16
+
17
+ from dap_database.urls import async_url_for, pg_sync_url
18
+
19
+ __all__ = [
20
+ "create_async_engine_for_url",
21
+ "create_postgresql_engine",
22
+ "create_sqlite_engine",
23
+ ]
24
+
25
+ # Allow up to 5 s of retry before raising "database is locked". Needed
26
+ # when a short-lived log session runs concurrently with the long-lived
27
+ # background session (#162).
28
+ SQLITE_BUSY_TIMEOUT_MS = 5000
29
+
30
+ # Connection-open busy wait — same contention scenario as above (#162).
31
+ SQLITE_CONNECT_TIMEOUT_S = 10
32
+
33
+
34
+ def _enable_sqlite_pragmas(dbapi_connection, _connection_record) -> None: # type: ignore[no-untyped-def]
35
+ cursor = dbapi_connection.cursor()
36
+ cursor.execute("PRAGMA journal_mode = WAL")
37
+ cursor.execute("PRAGMA synchronous = NORMAL")
38
+ cursor.execute("PRAGMA foreign_keys = ON")
39
+ cursor.execute(f"PRAGMA busy_timeout = {SQLITE_BUSY_TIMEOUT_MS}")
40
+ cursor.close()
41
+
42
+
43
+ def create_sqlite_engine(db_path: str) -> Engine:
44
+ """Synchronous SQLite engine with WAL pragmas; parent dirs are created."""
45
+ absolute = Path(db_path).resolve()
46
+ absolute.parent.mkdir(parents=True, exist_ok=True)
47
+
48
+ engine = create_engine(
49
+ f"sqlite:///{absolute}",
50
+ echo=False,
51
+ future=True,
52
+ connect_args={"timeout": SQLITE_CONNECT_TIMEOUT_S},
53
+ )
54
+ event.listen(engine, "connect", _enable_sqlite_pragmas)
55
+ return engine
56
+
57
+
58
+ def create_postgresql_engine(
59
+ database_url: str,
60
+ *,
61
+ pool_size: int = 5,
62
+ max_overflow: int = 10,
63
+ pool_recycle_s: int = 1800,
64
+ ) -> Engine:
65
+ """Synchronous PostgreSQL engine using psycopg (v3) as the DBAPI driver.
66
+
67
+ Accepts any postgres-family URL (``postgresql+asyncpg://`` is the
68
+ canonical DAP form) and rewrites it to ``postgresql+psycopg://``.
69
+
70
+ Pool defaults for a single long-running process:
71
+ - ``pool_size=5`` — modest default.
72
+ - ``max_overflow=10`` — burst headroom.
73
+ - ``pool_pre_ping=True`` — validate connections after idle periods
74
+ (k8s NodePort is behind NAT that drops idle TCP).
75
+ - ``pool_recycle_s=1800`` — recycle before NAT drops idle TCP.
76
+ """
77
+ return create_engine(
78
+ pg_sync_url(database_url),
79
+ echo=False,
80
+ future=True,
81
+ pool_size=pool_size,
82
+ max_overflow=max_overflow,
83
+ pool_pre_ping=True,
84
+ pool_recycle=pool_recycle_s,
85
+ )
86
+
87
+
88
+ def create_async_engine_for_url(
89
+ database_url: str | None,
90
+ db_path: str | None,
91
+ *,
92
+ pool_size: int = 2,
93
+ max_overflow: int = 4,
94
+ ) -> AsyncEngine:
95
+ """Async engine over the same database the sync engine uses.
96
+
97
+ Pool sizes default smaller than the sync engine's — the async side
98
+ (fastapi-users auth) is sparse traffic compared to the runs/state
99
+ endpoints. ``pool_pre_ping`` is on so a token-validation request
100
+ after a long idle period doesn't fail on a NAT-dropped TCP
101
+ connection.
102
+
103
+ Note: SQLite's aiosqlite dialect uses ``NullPool``-ish queueing where
104
+ the pool kwargs are still accepted; PostgreSQL honours them fully.
105
+ """
106
+ return create_async_engine(
107
+ async_url_for(database_url, db_path),
108
+ echo=False,
109
+ future=True,
110
+ pool_size=pool_size,
111
+ max_overflow=max_overflow,
112
+ pool_pre_ping=True,
113
+ )
dap_database/py.typed ADDED
File without changes
@@ -0,0 +1,49 @@
1
+ """Sync + async session factories and the transactional ``session_scope``.
2
+
3
+ Single home for the "session factory for this engine" pattern that was
4
+ split between ``dap_engine.persistence.db`` (sync) and
5
+ ``dap_engine.auth.db`` (async) — #778 Phase 1, finding 10.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Iterator
11
+ from contextlib import contextmanager
12
+
13
+ from sqlalchemy import Engine
14
+ from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
15
+ from sqlalchemy.orm import Session, sessionmaker
16
+
17
+ __all__ = [
18
+ "make_async_session_factory",
19
+ "make_session_factory",
20
+ "session_scope",
21
+ ]
22
+
23
+
24
+ def make_session_factory(engine: Engine) -> sessionmaker[Session]:
25
+ return sessionmaker(bind=engine, expire_on_commit=False, autoflush=False)
26
+
27
+
28
+ def make_async_session_factory(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]:
29
+ return async_sessionmaker(engine, expire_on_commit=False)
30
+
31
+
32
+ @contextmanager
33
+ def session_scope(factory: sessionmaker[Session]) -> Iterator[Session]:
34
+ """Commit on success, roll back on any exception, always close.
35
+
36
+ ``except BaseException`` (not ``Exception``) so ``KeyboardInterrupt`` /
37
+ ``SystemExit`` also roll back explicitly before close — otherwise a
38
+ Ctrl-C mid-transaction could leave the DB write lock held until the
39
+ process exits (PR #779 council review).
40
+ """
41
+ session = factory()
42
+ try:
43
+ yield session
44
+ session.commit()
45
+ except BaseException:
46
+ session.rollback()
47
+ raise
48
+ finally:
49
+ session.close()
dap_database/urls.py ADDED
@@ -0,0 +1,110 @@
1
+ """Database URL / dialect helpers.
2
+
3
+ Moved out of ``dap_engine.persistence.db`` and ``dap_engine.auth.db``
4
+ (#778 Phase 1) so the engine and the CLI share one implementation.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+ from typing import Literal
11
+
12
+ from sqlalchemy.engine import make_url
13
+ from sqlalchemy.exc import ArgumentError
14
+
15
+ __all__ = [
16
+ "async_url_for",
17
+ "detect_dialect",
18
+ "normalize_pg_prefix",
19
+ "pg_conn_string",
20
+ "pg_sync_url",
21
+ "redact_database_url",
22
+ ]
23
+
24
+
25
+ def detect_dialect(url: str) -> Literal["sqlite", "postgresql"]:
26
+ """Return ``"postgresql"`` for postgres-family URLs, else ``"sqlite"``.
27
+
28
+ Accepts ``postgresql+asyncpg://``, ``postgresql+psycopg://``, bare
29
+ ``postgresql://``, and heroku-style ``postgres://`` — all routed to the
30
+ PostgreSQL branch.
31
+ """
32
+ return "postgresql" if url.startswith(("postgresql", "postgres://")) else "sqlite"
33
+
34
+
35
+ def normalize_pg_prefix(url: str) -> str:
36
+ """Rewrite heroku-style ``postgres://`` to ``postgresql://`` for SQLAlchemy.
37
+
38
+ SQLAlchemy 1.4+ rejects the bare ``postgres://`` scheme; normalize at
39
+ consumption time so callers can pass either form.
40
+ """
41
+ if url.startswith("postgres://"):
42
+ return "postgresql://" + url[len("postgres://") :]
43
+ return url
44
+
45
+
46
+ def pg_sync_url(database_url: str) -> str:
47
+ """Return a SQLAlchemy URL guaranteed to use psycopg v3 as the sync driver.
48
+
49
+ Normalizes ``postgres://`` to ``postgresql://``, rewrites ``+asyncpg`` to
50
+ ``+psycopg``, and forces ``+psycopg`` on bare ``postgresql://`` URLs.
51
+ The bare scheme is critical: SQLAlchemy defaults bare ``postgresql://``
52
+ to psycopg2, which is not a project dependency, so create_engine would
53
+ fail at runtime without this rewrite.
54
+ """
55
+ url = normalize_pg_prefix(database_url)
56
+ url = url.replace("postgresql+asyncpg://", "postgresql+psycopg://", 1)
57
+ if url.startswith("postgresql://"):
58
+ url = "postgresql+psycopg://" + url[len("postgresql://") :]
59
+ return url
60
+
61
+
62
+ def pg_conn_string(database_url: str) -> str:
63
+ """Return a bare ``postgresql://`` conn string for psycopg (e.g. AsyncPostgresSaver)."""
64
+ url = normalize_pg_prefix(database_url)
65
+ return url.replace("postgresql+asyncpg://", "postgresql://", 1).replace(
66
+ "postgresql+psycopg://", "postgresql://", 1
67
+ )
68
+
69
+
70
+ def redact_database_url(url: str) -> str:
71
+ """Mask the password in a database URL for log/UI display.
72
+
73
+ Uses SQLAlchemy's ``make_url`` + ``render_as_string(hide_password=True)``
74
+ so URL-encoded passwords, IPv6 hosts, query params, and other quirks of
75
+ real-world database URLs round-trip safely. A naive string-splitting
76
+ redaction would leak credentials on URLs whose password contains ``@``
77
+ or other edge characters (Copilot review on PR #332 / #419).
78
+
79
+ Falls back to the input string if SQLAlchemy can't parse the URL — we
80
+ prefer surfacing a raw value over silently stripping something
81
+ important. Callers that log this should also fail loudly enough that
82
+ a malformed URL becomes obvious quickly.
83
+ """
84
+ try:
85
+ return make_url(url).render_as_string(hide_password=True)
86
+ except ArgumentError:
87
+ return url
88
+
89
+
90
+ def async_url_for(database_url: str | None, db_path: str | None) -> str:
91
+ """Build a SQLAlchemy async URL from the same inputs the sync engine uses.
92
+
93
+ Mirrors the sync-engine selection logic exactly: only PostgreSQL URLs in
94
+ ``database_url`` are honoured; SQLite URLs are ignored in favour of
95
+ ``db_path`` so both engines always point at the same underlying SQLite
96
+ file. Otherwise an operator setting ``DAP_DATABASE_URL=sqlite:///foo.db``
97
+ would silently get a different DB for auth than for the rest of the
98
+ engine.
99
+
100
+ Raises ``ValueError`` if neither input yields a usable URL —
101
+ callers must validate config before reaching this helper.
102
+ """
103
+ if database_url and detect_dialect(database_url) == "postgresql":
104
+ # psycopg v3 serves both sync and async over the same ``+psycopg``
105
+ # prefix; SQLAlchemy picks the mode from create_async_engine.
106
+ return pg_sync_url(database_url)
107
+ if db_path:
108
+ absolute = Path(db_path).resolve()
109
+ return f"sqlite+aiosqlite:///{absolute}"
110
+ raise ValueError("Either database_url (postgresql) or db_path must be provided")
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.5
2
+ Name: dap-database
3
+ Version: 0.4.1
4
+ Summary: Shared SQLAlchemy engine + session factories for DAP (SQLite WAL / PostgreSQL)
5
+ Project-URL: Homepage, https://github.com/lagowski/dap
6
+ Project-URL: Repository, https://github.com/lagowski/dap
7
+ Project-URL: Issues, https://github.com/lagowski/dap/issues
8
+ Project-URL: Author — Rafał Łagowski, https://www.linkedin.com/in/rafallagowski/
9
+ Project-URL: Author — Daniel Łagowski, https://www.linkedin.com/in/daniellagowski/
10
+ Author: Rafał Łagowski, Daniel Łagowski
11
+ License: MIT
12
+ Keywords: database,postgresql,sqlalchemy,sqlite
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.13
19
+ Requires-Dist: sqlalchemy>=2.0.52
20
+ Description-Content-Type: text/markdown
21
+
22
+ # dap-database
23
+
24
+ Shared SQLAlchemy plumbing for DAP (#778 Phase 1). Import path: `dap_database`.
25
+
26
+ One home for the pieces previously duplicated between
27
+ `dap_engine.persistence.db` (sync) and `dap_engine.auth.db` (async):
28
+
29
+ - **URL/dialect helpers** — `detect_dialect`, `normalize_pg_prefix`,
30
+ `pg_sync_url`, `pg_conn_string`, `redact_database_url`, `async_url_for`
31
+ - **Raw engine factories** — `create_sqlite_engine` (WAL pragmas, busy
32
+ timeout), `create_postgresql_engine` (psycopg v3, pre-ping, recycle),
33
+ `create_async_engine_for_url`
34
+ - **Session factories** — `make_session_factory`,
35
+ `make_async_session_factory`, `session_scope`
36
+
37
+ ## What deliberately stays out
38
+
39
+ - **ORM models and migrations** — schema ownership stays with the engine
40
+ (`dap_engine.persistence`). The factories here create *no* tables.
41
+ - **DB drivers** — `aiosqlite` / `psycopg` are consumer dependencies;
42
+ this package only requires `sqlalchemy`.
43
+
44
+ ```python
45
+ from dap_database import create_sqlite_engine, make_session_factory, session_scope
46
+
47
+ engine = create_sqlite_engine("/data/state.db")
48
+ factory = make_session_factory(engine)
49
+ with session_scope(factory) as session:
50
+ ...
51
+ ```
@@ -0,0 +1,8 @@
1
+ dap_database/__init__.py,sha256=mS5WEsBkyk8DFx4bSa24_ptu8odo0I2ltfgnKSEO6g0,1016
2
+ dap_database/engines.py,sha256=h-sh_qZKuEcfPkF9Um7hQAVs9BeFSCOutJQGfbB4k30,3768
3
+ dap_database/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ dap_database/sessions.py,sha256=jIUf8Ok4oNDvSCZj9Or6JtwtbOpUahDXhCnipFwhsic,1555
5
+ dap_database/urls.py,sha256=QRKwMIEiQOqlW0MFP8Sf-Dl-6T8PV4hGEnjVUlh2_ec,4319
6
+ dap_database-0.4.1.dist-info/METADATA,sha256=MHHPOq0YWuZcgrLaLid2hckh_1h9ovD4gZsoe6Ejk3U,2074
7
+ dap_database-0.4.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ dap_database-0.4.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any