psycopg-toolkit 0.1.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.
@@ -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,186 @@
1
+ # Psycopg Toolkit
2
+
3
+ A robust PostgreSQL database toolkit providing enterprise-grade connection pooling and database management capabilities for Python applications.
4
+
5
+ ## Features
6
+
7
+ - Async-first design with connection pooling via `psycopg-pool`
8
+ - Smart connection management with automatic retries and exponential backoff
9
+ - Configurable pool settings with runtime optimization
10
+ - Type-safe with full typing support
11
+ - Comprehensive error handling and custom exceptions
12
+ - Database health monitoring
13
+ - Initialization callback system for startup operations
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ pip install psycopg-toolkit
19
+ ```
20
+
21
+ ## Quick Start
22
+
23
+ Here's a simple example of connecting to PostgreSQL:
24
+
25
+ ```python
26
+ from psycopg_toolkit import Database, DatabaseSettings
27
+
28
+ # Configure database
29
+ settings = DatabaseSettings(
30
+ host="localhost",
31
+ port=5432,
32
+ dbname="your_database",
33
+ user="your_user",
34
+ password="your_password"
35
+ )
36
+
37
+ async def main():
38
+ # Initialize database with connection pool
39
+ db = Database(settings)
40
+ await db.init_db()
41
+
42
+ # Execute queries
43
+ async with db.connection() as conn:
44
+ async with conn.cursor() as cur:
45
+ await cur.execute("SELECT * FROM users")
46
+ users = await cur.fetchall()
47
+
48
+ # Clean up connections
49
+ await db.cleanup()
50
+ ```
51
+
52
+ ## Architecture
53
+
54
+ The toolkit manages database connections through a layered architecture:
55
+
56
+ 1. Connection Pool Layer - Handles connection lifecycle and pooling
57
+ 2. Transaction Layer - Manages database transactions and retries
58
+ 3. Error Management Layer - Provides custom exceptions and error handling
59
+ 4. Health Check Layer - Monitors database availability
60
+
61
+ ## Key Components
62
+
63
+ ### Database Settings
64
+
65
+ Configure your database connection:
66
+
67
+ ```python
68
+ settings = DatabaseSettings(
69
+ host="localhost",
70
+ port=5432,
71
+ dbname="your_database",
72
+ user="your_user",
73
+ password="your_password",
74
+ min_pool_size=5, # Optional
75
+ max_pool_size=20, # Optional
76
+ pool_timeout=30 # Optional
77
+ )
78
+ ```
79
+
80
+ ### Connection Management
81
+
82
+ The `Database` class provides connection handling:
83
+
84
+ ```python
85
+ # Connection context manager
86
+ async with db.connection() as conn:
87
+ # Your database operations here
88
+ pass # Connection automatically returned to pool
89
+
90
+ # Manual connection acquisition
91
+ conn = await db.acquire()
92
+ try:
93
+ # Your operations
94
+ pass
95
+ finally:
96
+ await db.release(conn)
97
+ ```
98
+
99
+ ### Initialization Callbacks
100
+
101
+ Register startup operations:
102
+
103
+ ```python
104
+ async def init_tables(pool):
105
+ async with pool.connection() as conn:
106
+ async with conn.cursor() as cur:
107
+ await cur.execute("""
108
+ CREATE TABLE IF NOT EXISTS users (
109
+ id SERIAL PRIMARY KEY,
110
+ name TEXT NOT NULL
111
+ )
112
+ """)
113
+
114
+ db.register_init_callback(init_tables)
115
+ ```
116
+
117
+ ### Error Handling
118
+
119
+ Comprehensive exception hierarchy:
120
+
121
+ ```python
122
+ try:
123
+ async with db.connection() as conn:
124
+ # Database operations
125
+ pass
126
+ except DatabaseConnectionError as e:
127
+ # Handle connection failures
128
+ except DatabasePoolError as e:
129
+ # Handle pool exhaustion
130
+ except DatabaseNotAvailable as e:
131
+ # Handle database unavailability
132
+ except PsycoDBException as e:
133
+ # Handle general database errors
134
+ ```
135
+
136
+ ## Advanced Usage
137
+
138
+ ### Health Monitoring
139
+
140
+ ```python
141
+ # Check database availability
142
+ is_healthy = await db.ping_postgres()
143
+
144
+ # Get pool statistics
145
+ stats = await db.get_pool_stats()
146
+ print(f"Active connections: {stats.active_connections}")
147
+ ```
148
+
149
+ ### Connection Pool Management
150
+
151
+ ```python
152
+ # Configure pool behavior
153
+ db = Database(
154
+ settings,
155
+ retry_attempts=3,
156
+ backoff_factor=2.0,
157
+ max_retry_delay=30.0
158
+ )
159
+ ```
160
+
161
+ ## Best Practices
162
+
163
+ 1. Always use async context managers for connection handling
164
+ 2. Configure appropriate pool sizes for your workload
165
+ 3. Implement proper error handling using provided exceptions
166
+ 4. Use health checks in production environments
167
+ 5. Clean up resources during application shutdown
168
+
169
+ ## Documentation
170
+
171
+ Detailed documentation for each component is available in the `docs/` directory:
172
+
173
+ - [Database Management](docs/database.md)
174
+ - [Transaction Management](docs/transaction_manager.md)
175
+ - [Base Repository](docs/base_repository.md)
176
+ - [PsycopgHelper](docs/psycopg_helper.md)
177
+
178
+ These guides provide in-depth explanations, examples, and best practices for each feature.
179
+
180
+ ## Contributing
181
+
182
+ Contributions are welcome! Please feel free to submit a Pull Request.
183
+
184
+ ## License
185
+
186
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,49 @@
1
+ [tool.poetry]
2
+ name = "psycopg-toolkit"
3
+ version = "0.1.0"
4
+ description = "A Python PostgreSQL database utility with connection pooling"
5
+ authors = ["Ove Ranheim <oranheim@gmail.com>"]
6
+ readme = "README.md"
7
+ packages = [{ include = "psycopg_toolkit", from = "src" }]
8
+ license = "MIT"
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Intended Audience :: Developers",
12
+ "Operating System :: OS Independent",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3.11",
15
+ "Topic :: Database",
16
+ "Topic :: Software Development :: Libraries :: Python Modules",
17
+ "Typing :: Typed"
18
+ ]
19
+ homepage = "https://github.com/descoped/psycopg-toolkit"
20
+ repository = "https://github.com/descoped/psycopg-toolkit"
21
+ documentation = "https://github.com/descoped/psycopg-toolkit/tree/master/docs"
22
+ keywords = ["postgresql", "database", "async", "pool", "psycopg"]
23
+
24
+ [tool.poetry.dependencies]
25
+ python = "^3.11"
26
+ psycopg = "^3.2.3"
27
+ psycopg-pool = "^3.2.4"
28
+ tenacity = "^9.0.0"
29
+ pydantic = "^2.10.5"
30
+
31
+ [tool.poetry.group.dev.dependencies]
32
+ pytest = "^8.3.0"
33
+ pytest-asyncio = "^0.25.2"
34
+ flake8 = "^7.1.0"
35
+ restructuredtext-lint = "^1.4.0"
36
+ pygments = "^2.19.1"
37
+
38
+ [build-system]
39
+ requires = ["poetry-core"]
40
+ build-backend = "poetry.core.masonry.api"
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["tests"]
44
+ python_files = ["test_*.py"]
45
+ asyncio_mode = "auto"
46
+ asyncio_default_fixture_loop_scope = "function"
47
+ markers = [
48
+ "asyncio: mark test as async",
49
+ ]
@@ -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,9 @@
1
+ from .config import DatabaseSettings
2
+ from .database import Database
3
+ from .transaction import TransactionManager
4
+
5
+ __all__ = [
6
+ "Database",
7
+ "DatabaseSettings",
8
+ "TransactionManager",
9
+ ]
@@ -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
+ )