dap-database 0.4.1__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.
- dap_database-0.4.1/.gitignore +94 -0
- dap_database-0.4.1/PKG-INFO +51 -0
- dap_database-0.4.1/README.md +30 -0
- dap_database-0.4.1/pyproject.toml +46 -0
- dap_database-0.4.1/src/dap_database/__init__.py +40 -0
- dap_database-0.4.1/src/dap_database/engines.py +113 -0
- dap_database-0.4.1/src/dap_database/py.typed +0 -0
- dap_database-0.4.1/src/dap_database/sessions.py +49 -0
- dap_database-0.4.1/src/dap_database/urls.py +110 -0
- dap_database-0.4.1/tests/test_engines_and_sessions.py +171 -0
- dap_database-0.4.1/tests/test_url_helpers.py +90 -0
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# --- Python ---
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
*.so
|
|
6
|
+
.Python
|
|
7
|
+
.venv/
|
|
8
|
+
venv/
|
|
9
|
+
env/
|
|
10
|
+
*.egg-info/
|
|
11
|
+
*.egg
|
|
12
|
+
dist/
|
|
13
|
+
build/
|
|
14
|
+
.eggs/
|
|
15
|
+
pip-log.txt
|
|
16
|
+
pip-delete-this-directory.txt
|
|
17
|
+
|
|
18
|
+
# uv
|
|
19
|
+
.uv-cache/
|
|
20
|
+
|
|
21
|
+
# Type checkers / linters
|
|
22
|
+
.mypy_cache/
|
|
23
|
+
.ruff_cache/
|
|
24
|
+
.pyright/
|
|
25
|
+
.pytype/
|
|
26
|
+
|
|
27
|
+
# pytest / coverage
|
|
28
|
+
.pytest_cache/
|
|
29
|
+
.coverage
|
|
30
|
+
.coverage.*
|
|
31
|
+
htmlcov/
|
|
32
|
+
.tox/
|
|
33
|
+
.nox/
|
|
34
|
+
coverage.xml
|
|
35
|
+
*.cover
|
|
36
|
+
|
|
37
|
+
# --- Node (dashboard) ---
|
|
38
|
+
node_modules/
|
|
39
|
+
.pnpm-store/
|
|
40
|
+
.next/
|
|
41
|
+
out/
|
|
42
|
+
*.tsbuildinfo
|
|
43
|
+
.turbo/
|
|
44
|
+
|
|
45
|
+
# --- Environment ---
|
|
46
|
+
.env
|
|
47
|
+
.env.local
|
|
48
|
+
.env.*.local
|
|
49
|
+
|
|
50
|
+
# --- DAP local state ---
|
|
51
|
+
.dap/
|
|
52
|
+
*.db
|
|
53
|
+
*.db-journal
|
|
54
|
+
*.db-wal
|
|
55
|
+
*.db-shm
|
|
56
|
+
|
|
57
|
+
# --- Logs ---
|
|
58
|
+
logs/
|
|
59
|
+
*.log
|
|
60
|
+
npm-debug.log*
|
|
61
|
+
pnpm-debug.log*
|
|
62
|
+
|
|
63
|
+
# --- IDE / Agents ---
|
|
64
|
+
.vscode/
|
|
65
|
+
.idea/
|
|
66
|
+
*.swp
|
|
67
|
+
*.swo
|
|
68
|
+
.claude/
|
|
69
|
+
|
|
70
|
+
# --- OS ---
|
|
71
|
+
.DS_Store
|
|
72
|
+
Thumbs.db
|
|
73
|
+
|
|
74
|
+
# --- Cache ---
|
|
75
|
+
.cache/
|
|
76
|
+
.eslintcache
|
|
77
|
+
|
|
78
|
+
# --- Built artefacts ---
|
|
79
|
+
# Dashboard bundle staged into the dap-cli wheel by
|
|
80
|
+
# scripts/build-dashboard-bundle.sh — regenerated on demand from
|
|
81
|
+
# apps/dashboard/.next. The ``.gitkeep`` is retained so hatchling's
|
|
82
|
+
# ``force-include`` always finds the directory; dev wheels built
|
|
83
|
+
# without running the bundle script ship an effectively-empty
|
|
84
|
+
# ``_dashboard/`` and ``dap start`` falls back to "dashboard not
|
|
85
|
+
# bundled".
|
|
86
|
+
apps/cli/src/dap_cli/_dashboard/*
|
|
87
|
+
!apps/cli/src/dap_cli/_dashboard/.gitkeep
|
|
88
|
+
.mcp.json
|
|
89
|
+
|
|
90
|
+
# --- Playwright (e2e) ---
|
|
91
|
+
e2e/.auth/
|
|
92
|
+
e2e/test-results/
|
|
93
|
+
e2e/playwright-report/
|
|
94
|
+
.gstack/
|
|
@@ -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,30 @@
|
|
|
1
|
+
# dap-database
|
|
2
|
+
|
|
3
|
+
Shared SQLAlchemy plumbing for DAP (#778 Phase 1). Import path: `dap_database`.
|
|
4
|
+
|
|
5
|
+
One home for the pieces previously duplicated between
|
|
6
|
+
`dap_engine.persistence.db` (sync) and `dap_engine.auth.db` (async):
|
|
7
|
+
|
|
8
|
+
- **URL/dialect helpers** — `detect_dialect`, `normalize_pg_prefix`,
|
|
9
|
+
`pg_sync_url`, `pg_conn_string`, `redact_database_url`, `async_url_for`
|
|
10
|
+
- **Raw engine factories** — `create_sqlite_engine` (WAL pragmas, busy
|
|
11
|
+
timeout), `create_postgresql_engine` (psycopg v3, pre-ping, recycle),
|
|
12
|
+
`create_async_engine_for_url`
|
|
13
|
+
- **Session factories** — `make_session_factory`,
|
|
14
|
+
`make_async_session_factory`, `session_scope`
|
|
15
|
+
|
|
16
|
+
## What deliberately stays out
|
|
17
|
+
|
|
18
|
+
- **ORM models and migrations** — schema ownership stays with the engine
|
|
19
|
+
(`dap_engine.persistence`). The factories here create *no* tables.
|
|
20
|
+
- **DB drivers** — `aiosqlite` / `psycopg` are consumer dependencies;
|
|
21
|
+
this package only requires `sqlalchemy`.
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from dap_database import create_sqlite_engine, make_session_factory, session_scope
|
|
25
|
+
|
|
26
|
+
engine = create_sqlite_engine("/data/state.db")
|
|
27
|
+
factory = make_session_factory(engine)
|
|
28
|
+
with session_scope(factory) as session:
|
|
29
|
+
...
|
|
30
|
+
```
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
# Shared SQLAlchemy plumbing for DAP (#778 Phase 1). Import path is
|
|
3
|
+
# ``dap_database``. Holds the dialect-agnostic pieces previously
|
|
4
|
+
# duplicated between ``dap_engine.persistence.db`` and
|
|
5
|
+
# ``dap_engine.auth.db``: URL/dialect helpers, raw engine factories
|
|
6
|
+
# (SQLite WAL pragmas, PostgreSQL pool tuning), and sync/async session
|
|
7
|
+
# factories. Schema creation and migrations stay in the engine — this
|
|
8
|
+
# package never imports ORM models.
|
|
9
|
+
name = "dap-database"
|
|
10
|
+
version = "0.4.1"
|
|
11
|
+
description = "Shared SQLAlchemy engine + session factories for DAP (SQLite WAL / PostgreSQL)"
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
requires-python = ">=3.13"
|
|
14
|
+
license = { text = "MIT" }
|
|
15
|
+
authors = [
|
|
16
|
+
{ name = "Rafał Łagowski" },
|
|
17
|
+
{ name = "Daniel Łagowski" },
|
|
18
|
+
]
|
|
19
|
+
dependencies = [
|
|
20
|
+
# DB drivers (aiosqlite, psycopg) are deliberately NOT declared here —
|
|
21
|
+
# the consumer picks its backend and ships the driver, mirroring how
|
|
22
|
+
# the engine already treats psycopg as its own dependency.
|
|
23
|
+
"sqlalchemy>=2.0.52",
|
|
24
|
+
]
|
|
25
|
+
keywords = ["sqlalchemy", "database", "sqlite", "postgresql"]
|
|
26
|
+
classifiers = [
|
|
27
|
+
"Development Status :: 3 - Alpha",
|
|
28
|
+
"Intended Audience :: Developers",
|
|
29
|
+
"Programming Language :: Python :: 3",
|
|
30
|
+
"Programming Language :: Python :: 3.13",
|
|
31
|
+
"Typing :: Typed",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[project.urls]
|
|
35
|
+
Homepage = "https://github.com/lagowski/dap"
|
|
36
|
+
Repository = "https://github.com/lagowski/dap"
|
|
37
|
+
Issues = "https://github.com/lagowski/dap/issues"
|
|
38
|
+
"Author — Rafał Łagowski" = "https://www.linkedin.com/in/rafallagowski/"
|
|
39
|
+
"Author — Daniel Łagowski" = "https://www.linkedin.com/in/daniellagowski/"
|
|
40
|
+
|
|
41
|
+
[build-system]
|
|
42
|
+
requires = ["hatchling"]
|
|
43
|
+
build-backend = "hatchling.build"
|
|
44
|
+
|
|
45
|
+
[tool.hatch.build.targets.wheel]
|
|
46
|
+
packages = ["src/dap_database"]
|
|
@@ -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
|
+
)
|
|
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()
|
|
@@ -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,171 @@
|
|
|
1
|
+
"""Unit tests for dap_database engine + session factories (#778 Phase 1).
|
|
2
|
+
|
|
3
|
+
The raw engine factories here create **no schema** — running migrations
|
|
4
|
+
is the consumer's job (``dap_engine.persistence.db`` keeps that part).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from unittest.mock import patch
|
|
11
|
+
|
|
12
|
+
import pytest
|
|
13
|
+
from dap_database import (
|
|
14
|
+
create_async_engine_for_url,
|
|
15
|
+
create_postgresql_engine,
|
|
16
|
+
create_sqlite_engine,
|
|
17
|
+
make_async_session_factory,
|
|
18
|
+
make_session_factory,
|
|
19
|
+
session_scope,
|
|
20
|
+
)
|
|
21
|
+
from sqlalchemy import text
|
|
22
|
+
from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker
|
|
23
|
+
from sqlalchemy.orm import Session
|
|
24
|
+
from sqlalchemy.pool import QueuePool
|
|
25
|
+
|
|
26
|
+
# ---------------------------------------------------------------------------
|
|
27
|
+
# SQLite engine
|
|
28
|
+
# ---------------------------------------------------------------------------
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_create_sqlite_engine_creates_parent_dirs(tmp_path: Path) -> None:
|
|
32
|
+
db_path = tmp_path / "nested" / "dir" / "state.db"
|
|
33
|
+
engine = create_sqlite_engine(str(db_path))
|
|
34
|
+
try:
|
|
35
|
+
with engine.connect() as conn:
|
|
36
|
+
conn.execute(text("SELECT 1"))
|
|
37
|
+
assert db_path.parent.is_dir()
|
|
38
|
+
finally:
|
|
39
|
+
engine.dispose()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_create_sqlite_engine_enables_wal_and_pragmas(tmp_path: Path) -> None:
|
|
43
|
+
engine = create_sqlite_engine(str(tmp_path / "state.db"))
|
|
44
|
+
try:
|
|
45
|
+
with engine.connect() as conn:
|
|
46
|
+
assert conn.execute(text("PRAGMA journal_mode")).scalar() == "wal"
|
|
47
|
+
assert conn.execute(text("PRAGMA foreign_keys")).scalar() == 1
|
|
48
|
+
assert conn.execute(text("PRAGMA busy_timeout")).scalar() == 5000
|
|
49
|
+
finally:
|
|
50
|
+
engine.dispose()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_create_sqlite_engine_does_not_create_schema(tmp_path: Path) -> None:
|
|
54
|
+
"""Raw factory must not bake in any app schema — that's the consumer's job."""
|
|
55
|
+
engine = create_sqlite_engine(str(tmp_path / "state.db"))
|
|
56
|
+
try:
|
|
57
|
+
with engine.connect() as conn:
|
|
58
|
+
tables = conn.execute(
|
|
59
|
+
text("SELECT name FROM sqlite_master WHERE type='table'")
|
|
60
|
+
).fetchall()
|
|
61
|
+
assert tables == []
|
|
62
|
+
finally:
|
|
63
|
+
engine.dispose()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# ---------------------------------------------------------------------------
|
|
67
|
+
# PostgreSQL engine (no live server — engine creation does not connect)
|
|
68
|
+
# ---------------------------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_create_postgresql_engine_rewrites_to_psycopg_driver() -> None:
|
|
72
|
+
engine = create_postgresql_engine("postgresql+asyncpg://u:p@localhost:1/db")
|
|
73
|
+
try:
|
|
74
|
+
assert engine.url.drivername == "postgresql+psycopg"
|
|
75
|
+
finally:
|
|
76
|
+
engine.dispose()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_create_postgresql_engine_pool_defaults() -> None:
|
|
80
|
+
engine = create_postgresql_engine("postgres://u:p@localhost:1/db")
|
|
81
|
+
try:
|
|
82
|
+
assert isinstance(engine.pool, QueuePool)
|
|
83
|
+
assert engine.pool.size() == 5
|
|
84
|
+
assert engine.pool._max_overflow == 10
|
|
85
|
+
finally:
|
|
86
|
+
engine.dispose()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_create_postgresql_engine_pool_overrides() -> None:
|
|
90
|
+
engine = create_postgresql_engine(
|
|
91
|
+
"postgresql://u:p@localhost:1/db", pool_size=7, max_overflow=3
|
|
92
|
+
)
|
|
93
|
+
try:
|
|
94
|
+
assert isinstance(engine.pool, QueuePool)
|
|
95
|
+
assert engine.pool.size() == 7
|
|
96
|
+
assert engine.pool._max_overflow == 3
|
|
97
|
+
finally:
|
|
98
|
+
engine.dispose()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# ---------------------------------------------------------------------------
|
|
102
|
+
# Session factories
|
|
103
|
+
# ---------------------------------------------------------------------------
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_session_scope_commits_on_success(tmp_path: Path) -> None:
|
|
107
|
+
engine = create_sqlite_engine(str(tmp_path / "state.db"))
|
|
108
|
+
try:
|
|
109
|
+
factory = make_session_factory(engine)
|
|
110
|
+
with session_scope(factory) as session:
|
|
111
|
+
session.execute(text("CREATE TABLE t (x INTEGER)"))
|
|
112
|
+
session.execute(text("INSERT INTO t VALUES (42)"))
|
|
113
|
+
with session_scope(factory) as session:
|
|
114
|
+
assert session.execute(text("SELECT x FROM t")).scalar() == 42
|
|
115
|
+
finally:
|
|
116
|
+
engine.dispose()
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def test_session_scope_rolls_back_on_error(tmp_path: Path) -> None:
|
|
120
|
+
engine = create_sqlite_engine(str(tmp_path / "state.db"))
|
|
121
|
+
try:
|
|
122
|
+
factory = make_session_factory(engine)
|
|
123
|
+
with session_scope(factory) as session:
|
|
124
|
+
session.execute(text("CREATE TABLE t (x INTEGER)"))
|
|
125
|
+
with pytest.raises(RuntimeError), session_scope(factory) as session:
|
|
126
|
+
session.execute(text("INSERT INTO t VALUES (1)"))
|
|
127
|
+
raise RuntimeError("boom")
|
|
128
|
+
with session_scope(factory) as session:
|
|
129
|
+
assert session.execute(text("SELECT COUNT(*) FROM t")).scalar() == 0
|
|
130
|
+
finally:
|
|
131
|
+
engine.dispose()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def test_session_scope_rolls_back_on_keyboard_interrupt(tmp_path: Path) -> None:
|
|
135
|
+
"""Ctrl-C inside the scope must roll back explicitly before close.
|
|
136
|
+
|
|
137
|
+
``KeyboardInterrupt`` inherits from ``BaseException``, not ``Exception``
|
|
138
|
+
— a bare ``except Exception`` would skip the rollback and leave the
|
|
139
|
+
write lock held until process exit (PR #779 council review, MEDIUM).
|
|
140
|
+
"""
|
|
141
|
+
engine = create_sqlite_engine(str(tmp_path / "state.db"))
|
|
142
|
+
try:
|
|
143
|
+
factory = make_session_factory(engine)
|
|
144
|
+
with patch.object(Session, "rollback", autospec=True) as rollback: # noqa: SIM117 — the raises() scope must not cover the mock assert
|
|
145
|
+
with pytest.raises(KeyboardInterrupt), session_scope(factory):
|
|
146
|
+
raise KeyboardInterrupt
|
|
147
|
+
rollback.assert_called_once()
|
|
148
|
+
finally:
|
|
149
|
+
engine.dispose()
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# ---------------------------------------------------------------------------
|
|
153
|
+
# Async engine
|
|
154
|
+
# ---------------------------------------------------------------------------
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def test_create_async_engine_for_url_sqlite(tmp_path: Path) -> None:
|
|
158
|
+
engine = create_async_engine_for_url(None, str(tmp_path / "state.db"))
|
|
159
|
+
assert isinstance(engine, AsyncEngine)
|
|
160
|
+
assert engine.url.drivername == "sqlite+aiosqlite"
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def test_create_async_engine_for_url_postgres() -> None:
|
|
164
|
+
engine = create_async_engine_for_url("postgresql+asyncpg://u:p@localhost:1/db", None)
|
|
165
|
+
assert engine.url.drivername == "postgresql+psycopg"
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def test_make_async_session_factory_shape(tmp_path: Path) -> None:
|
|
169
|
+
engine = create_async_engine_for_url(None, str(tmp_path / "state.db"))
|
|
170
|
+
factory = make_async_session_factory(engine)
|
|
171
|
+
assert isinstance(factory, async_sessionmaker)
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Unit tests for dap_database URL/dialect helpers (#778 Phase 1).
|
|
2
|
+
|
|
3
|
+
Canonical home of the behaviour previously tested via
|
|
4
|
+
``dap_engine.persistence.db`` in ``tests/smoke/test_db_url_helpers.py`` —
|
|
5
|
+
the engine module now re-exports from ``dap_database``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dap_database import (
|
|
11
|
+
async_url_for,
|
|
12
|
+
detect_dialect,
|
|
13
|
+
normalize_pg_prefix,
|
|
14
|
+
pg_conn_string,
|
|
15
|
+
pg_sync_url,
|
|
16
|
+
redact_database_url,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_detect_dialect_accepts_postgres_scheme() -> None:
|
|
21
|
+
assert detect_dialect("postgres://user:pw@host/db") == "postgresql"
|
|
22
|
+
assert detect_dialect("postgresql://x") == "postgresql"
|
|
23
|
+
assert detect_dialect("postgresql+asyncpg://x") == "postgresql"
|
|
24
|
+
assert detect_dialect("postgresql+psycopg://x") == "postgresql"
|
|
25
|
+
assert detect_dialect("sqlite:///x") == "sqlite"
|
|
26
|
+
assert detect_dialect("/bare/path.db") == "sqlite"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def test_normalize_pg_prefix() -> None:
|
|
30
|
+
assert normalize_pg_prefix("postgres://user:pw@host/db") == "postgresql://user:pw@host/db"
|
|
31
|
+
assert normalize_pg_prefix("postgresql://x") == "postgresql://x"
|
|
32
|
+
assert normalize_pg_prefix("postgresql+asyncpg://x") == "postgresql+asyncpg://x"
|
|
33
|
+
assert normalize_pg_prefix("sqlite:///x") == "sqlite:///x"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_pg_sync_url_forces_psycopg_driver() -> None:
|
|
37
|
+
assert pg_sync_url("postgresql+asyncpg://u:p@h/db") == "postgresql+psycopg://u:p@h/db"
|
|
38
|
+
assert pg_sync_url("postgresql://u:p@h/db") == "postgresql+psycopg://u:p@h/db"
|
|
39
|
+
assert pg_sync_url("postgres://u:p@h/db") == "postgresql+psycopg://u:p@h/db"
|
|
40
|
+
assert pg_sync_url("postgresql+psycopg://u:p@h/db") == "postgresql+psycopg://u:p@h/db"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_pg_conn_string_strips_driver_suffix() -> None:
|
|
44
|
+
assert pg_conn_string("postgres://u:p@h/db") == "postgresql://u:p@h/db"
|
|
45
|
+
assert pg_conn_string("postgresql+asyncpg://u:p@h/db") == "postgresql://u:p@h/db"
|
|
46
|
+
assert pg_conn_string("postgresql+psycopg://u:p@h/db") == "postgresql://u:p@h/db"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_redact_database_url_masks_password() -> None:
|
|
50
|
+
redacted = redact_database_url("postgresql+psycopg://user:s3cret@host:5432/db")
|
|
51
|
+
assert "s3cret" not in redacted
|
|
52
|
+
assert "user" in redacted
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_redact_database_url_handles_password_with_at_sign() -> None:
|
|
56
|
+
redacted = redact_database_url("postgresql://user:p%40ss@host/db")
|
|
57
|
+
assert "p%40ss" not in redacted
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_redact_database_url_falls_back_on_unparseable_input() -> None:
|
|
61
|
+
assert redact_database_url("not a url at all") == "not a url at all"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_async_url_for_prefers_postgres_database_url() -> None:
|
|
65
|
+
url = async_url_for("postgresql+asyncpg://u:p@h/db", "/tmp/state.db")
|
|
66
|
+
assert url == "postgresql+psycopg://u:p@h/db"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_async_url_for_bare_postgres_scheme_gets_psycopg() -> None:
|
|
70
|
+
url = async_url_for("postgresql://u:p@h/db", None)
|
|
71
|
+
assert url == "postgresql+psycopg://u:p@h/db"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_async_url_for_sqlite_database_url_is_ignored_in_favour_of_db_path(
|
|
75
|
+
tmp_path_factory: object,
|
|
76
|
+
) -> None:
|
|
77
|
+
# A sqlite:// DATABASE_URL must not diverge the auth DB from the main
|
|
78
|
+
# DB — only db_path is honoured for the sqlite branch.
|
|
79
|
+
url = async_url_for("sqlite:///elsewhere.db", "/data/state.db")
|
|
80
|
+
assert url.startswith("sqlite+aiosqlite:///")
|
|
81
|
+
assert url.endswith("/data/state.db")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_async_url_for_raises_without_usable_input() -> None:
|
|
85
|
+
import pytest
|
|
86
|
+
|
|
87
|
+
with pytest.raises(ValueError, match="db_path"):
|
|
88
|
+
async_url_for(None, None)
|
|
89
|
+
with pytest.raises(ValueError, match="db_path"):
|
|
90
|
+
async_url_for("sqlite:///x.db", None)
|