irmy-db 1.0.0__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.
irmy_db-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bendyna V. S.R.L.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
irmy_db-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: irmy-db
3
+ Version: 1.0.0
4
+ Summary: Async PostgreSQL (SQLAlchemy + asyncpg) access with healthcheck and Prometheus metrics for IRMy services
5
+ Author-email: "Bendyna V. S.R.L." <info@irmy.tech>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://irmy.tech
8
+ Project-URL: Documentation, https://irmy.tech/docs/
9
+ Project-URL: Source, https://github.com/IRMy-tech/irmy-db
10
+ Project-URL: Issues, https://github.com/IRMy-tech/irmy-db/issues
11
+ Project-URL: Changelog, https://github.com/IRMy-tech/irmy-db/blob/main/CHANGELOG.md
12
+ Keywords: irmy,postgresql,sqlalchemy,asyncpg,prometheus
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Database
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.12
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: SQLAlchemy<2.1,>=2.0.54
26
+ Requires-Dist: asyncpg<1,>=0.31.0
27
+ Requires-Dist: greenlet<4,>=3.5.6
28
+ Requires-Dist: prometheus-client<1,>=0.26.0
29
+ Provides-Extra: test
30
+ Requires-Dist: pytest>=8; extra == "test"
31
+ Requires-Dist: pytest-asyncio>=0.24; extra == "test"
32
+ Dynamic: license-file
33
+
34
+ # irmy-db
35
+
36
+ Async PostgreSQL access for IRMy Python services: a SQLAlchemy 2 async engine
37
+ (asyncpg) with a session factory, schema selection via `search_path`, a real
38
+ database healthcheck and Prometheus metrics for the connection pool and query
39
+ durations.
40
+
41
+ ```bash
42
+ pip install irmy-db
43
+ ```
44
+
45
+ Requires Python 3.12+. The import package is `irmy_db`.
46
+
47
+ ## Usage
48
+
49
+ ```python
50
+ import logging
51
+
52
+ from sqlalchemy import text
53
+ from irmy_db import InitializeDB
54
+
55
+ logger = logging.getLogger("my-service")
56
+
57
+ db = InitializeDB(
58
+ connection_string="postgresql+asyncpg://user:password@localhost:5432/irmy",
59
+ postgres_schema="public",
60
+ logger=logger,
61
+ )
62
+
63
+
64
+ async def do_something():
65
+ async with db.get_session() as session:
66
+ await session.execute(text("SELECT 1"))
67
+
68
+
69
+ async def healthcheck() -> bool:
70
+ # Runs SELECT 1 against the database, False on error or after 5 seconds.
71
+ return await db.get_health(timeout=5.0)
72
+
73
+
74
+ async def shutdown():
75
+ # Do not forget to close the connection pool.
76
+ await db.disconnect_from_db()
77
+ ```
78
+
79
+ `InitializeDB` arguments:
80
+
81
+ | Argument | Default | Description |
82
+ |---|---|---|
83
+ | `connection_string` | — | SQLAlchemy async URL (`postgresql+asyncpg://…`) |
84
+ | `postgres_schema` | — | Schema set as `search_path` for every connection |
85
+ | `logger` | — | `logging.Logger` |
86
+ | `pool` | `5` | Connections kept open (env `POSTGRESQL_POOL_SIZE` overrides) |
87
+ | `pool_overflow` | `10` | Connections allowed above the pool size, closed again when returned (env `POSTGRESQL_MAX_OVERFLOW` overrides) |
88
+ | `pool_recycle` | `3600` | Seconds after which a connection is replaced (env `POSTGRESQL_POOL_RECYCLE_SECONDS` overrides) |
89
+ | `enable_metrics` | `True` | Register Prometheus pool and query metrics |
90
+
91
+ ## Metrics
92
+
93
+ | Metric | Type | Description |
94
+ |---|---|---|
95
+ | `db_pool_size` | Gauge | Connection pool size |
96
+ | `db_pool_checkedin` | Gauge | Checked-in (idle) connections |
97
+ | `db_pool_checkedout` | Gauge | Checked-out (in use) connections |
98
+ | `db_pool_overflow` | Gauge | Overflow connections |
99
+ | `db_connections_opened_total` | Counter | Connections opened; a steady climb under load means the pool is too small |
100
+ | `db_query_duration_seconds` | Histogram, label `operation` | Query duration by SQL verb (`select`, `insert`, …) |
101
+
102
+ The pool gauges are process-wide: use one `InitializeDB` per process.
@@ -0,0 +1,69 @@
1
+ # irmy-db
2
+
3
+ Async PostgreSQL access for IRMy Python services: a SQLAlchemy 2 async engine
4
+ (asyncpg) with a session factory, schema selection via `search_path`, a real
5
+ database healthcheck and Prometheus metrics for the connection pool and query
6
+ durations.
7
+
8
+ ```bash
9
+ pip install irmy-db
10
+ ```
11
+
12
+ Requires Python 3.12+. The import package is `irmy_db`.
13
+
14
+ ## Usage
15
+
16
+ ```python
17
+ import logging
18
+
19
+ from sqlalchemy import text
20
+ from irmy_db import InitializeDB
21
+
22
+ logger = logging.getLogger("my-service")
23
+
24
+ db = InitializeDB(
25
+ connection_string="postgresql+asyncpg://user:password@localhost:5432/irmy",
26
+ postgres_schema="public",
27
+ logger=logger,
28
+ )
29
+
30
+
31
+ async def do_something():
32
+ async with db.get_session() as session:
33
+ await session.execute(text("SELECT 1"))
34
+
35
+
36
+ async def healthcheck() -> bool:
37
+ # Runs SELECT 1 against the database, False on error or after 5 seconds.
38
+ return await db.get_health(timeout=5.0)
39
+
40
+
41
+ async def shutdown():
42
+ # Do not forget to close the connection pool.
43
+ await db.disconnect_from_db()
44
+ ```
45
+
46
+ `InitializeDB` arguments:
47
+
48
+ | Argument | Default | Description |
49
+ |---|---|---|
50
+ | `connection_string` | — | SQLAlchemy async URL (`postgresql+asyncpg://…`) |
51
+ | `postgres_schema` | — | Schema set as `search_path` for every connection |
52
+ | `logger` | — | `logging.Logger` |
53
+ | `pool` | `5` | Connections kept open (env `POSTGRESQL_POOL_SIZE` overrides) |
54
+ | `pool_overflow` | `10` | Connections allowed above the pool size, closed again when returned (env `POSTGRESQL_MAX_OVERFLOW` overrides) |
55
+ | `pool_recycle` | `3600` | Seconds after which a connection is replaced (env `POSTGRESQL_POOL_RECYCLE_SECONDS` overrides) |
56
+ | `enable_metrics` | `True` | Register Prometheus pool and query metrics |
57
+
58
+ ## Metrics
59
+
60
+ | Metric | Type | Description |
61
+ |---|---|---|
62
+ | `db_pool_size` | Gauge | Connection pool size |
63
+ | `db_pool_checkedin` | Gauge | Checked-in (idle) connections |
64
+ | `db_pool_checkedout` | Gauge | Checked-out (in use) connections |
65
+ | `db_pool_overflow` | Gauge | Overflow connections |
66
+ | `db_connections_opened_total` | Counter | Connections opened; a steady climb under load means the pool is too small |
67
+ | `db_query_duration_seconds` | Histogram, label `operation` | Query duration by SQL verb (`select`, `insert`, …) |
68
+
69
+ The pool gauges are process-wide: use one `InitializeDB` per process.
@@ -0,0 +1 @@
1
+ from ._database import InitializeDB
@@ -0,0 +1,151 @@
1
+ import asyncio
2
+ import os
3
+ from contextlib import asynccontextmanager
4
+ from logging import Logger
5
+ from typing import AsyncGenerator
6
+
7
+ from prometheus_client import Counter, Gauge, Histogram
8
+ from sqlalchemy import event, text
9
+ from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
10
+ from sqlalchemy.pool import QueuePool
11
+ import time
12
+
13
+
14
+ _pool_size = Gauge("db_pool_size", "Connection pool size")
15
+ _pool_checked_in = Gauge("db_pool_checkedin", "Checked in connections")
16
+ _pool_checked_out = Gauge("db_pool_checkedout", "Checked out connections")
17
+ _pool_overflow = Gauge("db_pool_overflow", "Pool overflow connections")
18
+ _connections_opened = Counter(
19
+ "db_connections_opened_total",
20
+ "Database connections opened by the pool; a steady climb under load means the pool is too "
21
+ "small and overflow connections are opened and closed again",
22
+ )
23
+
24
+ # Environment variables override the pool settings given in code, so one image can be sized per
25
+ # deployment (a busy service gets a bigger pool through its Helm values).
26
+ ENV_POOL_SIZE = "POSTGRESQL_POOL_SIZE"
27
+ ENV_MAX_OVERFLOW = "POSTGRESQL_MAX_OVERFLOW"
28
+ ENV_POOL_RECYCLE = "POSTGRESQL_POOL_RECYCLE_SECONDS"
29
+
30
+
31
+ def _setting(env_name: str, value: int, minimum: int) -> int:
32
+ """`value`, or the integer in environment variable `env_name` when it is set."""
33
+ raw = os.environ.get(env_name)
34
+ if raw is not None and raw.strip() != "":
35
+ try:
36
+ value = int(raw)
37
+ except ValueError:
38
+ raise ValueError(f"{env_name} must be an integer, got {raw!r}") from None
39
+ if value < minimum:
40
+ raise ValueError(f"{env_name} must be at least {minimum}, got {value}")
41
+ return value
42
+
43
+ _query_duration = Histogram(
44
+ "db_query_duration_seconds",
45
+ "DB query duration",
46
+ ["operation"],
47
+ buckets=[0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0],
48
+ )
49
+
50
+
51
+ class InitializeDB:
52
+ def __init__(self, connection_string: str, postgres_schema: str, logger: Logger,
53
+ pool: int = 5, pool_overflow: int = 10, pool_recycle: int = 3600, enable_metrics: bool = True
54
+ ):
55
+ """
56
+ ``pool`` connections are kept open; up to ``pool_overflow`` more are opened under load and
57
+ closed as soon as they are returned, so a pool that is too small keeps reconnecting (each
58
+ new connection also re-reads type information and re-prepares its statements). Connections
59
+ older than ``pool_recycle`` seconds are replaced. ``POSTGRESQL_POOL_SIZE``,
60
+ ``POSTGRESQL_MAX_OVERFLOW`` and ``POSTGRESQL_POOL_RECYCLE_SECONDS`` override all three.
61
+ """
62
+ self._logger = logger
63
+ self._enable_metrics = enable_metrics
64
+ pool = _setting(ENV_POOL_SIZE, pool, 1)
65
+ pool_overflow = _setting(ENV_MAX_OVERFLOW, pool_overflow, 0)
66
+ pool_recycle = _setting(ENV_POOL_RECYCLE, pool_recycle, 1)
67
+ self._logger.info(
68
+ f"Initializing database connection (pool {pool}, overflow {pool_overflow}, "
69
+ f"recycle {pool_recycle}s)..."
70
+ )
71
+
72
+ self._engine = create_async_engine(
73
+ connection_string,
74
+ pool_size=pool,
75
+ max_overflow=pool_overflow,
76
+ pool_recycle=pool_recycle,
77
+ connect_args={"server_settings": {"search_path": postgres_schema}},
78
+ # Kept with the longer-lived pool: after a database restart it stops a dead connection
79
+ # from being handed out.
80
+ pool_pre_ping=True,
81
+ )
82
+ self._async_session_local = async_sessionmaker(bind=self._engine, expire_on_commit=False)
83
+ self._disposed = False
84
+
85
+ if self._enable_metrics:
86
+ self._setup_metrics()
87
+ self._logger.info("SQLAlchemy Prometheus metrics enabled.")
88
+
89
+ def _setup_metrics(self) -> None:
90
+ sync_engine = self._engine.sync_engine
91
+
92
+ def _update_pool_metrics() -> None:
93
+ pool: QueuePool = sync_engine.pool # type: ignore[assignment]
94
+ _pool_size.set(pool.size())
95
+ _pool_checked_in.set(pool.checkedin())
96
+ _pool_checked_out.set(pool.checkedout())
97
+ _pool_overflow.set(pool.overflow())
98
+
99
+ @event.listens_for(sync_engine, "connect")
100
+ def on_connect(dbapi_conn, connection_record):
101
+ _connections_opened.inc()
102
+ _update_pool_metrics()
103
+
104
+ @event.listens_for(sync_engine, "checkout")
105
+ def on_checkout(dbapi_conn, connection_record, connection_proxy):
106
+ _update_pool_metrics()
107
+
108
+ @event.listens_for(sync_engine, "checkin")
109
+ def on_checkin(dbapi_conn, connection_record):
110
+ _update_pool_metrics()
111
+
112
+ @event.listens_for(sync_engine, "before_cursor_execute")
113
+ def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
114
+ conn.info["query_start_time"] = time.perf_counter()
115
+
116
+ @event.listens_for(sync_engine, "after_cursor_execute")
117
+ def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
118
+ start = conn.info.get("query_start_time")
119
+ if start is None:
120
+ return
121
+ duration = time.perf_counter() - start
122
+ stripped = statement.strip()
123
+ if stripped.startswith("/*"):
124
+ stripped = stripped.split("*/", 1)[-1].strip()
125
+ operation = stripped.split()[0].lower() if stripped else "unknown"
126
+ _query_duration.labels(operation=operation).observe(duration)
127
+
128
+ @asynccontextmanager
129
+ async def get_session(self) -> AsyncGenerator[AsyncSession, None]:
130
+ async with self._async_session_local() as session:
131
+ yield session
132
+
133
+ async def disconnect_from_db(self) -> None:
134
+ self._disposed = True
135
+ await self._engine.dispose()
136
+
137
+ async def get_health(self, timeout: float = 5.0) -> bool:
138
+ """True if the database answers ``SELECT 1`` within ``timeout`` seconds."""
139
+ if self._disposed:
140
+ return False
141
+ try:
142
+ async with asyncio.timeout(timeout):
143
+ async with self._engine.connect() as connection:
144
+ await connection.execute(text("SELECT 1"))
145
+ return True
146
+ except TimeoutError:
147
+ self._logger.error(f"Database healthcheck timed out after {timeout}s")
148
+ return False
149
+ except Exception as e:
150
+ self._logger.error(f"Error during healthcheck of database: {e}")
151
+ return False
File without changes
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: irmy-db
3
+ Version: 1.0.0
4
+ Summary: Async PostgreSQL (SQLAlchemy + asyncpg) access with healthcheck and Prometheus metrics for IRMy services
5
+ Author-email: "Bendyna V. S.R.L." <info@irmy.tech>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://irmy.tech
8
+ Project-URL: Documentation, https://irmy.tech/docs/
9
+ Project-URL: Source, https://github.com/IRMy-tech/irmy-db
10
+ Project-URL: Issues, https://github.com/IRMy-tech/irmy-db/issues
11
+ Project-URL: Changelog, https://github.com/IRMy-tech/irmy-db/blob/main/CHANGELOG.md
12
+ Keywords: irmy,postgresql,sqlalchemy,asyncpg,prometheus
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Database
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.12
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: SQLAlchemy<2.1,>=2.0.54
26
+ Requires-Dist: asyncpg<1,>=0.31.0
27
+ Requires-Dist: greenlet<4,>=3.5.6
28
+ Requires-Dist: prometheus-client<1,>=0.26.0
29
+ Provides-Extra: test
30
+ Requires-Dist: pytest>=8; extra == "test"
31
+ Requires-Dist: pytest-asyncio>=0.24; extra == "test"
32
+ Dynamic: license-file
33
+
34
+ # irmy-db
35
+
36
+ Async PostgreSQL access for IRMy Python services: a SQLAlchemy 2 async engine
37
+ (asyncpg) with a session factory, schema selection via `search_path`, a real
38
+ database healthcheck and Prometheus metrics for the connection pool and query
39
+ durations.
40
+
41
+ ```bash
42
+ pip install irmy-db
43
+ ```
44
+
45
+ Requires Python 3.12+. The import package is `irmy_db`.
46
+
47
+ ## Usage
48
+
49
+ ```python
50
+ import logging
51
+
52
+ from sqlalchemy import text
53
+ from irmy_db import InitializeDB
54
+
55
+ logger = logging.getLogger("my-service")
56
+
57
+ db = InitializeDB(
58
+ connection_string="postgresql+asyncpg://user:password@localhost:5432/irmy",
59
+ postgres_schema="public",
60
+ logger=logger,
61
+ )
62
+
63
+
64
+ async def do_something():
65
+ async with db.get_session() as session:
66
+ await session.execute(text("SELECT 1"))
67
+
68
+
69
+ async def healthcheck() -> bool:
70
+ # Runs SELECT 1 against the database, False on error or after 5 seconds.
71
+ return await db.get_health(timeout=5.0)
72
+
73
+
74
+ async def shutdown():
75
+ # Do not forget to close the connection pool.
76
+ await db.disconnect_from_db()
77
+ ```
78
+
79
+ `InitializeDB` arguments:
80
+
81
+ | Argument | Default | Description |
82
+ |---|---|---|
83
+ | `connection_string` | — | SQLAlchemy async URL (`postgresql+asyncpg://…`) |
84
+ | `postgres_schema` | — | Schema set as `search_path` for every connection |
85
+ | `logger` | — | `logging.Logger` |
86
+ | `pool` | `5` | Connections kept open (env `POSTGRESQL_POOL_SIZE` overrides) |
87
+ | `pool_overflow` | `10` | Connections allowed above the pool size, closed again when returned (env `POSTGRESQL_MAX_OVERFLOW` overrides) |
88
+ | `pool_recycle` | `3600` | Seconds after which a connection is replaced (env `POSTGRESQL_POOL_RECYCLE_SECONDS` overrides) |
89
+ | `enable_metrics` | `True` | Register Prometheus pool and query metrics |
90
+
91
+ ## Metrics
92
+
93
+ | Metric | Type | Description |
94
+ |---|---|---|
95
+ | `db_pool_size` | Gauge | Connection pool size |
96
+ | `db_pool_checkedin` | Gauge | Checked-in (idle) connections |
97
+ | `db_pool_checkedout` | Gauge | Checked-out (in use) connections |
98
+ | `db_pool_overflow` | Gauge | Overflow connections |
99
+ | `db_connections_opened_total` | Counter | Connections opened; a steady climb under load means the pool is too small |
100
+ | `db_query_duration_seconds` | Histogram, label `operation` | Query duration by SQL verb (`select`, `insert`, …) |
101
+
102
+ The pool gauges are process-wide: use one `InitializeDB` per process.
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ irmy_db/__init__.py
5
+ irmy_db/_database.py
6
+ irmy_db/py.typed
7
+ irmy_db.egg-info/PKG-INFO
8
+ irmy_db.egg-info/SOURCES.txt
9
+ irmy_db.egg-info/dependency_links.txt
10
+ irmy_db.egg-info/requires.txt
11
+ irmy_db.egg-info/top_level.txt
12
+ tests/test_database.py
@@ -0,0 +1,8 @@
1
+ SQLAlchemy<2.1,>=2.0.54
2
+ asyncpg<1,>=0.31.0
3
+ greenlet<4,>=3.5.6
4
+ prometheus-client<1,>=0.26.0
5
+
6
+ [test]
7
+ pytest>=8
8
+ pytest-asyncio>=0.24
@@ -0,0 +1 @@
1
+ irmy_db
@@ -0,0 +1,54 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "irmy-db"
7
+ version = "1.0.0"
8
+ description = "Async PostgreSQL (SQLAlchemy + asyncpg) access with healthcheck and Prometheus metrics for IRMy services"
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Bendyna V. S.R.L.", email = "info@irmy.tech" }]
14
+ keywords = ["irmy", "postgresql", "sqlalchemy", "asyncpg", "prometheus"]
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Framework :: AsyncIO",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Database",
24
+ "Typing :: Typed",
25
+ ]
26
+ dependencies = [
27
+ "SQLAlchemy>=2.0.54,<2.1",
28
+ "asyncpg>=0.31.0,<1",
29
+ "greenlet>=3.5.6,<4",
30
+ "prometheus-client>=0.26.0,<1",
31
+ ]
32
+
33
+ [project.urls]
34
+ Homepage = "https://irmy.tech"
35
+ Documentation = "https://irmy.tech/docs/"
36
+ Source = "https://github.com/IRMy-tech/irmy-db"
37
+ Issues = "https://github.com/IRMy-tech/irmy-db/issues"
38
+ Changelog = "https://github.com/IRMy-tech/irmy-db/blob/main/CHANGELOG.md"
39
+
40
+ [project.optional-dependencies]
41
+ test = [
42
+ "pytest>=8",
43
+ "pytest-asyncio>=0.24",
44
+ ]
45
+
46
+ [tool.setuptools.packages.find]
47
+ include = ["irmy_db*"]
48
+
49
+ [tool.setuptools.package-data]
50
+ irmy_db = ["py.typed"]
51
+
52
+ [tool.pytest.ini_options]
53
+ testpaths = ["tests"]
54
+ asyncio_mode = "auto"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,126 @@
1
+ import asyncio
2
+ import logging
3
+ from contextlib import asynccontextmanager
4
+
5
+ import pytest
6
+
7
+ from irmy_db import InitializeDB
8
+
9
+ _LOGGER = logging.getLogger("irmy-db-test")
10
+
11
+
12
+ @pytest.fixture
13
+ def db():
14
+ # Nothing connects until a query runs, so no database is needed to construct it.
15
+ return InitializeDB(
16
+ connection_string="postgresql+asyncpg://u:p@127.0.0.1:1/irmy",
17
+ postgres_schema="public",
18
+ logger=_LOGGER,
19
+ enable_metrics=False,
20
+ )
21
+
22
+
23
+ class _FakeConnection:
24
+ def __init__(self, delay: float = 0.0, error: Exception | None = None):
25
+ self._delay = delay
26
+ self._error = error
27
+ self.statements: list[str] = []
28
+
29
+ async def execute(self, statement):
30
+ self.statements.append(str(statement))
31
+ if self._delay:
32
+ await asyncio.sleep(self._delay)
33
+ if self._error:
34
+ raise self._error
35
+
36
+
37
+ class _FakeEngine:
38
+ def __init__(self, connection: _FakeConnection):
39
+ self._connection = connection
40
+
41
+ @asynccontextmanager
42
+ async def connect(self):
43
+ yield self._connection
44
+
45
+
46
+ async def test_health_runs_select_1(db):
47
+ connection = _FakeConnection()
48
+ db._engine = _FakeEngine(connection)
49
+ assert await db.get_health() is True
50
+ assert connection.statements == ["SELECT 1"]
51
+
52
+
53
+ async def test_health_false_on_database_error(db):
54
+ db._engine = _FakeEngine(_FakeConnection(error=OSError("connection refused")))
55
+ assert await db.get_health() is False
56
+
57
+
58
+ async def test_health_false_on_timeout(db):
59
+ db._engine = _FakeEngine(_FakeConnection(delay=1.0))
60
+ assert await db.get_health(timeout=0.05) is False
61
+
62
+
63
+ async def test_health_false_when_unreachable(db):
64
+ assert await db.get_health(timeout=2.0) is False
65
+
66
+
67
+ async def test_health_false_after_disconnect(db):
68
+ await db.disconnect_from_db()
69
+ assert await db.get_health() is False
70
+
71
+
72
+ # --------------------------------------------------------------------------- pool settings
73
+
74
+
75
+ def _pool(monkeypatch=None, **kwargs):
76
+ return InitializeDB(
77
+ connection_string="postgresql+asyncpg://u:p@127.0.0.1:1/irmy",
78
+ postgres_schema="public", logger=_LOGGER, enable_metrics=False, **kwargs,
79
+ )._engine.sync_engine.pool
80
+
81
+
82
+ def test_pool_defaults(monkeypatch):
83
+ for name in ("POSTGRESQL_POOL_SIZE", "POSTGRESQL_MAX_OVERFLOW", "POSTGRESQL_POOL_RECYCLE_SECONDS"):
84
+ monkeypatch.delenv(name, raising=False)
85
+ pool = _pool()
86
+ assert (pool.size(), pool._max_overflow, pool._recycle) == (5, 10, 3600)
87
+
88
+
89
+ def test_environment_overrides_code(monkeypatch):
90
+ monkeypatch.setenv("POSTGRESQL_POOL_SIZE", "12")
91
+ monkeypatch.setenv("POSTGRESQL_MAX_OVERFLOW", "0")
92
+ monkeypatch.setenv("POSTGRESQL_POOL_RECYCLE_SECONDS", "600")
93
+ pool = _pool(pool=2, pool_overflow=3, pool_recycle=60)
94
+ assert (pool.size(), pool._max_overflow, pool._recycle) == (12, 0, 600)
95
+
96
+
97
+ def test_empty_environment_variable_keeps_the_code_value(monkeypatch):
98
+ monkeypatch.setenv("POSTGRESQL_POOL_SIZE", "")
99
+ assert _pool(pool=7).size() == 7
100
+
101
+
102
+ @pytest.mark.parametrize("name, value", [
103
+ ("POSTGRESQL_POOL_SIZE", "ten"),
104
+ ("POSTGRESQL_POOL_SIZE", "0"),
105
+ ("POSTGRESQL_MAX_OVERFLOW", "-1"),
106
+ ("POSTGRESQL_POOL_RECYCLE_SECONDS", "0"),
107
+ ])
108
+ def test_invalid_environment_value_fails_loudly(monkeypatch, name, value):
109
+ monkeypatch.setenv(name, value)
110
+ with pytest.raises(ValueError, match=name):
111
+ _pool()
112
+
113
+
114
+ def test_opened_connections_are_counted():
115
+ from irmy_db._database import _connections_opened
116
+
117
+ db = InitializeDB(
118
+ connection_string="postgresql+asyncpg://u:p@127.0.0.1:1/irmy",
119
+ postgres_schema="public", logger=_LOGGER, enable_metrics=True,
120
+ )
121
+ before = _connections_opened._value.get()
122
+ ours = [fn for fn in db._engine.sync_engine.pool.dispatch.connect
123
+ if getattr(fn, "__module__", "") == "irmy_db._database"]
124
+ assert len(ours) == 1
125
+ ours[0](None, None)
126
+ assert _connections_opened._value.get() == before + 1