psycopg-toolkit 0.3.0__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.0 → psycopg_toolkit-0.4.0}/PKG-INFO +8 -6
  2. {psycopg_toolkit-0.3.0 → psycopg_toolkit-0.4.0}/pyproject.toml +41 -17
  3. {psycopg_toolkit-0.3.0 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/__init__.py +2 -1
  4. {psycopg_toolkit-0.3.0 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/core/config.py +18 -4
  5. {psycopg_toolkit-0.3.0 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/core/database.py +65 -43
  6. {psycopg_toolkit-0.3.0 → 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.0 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/repositories/base.py +123 -146
  9. {psycopg_toolkit-0.3.0 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/utils/json_handler.py +26 -7
  10. {psycopg_toolkit-0.3.0 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/utils/psychopg_helper.py +12 -11
  11. {psycopg_toolkit-0.3.0 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/utils/type_inspector.py +13 -1
  12. psycopg_toolkit-0.3.0/.vscode/settings.json +0 -27
  13. {psycopg_toolkit-0.3.0 → psycopg_toolkit-0.4.0}/.gitignore +0 -0
  14. {psycopg_toolkit-0.3.0 → psycopg_toolkit-0.4.0}/LICENSE +0 -0
  15. {psycopg_toolkit-0.3.0 → psycopg_toolkit-0.4.0}/README.md +0 -0
  16. {psycopg_toolkit-0.3.0 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/core/__init__.py +0 -0
  17. {psycopg_toolkit-0.3.0 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/core/factory.py +0 -0
  18. {psycopg_toolkit-0.3.0 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/exceptions.py +0 -0
  19. {psycopg_toolkit-0.3.0 → psycopg_toolkit-0.4.0}/src/psycopg_toolkit/repositories/__init__.py +0 -0
  20. {psycopg_toolkit-0.3.0 → 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.0
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.0"
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,30 +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
42
- "pgvector>=0.4.1", # For pgvector integration tests
39
+ "pytest>=9.2.0",
40
+ "pytest-asyncio>=1.5.0",
41
+ "pytest-cov>=7.1.0",
42
+ "testcontainers>=4.15.0",
43
43
  ]
44
44
  dev = [
45
- "ruff>=0.8.0",
46
- ]
47
- vector = [
48
- "pgvector>=0.4.1",
45
+ "ruff>=0.17.6",
49
46
  ]
50
47
 
51
48
  [build-system]
52
- requires = ["hatchling>=1.26.3"]
49
+ requires = ["hatchling>=1.33.0"]
53
50
  build-backend = "hatchling.build"
54
51
 
55
52
  [tool.hatch.build.targets.wheel]
@@ -77,6 +74,7 @@ exclude = [
77
74
  ".env",
78
75
  "*.egg-info/",
79
76
  ".claude/*",
77
+ ".vscode/*",
80
78
  "uv.lock",
81
79
  ]
82
80
 
@@ -96,6 +94,12 @@ name = "testpypi"
96
94
  url = "https://test.pypi.org/simple/"
97
95
  publish-url = "https://test.pypi.org/legacy/"
98
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
+
99
103
  [tool.pytest.ini_options]
100
104
  testpaths = ["tests"]
101
105
  python_files = ["test_*.py"]
@@ -111,6 +115,10 @@ addopts = [
111
115
  "--tb=short",
112
116
  "-m", "not performance", # Exclude performance tests by default
113
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
+ ]
114
122
 
115
123
  [tool.coverage.run]
116
124
  source = ["src/psycopg_toolkit"]
@@ -136,6 +144,19 @@ precision = 2
136
144
  show_missing = true
137
145
  skip_covered = false
138
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
+
139
160
  [tool.ruff]
140
161
  target-version = "py311"
141
162
  line-length = 120
@@ -156,7 +177,7 @@ select = [
156
177
  "RUF", # Ruff-specific rules
157
178
  "C90", # mccabe complexity
158
179
  "PTH", # flake8-use-pathlib
159
- "TCH", # flake8-type-checking
180
+ "TC", # flake8-type-checking (formerly TCH)
160
181
  ]
161
182
  ignore =[
162
183
  "E501", # Line too long (handled by formatter)
@@ -193,6 +214,9 @@ keep-runtime-typing = true # For Pydantic
193
214
  ignore-names = ["model_*"] # For Pydantic models
194
215
 
195
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"]
196
220
  quote-style = "double"
197
221
  indent-style = "space"
198
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.
@@ -98,10 +102,17 @@ class BaseRepository(Generic[T, K]):
98
102
  treated as PostgreSQL arrays rather than JSONB. Only relevant when
99
103
  auto_detect_json=False. Defaults to None.
100
104
  vector_fields (Optional[Set[str]], optional): Explicit set of field names to treat
101
- as pgvector columns. If provided, overrides auto-detection. Defaults to None.
105
+ as pgvector columns. Vector fields are returned as strings from PostgreSQL and
106
+ automatically parsed to list[float] using JSON parsing. If provided, overrides
107
+ auto-detection. Defaults to None.
102
108
  auto_detect_vector (bool, optional): Whether to automatically detect vector fields
103
109
  (list[float]) from Pydantic type hints. Ignored if vector_fields is provided.
104
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``.
105
116
 
106
117
  Note:
107
118
  The model_class should be a Pydantic model that matches the database schema.
@@ -115,33 +126,34 @@ class BaseRepository(Generic[T, K]):
115
126
  """
116
127
  self.db_connection = db_connection
117
128
  self.table_name = table_name
129
+ self._decimal_as: DecimalMode = check_decimal_mode(decimal_as)
118
130
  self.model_class = model_class
119
131
  self.primary_key = primary_key
120
132
 
121
133
  # Vector field detection and configuration
122
134
  if vector_fields is not None:
123
135
  self._vector_fields = vector_fields
124
- 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)
125
137
  elif auto_detect_vector:
126
138
  self._vector_fields = TypeInspector.detect_vector_fields(model_class)
127
- 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)
128
140
  else:
129
141
  self._vector_fields = set()
130
- logger.debug(f"Vector field detection disabled for {table_name}")
142
+ logger.debug("Vector field detection disabled for %s", table_name)
131
143
 
132
144
  # JSON field detection and configuration
133
145
  if json_fields is not None:
134
146
  self._json_fields = json_fields
135
- 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)
136
148
  elif auto_detect_json:
137
149
  detected_fields = TypeInspector.detect_json_fields(model_class)
138
150
  # Exclude array fields and vector fields from JSON fields
139
151
  self._json_fields = detected_fields - (array_fields or set()) - self._vector_fields
140
- logger.debug(f"Auto-detected JSON fields for {table_name}: {detected_fields}")
141
- 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)
142
154
  else:
143
155
  self._json_fields = set()
144
- logger.debug(f"JSON field processing disabled for {table_name}")
156
+ logger.debug("JSON field processing disabled for %s", table_name)
145
157
 
146
158
  # Cache for performance and configuration
147
159
  self._auto_detect_json = auto_detect_json
@@ -150,48 +162,6 @@ class BaseRepository(Generic[T, K]):
150
162
  self._date_fields = date_fields or set()
151
163
  self._array_fields = array_fields or set()
152
164
 
153
- # Check if psycopg JSON adapters are enabled
154
- self._use_psycopg_adapters = self._check_psycopg_adapters()
155
-
156
- # Store flag for lazy registration of pgvector adapter
157
- self._vector_adapter_registered = False
158
- self._needs_vector_adapter = bool(self._vector_fields)
159
-
160
- async def _ensure_vector_adapter_registered(self):
161
- """Ensure pgvector adapter is registered on the connection.
162
-
163
- This is called lazily on first use to handle async registration properly.
164
- Uses the async variant of register_vector for async connections.
165
- """
166
- if not self._needs_vector_adapter or self._vector_adapter_registered:
167
- return
168
-
169
- try:
170
- from pgvector.psycopg import register_vector_async
171
-
172
- await register_vector_async(self.db_connection)
173
- self._vector_adapter_registered = True
174
- logger.info(f"Registered pgvector adapter for {self.table_name} with fields: {self._vector_fields}")
175
- except ImportError:
176
- logger.warning(
177
- f"pgvector package not installed but vector fields detected in {self.table_name}: {self._vector_fields}. "
178
- "Vector fields will be returned as strings. Install pgvector with: pip install pgvector"
179
- )
180
- self._needs_vector_adapter = False # Don't try again
181
- except Exception as e:
182
- logger.warning(f"Failed to register pgvector adapter for {self.table_name}: {e}")
183
- self._needs_vector_adapter = False # Don't try again
184
-
185
- def _check_psycopg_adapters(self) -> bool:
186
- """Check if psycopg JSON adapters are enabled on the connection.
187
-
188
- Returns:
189
- bool: True if psycopg JSON adapters are enabled, False otherwise.
190
- """
191
- # Never use psycopg adapters - this causes issues with arrays
192
- # When auto_detect_json=False, users expect NO JSON processing
193
- return False
194
-
195
165
  @property
196
166
  def json_fields(self) -> set[str]:
197
167
  """Get the set of field names that should be treated as JSON.
@@ -260,11 +230,11 @@ class BaseRepository(Generic[T, K]):
260
230
  if value is not None and isinstance(value, dict | list):
261
231
  # Skip array fields - they should remain as PostgreSQL arrays
262
232
  if field_name in self._array_fields:
263
- 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)
264
234
  continue
265
235
  # Wrap other dict/list fields with Json()
266
236
  processed_data[field_name] = Json(value)
267
- 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)
268
238
  return processed_data
269
239
 
270
240
  # Custom JSON processing mode - serialize to strings
@@ -274,11 +244,10 @@ class BaseRepository(Generic[T, K]):
274
244
  if isinstance(value, dict | list):
275
245
  try:
276
246
  # Serialize to JSON string for manual processing
277
- serialized = JSONHandler.serialize(value)
247
+ serialized = JSONHandler.serialize(value, decimal_as=self._decimal_as)
278
248
  processed_data[field_name] = serialized
279
- 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)
280
250
  except Exception as e:
281
- logger.error(f"Failed to serialize JSON field '{field_name}' in {self.table_name}: {e}")
282
251
  raise JSONSerializationError(
283
252
  f"JSON serialization failed for field '{field_name}': {e}",
284
253
  field_name=field_name,
@@ -288,11 +257,10 @@ class BaseRepository(Generic[T, K]):
288
257
  elif not isinstance(value, str):
289
258
  # Value is not dict/list/str, try to serialize it anyway
290
259
  try:
291
- serialized = JSONHandler.serialize(value)
260
+ serialized = JSONHandler.serialize(value, decimal_as=self._decimal_as)
292
261
  processed_data[field_name] = serialized
293
- 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)
294
263
  except Exception as e:
295
- logger.error(f"Failed to serialize JSON field '{field_name}' in {self.table_name}: {e}")
296
264
  raise JSONSerializationError(
297
265
  f"JSON serialization failed for field '{field_name}': {e}",
298
266
  field_name=field_name,
@@ -348,21 +316,47 @@ class BaseRepository(Generic[T, K]):
348
316
  f"Converted date field '{field_name}' from {type(value).__name__} to ISO string for {self.table_name}"
349
317
  )
350
318
 
319
+ # Parse vector fields from PostgreSQL string format to Python list[float]
320
+ # PostgreSQL returns vectors as strings like '[0.1,0.2,0.3]'
321
+ for field_name in self._vector_fields:
322
+ if field_name in processed_data and processed_data[field_name] is not None:
323
+ value = processed_data[field_name]
324
+ if isinstance(value, str):
325
+ try:
326
+ # Parse string to list[float] using json.loads()
327
+ parsed_vector = JSONHandler.deserialize(value)
328
+ if isinstance(parsed_vector, list):
329
+ processed_data[field_name] = parsed_vector
330
+ logger.debug(
331
+ f"Parsed vector field '{field_name}' from string to list[float] for {self.table_name}"
332
+ )
333
+ else:
334
+ logger.warning(
335
+ f"Vector field '{field_name}' parsed to {type(parsed_vector).__name__} instead of list for {self.table_name}"
336
+ )
337
+ except Exception as e:
338
+ logger.warning(
339
+ f"Failed to parse vector field '{field_name}' in {self.table_name}: {e}. Keeping as string."
340
+ )
341
+
351
342
  # If no JSON fields should be processed, return the processed data
352
343
  if not json_fields:
353
- 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)
354
345
  return processed_data
355
346
 
356
347
  for field_name in self._json_fields:
357
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
358
354
  try:
359
- serialized_value = processed_data[field_name]
360
355
  deserialized_value = JSONHandler.deserialize(serialized_value)
361
356
  processed_data[field_name] = deserialized_value
362
- 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)
363
358
  except Exception as e:
364
359
  if self._strict_json_processing:
365
- logger.error(f"Failed to deserialize JSON field '{field_name}' in {self.table_name}: {e}")
366
360
  raise JSONDeserializationError(
367
361
  f"JSON deserialization failed for field '{field_name}': {e}",
368
362
  field_name=field_name,
@@ -370,13 +364,40 @@ class BaseRepository(Generic[T, K]):
370
364
  original_error=e,
371
365
  ) from e
372
366
  else:
373
- 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
+ )
374
370
  # Keep the original value to prevent data loss
375
- 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)
376
372
 
377
- 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)
378
374
  return processed_data
379
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
+
380
401
  async def create(self, item: T) -> T:
381
402
  """
382
403
  Create a new record in the database.
@@ -388,8 +409,7 @@ class BaseRepository(Generic[T, K]):
388
409
  T: The created model instance with any database-generated fields.
389
410
 
390
411
  Raises:
391
- HTTPException: If the creation fails or database error occurs.
392
- OperationError: If the database operation doesn't return a result.
412
+ OperationError: If the database operation fails or returns no row.
393
413
  JSONSerializationError: If JSON serialization fails for any field.
394
414
 
395
415
  Example:
@@ -402,10 +422,7 @@ class BaseRepository(Generic[T, K]):
402
422
  If the model has JSON fields, they will be automatically serialized before
403
423
  insertion and deserialized when returning the created record.
404
424
  """
405
- # Ensure pgvector adapter is registered if needed
406
- await self._ensure_vector_adapter_registered()
407
-
408
- try:
425
+ async with self._errors("create", "Failed to create record", (OperationError, JSONProcessingError)):
409
426
  data = item.model_dump()
410
427
  # Preprocess data to serialize JSON fields
411
428
  processed_data = self._preprocess_data(data)
@@ -417,14 +434,7 @@ class BaseRepository(Generic[T, K]):
417
434
  if not result:
418
435
  raise OperationError(f"Failed to create {self.table_name} record")
419
436
 
420
- # Postprocess the result to deserialize JSON fields
421
- postprocessed_result = self._postprocess_data(dict(result))
422
- return self.model_class(**postprocessed_result)
423
- except Exception as e:
424
- logger.error(f"Error in create: {e}")
425
- if isinstance(e, OperationError | JSONProcessingError):
426
- raise
427
- raise OperationError(f"Failed to create record: {e!s}") from e
437
+ return self._row_to_model(result)
428
438
 
429
439
  async def create_bulk(self, items: list[T], batch_size: int = 100) -> list[T]:
430
440
  """
@@ -438,9 +448,9 @@ class BaseRepository(Generic[T, K]):
438
448
  List[T]: List of created model instances with database-generated fields.
439
449
 
440
450
  Raises:
441
- HTTPException: If the bulk creation fails or database error occurs.
442
- OperationError: If the database operation fails.
443
- 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__``.
444
454
 
445
455
  Example:
446
456
  ```python
@@ -455,7 +465,7 @@ class BaseRepository(Generic[T, K]):
455
465
  insertion and deserialized when returning the created records.
456
466
  """
457
467
  all_results = []
458
- try:
468
+ async with self._errors("create_bulk", "Failed to create records in bulk"):
459
469
  async with self.db_connection.transaction():
460
470
  for i in range(0, len(items), batch_size):
461
471
  batch = items[i : i + batch_size]
@@ -476,15 +486,10 @@ class BaseRepository(Generic[T, K]):
476
486
  await cur.execute(full_query, batch_values)
477
487
  results = await cur.fetchall()
478
488
 
479
- # Postprocess each result to deserialize JSON fields
480
- postprocessed_results = [self._postprocess_data(dict(row)) for row in results]
481
- 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)
482
490
  return all_results
483
- except Exception as e:
484
- logger.error(f"Error in create_bulk: {e}")
485
- raise OperationError(f"Failed to create records in bulk: {e!s}") from e
486
491
 
487
- async def get_by_id(self, record_id: K) -> T | None:
492
+ async def get_by_id(self, record_id: K) -> T:
488
493
  """
489
494
  Retrieve a record by its ID.
490
495
 
@@ -492,10 +497,11 @@ class BaseRepository(Generic[T, K]):
492
497
  record_id (K): The unique identifier of the record.
493
498
 
494
499
  Returns:
495
- Optional[T]: The found model instance or None if not found.
500
+ T: The found model instance.
496
501
 
497
502
  Raises:
498
- HTTPException: If the database query fails.
503
+ RecordNotFoundError: If no record has this ID.
504
+ OperationError: If the database query fails.
499
505
  JSONDeserializationError: If JSON deserialization fails and strict_json_processing is True.
500
506
 
501
507
  Example:
@@ -511,10 +517,7 @@ class BaseRepository(Generic[T, K]):
511
517
  If the model has JSON fields, they will be automatically deserialized
512
518
  from the database representation before creating the model instance.
513
519
  """
514
- # Ensure pgvector adapter is registered if needed
515
- await self._ensure_vector_adapter_registered()
516
-
517
- try:
520
+ async with self._errors("get_by_id", "Failed to get record", (RecordNotFoundError, JSONProcessingError)):
518
521
  select_query = PsycopgHelper.build_select_query(self.table_name, where_clause={self.primary_key: record_id})
519
522
  async with self.db_connection.cursor(row_factory=dict_row) as cur:
520
523
  await cur.execute(select_query, [record_id])
@@ -522,14 +525,7 @@ class BaseRepository(Generic[T, K]):
522
525
  if not result:
523
526
  raise RecordNotFoundError(f"Record with id {record_id} not found")
524
527
 
525
- # Postprocess the result to deserialize JSON fields
526
- postprocessed_result = self._postprocess_data(dict(result))
527
- return self.model_class(**postprocessed_result)
528
- except Exception as e:
529
- logger.error(f"Error in get_by_id: {e}")
530
- if isinstance(e, RecordNotFoundError | JSONProcessingError):
531
- raise
532
- raise OperationError(f"Failed to get record: {e!s}") from e
528
+ return self._row_to_model(result)
533
529
 
534
530
  async def get_all(self) -> list[T]:
535
531
  """
@@ -539,7 +535,7 @@ class BaseRepository(Generic[T, K]):
539
535
  List[T]: List of all model instances in the table.
540
536
 
541
537
  Raises:
542
- HTTPException: If the database query fails.
538
+ OperationError: If the database query fails.
543
539
  JSONDeserializationError: If JSON deserialization fails and strict_json_processing is True.
544
540
 
545
541
  Example:
@@ -556,23 +552,15 @@ class BaseRepository(Generic[T, K]):
556
552
  If the model has JSON fields, they will be automatically deserialized
557
553
  from the database representation before creating the model instances.
558
554
  """
559
- # Ensure pgvector adapter is registered if needed
560
- await self._ensure_vector_adapter_registered()
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()
561
562
 
562
- try:
563
- async with self.db_connection.cursor(row_factory=dict_row) as cur:
564
- query = SQL("SELECT * FROM {}").format(Identifier(self.table_name))
565
- await cur.execute(query)
566
- rows = await cur.fetchall()
567
-
568
- # Postprocess each row to deserialize JSON fields
569
- postprocessed_rows = [self._postprocess_data(dict(row)) for row in rows]
570
- return [self.model_class(**row) for row in postprocessed_rows]
571
- except Exception as e:
572
- logger.error(f"Error in get_all: {e}")
573
- if isinstance(e, JSONProcessingError):
574
- raise
575
- raise OperationError(f"Failed to get all records: {e!s}") from e
563
+ return [self._row_to_model(row) for row in rows]
576
564
 
577
565
  async def update(self, record_id: K, data: dict[str, Any]) -> T:
578
566
  """
@@ -586,7 +574,7 @@ class BaseRepository(Generic[T, K]):
586
574
  T: The updated model instance.
587
575
 
588
576
  Raises:
589
- HTTPException: If the update fails or database error occurs.
577
+ OperationError: If the database operation fails.
590
578
  RecordNotFoundError: If the record is not found.
591
579
  JSONSerializationError: If JSON serialization fails for any field.
592
580
  JSONDeserializationError: If JSON deserialization fails and strict_json_processing is True.
@@ -604,7 +592,7 @@ class BaseRepository(Generic[T, K]):
604
592
  If the data contains JSON fields, they will be automatically serialized before
605
593
  the update and deserialized when returning the updated record.
606
594
  """
607
- try:
595
+ async with self._errors("update", "Failed to update record", (RecordNotFoundError, JSONProcessingError)):
608
596
  # Preprocess data to serialize JSON fields
609
597
  processed_data = self._preprocess_data(data)
610
598
  update_query = PsycopgHelper.build_update_query(
@@ -617,14 +605,7 @@ class BaseRepository(Generic[T, K]):
617
605
  if not result:
618
606
  raise RecordNotFoundError(f"Record with id {record_id} not found")
619
607
 
620
- # Postprocess the result to deserialize JSON fields
621
- postprocessed_result = self._postprocess_data(dict(result))
622
- return self.model_class(**postprocessed_result)
623
- except Exception as e:
624
- logger.error(f"Error in update: {e}")
625
- if isinstance(e, RecordNotFoundError | JSONProcessingError):
626
- raise
627
- raise OperationError(f"Failed to update record: {e!s}") from e
608
+ return self._row_to_model(result)
628
609
 
629
610
  async def delete(self, record_id: K) -> None:
630
611
  """
@@ -634,7 +615,8 @@ class BaseRepository(Generic[T, K]):
634
615
  record_id (K): The unique identifier of the record to delete.
635
616
 
636
617
  Raises:
637
- 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.
638
620
 
639
621
  Example:
640
622
  ```python
@@ -648,17 +630,12 @@ class BaseRepository(Generic[T, K]):
648
630
  Note:
649
631
  This is a hard delete. Consider implementing soft delete if needed.
650
632
  """
651
- try:
633
+ async with self._errors("delete", "Failed to delete record", (RecordNotFoundError,)):
652
634
  delete_query = PsycopgHelper.build_delete_query(self.table_name, where_clause={self.primary_key: record_id})
653
635
  async with self.db_connection.cursor() as cur:
654
636
  await cur.execute(delete_query, [record_id])
655
637
  if cur.rowcount == 0:
656
638
  raise RecordNotFoundError(f"Record with id {record_id} not found")
657
- except Exception as e:
658
- logger.error(f"Error in delete: {e}")
659
- if isinstance(e, RecordNotFoundError):
660
- raise
661
- raise OperationError(f"Failed to delete record: {e!s}") from e
662
639
 
663
640
  async def exists(self, record_id: K) -> bool:
664
641
  """
@@ -671,7 +648,7 @@ class BaseRepository(Generic[T, K]):
671
648
  bool: True if the record exists, False otherwise.
672
649
 
673
650
  Raises:
674
- HTTPException: If the database query fails.
651
+ OperationError: If the database query fails.
675
652
 
676
653
  Example:
677
654
  ```python
@@ -684,10 +661,10 @@ class BaseRepository(Generic[T, K]):
684
661
  print("User exists")
685
662
  ```
686
663
  """
687
- 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
+ )
688
668
  async with self.db_connection.cursor() as cur:
689
- await cur.execute(f"SELECT 1 FROM {self.table_name} WHERE {self.primary_key} = %s", [record_id])
669
+ await cur.execute(query, [record_id])
690
670
  return bool(await cur.fetchone())
691
- except Exception as e:
692
- logger.error(f"Error in exists: {e}")
693
- 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