psycopg-toolkit 0.2.0__tar.gz → 0.2.2__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.
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/.gitignore +4 -0
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/PKG-INFO +49 -1
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/README.md +48 -0
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/pyproject.toml +5 -2
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/src/psycopg_toolkit/core/database.py +4 -5
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/src/psycopg_toolkit/repositories/base.py +58 -28
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/.vscode/settings.json +0 -0
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/LICENSE +0 -0
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/src/psycopg_toolkit/__init__.py +0 -0
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/src/psycopg_toolkit/core/__init__.py +0 -0
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/src/psycopg_toolkit/core/config.py +0 -0
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/src/psycopg_toolkit/core/factory.py +0 -0
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/src/psycopg_toolkit/core/transaction.py +0 -0
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/src/psycopg_toolkit/exceptions.py +0 -0
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/src/psycopg_toolkit/repositories/__init__.py +0 -0
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/src/psycopg_toolkit/utils/__init__.py +0 -0
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/src/psycopg_toolkit/utils/json_handler.py +0 -0
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/src/psycopg_toolkit/utils/psychopg_helper.py +0 -0
- {psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/src/psycopg_toolkit/utils/type_inspector.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: psycopg-toolkit
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
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
|
|
@@ -47,6 +47,8 @@ A robust PostgreSQL database toolkit providing enterprise-grade connection pooli
|
|
|
47
47
|
- Comprehensive transaction management with savepoint support
|
|
48
48
|
- Type-safe repository pattern with Pydantic model validation
|
|
49
49
|
- JSONB support with automatic field detection and psycopg JSON adapters
|
|
50
|
+
- PostgreSQL array field preservation (TEXT[], INTEGER[])
|
|
51
|
+
- Automatic date/timestamp conversion for Pydantic models
|
|
50
52
|
- SQL query builder with SQL injection protection
|
|
51
53
|
- Database schema and test data lifecycle management
|
|
52
54
|
- Automatic retry mechanism with exponential backoff
|
|
@@ -190,6 +192,52 @@ created_user = await repo.create(user)
|
|
|
190
192
|
retrieved_user = await repo.get_by_id(1)
|
|
191
193
|
```
|
|
192
194
|
|
|
195
|
+
### PostgreSQL Arrays and Date Fields
|
|
196
|
+
|
|
197
|
+
```python
|
|
198
|
+
from typing import List
|
|
199
|
+
from datetime import date
|
|
200
|
+
from pydantic import BaseModel
|
|
201
|
+
from psycopg_toolkit import BaseRepository
|
|
202
|
+
|
|
203
|
+
class User(BaseModel):
|
|
204
|
+
id: UUID
|
|
205
|
+
username: str
|
|
206
|
+
roles: List[str] # PostgreSQL TEXT[] array
|
|
207
|
+
permissions: List[str] # PostgreSQL TEXT[] array
|
|
208
|
+
metadata: Dict[str, Any] # JSONB field
|
|
209
|
+
birthdate: str # ISO date string (from DATE)
|
|
210
|
+
created_at: str # ISO datetime string (from TIMESTAMP)
|
|
211
|
+
updated_at: str # ISO datetime string (from TIMESTAMPTZ)
|
|
212
|
+
last_login: str | None # Optional timestamp field
|
|
213
|
+
|
|
214
|
+
class UserRepository(BaseRepository[User, UUID]):
|
|
215
|
+
def __init__(self, conn):
|
|
216
|
+
super().__init__(
|
|
217
|
+
db_connection=conn,
|
|
218
|
+
table_name="users",
|
|
219
|
+
model_class=User,
|
|
220
|
+
primary_key="id",
|
|
221
|
+
# Preserve PostgreSQL arrays instead of JSONB
|
|
222
|
+
array_fields={"roles", "permissions"},
|
|
223
|
+
# Auto-convert ALL date/timestamp fields to/from strings
|
|
224
|
+
date_fields={"birthdate", "created_at", "updated_at", "last_login"}
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
# PostgreSQL arrays are preserved, dates are auto-converted
|
|
228
|
+
user = User(
|
|
229
|
+
id=uuid4(),
|
|
230
|
+
username="john",
|
|
231
|
+
roles=["admin", "user"], # Stored as TEXT[]
|
|
232
|
+
permissions=["read", "write"], # Stored as TEXT[]
|
|
233
|
+
metadata={"dept": "IT"}, # Stored as JSONB
|
|
234
|
+
birthdate="1990-01-01", # Converts to/from PostgreSQL DATE
|
|
235
|
+
created_at="2024-01-01T12:00:00", # Converts to/from TIMESTAMP
|
|
236
|
+
updated_at="2024-01-01T12:00:00", # Converts to/from TIMESTAMPTZ
|
|
237
|
+
last_login=None # Nullable timestamp field
|
|
238
|
+
)
|
|
239
|
+
```
|
|
240
|
+
|
|
193
241
|
### Schema Management
|
|
194
242
|
|
|
195
243
|
```python
|
|
@@ -14,6 +14,8 @@ A robust PostgreSQL database toolkit providing enterprise-grade connection pooli
|
|
|
14
14
|
- Comprehensive transaction management with savepoint support
|
|
15
15
|
- Type-safe repository pattern with Pydantic model validation
|
|
16
16
|
- JSONB support with automatic field detection and psycopg JSON adapters
|
|
17
|
+
- PostgreSQL array field preservation (TEXT[], INTEGER[])
|
|
18
|
+
- Automatic date/timestamp conversion for Pydantic models
|
|
17
19
|
- SQL query builder with SQL injection protection
|
|
18
20
|
- Database schema and test data lifecycle management
|
|
19
21
|
- Automatic retry mechanism with exponential backoff
|
|
@@ -157,6 +159,52 @@ created_user = await repo.create(user)
|
|
|
157
159
|
retrieved_user = await repo.get_by_id(1)
|
|
158
160
|
```
|
|
159
161
|
|
|
162
|
+
### PostgreSQL Arrays and Date Fields
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
from typing import List
|
|
166
|
+
from datetime import date
|
|
167
|
+
from pydantic import BaseModel
|
|
168
|
+
from psycopg_toolkit import BaseRepository
|
|
169
|
+
|
|
170
|
+
class User(BaseModel):
|
|
171
|
+
id: UUID
|
|
172
|
+
username: str
|
|
173
|
+
roles: List[str] # PostgreSQL TEXT[] array
|
|
174
|
+
permissions: List[str] # PostgreSQL TEXT[] array
|
|
175
|
+
metadata: Dict[str, Any] # JSONB field
|
|
176
|
+
birthdate: str # ISO date string (from DATE)
|
|
177
|
+
created_at: str # ISO datetime string (from TIMESTAMP)
|
|
178
|
+
updated_at: str # ISO datetime string (from TIMESTAMPTZ)
|
|
179
|
+
last_login: str | None # Optional timestamp field
|
|
180
|
+
|
|
181
|
+
class UserRepository(BaseRepository[User, UUID]):
|
|
182
|
+
def __init__(self, conn):
|
|
183
|
+
super().__init__(
|
|
184
|
+
db_connection=conn,
|
|
185
|
+
table_name="users",
|
|
186
|
+
model_class=User,
|
|
187
|
+
primary_key="id",
|
|
188
|
+
# Preserve PostgreSQL arrays instead of JSONB
|
|
189
|
+
array_fields={"roles", "permissions"},
|
|
190
|
+
# Auto-convert ALL date/timestamp fields to/from strings
|
|
191
|
+
date_fields={"birthdate", "created_at", "updated_at", "last_login"}
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
# PostgreSQL arrays are preserved, dates are auto-converted
|
|
195
|
+
user = User(
|
|
196
|
+
id=uuid4(),
|
|
197
|
+
username="john",
|
|
198
|
+
roles=["admin", "user"], # Stored as TEXT[]
|
|
199
|
+
permissions=["read", "write"], # Stored as TEXT[]
|
|
200
|
+
metadata={"dept": "IT"}, # Stored as JSONB
|
|
201
|
+
birthdate="1990-01-01", # Converts to/from PostgreSQL DATE
|
|
202
|
+
created_at="2024-01-01T12:00:00", # Converts to/from TIMESTAMP
|
|
203
|
+
updated_at="2024-01-01T12:00:00", # Converts to/from TIMESTAMPTZ
|
|
204
|
+
last_login=None # Nullable timestamp field
|
|
205
|
+
)
|
|
206
|
+
```
|
|
207
|
+
|
|
160
208
|
### Schema Management
|
|
161
209
|
|
|
162
210
|
```python
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "psycopg-toolkit"
|
|
3
|
-
version = "0.2.
|
|
3
|
+
version = "0.2.2"
|
|
4
4
|
description = "A Python PostgreSQL database utility with connection pooling"
|
|
5
5
|
authors = [
|
|
6
6
|
{ name = "Ove Ranheim", email = "oranheim@gmail.com" }
|
|
@@ -37,7 +37,7 @@ test = [
|
|
|
37
37
|
"pytest>=8.3.0",
|
|
38
38
|
"pytest-asyncio>=0.25.2",
|
|
39
39
|
"pytest-cov>=6.0.0",
|
|
40
|
-
"testcontainers[
|
|
40
|
+
"testcontainers[postgres]>=4.12.0",
|
|
41
41
|
"psutil>=6.1.0", # For performance benchmarks
|
|
42
42
|
]
|
|
43
43
|
dev = [
|
|
@@ -173,6 +173,9 @@ extend-ignore = [
|
|
|
173
173
|
"S105", # Allow hardcoded secrets in tests
|
|
174
174
|
"T201", # Print found (allow print statements)
|
|
175
175
|
]
|
|
176
|
+
"src/psycopg_toolkit/repositories/base.py" = [
|
|
177
|
+
"C901", # _postprocess_data handles multiple concerns (date/JSON processing)
|
|
178
|
+
]
|
|
176
179
|
"examples/*" = [
|
|
177
180
|
"T201", # Allow print statements in examples
|
|
178
181
|
"T203", # Allow pprint in examples
|
|
@@ -6,7 +6,6 @@ from typing import TYPE_CHECKING
|
|
|
6
6
|
if TYPE_CHECKING:
|
|
7
7
|
from .transaction import TransactionManager
|
|
8
8
|
|
|
9
|
-
import psycopg
|
|
10
9
|
from psycopg import AsyncConnection
|
|
11
10
|
from psycopg.types import json
|
|
12
11
|
from psycopg_pool import AsyncConnectionPool
|
|
@@ -74,7 +73,7 @@ class Database:
|
|
|
74
73
|
logger.debug("JSON adapters disabled in settings")
|
|
75
74
|
|
|
76
75
|
@retry(stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=4, max=10))
|
|
77
|
-
def ping_postgres(self) -> bool:
|
|
76
|
+
async def ping_postgres(self) -> bool:
|
|
78
77
|
"""Test database connectivity with exponential backoff retry.
|
|
79
78
|
|
|
80
79
|
Returns:
|
|
@@ -85,8 +84,8 @@ class Database:
|
|
|
85
84
|
"""
|
|
86
85
|
try:
|
|
87
86
|
logger.info(f"Pinging PostgreSQL at {self._settings.host}")
|
|
88
|
-
conn =
|
|
89
|
-
conn.close()
|
|
87
|
+
conn = await AsyncConnection.connect(self._settings.get_connection_string(self._settings.connection_timeout))
|
|
88
|
+
await conn.close()
|
|
90
89
|
logger.info("Successfully connected to PostgreSQL")
|
|
91
90
|
return True
|
|
92
91
|
except Exception as e:
|
|
@@ -104,7 +103,7 @@ class Database:
|
|
|
104
103
|
DatabasePoolError: If pool creation or initialization fails
|
|
105
104
|
"""
|
|
106
105
|
try:
|
|
107
|
-
if not self.ping_postgres():
|
|
106
|
+
if not await self.ping_postgres():
|
|
108
107
|
raise DatabaseConnectionError("Failed to ping database")
|
|
109
108
|
|
|
110
109
|
logger.info("Initializing connection pool")
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import logging
|
|
2
|
+
from datetime import date, datetime
|
|
2
3
|
from typing import Any, Generic, TypeVar
|
|
3
4
|
|
|
4
5
|
from psycopg import AsyncConnection
|
|
@@ -71,6 +72,8 @@ class BaseRepository(Generic[T, K]):
|
|
|
71
72
|
json_fields: set[str] | None = None,
|
|
72
73
|
auto_detect_json: bool = True,
|
|
73
74
|
strict_json_processing: bool = False,
|
|
75
|
+
date_fields: set[str] | None = None,
|
|
76
|
+
array_fields: set[str] | None = None,
|
|
74
77
|
):
|
|
75
78
|
"""
|
|
76
79
|
Initialize the base repository.
|
|
@@ -86,6 +89,12 @@ class BaseRepository(Generic[T, K]):
|
|
|
86
89
|
Pydantic type hints. Ignored if json_fields is provided. Defaults to True.
|
|
87
90
|
strict_json_processing (bool, optional): Whether to raise exceptions for JSON
|
|
88
91
|
deserialization errors instead of logging warnings. Defaults to False.
|
|
92
|
+
date_fields (Optional[Set[str]], optional): Set of field names that contain
|
|
93
|
+
date/datetime values needing conversion to ISO strings. Include ALL date,
|
|
94
|
+
timestamp, and timestamptz fields from your model. Defaults to None.
|
|
95
|
+
array_fields (Optional[Set[str]], optional): Set of field names that should be
|
|
96
|
+
treated as PostgreSQL arrays rather than JSONB. Only relevant when
|
|
97
|
+
auto_detect_json=False. Defaults to None.
|
|
89
98
|
|
|
90
99
|
Note:
|
|
91
100
|
The model_class should be a Pydantic model that matches the database schema.
|
|
@@ -107,8 +116,11 @@ class BaseRepository(Generic[T, K]):
|
|
|
107
116
|
self._json_fields = json_fields
|
|
108
117
|
logger.debug(f"Using explicit JSON fields for {table_name}: {json_fields}")
|
|
109
118
|
elif auto_detect_json:
|
|
110
|
-
|
|
111
|
-
|
|
119
|
+
detected_fields = TypeInspector.detect_json_fields(model_class)
|
|
120
|
+
# Exclude array fields from JSON fields
|
|
121
|
+
self._json_fields = detected_fields - (array_fields or set())
|
|
122
|
+
logger.debug(f"Auto-detected JSON fields for {table_name}: {detected_fields}")
|
|
123
|
+
logger.debug(f"JSON fields after excluding arrays: {self._json_fields}")
|
|
112
124
|
else:
|
|
113
125
|
self._json_fields = set()
|
|
114
126
|
logger.debug(f"JSON field processing disabled for {table_name}")
|
|
@@ -116,6 +128,8 @@ class BaseRepository(Generic[T, K]):
|
|
|
116
128
|
# Cache for performance and configuration
|
|
117
129
|
self._auto_detect_json = auto_detect_json
|
|
118
130
|
self._strict_json_processing = strict_json_processing
|
|
131
|
+
self._date_fields = date_fields or set()
|
|
132
|
+
self._array_fields = array_fields or set()
|
|
119
133
|
|
|
120
134
|
# Check if psycopg JSON adapters are enabled
|
|
121
135
|
self._use_psycopg_adapters = self._check_psycopg_adapters()
|
|
@@ -126,13 +140,9 @@ class BaseRepository(Generic[T, K]):
|
|
|
126
140
|
Returns:
|
|
127
141
|
bool: True if psycopg JSON adapters are enabled, False otherwise.
|
|
128
142
|
"""
|
|
129
|
-
#
|
|
130
|
-
#
|
|
131
|
-
|
|
132
|
-
#
|
|
133
|
-
# If explicit json_fields are provided, we use custom processing
|
|
134
|
-
# to have fine-grained control over which fields are processed
|
|
135
|
-
return not self._auto_detect_json and not self._json_fields
|
|
143
|
+
# Never use psycopg adapters - this causes issues with arrays
|
|
144
|
+
# When auto_detect_json=False, users expect NO JSON processing
|
|
145
|
+
return False
|
|
136
146
|
|
|
137
147
|
@property
|
|
138
148
|
def json_fields(self) -> set[str]:
|
|
@@ -143,7 +153,7 @@ class BaseRepository(Generic[T, K]):
|
|
|
143
153
|
"""
|
|
144
154
|
return self._json_fields.copy()
|
|
145
155
|
|
|
146
|
-
def _preprocess_data(self, data: dict[str, Any]) -> dict[str, Any]:
|
|
156
|
+
def _preprocess_data(self, data: dict[str, Any]) -> dict[str, Any]:
|
|
147
157
|
"""Preprocess data by handling JSON fields according to processing mode.
|
|
148
158
|
|
|
149
159
|
In psycopg adapter mode, JSON fields are wrapped with Json() adapter.
|
|
@@ -170,21 +180,33 @@ class BaseRepository(Generic[T, K]):
|
|
|
170
180
|
"""
|
|
171
181
|
processed_data = data.copy()
|
|
172
182
|
|
|
173
|
-
#
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
183
|
+
# Convert date fields to appropriate format if needed
|
|
184
|
+
for field_name in self._date_fields:
|
|
185
|
+
if field_name in data and data[field_name] is not None:
|
|
186
|
+
value = data[field_name]
|
|
187
|
+
if isinstance(value, date | datetime):
|
|
188
|
+
# Convert date/datetime to ISO string for storage
|
|
189
|
+
processed_data[field_name] = value.isoformat()
|
|
190
|
+
logger.debug(f"Converted date field '{field_name}' from {type(value).__name__} to ISO string for {self.table_name}")
|
|
180
191
|
|
|
181
192
|
# For custom JSON processing, determine which fields need processing
|
|
182
193
|
json_fields = self._json_fields
|
|
183
|
-
if not json_fields and self._auto_detect_json:
|
|
184
|
-
json_fields = TypeInspector.detect_json_fields(self.model_class)
|
|
185
194
|
|
|
195
|
+
# If no JSON fields should be processed
|
|
186
196
|
if not json_fields:
|
|
187
|
-
|
|
197
|
+
# When auto_detect_json is False, wrap dict/list values with Json()
|
|
198
|
+
# unless they are explicitly marked as array fields
|
|
199
|
+
if not self._auto_detect_json:
|
|
200
|
+
for field_name, value in data.items():
|
|
201
|
+
if value is not None and isinstance(value, dict | list):
|
|
202
|
+
# Skip array fields - they should remain as PostgreSQL arrays
|
|
203
|
+
if field_name in self._array_fields:
|
|
204
|
+
logger.debug(f"Preserving array field '{field_name}' for PostgreSQL array handling")
|
|
205
|
+
continue
|
|
206
|
+
# Wrap other dict/list fields with Json()
|
|
207
|
+
processed_data[field_name] = Json(value)
|
|
208
|
+
logger.debug(f"Wrapped field '{field_name}' with Json() for PostgreSQL JSONB handling")
|
|
209
|
+
return processed_data
|
|
188
210
|
|
|
189
211
|
# Custom JSON processing mode - serialize to strings
|
|
190
212
|
for field_name in json_fields:
|
|
@@ -251,17 +273,25 @@ class BaseRepository(Generic[T, K]):
|
|
|
251
273
|
# processed["metadata"] is now {"key": "value"}
|
|
252
274
|
```
|
|
253
275
|
"""
|
|
254
|
-
#
|
|
255
|
-
|
|
256
|
-
return data.copy()
|
|
257
|
-
|
|
258
|
-
# Original logic for custom JSON processing
|
|
259
|
-
if not self._json_fields:
|
|
260
|
-
logger.debug(f"No JSON fields configured for {self.table_name}, skipping postprocessing")
|
|
261
|
-
return data.copy()
|
|
276
|
+
# Check which fields should be processed
|
|
277
|
+
json_fields = self._json_fields
|
|
262
278
|
|
|
263
279
|
processed_data = data.copy()
|
|
264
280
|
|
|
281
|
+
# Convert date fields from database format to string if needed
|
|
282
|
+
for field_name in self._date_fields:
|
|
283
|
+
if field_name in processed_data and processed_data[field_name] is not None:
|
|
284
|
+
value = processed_data[field_name]
|
|
285
|
+
if isinstance(value, date | datetime):
|
|
286
|
+
# Convert date/datetime to ISO string for Pydantic
|
|
287
|
+
processed_data[field_name] = value.isoformat()
|
|
288
|
+
logger.debug(f"Converted date field '{field_name}' from {type(value).__name__} to ISO string for {self.table_name}")
|
|
289
|
+
|
|
290
|
+
# If no JSON fields should be processed, return the processed data
|
|
291
|
+
if not json_fields:
|
|
292
|
+
logger.debug(f"No JSON fields configured for {self.table_name}, skipping JSON postprocessing")
|
|
293
|
+
return processed_data
|
|
294
|
+
|
|
265
295
|
for field_name in self._json_fields:
|
|
266
296
|
if field_name in processed_data and processed_data[field_name] is not None:
|
|
267
297
|
try:
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/src/psycopg_toolkit/repositories/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{psycopg_toolkit-0.2.0 → psycopg_toolkit-0.2.2}/src/psycopg_toolkit/utils/psychopg_helper.py
RENAMED
|
File without changes
|
|
File without changes
|