psycopg-toolkit 0.1.0__py3-none-any.whl
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/__init__.py +30 -0
- psycopg_toolkit/core/__init__.py +9 -0
- psycopg_toolkit/core/config.py +28 -0
- psycopg_toolkit/core/database.py +180 -0
- psycopg_toolkit/core/transaction.py +41 -0
- psycopg_toolkit/exceptions.py +48 -0
- psycopg_toolkit/repositories/__init__.py +5 -0
- psycopg_toolkit/repositories/base.py +374 -0
- psycopg_toolkit/utils/__init__.py +5 -0
- psycopg_toolkit/utils/psychopg_helper.py +197 -0
- psycopg_toolkit-0.1.0.dist-info/LICENSE +21 -0
- psycopg_toolkit-0.1.0.dist-info/METADATA +216 -0
- psycopg_toolkit-0.1.0.dist-info/RECORD +14 -0
- psycopg_toolkit-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from .core.config import DatabaseSettings
|
|
2
|
+
from .core.database import Database
|
|
3
|
+
from .core.transaction import TransactionManager
|
|
4
|
+
from .exceptions import (
|
|
5
|
+
PsycoDBException,
|
|
6
|
+
DatabaseConnectionError,
|
|
7
|
+
DatabasePoolError,
|
|
8
|
+
DatabaseNotAvailable,
|
|
9
|
+
RepositoryError,
|
|
10
|
+
RecordNotFoundError,
|
|
11
|
+
InvalidDataError,
|
|
12
|
+
OperationError
|
|
13
|
+
)
|
|
14
|
+
from .repositories.base import BaseRepository
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"Database",
|
|
18
|
+
"DatabaseSettings",
|
|
19
|
+
"TransactionManager",
|
|
20
|
+
"BaseRepository",
|
|
21
|
+
"PsycoDBException",
|
|
22
|
+
"DatabaseConnectionError",
|
|
23
|
+
"DatabasePoolError",
|
|
24
|
+
"DatabaseNotAvailable",
|
|
25
|
+
"RepositoryError",
|
|
26
|
+
"RecordNotFoundError",
|
|
27
|
+
"InvalidDataError",
|
|
28
|
+
"OperationError",
|
|
29
|
+
|
|
30
|
+
]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import Optional
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
@dataclass
|
|
6
|
+
class DatabaseSettings:
|
|
7
|
+
"""Database connection settings."""
|
|
8
|
+
host: str
|
|
9
|
+
port: int
|
|
10
|
+
dbname: str
|
|
11
|
+
user: str
|
|
12
|
+
password: str
|
|
13
|
+
min_pool_size: int = 5
|
|
14
|
+
max_pool_size: int = 20
|
|
15
|
+
pool_timeout: int = 30
|
|
16
|
+
connection_timeout: float = 5.0 # seconds
|
|
17
|
+
statement_timeout: Optional[float] = None
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def connection_string(self) -> str:
|
|
21
|
+
"""Generate connection string from settings."""
|
|
22
|
+
return (
|
|
23
|
+
f"host={self.host} "
|
|
24
|
+
f"port={self.port} "
|
|
25
|
+
f"dbname={self.dbname} "
|
|
26
|
+
f"user={self.user} "
|
|
27
|
+
f"password={self.password}"
|
|
28
|
+
)
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from asyncio import Lock
|
|
3
|
+
from contextlib import asynccontextmanager
|
|
4
|
+
from typing import AsyncGenerator, Callable, List, Optional, Awaitable
|
|
5
|
+
|
|
6
|
+
import psycopg
|
|
7
|
+
from psycopg_pool import AsyncConnectionPool
|
|
8
|
+
from tenacity import retry, stop_after_attempt, wait_exponential
|
|
9
|
+
|
|
10
|
+
from .config import DatabaseSettings
|
|
11
|
+
from .transaction import TransactionManager
|
|
12
|
+
from ..exceptions import DatabaseConnectionError, DatabaseNotAvailable, DatabasePoolError
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Database:
|
|
18
|
+
"""
|
|
19
|
+
Database management class that handles connection pooling and database operations.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, settings: DatabaseSettings):
|
|
23
|
+
self._pool: Optional[AsyncConnectionPool] = None
|
|
24
|
+
self._settings = settings
|
|
25
|
+
self._init_callbacks: List[Callable[[AsyncConnectionPool], Awaitable[None]]] = []
|
|
26
|
+
self._transaction_manager: Optional[TransactionManager] = None
|
|
27
|
+
self._pool_lock = Lock() # Add thread lock
|
|
28
|
+
self._callbacks_lock = Lock() # Separate lock for callbacks
|
|
29
|
+
self._transaction_manager_lock = Lock()
|
|
30
|
+
|
|
31
|
+
async def get_transaction_manager(self) -> TransactionManager:
|
|
32
|
+
"""
|
|
33
|
+
Get the transaction manager instance.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
TransactionManager: Instance for managing database transactions
|
|
37
|
+
"""
|
|
38
|
+
async with self._transaction_manager_lock:
|
|
39
|
+
if self._transaction_manager is None:
|
|
40
|
+
self._transaction_manager = TransactionManager(self)
|
|
41
|
+
return self._transaction_manager
|
|
42
|
+
|
|
43
|
+
async def register_init_callback(self, callback: Callable[[AsyncConnectionPool], Awaitable[None]]) -> None:
|
|
44
|
+
"""
|
|
45
|
+
Register a callback to be executed after pool initialization.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
callback: Async function that takes a pool instance and performs initialization
|
|
49
|
+
"""
|
|
50
|
+
async with self._callbacks_lock:
|
|
51
|
+
self._init_callbacks.append(callback)
|
|
52
|
+
|
|
53
|
+
@retry(
|
|
54
|
+
stop=stop_after_attempt(5),
|
|
55
|
+
wait=wait_exponential(multiplier=1, min=4, max=10)
|
|
56
|
+
)
|
|
57
|
+
def ping_postgres(self) -> bool:
|
|
58
|
+
"""
|
|
59
|
+
Ping the PostgreSQL database to check if it's up and reachable.
|
|
60
|
+
|
|
61
|
+
Raises:
|
|
62
|
+
DatabaseConnectionError: If connection fails
|
|
63
|
+
"""
|
|
64
|
+
try:
|
|
65
|
+
logger.info(f"Pinging PostgreSQL at host: {self._settings.host}, "
|
|
66
|
+
f"dbname: {self._settings.dbname}, "
|
|
67
|
+
f"user: {self._settings.user}")
|
|
68
|
+
|
|
69
|
+
conn = psycopg.connect(self._settings.connection_string)
|
|
70
|
+
conn.close()
|
|
71
|
+
logger.info("Successfully connected to PostgreSQL.")
|
|
72
|
+
return True
|
|
73
|
+
except Exception as e:
|
|
74
|
+
error_msg = f"Could not connect to PostgreSQL"
|
|
75
|
+
logger.error(f"Error: {error_msg}. Details: {e}")
|
|
76
|
+
raise DatabaseConnectionError(error_msg, original_error=e)
|
|
77
|
+
|
|
78
|
+
async def create_pool(self) -> Optional[AsyncConnectionPool]:
|
|
79
|
+
"""
|
|
80
|
+
Create a database connection pool if PostgreSQL is reachable.
|
|
81
|
+
|
|
82
|
+
Raises:
|
|
83
|
+
DatabasePoolError: If pool creation fails
|
|
84
|
+
"""
|
|
85
|
+
try:
|
|
86
|
+
self.ping_postgres()
|
|
87
|
+
logger.info("Initializing connection pool to PostgreSQL.")
|
|
88
|
+
|
|
89
|
+
pool = AsyncConnectionPool(
|
|
90
|
+
conninfo=self._settings.connection_string,
|
|
91
|
+
min_size=self._settings.min_pool_size,
|
|
92
|
+
max_size=self._settings.max_pool_size,
|
|
93
|
+
timeout=self._settings.pool_timeout,
|
|
94
|
+
open=False
|
|
95
|
+
)
|
|
96
|
+
await pool.open()
|
|
97
|
+
self._pool = pool
|
|
98
|
+
return pool
|
|
99
|
+
except Exception as e:
|
|
100
|
+
error_msg = "Could not create connection pool to PostgreSQL"
|
|
101
|
+
logger.error(f"Error: {error_msg}. Details: {e}")
|
|
102
|
+
raise DatabasePoolError(error_msg)
|
|
103
|
+
|
|
104
|
+
async def get_pool(self) -> AsyncConnectionPool:
|
|
105
|
+
"""
|
|
106
|
+
Get existing pool or create new one if none exists.
|
|
107
|
+
|
|
108
|
+
Raises:
|
|
109
|
+
DatabaseNotAvailable: If database is not available
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
if self._pool is not None:
|
|
113
|
+
return self._pool
|
|
114
|
+
|
|
115
|
+
async with self._pool_lock:
|
|
116
|
+
if self._pool is not None:
|
|
117
|
+
return self._pool
|
|
118
|
+
|
|
119
|
+
try:
|
|
120
|
+
self._pool = await self.create_pool()
|
|
121
|
+
except Exception as e:
|
|
122
|
+
raise DatabaseNotAvailable("Database is not available") from e
|
|
123
|
+
return self._pool
|
|
124
|
+
|
|
125
|
+
@asynccontextmanager
|
|
126
|
+
async def connection(self) -> AsyncGenerator[AsyncConnectionPool, None]:
|
|
127
|
+
"""
|
|
128
|
+
Get a database connection from the pool.
|
|
129
|
+
"""
|
|
130
|
+
pool = await self.get_pool()
|
|
131
|
+
async with pool.connection() as conn:
|
|
132
|
+
yield conn
|
|
133
|
+
|
|
134
|
+
async def init_db(self) -> None:
|
|
135
|
+
"""
|
|
136
|
+
Initialize the database pool and execute registered callbacks.
|
|
137
|
+
"""
|
|
138
|
+
try:
|
|
139
|
+
pool = await self.get_pool()
|
|
140
|
+
async with pool.connection():
|
|
141
|
+
logger.info("Database pool initialized successfully.")
|
|
142
|
+
|
|
143
|
+
# Execute registered initialization callbacks
|
|
144
|
+
for callback in self._init_callbacks:
|
|
145
|
+
await callback(pool)
|
|
146
|
+
|
|
147
|
+
except Exception as e:
|
|
148
|
+
logger.error(f"Failed to initialize database: {e}")
|
|
149
|
+
raise
|
|
150
|
+
|
|
151
|
+
async def cleanup(self) -> None:
|
|
152
|
+
"""
|
|
153
|
+
Cleanup database resources on shutdown.
|
|
154
|
+
"""
|
|
155
|
+
async with self._pool_lock:
|
|
156
|
+
if self._pool is not None:
|
|
157
|
+
logger.info("Closing database connection pool...")
|
|
158
|
+
try:
|
|
159
|
+
await self._pool.close()
|
|
160
|
+
logger.info("Database connection pool closed successfully.")
|
|
161
|
+
except Exception as e:
|
|
162
|
+
logger.error(f"Error closing database pool: {e}")
|
|
163
|
+
raise DatabasePoolError("Failed to close database pool") from e
|
|
164
|
+
finally:
|
|
165
|
+
self._pool = None
|
|
166
|
+
|
|
167
|
+
def is_pool_active(self) -> bool:
|
|
168
|
+
return self._pool is not None and not self._pool.closed
|
|
169
|
+
|
|
170
|
+
async def check_pool_health(self) -> bool:
|
|
171
|
+
try:
|
|
172
|
+
pool = await self.get_pool()
|
|
173
|
+
async with pool.connection() as conn:
|
|
174
|
+
async with conn.cursor() as cur:
|
|
175
|
+
await cur.execute("SELECT 1")
|
|
176
|
+
result = await cur.fetchone()
|
|
177
|
+
return result is not None and result[0] == 1
|
|
178
|
+
except Exception as e:
|
|
179
|
+
logger.error(f"Pool health check failed: {e}")
|
|
180
|
+
return False
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from contextlib import asynccontextmanager
|
|
3
|
+
from typing import AsyncGenerator
|
|
4
|
+
|
|
5
|
+
from psycopg import AsyncConnection
|
|
6
|
+
|
|
7
|
+
logger = logging.getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TransactionManager:
|
|
11
|
+
"""
|
|
12
|
+
Manages database transactions with automatic rollback on exception.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(self, database: 'Database'): # type: ignore
|
|
16
|
+
self._database = database
|
|
17
|
+
|
|
18
|
+
@asynccontextmanager
|
|
19
|
+
async def transaction(self) -> AsyncGenerator[AsyncConnection, None]:
|
|
20
|
+
"""
|
|
21
|
+
Context manager for handling database transactions with automatic
|
|
22
|
+
rollback on exception.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
AsyncGenerator[AsyncConnection, None]: Database connection with active transaction
|
|
26
|
+
|
|
27
|
+
Raises:
|
|
28
|
+
DatabaseNotAvailable: If database is not available
|
|
29
|
+
DatabaseConnectionError: If connection fails
|
|
30
|
+
DatabasePoolError: If pool operations fail
|
|
31
|
+
"""
|
|
32
|
+
try:
|
|
33
|
+
pool = await self._database.get_pool()
|
|
34
|
+
async with pool.connection() as conn:
|
|
35
|
+
async with conn.transaction():
|
|
36
|
+
yield conn
|
|
37
|
+
# Transaction is automatically committed if no exception occurs
|
|
38
|
+
except Exception as e:
|
|
39
|
+
# Transaction is automatically rolled back on exception
|
|
40
|
+
logger.error(f"Transaction failed: {e}")
|
|
41
|
+
raise
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
# Database exceptions
|
|
5
|
+
|
|
6
|
+
class PsycoDBException(Exception):
|
|
7
|
+
"""Base exception for all psycopg-toolkit exceptions."""
|
|
8
|
+
pass
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class DatabaseConnectionError(PsycoDBException):
|
|
12
|
+
"""Raised when database connection fails."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, message: str, original_error: Optional[Exception] = None):
|
|
15
|
+
self.original_error = original_error
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class DatabasePoolError(PsycoDBException):
|
|
20
|
+
"""Raised when pool operations fail."""
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class DatabaseNotAvailable(PsycoDBException):
|
|
25
|
+
"""Raised when database is not available."""
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# Repository exceptions
|
|
30
|
+
|
|
31
|
+
class RepositoryError(PsycoDBException):
|
|
32
|
+
"""Base exception for repository-related errors."""
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class RecordNotFoundError(RepositoryError):
|
|
37
|
+
"""Raised when a requested record is not found."""
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class InvalidDataError(RepositoryError):
|
|
42
|
+
"""Raised when data validation fails."""
|
|
43
|
+
pass
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class OperationError(RepositoryError):
|
|
47
|
+
"""Raised when a repository operation fails."""
|
|
48
|
+
pass
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Generic base repository module for database operations.
|
|
3
|
+
|
|
4
|
+
This module provides a generic base repository class that can be used to implement
|
|
5
|
+
the repository pattern for any database table. It uses generics to ensure type safety
|
|
6
|
+
and provides common CRUD (Create, Read, Update, Delete) operations.
|
|
7
|
+
|
|
8
|
+
The BaseRepository class is designed to work with PostgreSQL databases using psycopg3,
|
|
9
|
+
and expects Pydantic models for data validation and serialization.
|
|
10
|
+
|
|
11
|
+
Example:
|
|
12
|
+
```python
|
|
13
|
+
class UserModel(BaseModel):
|
|
14
|
+
id: UUID
|
|
15
|
+
name: str
|
|
16
|
+
email: str
|
|
17
|
+
|
|
18
|
+
class UserRepository(BaseRepository[UserModel]):
|
|
19
|
+
def __init__(self, db_connection: AsyncConnection):
|
|
20
|
+
super().__init__(
|
|
21
|
+
db_connection=db_connection,
|
|
22
|
+
table_name="users",
|
|
23
|
+
model_class=UserModel,
|
|
24
|
+
primary_key="id"
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
# Usage
|
|
28
|
+
user_repo = UserRepository(db_connection)
|
|
29
|
+
user = await user_repo.get_by_id(user_id)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Attributes:
|
|
33
|
+
T: Generic type variable representing the model type this repository handles
|
|
34
|
+
logger: Logger instance for the module
|
|
35
|
+
|
|
36
|
+
Dependencies:
|
|
37
|
+
- psycopg: For PostgreSQL database operations
|
|
38
|
+
- pydantic: For data validation and serialization
|
|
39
|
+
- fastapi: For HTTP exception handling
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
import logging
|
|
43
|
+
from typing import TypeVar, Generic, List, Optional, Dict, Any
|
|
44
|
+
from uuid import UUID
|
|
45
|
+
|
|
46
|
+
from psycopg import AsyncConnection
|
|
47
|
+
from psycopg.rows import dict_row
|
|
48
|
+
from psycopg.sql import SQL
|
|
49
|
+
|
|
50
|
+
from ..exceptions import (
|
|
51
|
+
RecordNotFoundError,
|
|
52
|
+
OperationError
|
|
53
|
+
)
|
|
54
|
+
from ..utils import PsycopgHelper
|
|
55
|
+
|
|
56
|
+
# Generic type variable for models
|
|
57
|
+
T = TypeVar('T')
|
|
58
|
+
|
|
59
|
+
logger = logging.getLogger(__name__)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class BaseRepository(Generic[T]):
|
|
63
|
+
"""
|
|
64
|
+
Generic base repository implementing common database operations.
|
|
65
|
+
|
|
66
|
+
This class provides a foundation for implementing the repository pattern with
|
|
67
|
+
PostgreSQL databases. It includes basic CRUD operations and uses generics to
|
|
68
|
+
ensure type safety with different model types.
|
|
69
|
+
|
|
70
|
+
Type Parameters:
|
|
71
|
+
T: The model type this repository handles. Must be a Pydantic model.
|
|
72
|
+
|
|
73
|
+
Attributes:
|
|
74
|
+
db_connection (AsyncConnection): Active database connection.
|
|
75
|
+
table_name (str): Name of the database table.
|
|
76
|
+
model_class (type[T]): The Pydantic model class for type T.
|
|
77
|
+
primary_key (str): Name of the primary key column in the table.
|
|
78
|
+
|
|
79
|
+
Example:
|
|
80
|
+
```python
|
|
81
|
+
class DocumentRepository(BaseRepository[Document]):
|
|
82
|
+
def __init__(self, db_connection: AsyncConnection):
|
|
83
|
+
super().__init__(
|
|
84
|
+
db_connection=db_connection,
|
|
85
|
+
table_name="documents",
|
|
86
|
+
model_class=Document,
|
|
87
|
+
primary_key="document_id"
|
|
88
|
+
)
|
|
89
|
+
```
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
def __init__(
|
|
93
|
+
self,
|
|
94
|
+
db_connection: AsyncConnection,
|
|
95
|
+
table_name: str,
|
|
96
|
+
model_class: type[T],
|
|
97
|
+
primary_key: str = "id"
|
|
98
|
+
):
|
|
99
|
+
"""
|
|
100
|
+
Initialize the base repository.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
db_connection (AsyncConnection): Active database connection to use for operations.
|
|
104
|
+
table_name (str): Name of the database table being accessed.
|
|
105
|
+
model_class (type[T]): The Pydantic model class used for type T.
|
|
106
|
+
primary_key (str, optional): Name of the primary key column. Defaults to "id".
|
|
107
|
+
|
|
108
|
+
Note:
|
|
109
|
+
The model_class should be a Pydantic model that matches the database schema.
|
|
110
|
+
The primary_key should match the actual primary key column name in the database.
|
|
111
|
+
"""
|
|
112
|
+
self.db_connection = db_connection
|
|
113
|
+
self.table_name = table_name
|
|
114
|
+
self.model_class = model_class
|
|
115
|
+
self.primary_key = primary_key
|
|
116
|
+
|
|
117
|
+
async def create(self, item: T) -> T:
|
|
118
|
+
"""
|
|
119
|
+
Create a new record in the database.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
item (T): The model instance to create in the database.
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
T: The created model instance with any database-generated fields.
|
|
126
|
+
|
|
127
|
+
Raises:
|
|
128
|
+
HTTPException: If the creation fails or database error occurs.
|
|
129
|
+
ValueError: If the database operation doesn't return a result.
|
|
130
|
+
|
|
131
|
+
Example:
|
|
132
|
+
```python
|
|
133
|
+
new_item = ItemModel(name="test", description="test item")
|
|
134
|
+
created_item = await repo.create(new_item)
|
|
135
|
+
```
|
|
136
|
+
"""
|
|
137
|
+
try:
|
|
138
|
+
data = item.model_dump()
|
|
139
|
+
insert_query = PsycopgHelper.build_insert_query(self.table_name, data)
|
|
140
|
+
|
|
141
|
+
async with self.db_connection.cursor(row_factory=dict_row) as cur:
|
|
142
|
+
await cur.execute(insert_query + SQL(" RETURNING *"), list(data.values()))
|
|
143
|
+
result = await cur.fetchone()
|
|
144
|
+
if not result:
|
|
145
|
+
raise OperationError(f"Failed to create {self.table_name} record")
|
|
146
|
+
return self.model_class(**result)
|
|
147
|
+
except Exception as e:
|
|
148
|
+
logger.error(f"Error in create: {e}")
|
|
149
|
+
if isinstance(e, OperationError):
|
|
150
|
+
raise
|
|
151
|
+
raise OperationError(f"Failed to create record: {str(e)}") from e
|
|
152
|
+
|
|
153
|
+
async def create_bulk(self, items: List[T], batch_size: int = 100) -> List[T]:
|
|
154
|
+
"""
|
|
155
|
+
Create multiple records in batches.
|
|
156
|
+
|
|
157
|
+
Args:
|
|
158
|
+
items (List[T]): List of model instances to create.
|
|
159
|
+
batch_size (int, optional): Number of records per batch. Defaults to 100.
|
|
160
|
+
|
|
161
|
+
Returns:
|
|
162
|
+
List[T]: List of created model instances with database-generated fields.
|
|
163
|
+
|
|
164
|
+
Raises:
|
|
165
|
+
HTTPException: If the bulk creation fails or database error occurs.
|
|
166
|
+
|
|
167
|
+
Example:
|
|
168
|
+
```python
|
|
169
|
+
items = [ItemModel(name=f"item_{i}") for i in range(500)]
|
|
170
|
+
created_items = await repo.create_bulk(items, batch_size=50)
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
Note:
|
|
174
|
+
Uses database transactions to ensure all-or-nothing batch operations.
|
|
175
|
+
Large lists are automatically processed in batches for better performance.
|
|
176
|
+
"""
|
|
177
|
+
all_results = []
|
|
178
|
+
try:
|
|
179
|
+
async with self.db_connection.transaction():
|
|
180
|
+
for i in range(0, len(items), batch_size):
|
|
181
|
+
batch = items[i:i + batch_size]
|
|
182
|
+
data_list = [item.model_dump() for item in batch]
|
|
183
|
+
if not data_list:
|
|
184
|
+
continue
|
|
185
|
+
|
|
186
|
+
batch_insert_query = PsycopgHelper.build_insert_query(
|
|
187
|
+
self.table_name,
|
|
188
|
+
data_list[0],
|
|
189
|
+
batch_size=len(data_list)
|
|
190
|
+
)
|
|
191
|
+
batch_values = [val for data in data_list for val in data.values()]
|
|
192
|
+
|
|
193
|
+
async with self.db_connection.cursor(row_factory=dict_row) as cur:
|
|
194
|
+
full_query = batch_insert_query + SQL(" RETURNING *")
|
|
195
|
+
await cur.execute(full_query, batch_values)
|
|
196
|
+
results = await cur.fetchall()
|
|
197
|
+
all_results.extend([self.model_class(**row) for row in results])
|
|
198
|
+
return all_results
|
|
199
|
+
except Exception as e:
|
|
200
|
+
logger.error(f"Error in create_bulk: {e}")
|
|
201
|
+
raise OperationError(f"Failed to create records in bulk: {str(e)}") from e
|
|
202
|
+
|
|
203
|
+
async def get_by_id(self, record_id: UUID) -> Optional[T]:
|
|
204
|
+
"""
|
|
205
|
+
Retrieve a record by its ID.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
record_id (UUID): The unique identifier of the record.
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
Optional[T]: The found model instance or None if not found.
|
|
212
|
+
|
|
213
|
+
Raises:
|
|
214
|
+
HTTPException: If the database query fails.
|
|
215
|
+
|
|
216
|
+
Example:
|
|
217
|
+
```python
|
|
218
|
+
item = await repo.get_by_id(uuid.UUID('...'))
|
|
219
|
+
if item:
|
|
220
|
+
print(f"Found item: {item.name}")
|
|
221
|
+
```
|
|
222
|
+
"""
|
|
223
|
+
try:
|
|
224
|
+
select_query = PsycopgHelper.build_select_query(
|
|
225
|
+
self.table_name,
|
|
226
|
+
where_clause={self.primary_key: record_id}
|
|
227
|
+
)
|
|
228
|
+
async with self.db_connection.cursor(row_factory=dict_row) as cur:
|
|
229
|
+
await cur.execute(select_query, [record_id])
|
|
230
|
+
result = await cur.fetchone()
|
|
231
|
+
if not result:
|
|
232
|
+
raise RecordNotFoundError(f"Record with id {record_id} not found")
|
|
233
|
+
return self.model_class(**result)
|
|
234
|
+
except Exception as e:
|
|
235
|
+
logger.error(f"Error in get_by_id: {e}")
|
|
236
|
+
if isinstance(e, RecordNotFoundError):
|
|
237
|
+
raise
|
|
238
|
+
raise OperationError(f"Failed to get record: {str(e)}") from e
|
|
239
|
+
|
|
240
|
+
async def get_all(self) -> List[T]:
|
|
241
|
+
"""
|
|
242
|
+
Retrieve all records from the table.
|
|
243
|
+
|
|
244
|
+
Returns:
|
|
245
|
+
List[T]: List of all model instances in the table.
|
|
246
|
+
|
|
247
|
+
Raises:
|
|
248
|
+
HTTPException: If the database query fails.
|
|
249
|
+
|
|
250
|
+
Example:
|
|
251
|
+
```python
|
|
252
|
+
all_items = await repo.get_all()
|
|
253
|
+
for item in all_items:
|
|
254
|
+
print(f"Item: {item.name}")
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
Warning:
|
|
258
|
+
Use with caution on large tables as it loads all records into memory.
|
|
259
|
+
"""
|
|
260
|
+
try:
|
|
261
|
+
async with self.db_connection.cursor(row_factory=dict_row) as cur:
|
|
262
|
+
await cur.execute(f"SELECT * FROM {self.table_name}")
|
|
263
|
+
rows = await cur.fetchall()
|
|
264
|
+
return [self.model_class(**row) for row in rows]
|
|
265
|
+
except Exception as e:
|
|
266
|
+
logger.error(f"Error in get_all: {e}")
|
|
267
|
+
raise OperationError(f"Failed to get all records: {str(e)}") from e
|
|
268
|
+
|
|
269
|
+
async def update(self, record_id: UUID, data: Dict[str, Any]) -> T:
|
|
270
|
+
"""
|
|
271
|
+
Update a record by its ID.
|
|
272
|
+
|
|
273
|
+
Args:
|
|
274
|
+
record_id (UUID): The unique identifier of the record to update.
|
|
275
|
+
data (Dict[str, Any]): Dictionary of fields and values to update.
|
|
276
|
+
|
|
277
|
+
Returns:
|
|
278
|
+
T: The updated model instance.
|
|
279
|
+
|
|
280
|
+
Raises:
|
|
281
|
+
HTTPException: If the update fails or database error occurs.
|
|
282
|
+
ValueError: If the record is not found.
|
|
283
|
+
|
|
284
|
+
Example:
|
|
285
|
+
```python
|
|
286
|
+
updated_item = await repo.update(
|
|
287
|
+
item_id,
|
|
288
|
+
{"name": "new name", "description": "new description"}
|
|
289
|
+
)
|
|
290
|
+
```
|
|
291
|
+
"""
|
|
292
|
+
try:
|
|
293
|
+
update_query = PsycopgHelper.build_update_query(
|
|
294
|
+
self.table_name,
|
|
295
|
+
data,
|
|
296
|
+
where_clause={self.primary_key: record_id}
|
|
297
|
+
)
|
|
298
|
+
values = list(data.values()) + [record_id]
|
|
299
|
+
async with self.db_connection.cursor(row_factory=dict_row) as cur:
|
|
300
|
+
await cur.execute(update_query + SQL(" RETURNING *"), values)
|
|
301
|
+
result = await cur.fetchone()
|
|
302
|
+
if not result:
|
|
303
|
+
raise RecordNotFoundError(f"Record with id {record_id} not found")
|
|
304
|
+
if result:
|
|
305
|
+
return self.model_class(**result)
|
|
306
|
+
raise ValueError(f"Failed to update {self.table_name} record")
|
|
307
|
+
except Exception as e:
|
|
308
|
+
logger.error(f"Error in update: {e}")
|
|
309
|
+
if isinstance(e, RecordNotFoundError):
|
|
310
|
+
raise
|
|
311
|
+
raise OperationError(f"Failed to update record: {str(e)}") from e
|
|
312
|
+
|
|
313
|
+
async def delete(self, record_id: UUID) -> None:
|
|
314
|
+
"""
|
|
315
|
+
Delete a record by its ID.
|
|
316
|
+
|
|
317
|
+
Args:
|
|
318
|
+
record_id (UUID): The unique identifier of the record to delete.
|
|
319
|
+
|
|
320
|
+
Raises:
|
|
321
|
+
HTTPException: If the deletion fails or database error occurs.
|
|
322
|
+
|
|
323
|
+
Example:
|
|
324
|
+
```python
|
|
325
|
+
await repo.delete(item_id)
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
Note:
|
|
329
|
+
This is a hard delete. Consider implementing soft delete if needed.
|
|
330
|
+
"""
|
|
331
|
+
try:
|
|
332
|
+
delete_query = PsycopgHelper.build_delete_query(
|
|
333
|
+
self.table_name,
|
|
334
|
+
where_clause={self.primary_key: record_id}
|
|
335
|
+
)
|
|
336
|
+
async with self.db_connection.cursor() as cur:
|
|
337
|
+
await cur.execute(delete_query, [record_id])
|
|
338
|
+
if cur.rowcount == 0:
|
|
339
|
+
raise RecordNotFoundError(f"Record with id {record_id} not found")
|
|
340
|
+
except Exception as e:
|
|
341
|
+
logger.error(f"Error in delete: {e}")
|
|
342
|
+
if isinstance(e, RecordNotFoundError):
|
|
343
|
+
raise
|
|
344
|
+
raise OperationError(f"Failed to delete record: {str(e)}") from e
|
|
345
|
+
|
|
346
|
+
async def exists(self, record_id: UUID) -> bool:
|
|
347
|
+
"""
|
|
348
|
+
Check if a record exists by its ID.
|
|
349
|
+
|
|
350
|
+
Args:
|
|
351
|
+
record_id (UUID): The unique identifier to check.
|
|
352
|
+
|
|
353
|
+
Returns:
|
|
354
|
+
bool: True if the record exists, False otherwise.
|
|
355
|
+
|
|
356
|
+
Raises:
|
|
357
|
+
HTTPException: If the database query fails.
|
|
358
|
+
|
|
359
|
+
Example:
|
|
360
|
+
```python
|
|
361
|
+
if await repo.exists(item_id):
|
|
362
|
+
print("Item exists")
|
|
363
|
+
```
|
|
364
|
+
"""
|
|
365
|
+
try:
|
|
366
|
+
async with self.db_connection.cursor() as cur:
|
|
367
|
+
await cur.execute(
|
|
368
|
+
f"SELECT 1 FROM {self.table_name} WHERE {self.primary_key} = %s",
|
|
369
|
+
[record_id]
|
|
370
|
+
)
|
|
371
|
+
return bool(await cur.fetchone())
|
|
372
|
+
except Exception as e:
|
|
373
|
+
logger.error(f"Error in exists: {e}")
|
|
374
|
+
raise OperationError(f"Failed to check record existence: {str(e)}") from e
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PsycopgHelper: A utility class for safe SQL query construction using psycopg3.
|
|
3
|
+
|
|
4
|
+
This class provides methods to build SQL queries safely using psycopg3's SQL composition
|
|
5
|
+
functionality, preventing SQL injection attacks by properly escaping all user inputs.
|
|
6
|
+
|
|
7
|
+
Key security features:
|
|
8
|
+
- Uses psycopg.sql.SQL for safe query composition
|
|
9
|
+
- Uses psycopg.sql.Identifier for table and column names
|
|
10
|
+
- Uses psycopg.sql.Placeholder for parameter values
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from typing import List, Dict, Any, Optional
|
|
14
|
+
|
|
15
|
+
from psycopg.sql import SQL, Identifier, Placeholder
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class PsycopgHelper:
|
|
19
|
+
@staticmethod
|
|
20
|
+
def get_columns(keys: Dict[str, Any]) -> List[Identifier]:
|
|
21
|
+
"""
|
|
22
|
+
Convert dictionary keys to a list of SQL Identifiers for safe column name handling.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
keys: Dictionary keys representing column names
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
List of SQL-safe Identifier objects
|
|
29
|
+
"""
|
|
30
|
+
return [Identifier(k) for k in keys]
|
|
31
|
+
|
|
32
|
+
@staticmethod
|
|
33
|
+
def get_columns_as_list(keys: Dict[str, Any]) -> List[str]:
|
|
34
|
+
"""
|
|
35
|
+
Convert dictionary keys to a list of column names as strings.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
keys: Dictionary keys representing column names
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
List of column names as strings
|
|
42
|
+
"""
|
|
43
|
+
return [k for k in keys]
|
|
44
|
+
|
|
45
|
+
@staticmethod
|
|
46
|
+
def get_placeholders(count: int) -> List[Placeholder]:
|
|
47
|
+
"""
|
|
48
|
+
Generate a list of SQL placeholders for parameterized queries.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
count: Number of placeholders needed
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
List of Placeholder objects for safe parameter binding
|
|
55
|
+
"""
|
|
56
|
+
return [Placeholder() for _ in range(count)]
|
|
57
|
+
|
|
58
|
+
@staticmethod
|
|
59
|
+
def build_select_query(
|
|
60
|
+
table_name: str,
|
|
61
|
+
columns: Optional[List[str]] = None,
|
|
62
|
+
where_clause: Optional[Dict[str, Any]] = None
|
|
63
|
+
) -> SQL:
|
|
64
|
+
"""
|
|
65
|
+
Build a safe SELECT query with optional column selection and WHERE clause.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
table_name: Name of the table to query
|
|
69
|
+
columns: Optional list of column names to select (defaults to *)
|
|
70
|
+
where_clause: Optional dictionary of column-value pairs for WHERE conditions
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
SQL object representing the parameterized query
|
|
74
|
+
"""
|
|
75
|
+
select_columns = SQL('*') if not columns else SQL(', ').join(map(Identifier, columns))
|
|
76
|
+
|
|
77
|
+
if where_clause:
|
|
78
|
+
conditions = SQL(' AND ').join([
|
|
79
|
+
SQL("{} = {}").format(Identifier(k), Placeholder())
|
|
80
|
+
for k in where_clause.keys()
|
|
81
|
+
])
|
|
82
|
+
where_sql = SQL(" WHERE {}").format(conditions)
|
|
83
|
+
else:
|
|
84
|
+
where_sql = SQL("")
|
|
85
|
+
|
|
86
|
+
query = SQL("SELECT {} FROM {}{}").format(
|
|
87
|
+
select_columns,
|
|
88
|
+
Identifier(table_name),
|
|
89
|
+
where_sql
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
return query
|
|
93
|
+
|
|
94
|
+
@staticmethod
|
|
95
|
+
def build_insert_query(
|
|
96
|
+
table_name: str,
|
|
97
|
+
data: Dict[str, Any],
|
|
98
|
+
batch_size: int = 1
|
|
99
|
+
) -> SQL:
|
|
100
|
+
"""
|
|
101
|
+
Build a safe INSERT query, supporting batch inserts.
|
|
102
|
+
|
|
103
|
+
Args:
|
|
104
|
+
table_name: Name of the table to insert into
|
|
105
|
+
data: Dictionary of column-value pairs to insert (single record)
|
|
106
|
+
batch_size: Number of records to insert (for batch inserts)
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
SQL object representing the parameterized query
|
|
110
|
+
|
|
111
|
+
Example:
|
|
112
|
+
>>> query = PsycopgHelper.build_insert_query("users", {"name": "John", "age": 30}, batch_size=1)
|
|
113
|
+
>>> cur.execute(query, list(data.values()))
|
|
114
|
+
"""
|
|
115
|
+
columns = PsycopgHelper.get_columns(data.keys())
|
|
116
|
+
|
|
117
|
+
# Generate placeholders for batch insert
|
|
118
|
+
batch_placeholders = []
|
|
119
|
+
for _ in range(batch_size):
|
|
120
|
+
placeholders = PsycopgHelper.get_placeholders(len(data))
|
|
121
|
+
batch_placeholders.append(
|
|
122
|
+
SQL('({})').format(SQL(', ').join(placeholders))
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
return SQL("INSERT INTO {} ({}) VALUES {}").format(
|
|
126
|
+
Identifier(table_name),
|
|
127
|
+
SQL(', ').join(columns),
|
|
128
|
+
SQL(', ').join(batch_placeholders)
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
@staticmethod
|
|
132
|
+
def build_update_query(
|
|
133
|
+
table_name: str,
|
|
134
|
+
data: Dict[str, Any],
|
|
135
|
+
where_clause: Dict[str, Any]
|
|
136
|
+
) -> SQL:
|
|
137
|
+
"""
|
|
138
|
+
Build a safe UPDATE query with SET and WHERE clauses.
|
|
139
|
+
|
|
140
|
+
Args:
|
|
141
|
+
table_name: Name of the table to update
|
|
142
|
+
data: Dictionary of column-value pairs to update
|
|
143
|
+
where_clause: Dictionary of column-value pairs for WHERE conditions
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
SQL object representing the parameterized query
|
|
147
|
+
|
|
148
|
+
Example:
|
|
149
|
+
>>> query = PsycopgHelper.build_update_query("users",
|
|
150
|
+
{"name": "John"},
|
|
151
|
+
{"id": 1})
|
|
152
|
+
>>> cur.execute(query, list(data.values()) + list(where_clause.values()))
|
|
153
|
+
"""
|
|
154
|
+
set_items = SQL(', ').join([
|
|
155
|
+
SQL("{} = {}").format(Identifier(k), Placeholder())
|
|
156
|
+
for k in data.keys()
|
|
157
|
+
])
|
|
158
|
+
|
|
159
|
+
where_conditions = SQL(' AND ').join([
|
|
160
|
+
SQL("{} = {}").format(Identifier(k), Placeholder())
|
|
161
|
+
for k in where_clause.keys()
|
|
162
|
+
])
|
|
163
|
+
|
|
164
|
+
return SQL("UPDATE {} SET {} WHERE {}").format(
|
|
165
|
+
Identifier(table_name),
|
|
166
|
+
set_items,
|
|
167
|
+
where_conditions
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
@staticmethod
|
|
171
|
+
def build_delete_query(
|
|
172
|
+
table_name: str,
|
|
173
|
+
where_clause: Dict[str, Any]
|
|
174
|
+
) -> SQL:
|
|
175
|
+
"""
|
|
176
|
+
Build a safe DELETE query with WHERE clause.
|
|
177
|
+
|
|
178
|
+
Args:
|
|
179
|
+
table_name: Name of the table to delete from
|
|
180
|
+
where_clause: Dictionary of column-value pairs for WHERE conditions
|
|
181
|
+
|
|
182
|
+
Returns:
|
|
183
|
+
SQL object representing the parameterized query
|
|
184
|
+
|
|
185
|
+
Example:
|
|
186
|
+
>>> query = PsycopgHelper.build_delete_query("users", {"id": 1})
|
|
187
|
+
>>> cur.execute(query, list(where_clause.values()))
|
|
188
|
+
"""
|
|
189
|
+
conditions = SQL(' AND ').join([
|
|
190
|
+
SQL("{} = {}").format(Identifier(k), Placeholder())
|
|
191
|
+
for k in where_clause.keys()
|
|
192
|
+
])
|
|
193
|
+
|
|
194
|
+
return SQL("DELETE FROM {} WHERE {}").format(
|
|
195
|
+
Identifier(table_name),
|
|
196
|
+
conditions
|
|
197
|
+
)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Descoped
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: psycopg-toolkit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A Python PostgreSQL database utility with connection pooling
|
|
5
|
+
License: MIT
|
|
6
|
+
Keywords: postgresql,database,async,pool,psycopg
|
|
7
|
+
Author: Ove Ranheim
|
|
8
|
+
Author-email: oranheim@gmail.com
|
|
9
|
+
Requires-Python: >=3.11,<4.0
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Database
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Dist: psycopg (>=3.2.3,<4.0.0)
|
|
22
|
+
Requires-Dist: psycopg-pool (>=3.2.4,<4.0.0)
|
|
23
|
+
Requires-Dist: pydantic (>=2.10.5,<3.0.0)
|
|
24
|
+
Requires-Dist: tenacity (>=9.0.0,<10.0.0)
|
|
25
|
+
Project-URL: Documentation, https://github.com/descoped/psycopg-toolkit/tree/master/docs
|
|
26
|
+
Project-URL: Homepage, https://github.com/descoped/psycopg-toolkit
|
|
27
|
+
Project-URL: Repository, https://github.com/descoped/psycopg-toolkit
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# Psycopg Toolkit
|
|
31
|
+
|
|
32
|
+
A robust PostgreSQL database toolkit providing enterprise-grade connection pooling and database management capabilities for Python applications.
|
|
33
|
+
|
|
34
|
+
## Features
|
|
35
|
+
|
|
36
|
+
- Async-first design with connection pooling via `psycopg-pool`
|
|
37
|
+
- Smart connection management with automatic retries and exponential backoff
|
|
38
|
+
- Configurable pool settings with runtime optimization
|
|
39
|
+
- Type-safe with full typing support
|
|
40
|
+
- Comprehensive error handling and custom exceptions
|
|
41
|
+
- Database health monitoring
|
|
42
|
+
- Initialization callback system for startup operations
|
|
43
|
+
|
|
44
|
+
## Installation
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install psycopg-toolkit
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Quick Start
|
|
51
|
+
|
|
52
|
+
Here's a simple example of connecting to PostgreSQL:
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from psycopg_toolkit import Database, DatabaseSettings
|
|
56
|
+
|
|
57
|
+
# Configure database
|
|
58
|
+
settings = DatabaseSettings(
|
|
59
|
+
host="localhost",
|
|
60
|
+
port=5432,
|
|
61
|
+
dbname="your_database",
|
|
62
|
+
user="your_user",
|
|
63
|
+
password="your_password"
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
async def main():
|
|
67
|
+
# Initialize database with connection pool
|
|
68
|
+
db = Database(settings)
|
|
69
|
+
await db.init_db()
|
|
70
|
+
|
|
71
|
+
# Execute queries
|
|
72
|
+
async with db.connection() as conn:
|
|
73
|
+
async with conn.cursor() as cur:
|
|
74
|
+
await cur.execute("SELECT * FROM users")
|
|
75
|
+
users = await cur.fetchall()
|
|
76
|
+
|
|
77
|
+
# Clean up connections
|
|
78
|
+
await db.cleanup()
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Architecture
|
|
82
|
+
|
|
83
|
+
The toolkit manages database connections through a layered architecture:
|
|
84
|
+
|
|
85
|
+
1. Connection Pool Layer - Handles connection lifecycle and pooling
|
|
86
|
+
2. Transaction Layer - Manages database transactions and retries
|
|
87
|
+
3. Error Management Layer - Provides custom exceptions and error handling
|
|
88
|
+
4. Health Check Layer - Monitors database availability
|
|
89
|
+
|
|
90
|
+
## Key Components
|
|
91
|
+
|
|
92
|
+
### Database Settings
|
|
93
|
+
|
|
94
|
+
Configure your database connection:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
settings = DatabaseSettings(
|
|
98
|
+
host="localhost",
|
|
99
|
+
port=5432,
|
|
100
|
+
dbname="your_database",
|
|
101
|
+
user="your_user",
|
|
102
|
+
password="your_password",
|
|
103
|
+
min_pool_size=5, # Optional
|
|
104
|
+
max_pool_size=20, # Optional
|
|
105
|
+
pool_timeout=30 # Optional
|
|
106
|
+
)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Connection Management
|
|
110
|
+
|
|
111
|
+
The `Database` class provides connection handling:
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
# Connection context manager
|
|
115
|
+
async with db.connection() as conn:
|
|
116
|
+
# Your database operations here
|
|
117
|
+
pass # Connection automatically returned to pool
|
|
118
|
+
|
|
119
|
+
# Manual connection acquisition
|
|
120
|
+
conn = await db.acquire()
|
|
121
|
+
try:
|
|
122
|
+
# Your operations
|
|
123
|
+
pass
|
|
124
|
+
finally:
|
|
125
|
+
await db.release(conn)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Initialization Callbacks
|
|
129
|
+
|
|
130
|
+
Register startup operations:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
async def init_tables(pool):
|
|
134
|
+
async with pool.connection() as conn:
|
|
135
|
+
async with conn.cursor() as cur:
|
|
136
|
+
await cur.execute("""
|
|
137
|
+
CREATE TABLE IF NOT EXISTS users (
|
|
138
|
+
id SERIAL PRIMARY KEY,
|
|
139
|
+
name TEXT NOT NULL
|
|
140
|
+
)
|
|
141
|
+
""")
|
|
142
|
+
|
|
143
|
+
db.register_init_callback(init_tables)
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### Error Handling
|
|
147
|
+
|
|
148
|
+
Comprehensive exception hierarchy:
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
try:
|
|
152
|
+
async with db.connection() as conn:
|
|
153
|
+
# Database operations
|
|
154
|
+
pass
|
|
155
|
+
except DatabaseConnectionError as e:
|
|
156
|
+
# Handle connection failures
|
|
157
|
+
except DatabasePoolError as e:
|
|
158
|
+
# Handle pool exhaustion
|
|
159
|
+
except DatabaseNotAvailable as e:
|
|
160
|
+
# Handle database unavailability
|
|
161
|
+
except PsycoDBException as e:
|
|
162
|
+
# Handle general database errors
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
## Advanced Usage
|
|
166
|
+
|
|
167
|
+
### Health Monitoring
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
# Check database availability
|
|
171
|
+
is_healthy = await db.ping_postgres()
|
|
172
|
+
|
|
173
|
+
# Get pool statistics
|
|
174
|
+
stats = await db.get_pool_stats()
|
|
175
|
+
print(f"Active connections: {stats.active_connections}")
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### Connection Pool Management
|
|
179
|
+
|
|
180
|
+
```python
|
|
181
|
+
# Configure pool behavior
|
|
182
|
+
db = Database(
|
|
183
|
+
settings,
|
|
184
|
+
retry_attempts=3,
|
|
185
|
+
backoff_factor=2.0,
|
|
186
|
+
max_retry_delay=30.0
|
|
187
|
+
)
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## Best Practices
|
|
191
|
+
|
|
192
|
+
1. Always use async context managers for connection handling
|
|
193
|
+
2. Configure appropriate pool sizes for your workload
|
|
194
|
+
3. Implement proper error handling using provided exceptions
|
|
195
|
+
4. Use health checks in production environments
|
|
196
|
+
5. Clean up resources during application shutdown
|
|
197
|
+
|
|
198
|
+
## Documentation
|
|
199
|
+
|
|
200
|
+
Detailed documentation for each component is available in the `docs/` directory:
|
|
201
|
+
|
|
202
|
+
- [Database Management](docs/database.md)
|
|
203
|
+
- [Transaction Management](docs/transaction_manager.md)
|
|
204
|
+
- [Base Repository](docs/base_repository.md)
|
|
205
|
+
- [PsycopgHelper](docs/psycopg_helper.md)
|
|
206
|
+
|
|
207
|
+
These guides provide in-depth explanations, examples, and best practices for each feature.
|
|
208
|
+
|
|
209
|
+
## Contributing
|
|
210
|
+
|
|
211
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
212
|
+
|
|
213
|
+
## License
|
|
214
|
+
|
|
215
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
216
|
+
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
psycopg_toolkit/__init__.py,sha256=Dn3ycgwr0xvVPmUud11BZ80inTsXBWsnVeyDXchjW8M,696
|
|
2
|
+
psycopg_toolkit/core/__init__.py,sha256=aT5nSRqCHvbK-4ADSNU7E8mLLWueiEhf3FvayXr_eos,193
|
|
3
|
+
psycopg_toolkit/core/config.py,sha256=w9YVn2K7EAWFKivtR6M0KwStKaH4GpdakooCsOGX3Mg,704
|
|
4
|
+
psycopg_toolkit/core/database.py,sha256=6wPmTc2bXUf3TLIywTGK3OiErzpFxg4g4l4AbJ5kgnM,6527
|
|
5
|
+
psycopg_toolkit/core/transaction.py,sha256=OmZhzmuxT3LpDB6zn8xT56f_lxqFkz4OgbN2wc7r6io,1360
|
|
6
|
+
psycopg_toolkit/exceptions.py,sha256=y4lvbqHVZd1_EFZGPQLrANrWRBoqAXmkDbzfshkXxVE,1066
|
|
7
|
+
psycopg_toolkit/repositories/__init__.py,sha256=nE7RaZwzhKfNsIOOxEM3yfQnL5HA8YrhzUlrgXaanqA,69
|
|
8
|
+
psycopg_toolkit/repositories/base.py,sha256=VHVhpU2HpcA8tbheamVlWTtyA4lTJqBZlvw8D1-ivEo,13369
|
|
9
|
+
psycopg_toolkit/utils/__init__.py,sha256=7jZdt8sEext16m7FvaVSFVP4vvpKyEoYiUk-_FympnE,79
|
|
10
|
+
psycopg_toolkit/utils/psychopg_helper.py,sha256=rB5RTIQ6rgcdBcGW0eHs_cH672IiKMGarD8EYALMoR4,6326
|
|
11
|
+
psycopg_toolkit-0.1.0.dist-info/LICENSE,sha256=FS7LYVt91OiPx9wiH1K3jAWLS90HpvzKnNAvW_XLeqo,1065
|
|
12
|
+
psycopg_toolkit-0.1.0.dist-info/METADATA,sha256=J51fuzmukhlOqkfKoXl2mluV2UCs10RqancgXVZg93Q,5735
|
|
13
|
+
psycopg_toolkit-0.1.0.dist-info/WHEEL,sha256=IYZQI976HJqqOpQU6PHkJ8fb3tMNBFjg-Cn-pwAbaFM,88
|
|
14
|
+
psycopg_toolkit-0.1.0.dist-info/RECORD,,
|