psycopg-toolkit 0.3.1__tar.gz → 0.4.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.
Files changed (20) hide show
  1. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/PKG-INFO +8 -6
  2. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/pyproject.toml +41 -13
  3. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/__init__.py +2 -1
  4. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/core/config.py +18 -4
  5. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/core/database.py +65 -43
  6. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/core/transaction.py +37 -23
  7. psycopg_toolkit-0.4.0/src/psycopg_toolkit/py.typed +0 -0
  8. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/repositories/base.py +97 -107
  9. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/utils/json_handler.py +26 -7
  10. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/utils/psychopg_helper.py +12 -11
  11. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/utils/type_inspector.py +13 -1
  12. psycopg_toolkit-0.3.1/.vscode/settings.json +0 -27
  13. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/.gitignore +0 -0
  14. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/LICENSE +0 -0
  15. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/README.md +0 -0
  16. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/core/__init__.py +0 -0
  17. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/core/factory.py +0 -0
  18. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/exceptions.py +0 -0
  19. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/repositories/__init__.py +0 -0
  20. {psycopg_toolkit-0.3.1 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/utils/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: psycopg-toolkit
3
- Version: 0.3.1
3
+ Version: 0.4.0
4
4
  Summary: A Python PostgreSQL database utility with connection pooling
5
5
  Project-URL: Homepage, https://github.com/descoped/psycopg-toolkit
6
6
  Project-URL: Repository, https://github.com/descoped/psycopg-toolkit
@@ -20,15 +20,17 @@ Classifier: Programming Language :: Python :: 3
20
20
  Classifier: Programming Language :: Python :: 3.11
21
21
  Classifier: Programming Language :: Python :: 3.12
22
22
  Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Programming Language :: Python :: 3.15
23
25
  Classifier: Topic :: Database
24
26
  Classifier: Topic :: Database :: Database Engines/Servers
25
27
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
28
  Classifier: Typing :: Typed
27
29
  Requires-Python: >=3.11
28
- Requires-Dist: psycopg-pool>=3.2.4
29
- Requires-Dist: psycopg>=3.2.3
30
- Requires-Dist: pydantic>=2.10.5
31
- Requires-Dist: tenacity>=9.0.0
30
+ Requires-Dist: psycopg-pool>=3.3.3
31
+ Requires-Dist: psycopg>=3.3.9
32
+ Requires-Dist: pydantic>=2.14.4
33
+ Requires-Dist: tenacity>=9.2.1
32
34
  Description-Content-Type: text/markdown
33
35
 
34
36
  # Psycopg Toolkit
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "psycopg-toolkit"
3
- version = "0.3.1"
3
+ version = "0.4.0"
4
4
  description = "A Python PostgreSQL database utility with connection pooling"
5
5
  authors = [
6
6
  { name = "Ove Ranheim", email = "oranheim@gmail.com" }
@@ -17,6 +17,8 @@ classifiers = [
17
17
  "Programming Language :: Python :: 3.11",
18
18
  "Programming Language :: Python :: 3.12",
19
19
  "Programming Language :: Python :: 3.13",
20
+ "Programming Language :: Python :: 3.14",
21
+ "Programming Language :: Python :: 3.15",
20
22
  "Topic :: Database",
21
23
  "Topic :: Database :: Database Engines/Servers",
22
24
  "Topic :: Software Development :: Libraries :: Python Modules",
@@ -26,26 +28,25 @@ classifiers = [
26
28
  "Framework :: Pydantic :: 2",
27
29
  ]
28
30
  dependencies = [
29
- "psycopg>=3.2.3",
30
- "psycopg-pool>=3.2.4",
31
- "tenacity>=9.0.0",
32
- "pydantic>=2.10.5",
31
+ "psycopg>=3.3.9",
32
+ "psycopg-pool>=3.3.3",
33
+ "tenacity>=9.2.1",
34
+ "pydantic>=2.14.4",
33
35
  ]
34
36
 
35
37
  [dependency-groups]
36
38
  test = [
37
- "pytest>=8.3.0",
38
- "pytest-asyncio>=0.25.2",
39
- "pytest-cov>=6.0.0",
40
- "testcontainers[postgres]>=4.12.0",
41
- "psutil>=6.1.0", # For performance benchmarks
39
+ "pytest>=9.2.0",
40
+ "pytest-asyncio>=1.5.0",
41
+ "pytest-cov>=7.1.0",
42
+ "testcontainers>=4.15.0",
42
43
  ]
43
44
  dev = [
44
- "ruff>=0.8.0",
45
+ "ruff>=0.17.6",
45
46
  ]
46
47
 
47
48
  [build-system]
48
- requires = ["hatchling>=1.26.3"]
49
+ requires = ["hatchling>=1.33.0"]
49
50
  build-backend = "hatchling.build"
50
51
 
51
52
  [tool.hatch.build.targets.wheel]
@@ -73,6 +74,7 @@ exclude = [
73
74
  ".env",
74
75
  "*.egg-info/",
75
76
  ".claude/*",
77
+ ".vscode/*",
76
78
  "uv.lock",
77
79
  ]
78
80
 
@@ -92,6 +94,12 @@ name = "testpypi"
92
94
  url = "https://test.pypi.org/simple/"
93
95
  publish-url = "https://test.pypi.org/legacy/"
94
96
 
97
+ [tool.uv]
98
+ # Keep the dev/test environment lean. charset-normalizer (1.3 MB) is pulled in by
99
+ # requests via docker/testcontainers, but requests treats it as optional and the
100
+ # Docker API client only decodes JSON, so character-set detection is never used.
101
+ exclude-dependencies = ["charset-normalizer"]
102
+
95
103
  [tool.pytest.ini_options]
96
104
  testpaths = ["tests"]
97
105
  python_files = ["test_*.py"]
@@ -107,6 +115,10 @@ addopts = [
107
115
  "--tb=short",
108
116
  "-m", "not performance", # Exclude performance tests by default
109
117
  ]
118
+ filterwarnings = [
119
+ # charset-normalizer is excluded on purpose (see [tool.uv]); requests warns once on import
120
+ "ignore:Unable to find acceptable character detection dependency:Warning:requests",
121
+ ]
110
122
 
111
123
  [tool.coverage.run]
112
124
  source = ["src/psycopg_toolkit"]
@@ -132,6 +144,19 @@ precision = 2
132
144
  show_missing = true
133
145
  skip_covered = false
134
146
 
147
+ [tool.pyright]
148
+ # Used by the pyright language server (editor / Claude Code LSP) and the `pyright` CLI.
149
+ # uv creates the project environment as `.venv` next to this file (`uv sync`, or on first
150
+ # `uv run`). Pyright does not discover it on its own: without venvPath/venv it falls back to
151
+ # whatever `python` is on PATH. The path is relative and fixed by uv, so it is the same for
152
+ # every checkout and safe to commit.
153
+ venvPath = "."
154
+ venv = ".venv"
155
+ include = ["src", "tests", "examples"]
156
+ # Check against the lowest supported Python so newer-only syntax is caught.
157
+ pythonVersion = "3.11"
158
+ typeCheckingMode = "standard"
159
+
135
160
  [tool.ruff]
136
161
  target-version = "py311"
137
162
  line-length = 120
@@ -152,7 +177,7 @@ select = [
152
177
  "RUF", # Ruff-specific rules
153
178
  "C90", # mccabe complexity
154
179
  "PTH", # flake8-use-pathlib
155
- "TCH", # flake8-type-checking
180
+ "TC", # flake8-type-checking (formerly TCH)
156
181
  ]
157
182
  ignore =[
158
183
  "E501", # Line too long (handled by formatter)
@@ -189,6 +214,9 @@ keep-runtime-typing = true # For Pydantic
189
214
  ignore-names = ["model_*"] # For Pydantic models
190
215
 
191
216
  [tool.ruff.format]
217
+ # ruff 0.16+ formats Python code blocks in Markdown by default; our docs contain
218
+ # illustrative fragments, not runnable modules, so keep the formatter on .py files.
219
+ exclude = ["*.md"]
192
220
  quote-style = "double"
193
221
  indent-style = "space"
194
222
  skip-magic-trailing-comma = false
@@ -15,7 +15,7 @@ from .exceptions import (
15
15
  RepositoryError,
16
16
  )
17
17
  from .repositories.base import BaseRepository
18
- from .utils.json_handler import CustomJSONEncoder, JSONHandler
18
+ from .utils.json_handler import CustomJSONEncoder, DecimalMode, JSONHandler
19
19
  from .utils.type_inspector import TypeInspector
20
20
 
21
21
  __all__ = [
@@ -27,6 +27,7 @@ __all__ = [
27
27
  "DatabaseNotAvailable",
28
28
  "DatabasePoolError",
29
29
  "DatabaseSettings",
30
+ "DecimalMode",
30
31
  "InvalidDataError",
31
32
  "JSONDeserializationError",
32
33
  # JSON/JSONB Support
@@ -1,6 +1,8 @@
1
1
  from dataclasses import dataclass
2
2
  from typing import Any
3
3
 
4
+ from psycopg.conninfo import make_conninfo
5
+
4
6
 
5
7
  @dataclass
6
8
  class DatabaseSettings:
@@ -20,7 +22,10 @@ class DatabaseSettings:
20
22
  pool_timeout (int): Maximum time in seconds to wait for a connection (default: 30)
21
23
  connection_timeout (float): Connection establishment timeout in seconds (default: 5.0)
22
24
  statement_timeout (Optional[float]): SQL statement execution timeout in seconds (default: None)
23
- enable_json_adapters (bool): Whether to enable psycopg JSON adapters for JSONB support (default: True)
25
+ enable_json_adapters (bool): Reset every connection the toolkit hands out to the standard
26
+ library's JSON loads/dumps, overriding loaders registered globally with
27
+ ``psycopg.types.json.set_json_loads`` (default: True). With False the connection keeps
28
+ its own loaders. psycopg decodes json/jsonb to Python objects either way.
24
29
  """
25
30
 
26
31
  host: str
@@ -47,16 +52,25 @@ class DatabaseSettings:
47
52
  def get_connection_string(self, timeout: float | None = None) -> str:
48
53
  """Generate a PostgreSQL connection string with optional timeout override.
49
54
 
55
+ Values are quoted by libpq rules where needed (spaces, quotes, backslashes), so any
56
+ password or name is passed through intact.
57
+
50
58
  Args:
51
59
  timeout (Optional[float]): Optional connection timeout override in seconds
52
60
 
53
61
  Returns:
54
62
  str: Formatted connection string for psycopg
55
63
  """
56
- conn_str = f"host={self.host} port={self.port} dbname={self.dbname} user={self.user} password={self.password}"
64
+ params: dict[str, Any] = {
65
+ "host": self.host,
66
+ "port": self.port,
67
+ "dbname": self.dbname,
68
+ "user": self.user,
69
+ "password": self.password,
70
+ }
57
71
  if timeout:
58
- conn_str += f" connect_timeout={int(timeout)}"
59
- return conn_str
72
+ params["connect_timeout"] = int(timeout)
73
+ return make_conninfo(**params)
60
74
 
61
75
  def to_dict(self, connection_only: bool = True) -> dict[str, Any]:
62
76
  """Convert settings to a dictionary.
@@ -1,17 +1,19 @@
1
+ import asyncio
2
+ import json as stdlib_json
1
3
  import logging
2
4
  from collections.abc import AsyncGenerator, Awaitable, Callable
3
5
  from contextlib import asynccontextmanager
4
- from typing import TYPE_CHECKING
6
+ from typing import TYPE_CHECKING, cast
5
7
 
6
8
  if TYPE_CHECKING:
7
9
  from .transaction import TransactionManager
8
10
 
9
- from psycopg import AsyncConnection
11
+ from psycopg import AsyncConnection, sql
10
12
  from psycopg.types import json
11
13
  from psycopg_pool import AsyncConnectionPool
12
14
  from tenacity import retry, stop_after_attempt, wait_exponential
13
15
 
14
- from ..exceptions import DatabaseConnectionError, DatabaseNotAvailable, DatabasePoolError
16
+ from ..exceptions import DatabaseConnectionError, DatabasePoolError
15
17
  from .config import DatabaseSettings
16
18
 
17
19
  logger = logging.getLogger(__name__)
@@ -47,31 +49,43 @@ class Database:
47
49
  self._pool: AsyncConnectionPool | None = None
48
50
  self._init_callbacks: list[Callable[[AsyncConnectionPool], Awaitable[None]]] = []
49
51
  self._transaction_manager: TransactionManager | None = None
52
+ # Serializes pool creation so concurrent first callers share one pool
53
+ self._pool_lock = asyncio.Lock()
50
54
 
51
55
  def _configure_json_adapters(self, connection: AsyncConnection) -> None:
52
- """Configure psycopg JSON adapters for JSONB support.
56
+ """Reset the connection's JSON loads/dumps to the standard library's, if enabled.
53
57
 
54
- This method sets up automatic JSON/JSONB handling using psycopg's built-in
55
- JSON adapters, which provide seamless conversion between Python objects
56
- and PostgreSQL JSON/JSONB data types.
58
+ psycopg decodes json/jsonb to Python objects by default; this does not change that. With
59
+ ``enable_json_adapters`` set, it pins ``json.loads``/``json.dumps`` on this connection, which
60
+ overrides any loader registered globally with ``psycopg.types.json.set_json_loads``. With it
61
+ unset, the connection keeps whatever loaders are in effect.
62
+
63
+ Called on every checkout by ``connection()``, ``transaction()`` and the TransactionManager.
57
64
 
58
65
  Args:
59
66
  connection: The database connection to configure
60
-
61
- Note:
62
- This is called automatically when enable_json_adapters is True in settings.
63
- The adapters handle serialization/deserialization transparently at the
64
- driver level, which can be more efficient than manual processing.
65
67
  """
66
68
  if self._settings.enable_json_adapters:
67
69
  logger.debug("Configuring JSON adapters for connection")
68
70
  # Set up JSON adapters to handle JSONB columns automatically
69
- json.set_json_loads(loads=json.json.loads, context=connection)
70
- json.set_json_dumps(dumps=json.json.dumps, context=connection)
71
+ json.set_json_loads(loads=stdlib_json.loads, context=connection)
72
+ json.set_json_dumps(dumps=stdlib_json.dumps, context=connection)
71
73
  logger.debug("JSON adapters configured successfully")
72
74
  else:
73
75
  logger.debug("JSON adapters disabled in settings")
74
76
 
77
+ async def _configure_new_connection(self, connection: AsyncConnection) -> None:
78
+ """Apply session settings once to every connection the pool creates.
79
+
80
+ Runs as the pool's ``configure`` callback, so the statement timeout holds for every
81
+ pooled connection, whether it is used through ``connection()``, ``transaction()`` or a
82
+ ``TransactionManager``. The connection is left idle, as the pool requires.
83
+ """
84
+ if self._settings.statement_timeout:
85
+ timeout_ms = int(self._settings.statement_timeout * 1000)
86
+ await connection.execute(sql.SQL("SET statement_timeout = {}").format(sql.Literal(timeout_ms)))
87
+ await connection.commit()
88
+
75
89
  @retry(stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=4, max=10))
76
90
  async def ping_postgres(self) -> bool:
77
91
  """Test database connectivity with exponential backoff retry.
@@ -80,7 +94,8 @@ class Database:
80
94
  bool: True if connection successful
81
95
 
82
96
  Raises:
83
- DatabaseConnectionError: If connection fails after retries
97
+ tenacity.RetryError: If all 5 attempts fail. The last attempt's
98
+ DatabaseConnectionError is available via ``err.last_attempt.exception()``.
84
99
  """
85
100
  try:
86
101
  logger.info(f"Pinging PostgreSQL at {self._settings.host}")
@@ -101,20 +116,24 @@ class Database:
101
116
  AsyncConnectionPool: Configured connection pool
102
117
 
103
118
  Raises:
104
- DatabaseConnectionError: If database ping fails
105
- DatabasePoolError: If pool creation or initialization fails
119
+ DatabasePoolError: If the database cannot be reached (ping retries exhausted)
120
+ or the pool cannot be created or opened. The cause is chained.
106
121
  """
107
122
  try:
108
- if not await self.ping_postgres():
109
- raise DatabaseConnectionError("Failed to ping database")
123
+ await self.ping_postgres()
110
124
 
111
125
  logger.info("Initializing connection pool")
112
- pool = AsyncConnectionPool(
113
- conninfo=self._settings.connection_string,
114
- min_size=self._settings.min_pool_size,
115
- max_size=self._settings.max_pool_size,
116
- timeout=self._settings.pool_timeout,
117
- open=False,
126
+ # cast: psycopg_pool cannot infer the connection type parameter from these arguments
127
+ pool = cast(
128
+ "AsyncConnectionPool[AsyncConnection]",
129
+ AsyncConnectionPool(
130
+ conninfo=self._settings.connection_string,
131
+ min_size=self._settings.min_pool_size,
132
+ max_size=self._settings.max_pool_size,
133
+ timeout=self._settings.pool_timeout,
134
+ configure=self._configure_new_connection,
135
+ open=False,
136
+ ),
118
137
  )
119
138
 
120
139
  try:
@@ -135,13 +154,15 @@ class Database:
135
154
  Returns:
136
155
  AsyncConnectionPool: Active connection pool
137
156
 
157
+ Safe to call concurrently: only one pool is ever created.
158
+
138
159
  Raises:
139
- DatabaseNotAvailable: If pool creation fails
160
+ DatabasePoolError: If pool creation fails
140
161
  """
141
- if not self._pool or self._pool.closed:
142
- self._pool = await self.create_pool()
143
- if not self._pool:
144
- raise DatabaseNotAvailable("Database is not available")
162
+ if self._pool is None or self._pool.closed:
163
+ async with self._pool_lock:
164
+ if self._pool is None or self._pool.closed:
165
+ self._pool = await self.create_pool()
145
166
  return self._pool
146
167
 
147
168
  async def register_init_callback(self, callback: Callable[[AsyncConnectionPool], Awaitable[None]]) -> None:
@@ -157,18 +178,24 @@ class Database:
157
178
  """Get database connection with configured statement timeout and JSON adapters.
158
179
 
159
180
  Yields:
160
- AsyncConnection: Database connection
181
+ AsyncConnection: Database connection, idle (no transaction open)
161
182
 
162
183
  Raises:
163
- DatabaseConnectionError: If connection acquisition fails
184
+ DatabasePoolError: If the pool cannot be created
185
+ psycopg_pool.PoolTimeout: If no connection becomes available within pool_timeout
186
+ """
187
+ async with self._checkout() as conn:
188
+ yield conn
189
+
190
+ @asynccontextmanager
191
+ async def _checkout(self) -> AsyncGenerator[AsyncConnection, None]:
192
+ """Borrow a pooled connection with JSON adapters configured.
193
+
194
+ The statement timeout is applied once per connection by the pool's configure callback.
164
195
  """
165
196
  pool = await self.get_pool()
166
197
  async with pool.connection() as conn:
167
- # Configure JSON adapters if enabled
168
198
  self._configure_json_adapters(conn)
169
-
170
- if self._settings.statement_timeout:
171
- await conn.execute(f"SET statement_timeout = {int(self._settings.statement_timeout * 1000)}")
172
199
  yield conn
173
200
 
174
201
  async def init_db(self) -> None:
@@ -257,10 +284,5 @@ class Database:
257
284
  Yields:
258
285
  AsyncConnection: Database connection in transaction
259
286
  """
260
- pool = await self.get_pool()
261
- async with pool.connection() as conn:
262
- # Configure JSON adapters if enabled
263
- self._configure_json_adapters(conn)
264
-
265
- async with conn.transaction():
266
- yield conn
287
+ async with self._checkout() as conn, conn.transaction():
288
+ yield conn
@@ -5,7 +5,8 @@ from contextlib import asynccontextmanager
5
5
  from dataclasses import dataclass
6
6
  from typing import Generic, TypeVar
7
7
 
8
- from psycopg import AsyncConnection
8
+ from psycopg import AsyncConnection, sql
9
+ from psycopg.pq import TransactionStatus
9
10
  from psycopg_pool import AsyncConnectionPool
10
11
 
11
12
  from ..exceptions import DatabaseConnectionError, DatabaseNotAvailable, DatabasePoolError
@@ -91,13 +92,13 @@ class TransactionContext:
91
92
  AsyncConnection: Database connection
92
93
  """
93
94
  if self.savepoint_name:
94
- await self.conn.execute(f"SAVEPOINT {self.savepoint_name}")
95
+ await self.conn.execute(sql.SQL("SAVEPOINT {}").format(sql.Identifier(self.savepoint_name)))
95
96
  return self.conn
96
97
 
97
98
  async def __aexit__(self, exc_type, exc_val, exc_tb):
98
99
  """Exit transaction context, rolling back to savepoint on error."""
99
100
  if exc_type and self.savepoint_name:
100
- await self.conn.execute(f"ROLLBACK TO SAVEPOINT {self.savepoint_name}")
101
+ await self.conn.execute(sql.SQL("ROLLBACK TO SAVEPOINT {}").format(sql.Identifier(self.savepoint_name)))
101
102
 
102
103
 
103
104
  class TransactionManager:
@@ -189,16 +190,32 @@ class TransactionManager:
189
190
  Yields:
190
191
  D: Test data configuration
191
192
  """
192
- async with self.transaction() as conn:
193
- try:
194
- data = await data_manager.setup_data(conn)
195
- yield data
196
- finally:
193
+ async with self.transaction() as conn, self._data_scope(conn, data_manager) as data:
194
+ yield data
195
+
196
+ @asynccontextmanager
197
+ async def _data_scope(self, conn: AsyncConnection, data_manager: DataManager[D]) -> AsyncGenerator[D, None]:
198
+ """Set up test data on ``conn``, yield it, and clean it up afterwards.
199
+
200
+ If setup fails, cleanup is skipped: the surrounding transaction rolls the partial setup back.
201
+ If the body fails, cleanup is attempted only while the transaction is still usable, and a
202
+ cleanup failure is logged without replacing the original error.
203
+ """
204
+ data = await data_manager.setup_data(conn)
205
+ try:
206
+ yield data
207
+ except BaseException:
208
+ if conn.info.transaction_status != TransactionStatus.INERROR:
197
209
  try:
198
210
  await data_manager.cleanup_data(conn)
199
- except Exception as e:
200
- logger.error(f"Data cleanup failed: {e}")
201
- raise
211
+ except Exception as cleanup_error:
212
+ logger.error(f"Data cleanup failed: {cleanup_error}")
213
+ raise
214
+ try:
215
+ await data_manager.cleanup_data(conn)
216
+ except Exception as e:
217
+ logger.error(f"Data cleanup failed: {e}")
218
+ raise
202
219
 
203
220
  @asynccontextmanager
204
221
  async def managed_transaction(
@@ -206,6 +223,10 @@ class TransactionManager:
206
223
  ) -> AsyncGenerator[AsyncConnection, None]:
207
224
  """Combined context manager for schema and data operations.
208
225
 
226
+ Schema creation, data setup, the body and data cleanup all run on one connection in one
227
+ transaction, so each step sees the previous one's uncommitted changes. On success the
228
+ schema is kept and the test data is cleaned up; on error everything is rolled back.
229
+
209
230
  Args:
210
231
  schema_manager: Optional schema manager implementation
211
232
  data_manager: Optional test data manager implementation
@@ -213,18 +234,11 @@ class TransactionManager:
213
234
  Yields:
214
235
  AsyncConnection: Database connection
215
236
  """
216
- if schema_manager:
217
- async with self.with_schema(schema_manager):
218
- if data_manager:
219
- async with self.with_test_data(data_manager), self.transaction() as conn:
220
- yield conn
221
- else:
222
- async with self.transaction() as conn:
223
- yield conn
224
- else:
237
+ async with self.transaction() as conn:
238
+ if schema_manager:
239
+ await schema_manager.create_schema(conn)
225
240
  if data_manager:
226
- async with self.with_test_data(data_manager), self.transaction() as conn:
241
+ async with self._data_scope(conn, data_manager):
227
242
  yield conn
228
243
  else:
229
- async with self.transaction() as conn:
230
- yield conn
244
+ yield conn
File without changes
@@ -1,4 +1,6 @@
1
1
  import logging
2
+ from collections.abc import AsyncGenerator
3
+ from contextlib import asynccontextmanager
2
4
  from datetime import date, datetime
3
5
  from typing import Any, Generic, TypeVar
4
6
 
@@ -6,6 +8,7 @@ from psycopg import AsyncConnection
6
8
  from psycopg.rows import dict_row
7
9
  from psycopg.sql import SQL, Identifier
8
10
  from psycopg.types.json import Json
11
+ from pydantic import BaseModel
9
12
 
10
13
  from ..exceptions import (
11
14
  JSONDeserializationError,
@@ -15,11 +18,11 @@ from ..exceptions import (
15
18
  RecordNotFoundError,
16
19
  )
17
20
  from ..utils import PsycopgHelper
18
- from ..utils.json_handler import JSONHandler
21
+ from ..utils.json_handler import DecimalMode, JSONHandler, check_decimal_mode
19
22
  from ..utils.type_inspector import TypeInspector
20
23
 
21
24
  # Generic type variables for model and primary key
22
- T = TypeVar("T")
25
+ T = TypeVar("T", bound=BaseModel)
23
26
  K = TypeVar("K")
24
27
 
25
28
  logger = logging.getLogger(__name__)
@@ -76,6 +79,7 @@ class BaseRepository(Generic[T, K]):
76
79
  array_fields: set[str] | None = None,
77
80
  vector_fields: set[str] | None = None,
78
81
  auto_detect_vector: bool = True,
82
+ decimal_as: DecimalMode = "float",
79
83
  ):
80
84
  """
81
85
  Initialize the base repository.
@@ -104,6 +108,11 @@ class BaseRepository(Generic[T, K]):
104
108
  auto_detect_vector (bool, optional): Whether to automatically detect vector fields
105
109
  (list[float]) from Pydantic type hints. Ignored if vector_fields is provided.
106
110
  Defaults to True.
111
+ decimal_as (DecimalMode, optional): How Decimal values inside JSON fields are
112
+ written. "float" (default) may lose digits; "str" keeps every digit by writing
113
+ the value as a JSON string, which reads back as ``str`` (convert with
114
+ ``Decimal(value)``). Applies to the toolkit's own JSON serialization, not to
115
+ values wrapped with ``Json()`` when ``auto_detect_json=False``.
107
116
 
108
117
  Note:
109
118
  The model_class should be a Pydantic model that matches the database schema.
@@ -117,33 +126,34 @@ class BaseRepository(Generic[T, K]):
117
126
  """
118
127
  self.db_connection = db_connection
119
128
  self.table_name = table_name
129
+ self._decimal_as: DecimalMode = check_decimal_mode(decimal_as)
120
130
  self.model_class = model_class
121
131
  self.primary_key = primary_key
122
132
 
123
133
  # Vector field detection and configuration
124
134
  if vector_fields is not None:
125
135
  self._vector_fields = vector_fields
126
- logger.debug(f"Using explicit vector fields for {table_name}: {vector_fields}")
136
+ logger.debug("Using explicit vector fields for %s: %s", table_name, vector_fields)
127
137
  elif auto_detect_vector:
128
138
  self._vector_fields = TypeInspector.detect_vector_fields(model_class)
129
- logger.debug(f"Auto-detected vector fields for {table_name}: {self._vector_fields}")
139
+ logger.debug("Auto-detected vector fields for %s: %s", table_name, self._vector_fields)
130
140
  else:
131
141
  self._vector_fields = set()
132
- logger.debug(f"Vector field detection disabled for {table_name}")
142
+ logger.debug("Vector field detection disabled for %s", table_name)
133
143
 
134
144
  # JSON field detection and configuration
135
145
  if json_fields is not None:
136
146
  self._json_fields = json_fields
137
- logger.debug(f"Using explicit JSON fields for {table_name}: {json_fields}")
147
+ logger.debug("Using explicit JSON fields for %s: %s", table_name, json_fields)
138
148
  elif auto_detect_json:
139
149
  detected_fields = TypeInspector.detect_json_fields(model_class)
140
150
  # Exclude array fields and vector fields from JSON fields
141
151
  self._json_fields = detected_fields - (array_fields or set()) - self._vector_fields
142
- logger.debug(f"Auto-detected JSON fields for {table_name}: {detected_fields}")
143
- logger.debug(f"JSON fields after excluding arrays and vectors: {self._json_fields}")
152
+ logger.debug("Auto-detected JSON fields for %s: %s", table_name, detected_fields)
153
+ logger.debug("JSON fields after excluding arrays and vectors: %s", self._json_fields)
144
154
  else:
145
155
  self._json_fields = set()
146
- logger.debug(f"JSON field processing disabled for {table_name}")
156
+ logger.debug("JSON field processing disabled for %s", table_name)
147
157
 
148
158
  # Cache for performance and configuration
149
159
  self._auto_detect_json = auto_detect_json
@@ -152,19 +162,6 @@ class BaseRepository(Generic[T, K]):
152
162
  self._date_fields = date_fields or set()
153
163
  self._array_fields = array_fields or set()
154
164
 
155
- # Check if psycopg JSON adapters are enabled
156
- self._use_psycopg_adapters = self._check_psycopg_adapters()
157
-
158
- def _check_psycopg_adapters(self) -> bool:
159
- """Check if psycopg JSON adapters are enabled on the connection.
160
-
161
- Returns:
162
- bool: True if psycopg JSON adapters are enabled, False otherwise.
163
- """
164
- # Never use psycopg adapters - this causes issues with arrays
165
- # When auto_detect_json=False, users expect NO JSON processing
166
- return False
167
-
168
165
  @property
169
166
  def json_fields(self) -> set[str]:
170
167
  """Get the set of field names that should be treated as JSON.
@@ -233,11 +230,11 @@ class BaseRepository(Generic[T, K]):
233
230
  if value is not None and isinstance(value, dict | list):
234
231
  # Skip array fields - they should remain as PostgreSQL arrays
235
232
  if field_name in self._array_fields:
236
- logger.debug(f"Preserving array field '{field_name}' for PostgreSQL array handling")
233
+ logger.debug("Preserving array field '%s' for PostgreSQL array handling", field_name)
237
234
  continue
238
235
  # Wrap other dict/list fields with Json()
239
236
  processed_data[field_name] = Json(value)
240
- logger.debug(f"Wrapped field '{field_name}' with Json() for PostgreSQL JSONB handling")
237
+ logger.debug("Wrapped field '%s' with Json() for PostgreSQL JSONB handling", field_name)
241
238
  return processed_data
242
239
 
243
240
  # Custom JSON processing mode - serialize to strings
@@ -247,11 +244,10 @@ class BaseRepository(Generic[T, K]):
247
244
  if isinstance(value, dict | list):
248
245
  try:
249
246
  # Serialize to JSON string for manual processing
250
- serialized = JSONHandler.serialize(value)
247
+ serialized = JSONHandler.serialize(value, decimal_as=self._decimal_as)
251
248
  processed_data[field_name] = serialized
252
- logger.debug(f"Serialized JSON field '{field_name}' for {self.table_name}")
249
+ logger.debug("Serialized JSON field '%s' for %s", field_name, self.table_name)
253
250
  except Exception as e:
254
- logger.error(f"Failed to serialize JSON field '{field_name}' in {self.table_name}: {e}")
255
251
  raise JSONSerializationError(
256
252
  f"JSON serialization failed for field '{field_name}': {e}",
257
253
  field_name=field_name,
@@ -261,11 +257,10 @@ class BaseRepository(Generic[T, K]):
261
257
  elif not isinstance(value, str):
262
258
  # Value is not dict/list/str, try to serialize it anyway
263
259
  try:
264
- serialized = JSONHandler.serialize(value)
260
+ serialized = JSONHandler.serialize(value, decimal_as=self._decimal_as)
265
261
  processed_data[field_name] = serialized
266
- logger.debug(f"Serialized non-standard JSON field '{field_name}' for {self.table_name}")
262
+ logger.debug("Serialized non-standard JSON field '%s' for %s", field_name, self.table_name)
267
263
  except Exception as e:
268
- logger.error(f"Failed to serialize JSON field '{field_name}' in {self.table_name}: {e}")
269
264
  raise JSONSerializationError(
270
265
  f"JSON serialization failed for field '{field_name}': {e}",
271
266
  field_name=field_name,
@@ -346,19 +341,22 @@ class BaseRepository(Generic[T, K]):
346
341
 
347
342
  # If no JSON fields should be processed, return the processed data
348
343
  if not json_fields:
349
- logger.debug(f"No JSON fields configured for {self.table_name}, skipping JSON postprocessing")
344
+ logger.debug("No JSON fields configured for %s, skipping JSON postprocessing", self.table_name)
350
345
  return processed_data
351
346
 
352
347
  for field_name in self._json_fields:
353
348
  if field_name in processed_data and processed_data[field_name] is not None:
349
+ serialized_value = processed_data[field_name]
350
+ if not isinstance(serialized_value, str | bytes):
351
+ # psycopg always decodes json/jsonb columns to Python objects,
352
+ # so a dict/list here is already deserialized
353
+ continue
354
354
  try:
355
- serialized_value = processed_data[field_name]
356
355
  deserialized_value = JSONHandler.deserialize(serialized_value)
357
356
  processed_data[field_name] = deserialized_value
358
- logger.debug(f"Deserialized JSON field '{field_name}' for {self.table_name}")
357
+ logger.debug("Deserialized JSON field '%s' for %s", field_name, self.table_name)
359
358
  except Exception as e:
360
359
  if self._strict_json_processing:
361
- logger.error(f"Failed to deserialize JSON field '{field_name}' in {self.table_name}: {e}")
362
360
  raise JSONDeserializationError(
363
361
  f"JSON deserialization failed for field '{field_name}': {e}",
364
362
  field_name=field_name,
@@ -366,13 +364,40 @@ class BaseRepository(Generic[T, K]):
366
364
  original_error=e,
367
365
  ) from e
368
366
  else:
369
- logger.warning(f"Failed to deserialize JSON field '{field_name}' in {self.table_name}: {e}")
367
+ logger.warning(
368
+ "Failed to deserialize JSON field '%s' in %s: %s", field_name, self.table_name, e
369
+ )
370
370
  # Keep the original value to prevent data loss
371
- logger.warning(f"Keeping original value for field '{field_name}' in {self.table_name}")
371
+ logger.warning("Keeping original value for field '%s' in %s", field_name, self.table_name)
372
372
 
373
- logger.debug(f"Postprocessed {len(self._json_fields)} JSON fields for {self.table_name}")
373
+ logger.debug("Postprocessed %s JSON fields for %s", len(self._json_fields), self.table_name)
374
374
  return processed_data
375
375
 
376
+ def _row_to_model(self, row: Any) -> T:
377
+ """Convert a database row (mapping) into the model, postprocessing JSON/date/vector fields."""
378
+ return self.model_class(**self._postprocess_data(dict(row)))
379
+
380
+ @asynccontextmanager
381
+ async def _errors(
382
+ self, operation: str, message: str, passthrough: tuple[type[Exception], ...] = ()
383
+ ) -> AsyncGenerator[None, None]:
384
+ """Translate errors raised by a CRUD operation into the repository exception contract.
385
+
386
+ Exceptions of a ``passthrough`` type are re-raised unchanged; anything else becomes an
387
+ ``OperationError("<message>: <error>")`` chained to the original. Each failure is logged
388
+ once here: missing records at DEBUG (an expected outcome), everything else at ERROR.
389
+ """
390
+ try:
391
+ yield
392
+ except Exception as e:
393
+ if isinstance(e, RecordNotFoundError):
394
+ logger.debug("%s: %s", operation, e)
395
+ else:
396
+ logger.error("Error in %s: %s", operation, e)
397
+ if isinstance(e, passthrough):
398
+ raise
399
+ raise OperationError(f"{message}: {e!s}") from e
400
+
376
401
  async def create(self, item: T) -> T:
377
402
  """
378
403
  Create a new record in the database.
@@ -384,8 +409,7 @@ class BaseRepository(Generic[T, K]):
384
409
  T: The created model instance with any database-generated fields.
385
410
 
386
411
  Raises:
387
- HTTPException: If the creation fails or database error occurs.
388
- OperationError: If the database operation doesn't return a result.
412
+ OperationError: If the database operation fails or returns no row.
389
413
  JSONSerializationError: If JSON serialization fails for any field.
390
414
 
391
415
  Example:
@@ -398,7 +422,7 @@ class BaseRepository(Generic[T, K]):
398
422
  If the model has JSON fields, they will be automatically serialized before
399
423
  insertion and deserialized when returning the created record.
400
424
  """
401
- try:
425
+ async with self._errors("create", "Failed to create record", (OperationError, JSONProcessingError)):
402
426
  data = item.model_dump()
403
427
  # Preprocess data to serialize JSON fields
404
428
  processed_data = self._preprocess_data(data)
@@ -410,14 +434,7 @@ class BaseRepository(Generic[T, K]):
410
434
  if not result:
411
435
  raise OperationError(f"Failed to create {self.table_name} record")
412
436
 
413
- # Postprocess the result to deserialize JSON fields
414
- postprocessed_result = self._postprocess_data(dict(result))
415
- return self.model_class(**postprocessed_result)
416
- except Exception as e:
417
- logger.error(f"Error in create: {e}")
418
- if isinstance(e, OperationError | JSONProcessingError):
419
- raise
420
- raise OperationError(f"Failed to create record: {e!s}") from e
437
+ return self._row_to_model(result)
421
438
 
422
439
  async def create_bulk(self, items: list[T], batch_size: int = 100) -> list[T]:
423
440
  """
@@ -431,9 +448,9 @@ class BaseRepository(Generic[T, K]):
431
448
  List[T]: List of created model instances with database-generated fields.
432
449
 
433
450
  Raises:
434
- HTTPException: If the bulk creation fails or database error occurs.
435
- OperationError: If the database operation fails.
436
- JSONSerializationError: If JSON serialization fails for any record.
451
+ OperationError: If the database operation fails, or if JSON serialization fails
452
+ for any record. Unlike ``create``, a serialization failure is not raised
453
+ directly: it is wrapped, with the JSONSerializationError as ``__cause__``.
437
454
 
438
455
  Example:
439
456
  ```python
@@ -448,7 +465,7 @@ class BaseRepository(Generic[T, K]):
448
465
  insertion and deserialized when returning the created records.
449
466
  """
450
467
  all_results = []
451
- try:
468
+ async with self._errors("create_bulk", "Failed to create records in bulk"):
452
469
  async with self.db_connection.transaction():
453
470
  for i in range(0, len(items), batch_size):
454
471
  batch = items[i : i + batch_size]
@@ -469,15 +486,10 @@ class BaseRepository(Generic[T, K]):
469
486
  await cur.execute(full_query, batch_values)
470
487
  results = await cur.fetchall()
471
488
 
472
- # Postprocess each result to deserialize JSON fields
473
- postprocessed_results = [self._postprocess_data(dict(row)) for row in results]
474
- all_results.extend([self.model_class(**row) for row in postprocessed_results])
489
+ all_results.extend(self._row_to_model(row) for row in results)
475
490
  return all_results
476
- except Exception as e:
477
- logger.error(f"Error in create_bulk: {e}")
478
- raise OperationError(f"Failed to create records in bulk: {e!s}") from e
479
491
 
480
- async def get_by_id(self, record_id: K) -> T | None:
492
+ async def get_by_id(self, record_id: K) -> T:
481
493
  """
482
494
  Retrieve a record by its ID.
483
495
 
@@ -485,10 +497,11 @@ class BaseRepository(Generic[T, K]):
485
497
  record_id (K): The unique identifier of the record.
486
498
 
487
499
  Returns:
488
- Optional[T]: The found model instance or None if not found.
500
+ T: The found model instance.
489
501
 
490
502
  Raises:
491
- HTTPException: If the database query fails.
503
+ RecordNotFoundError: If no record has this ID.
504
+ OperationError: If the database query fails.
492
505
  JSONDeserializationError: If JSON deserialization fails and strict_json_processing is True.
493
506
 
494
507
  Example:
@@ -504,7 +517,7 @@ class BaseRepository(Generic[T, K]):
504
517
  If the model has JSON fields, they will be automatically deserialized
505
518
  from the database representation before creating the model instance.
506
519
  """
507
- try:
520
+ async with self._errors("get_by_id", "Failed to get record", (RecordNotFoundError, JSONProcessingError)):
508
521
  select_query = PsycopgHelper.build_select_query(self.table_name, where_clause={self.primary_key: record_id})
509
522
  async with self.db_connection.cursor(row_factory=dict_row) as cur:
510
523
  await cur.execute(select_query, [record_id])
@@ -512,14 +525,7 @@ class BaseRepository(Generic[T, K]):
512
525
  if not result:
513
526
  raise RecordNotFoundError(f"Record with id {record_id} not found")
514
527
 
515
- # Postprocess the result to deserialize JSON fields
516
- postprocessed_result = self._postprocess_data(dict(result))
517
- return self.model_class(**postprocessed_result)
518
- except Exception as e:
519
- logger.error(f"Error in get_by_id: {e}")
520
- if isinstance(e, RecordNotFoundError | JSONProcessingError):
521
- raise
522
- raise OperationError(f"Failed to get record: {e!s}") from e
528
+ return self._row_to_model(result)
523
529
 
524
530
  async def get_all(self) -> list[T]:
525
531
  """
@@ -529,7 +535,7 @@ class BaseRepository(Generic[T, K]):
529
535
  List[T]: List of all model instances in the table.
530
536
 
531
537
  Raises:
532
- HTTPException: If the database query fails.
538
+ OperationError: If the database query fails.
533
539
  JSONDeserializationError: If JSON deserialization fails and strict_json_processing is True.
534
540
 
535
541
  Example:
@@ -546,20 +552,15 @@ class BaseRepository(Generic[T, K]):
546
552
  If the model has JSON fields, they will be automatically deserialized
547
553
  from the database representation before creating the model instances.
548
554
  """
549
- try:
550
- async with self.db_connection.cursor(row_factory=dict_row) as cur:
551
- query = SQL("SELECT * FROM {}").format(Identifier(self.table_name))
552
- await cur.execute(query)
553
- rows = await cur.fetchall()
555
+ async with (
556
+ self._errors("get_all", "Failed to get all records", (JSONProcessingError,)),
557
+ self.db_connection.cursor(row_factory=dict_row) as cur,
558
+ ):
559
+ query = SQL("SELECT * FROM {}").format(Identifier(self.table_name))
560
+ await cur.execute(query)
561
+ rows = await cur.fetchall()
554
562
 
555
- # Postprocess each row to deserialize JSON fields
556
- postprocessed_rows = [self._postprocess_data(dict(row)) for row in rows]
557
- return [self.model_class(**row) for row in postprocessed_rows]
558
- except Exception as e:
559
- logger.error(f"Error in get_all: {e}")
560
- if isinstance(e, JSONProcessingError):
561
- raise
562
- raise OperationError(f"Failed to get all records: {e!s}") from e
563
+ return [self._row_to_model(row) for row in rows]
563
564
 
564
565
  async def update(self, record_id: K, data: dict[str, Any]) -> T:
565
566
  """
@@ -573,7 +574,7 @@ class BaseRepository(Generic[T, K]):
573
574
  T: The updated model instance.
574
575
 
575
576
  Raises:
576
- HTTPException: If the update fails or database error occurs.
577
+ OperationError: If the database operation fails.
577
578
  RecordNotFoundError: If the record is not found.
578
579
  JSONSerializationError: If JSON serialization fails for any field.
579
580
  JSONDeserializationError: If JSON deserialization fails and strict_json_processing is True.
@@ -591,7 +592,7 @@ class BaseRepository(Generic[T, K]):
591
592
  If the data contains JSON fields, they will be automatically serialized before
592
593
  the update and deserialized when returning the updated record.
593
594
  """
594
- try:
595
+ async with self._errors("update", "Failed to update record", (RecordNotFoundError, JSONProcessingError)):
595
596
  # Preprocess data to serialize JSON fields
596
597
  processed_data = self._preprocess_data(data)
597
598
  update_query = PsycopgHelper.build_update_query(
@@ -604,14 +605,7 @@ class BaseRepository(Generic[T, K]):
604
605
  if not result:
605
606
  raise RecordNotFoundError(f"Record with id {record_id} not found")
606
607
 
607
- # Postprocess the result to deserialize JSON fields
608
- postprocessed_result = self._postprocess_data(dict(result))
609
- return self.model_class(**postprocessed_result)
610
- except Exception as e:
611
- logger.error(f"Error in update: {e}")
612
- if isinstance(e, RecordNotFoundError | JSONProcessingError):
613
- raise
614
- raise OperationError(f"Failed to update record: {e!s}") from e
608
+ return self._row_to_model(result)
615
609
 
616
610
  async def delete(self, record_id: K) -> None:
617
611
  """
@@ -621,7 +615,8 @@ class BaseRepository(Generic[T, K]):
621
615
  record_id (K): The unique identifier of the record to delete.
622
616
 
623
617
  Raises:
624
- HTTPException: If the deletion fails or database error occurs.
618
+ RecordNotFoundError: If no record has the given ID.
619
+ OperationError: If the database operation fails.
625
620
 
626
621
  Example:
627
622
  ```python
@@ -635,17 +630,12 @@ class BaseRepository(Generic[T, K]):
635
630
  Note:
636
631
  This is a hard delete. Consider implementing soft delete if needed.
637
632
  """
638
- try:
633
+ async with self._errors("delete", "Failed to delete record", (RecordNotFoundError,)):
639
634
  delete_query = PsycopgHelper.build_delete_query(self.table_name, where_clause={self.primary_key: record_id})
640
635
  async with self.db_connection.cursor() as cur:
641
636
  await cur.execute(delete_query, [record_id])
642
637
  if cur.rowcount == 0:
643
638
  raise RecordNotFoundError(f"Record with id {record_id} not found")
644
- except Exception as e:
645
- logger.error(f"Error in delete: {e}")
646
- if isinstance(e, RecordNotFoundError):
647
- raise
648
- raise OperationError(f"Failed to delete record: {e!s}") from e
649
639
 
650
640
  async def exists(self, record_id: K) -> bool:
651
641
  """
@@ -658,7 +648,7 @@ class BaseRepository(Generic[T, K]):
658
648
  bool: True if the record exists, False otherwise.
659
649
 
660
650
  Raises:
661
- HTTPException: If the database query fails.
651
+ OperationError: If the database query fails.
662
652
 
663
653
  Example:
664
654
  ```python
@@ -671,10 +661,10 @@ class BaseRepository(Generic[T, K]):
671
661
  print("User exists")
672
662
  ```
673
663
  """
674
- try:
664
+ async with self._errors("exists", "Failed to check record existence"):
665
+ query = SQL("SELECT 1 FROM {} WHERE {} = %s").format(
666
+ Identifier(self.table_name), Identifier(self.primary_key)
667
+ )
675
668
  async with self.db_connection.cursor() as cur:
676
- await cur.execute(f"SELECT 1 FROM {self.table_name} WHERE {self.primary_key} = %s", [record_id])
669
+ await cur.execute(query, [record_id])
677
670
  return bool(await cur.fetchone())
678
- except Exception as e:
679
- logger.error(f"Error in exists: {e}")
680
- raise OperationError(f"Failed to check record existence: {e!s}") from e
@@ -4,20 +4,40 @@ import json
4
4
  import logging
5
5
  from datetime import date, datetime, time
6
6
  from decimal import Decimal
7
- from typing import Any
7
+ from typing import Any, Literal, cast, get_args
8
8
  from uuid import UUID
9
9
 
10
10
  logger = logging.getLogger(__name__)
11
11
 
12
+ DecimalMode = Literal["float", "str"]
13
+ """How Decimal values are written to JSON: ``"float"`` (default, may lose digits) or ``"str"`` (lossless)."""
14
+
15
+
16
+ def check_decimal_mode(decimal_as: str) -> DecimalMode:
17
+ """Return ``decimal_as`` if it is a valid DecimalMode, else raise ValueError."""
18
+ if decimal_as not in get_args(DecimalMode):
19
+ raise ValueError(f"decimal_as must be one of {get_args(DecimalMode)}, got {decimal_as!r}")
20
+ return cast("DecimalMode", decimal_as)
21
+
12
22
 
13
23
  class CustomJSONEncoder(json.JSONEncoder):
14
24
  """Custom JSON encoder for common Python types.
15
25
 
16
26
  Handles serialization of UUID, datetime, date, time, Decimal, set, frozenset, and Pydantic models
17
27
  that are commonly used in applications but not natively JSON serializable.
28
+
29
+ Decimal is written as a float by default, which can lose digits (JSON numbers decode to float).
30
+ Pass ``decimal_as="str"`` to write it as a string that keeps every digit, e.g.
31
+ ``json.dumps(data, cls=CustomJSONEncoder, decimal_as="str")``.
18
32
  """
19
33
 
20
- def default(self, obj: Any) -> Any:
34
+ def __init__(self, *args: Any, decimal_as: DecimalMode = "float", **kwargs: Any) -> None:
35
+ super().__init__(*args, **kwargs)
36
+ self.decimal_as = check_decimal_mode(decimal_as)
37
+
38
+ # The parameter keeps its public name `obj` (the base class calls it `o`); renaming it would
39
+ # break callers that pass it by keyword.
40
+ def default(self, obj: Any) -> Any: # pyright: ignore[reportIncompatibleMethodOverride]
21
41
  """Convert objects to JSON-serializable format.
22
42
 
23
43
  Args:
@@ -34,7 +54,7 @@ class CustomJSONEncoder(json.JSONEncoder):
34
54
  elif isinstance(obj, datetime | date | time):
35
55
  return obj.isoformat()
36
56
  elif isinstance(obj, Decimal):
37
- return float(obj)
57
+ return str(obj) if self.decimal_as == "str" else float(obj)
38
58
  elif isinstance(obj, set | frozenset):
39
59
  return list(obj)
40
60
  elif hasattr(obj, "model_dump"): # Pydantic model
@@ -52,11 +72,12 @@ class JSONHandler:
52
72
  """
53
73
 
54
74
  @staticmethod
55
- def serialize(data: Any) -> str:
75
+ def serialize(data: Any, *, decimal_as: DecimalMode = "float") -> str:
56
76
  """Serialize Python objects to JSON string.
57
77
 
58
78
  Args:
59
79
  data: The Python object to serialize
80
+ decimal_as: How to write Decimal values: ``"float"`` (default) or ``"str"`` (lossless)
60
81
 
61
82
  Returns:
62
83
  JSON string representation of the data
@@ -65,9 +86,8 @@ class JSONHandler:
65
86
  ValueError: If the serialization fails with descriptive error message
66
87
  """
67
88
  try:
68
- return json.dumps(data, cls=CustomJSONEncoder, ensure_ascii=False, allow_nan=False)
89
+ return json.dumps(data, cls=CustomJSONEncoder, ensure_ascii=False, allow_nan=False, decimal_as=decimal_as)
69
90
  except (TypeError, ValueError, OverflowError) as e:
70
- logger.error(f"JSON serialization failed for data type {type(data).__name__}: {e}")
71
91
  raise ValueError(f"Cannot serialize to JSON: {e}") from e
72
92
 
73
93
  @staticmethod
@@ -91,7 +111,6 @@ class JSONHandler:
91
111
  json_str = json_str.decode("utf-8")
92
112
  return json.loads(json_str)
93
113
  except (json.JSONDecodeError, UnicodeDecodeError) as e:
94
- logger.error(f"JSON deserialization failed: {e}")
95
114
  raise ValueError(f"Cannot deserialize JSON: {e}") from e
96
115
 
97
116
  @staticmethod
@@ -10,14 +10,15 @@ Key security features:
10
10
  - Uses psycopg.sql.Placeholder for parameter values
11
11
  """
12
12
 
13
+ from collections.abc import Iterable
13
14
  from typing import Any
14
15
 
15
- from psycopg.sql import SQL, Identifier, Placeholder
16
+ from psycopg.sql import SQL, Composed, Identifier, Placeholder
16
17
 
17
18
 
18
19
  class PsycopgHelper:
19
20
  @staticmethod
20
- def get_columns(keys: dict[str, Any]) -> list[Identifier]:
21
+ def get_columns(keys: Iterable[str]) -> list[Identifier]:
21
22
  """
22
23
  Convert dictionary keys to a list of SQL Identifiers for safe column name handling.
23
24
 
@@ -30,7 +31,7 @@ class PsycopgHelper:
30
31
  return [Identifier(k) for k in keys]
31
32
 
32
33
  @staticmethod
33
- def get_columns_as_list(keys: dict[str, Any]) -> list[str]:
34
+ def get_columns_as_list(keys: Iterable[str]) -> list[str]:
34
35
  """
35
36
  Convert dictionary keys to a list of column names as strings.
36
37
 
@@ -58,7 +59,7 @@ class PsycopgHelper:
58
59
  @staticmethod
59
60
  def build_select_query(
60
61
  table_name: str, columns: list[str] | None = None, where_clause: dict[str, Any] | None = None
61
- ) -> SQL:
62
+ ) -> Composed:
62
63
  """
63
64
  Build a safe SELECT query with optional column selection and WHERE clause.
64
65
 
@@ -68,7 +69,7 @@ class PsycopgHelper:
68
69
  where_clause: Optional dictionary of column-value pairs for WHERE conditions
69
70
 
70
71
  Returns:
71
- SQL object representing the parameterized query
72
+ Composed SQL object representing the parameterized query
72
73
  """
73
74
  select_columns = SQL("*") if not columns else SQL(", ").join(map(Identifier, columns))
74
75
 
@@ -83,7 +84,7 @@ class PsycopgHelper:
83
84
  return query
84
85
 
85
86
  @staticmethod
86
- def build_insert_query(table_name: str, data: dict[str, Any], batch_size: int = 1) -> SQL:
87
+ def build_insert_query(table_name: str, data: dict[str, Any], batch_size: int = 1) -> Composed:
87
88
  """
88
89
  Build a safe INSERT query, supporting batch inserts.
89
90
 
@@ -93,7 +94,7 @@ class PsycopgHelper:
93
94
  batch_size: Number of records to insert (for batch inserts)
94
95
 
95
96
  Returns:
96
- SQL object representing the parameterized query
97
+ Composed SQL object representing the parameterized query
97
98
 
98
99
  Example:
99
100
  >>> query = PsycopgHelper.build_insert_query("users", {"name": "John", "age": 30}, batch_size=1)
@@ -112,7 +113,7 @@ class PsycopgHelper:
112
113
  )
113
114
 
114
115
  @staticmethod
115
- def build_update_query(table_name: str, data: dict[str, Any], where_clause: dict[str, Any]) -> SQL:
116
+ def build_update_query(table_name: str, data: dict[str, Any], where_clause: dict[str, Any]) -> Composed:
116
117
  """
117
118
  Build a safe UPDATE query with SET and WHERE clauses.
118
119
 
@@ -122,7 +123,7 @@ class PsycopgHelper:
122
123
  where_clause: Dictionary of column-value pairs for WHERE conditions
123
124
 
124
125
  Returns:
125
- SQL object representing the parameterized query
126
+ Composed SQL object representing the parameterized query
126
127
 
127
128
  Example:
128
129
  >>> query = PsycopgHelper.build_update_query("users",
@@ -139,7 +140,7 @@ class PsycopgHelper:
139
140
  return SQL("UPDATE {} SET {} WHERE {}").format(Identifier(table_name), set_items, where_conditions)
140
141
 
141
142
  @staticmethod
142
- def build_delete_query(table_name: str, where_clause: dict[str, Any]) -> SQL:
143
+ def build_delete_query(table_name: str, where_clause: dict[str, Any]) -> Composed:
143
144
  """
144
145
  Build a safe DELETE query with WHERE clause.
145
146
 
@@ -148,7 +149,7 @@ class PsycopgHelper:
148
149
  where_clause: Dictionary of column-value pairs for WHERE conditions
149
150
 
150
151
  Returns:
151
- SQL object representing the parameterized query
152
+ Composed SQL object representing the parameterized query
152
153
 
153
154
  Example:
154
155
  >>> query = PsycopgHelper.build_delete_query("users", {"id": 1})
@@ -6,7 +6,7 @@ import types
6
6
  import typing
7
7
  from typing import Any, Union
8
8
 
9
- from pydantic import BaseModel
9
+ from pydantic import BaseModel, RootModel
10
10
  from pydantic.fields import FieldInfo
11
11
 
12
12
  logger = logging.getLogger(__name__)
@@ -189,6 +189,18 @@ class TypeInspector:
189
189
  if annotation is None:
190
190
  return False
191
191
 
192
+ # A bare `dict` carries no type parameters but is still a JSON object.
193
+ # A bare `list` is deliberately not detected: it has always been passed
194
+ # through unchanged so psycopg can adapt it to a PostgreSQL array.
195
+ if annotation is dict:
196
+ return True
197
+
198
+ # Nested Pydantic models are dumped to dicts by model_dump() and stored as JSON.
199
+ # RootModel wrappers are excluded: they dump to their root value (str, list, ...),
200
+ # not a dict, and keep their previous pass-through behaviour.
201
+ if isinstance(annotation, type) and issubclass(annotation, BaseModel) and not issubclass(annotation, RootModel):
202
+ return True
203
+
192
204
  # Check direct origin types
193
205
  if TypeInspector._check_origin_type(annotation):
194
206
  return True
@@ -1,27 +0,0 @@
1
- {
2
- "terminal.integrated.env.osx": {
3
- "PYTHONPATH": "${workspaceFolder}/src"
4
- },
5
- "terminal.integrated.env.linux": {
6
- "PYTHONPATH": "${workspaceFolder}/src"
7
- },
8
- "terminal.integrated.env.windows": {
9
- "PYTHONPATH": "${workspaceFolder}/src"
10
- },
11
- "python.envFile": "${workspaceFolder}/.env",
12
- "python.testing.pytestEnabled": true,
13
- "python.testing.unittestEnabled": false,
14
- "python.testing.pytestArgs": [
15
- "tests",
16
- "-v",
17
- "-s",
18
- "--tb=short"
19
- ],
20
- "python.testing.unittestArgs": [
21
- "-v",
22
- "-s",
23
- "./tests",
24
- "-p",
25
- "test_*.py"
26
- ]
27
- }
File without changes