pgsqlasync2fast-fastapi 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.
- pgsqlasync2fast_fastapi-0.1.0/LICENSE +21 -0
- pgsqlasync2fast_fastapi-0.1.0/MANIFEST.in +4 -0
- pgsqlasync2fast_fastapi-0.1.0/PKG-INFO +311 -0
- pgsqlasync2fast_fastapi-0.1.0/README.md +253 -0
- pgsqlasync2fast_fastapi-0.1.0/docs/.env.example +50 -0
- pgsqlasync2fast_fastapi-0.1.0/pyproject.toml +70 -0
- pgsqlasync2fast_fastapi-0.1.0/setup.cfg +4 -0
- pgsqlasync2fast_fastapi-0.1.0/src/pgsqlasync2fast_fastapi/__init__.py +49 -0
- pgsqlasync2fast_fastapi-0.1.0/src/pgsqlasync2fast_fastapi/__version__.py +1 -0
- pgsqlasync2fast_fastapi-0.1.0/src/pgsqlasync2fast_fastapi/connection.py +196 -0
- pgsqlasync2fast_fastapi-0.1.0/src/pgsqlasync2fast_fastapi/database.py +262 -0
- pgsqlasync2fast_fastapi-0.1.0/src/pgsqlasync2fast_fastapi/dependencies.py +147 -0
- pgsqlasync2fast_fastapi-0.1.0/src/pgsqlasync2fast_fastapi/settings.py +198 -0
- pgsqlasync2fast_fastapi-0.1.0/src/pgsqlasync2fast_fastapi.egg-info/PKG-INFO +311 -0
- pgsqlasync2fast_fastapi-0.1.0/src/pgsqlasync2fast_fastapi.egg-info/SOURCES.txt +17 -0
- pgsqlasync2fast_fastapi-0.1.0/src/pgsqlasync2fast_fastapi.egg-info/dependency_links.txt +1 -0
- pgsqlasync2fast_fastapi-0.1.0/src/pgsqlasync2fast_fastapi.egg-info/requires.txt +12 -0
- pgsqlasync2fast_fastapi-0.1.0/src/pgsqlasync2fast_fastapi.egg-info/top_level.txt +1 -0
- pgsqlasync2fast_fastapi-0.1.0/tests/test_completo.py +199 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Angel Daniel Sanchez Castillo
|
|
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,311 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pgsqlasync2fast-fastapi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Simple and fast PostgreSQL async module for FastAPI with multi-database support
|
|
5
|
+
Author-email: Angel Daniel Sanchez Castillo <angeldaniel.sanchezcastillo@gmail.com>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2026 Angel Daniel Sanchez Castillo
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://github.com/AngelDanielSanchezCastillo/pgsqlasync2fast-fastapi
|
|
29
|
+
Project-URL: Documentation, https://github.com/AngelDanielSanchezCastillo/pgsqlasync2fast-fastapi/tree/main/docs
|
|
30
|
+
Project-URL: Repository, https://github.com/AngelDanielSanchezCastillo/pgsqlasync2fast-fastapi
|
|
31
|
+
Project-URL: Issues, https://github.com/AngelDanielSanchezCastillo/pgsqlasync2fast-fastapi/issues
|
|
32
|
+
Keywords: fastapi,postgresql,async,sqlalchemy,database,multi-database
|
|
33
|
+
Classifier: Development Status :: 3 - Alpha
|
|
34
|
+
Classifier: Intended Audience :: Developers
|
|
35
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
36
|
+
Classifier: Programming Language :: Python :: 3
|
|
37
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
40
|
+
Classifier: Framework :: FastAPI
|
|
41
|
+
Classifier: Topic :: Database
|
|
42
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
43
|
+
Requires-Python: >=3.10
|
|
44
|
+
Description-Content-Type: text/markdown
|
|
45
|
+
License-File: LICENSE
|
|
46
|
+
Requires-Dist: fastapi>=0.100.0
|
|
47
|
+
Requires-Dist: pydantic>=2.0.0
|
|
48
|
+
Requires-Dist: pydantic-settings>=2.0.0
|
|
49
|
+
Requires-Dist: sqlalchemy>=2.0.0
|
|
50
|
+
Requires-Dist: asyncpg>=0.29.0
|
|
51
|
+
Provides-Extra: dev
|
|
52
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
53
|
+
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
|
|
54
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
|
|
55
|
+
Requires-Dist: httpx>=0.24.0; extra == "dev"
|
|
56
|
+
Requires-Dist: mypy>=1.0.0; extra == "dev"
|
|
57
|
+
Dynamic: license-file
|
|
58
|
+
|
|
59
|
+
# pgsqlasync2fast-fastapi
|
|
60
|
+
|
|
61
|
+
Simple and fast PostgreSQL async module for FastAPI with multi-database support and automatic database creation.
|
|
62
|
+
|
|
63
|
+
## Features
|
|
64
|
+
|
|
65
|
+
- ✅ **Multiple Database Connections**: Configure and manage multiple PostgreSQL databases
|
|
66
|
+
- ✅ **Async Support**: Built on SQLAlchemy 2.0+ async engine with asyncpg
|
|
67
|
+
- ✅ **Database Creation**: Automatic database creation with superuser support
|
|
68
|
+
- ✅ **FastAPI Integration**: Ready-to-use dependencies for seamless FastAPI integration
|
|
69
|
+
- ✅ **Connection Pooling**: Configurable connection pools per database
|
|
70
|
+
- ✅ **Health Checks**: Built-in connection health monitoring
|
|
71
|
+
- ✅ **Lazy Loading**: Engines created only when needed
|
|
72
|
+
- ✅ **Type Safe**: Full Pydantic settings with validation
|
|
73
|
+
|
|
74
|
+
## Installation
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
pip install pgsqlasync2fast-fastapi
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Quick Start
|
|
81
|
+
|
|
82
|
+
### 1. Configure your databases in `.env`
|
|
83
|
+
|
|
84
|
+
```env
|
|
85
|
+
# Default database connection
|
|
86
|
+
DB_CONNECTIONS__DEFAULT__HOST=localhost
|
|
87
|
+
DB_CONNECTIONS__DEFAULT__PORT=5432
|
|
88
|
+
DB_CONNECTIONS__DEFAULT__USERNAME=myuser
|
|
89
|
+
DB_CONNECTIONS__DEFAULT__PASSWORD=mypassword
|
|
90
|
+
DB_CONNECTIONS__DEFAULT__DATABASE=mydb
|
|
91
|
+
|
|
92
|
+
# Business database connection
|
|
93
|
+
DB_CONNECTIONS__BUSINESS__HOST=localhost
|
|
94
|
+
DB_CONNECTIONS__BUSINESS__PORT=5432
|
|
95
|
+
DB_CONNECTIONS__BUSINESS__USERNAME=business_user
|
|
96
|
+
DB_CONNECTIONS__BUSINESS__PASSWORD=business_password
|
|
97
|
+
DB_CONNECTIONS__BUSINESS__DATABASE=business_db
|
|
98
|
+
|
|
99
|
+
# Admin connection with superuser privileges
|
|
100
|
+
DB_CONNECTIONS__ADMIN__HOST=localhost
|
|
101
|
+
DB_CONNECTIONS__ADMIN__PORT=5432
|
|
102
|
+
DB_CONNECTIONS__ADMIN__USERNAME=postgres
|
|
103
|
+
DB_CONNECTIONS__ADMIN__PASSWORD=postgres_password
|
|
104
|
+
DB_CONNECTIONS__ADMIN__DATABASE=postgres
|
|
105
|
+
DB_CONNECTIONS__ADMIN__IS_SUPERUSER=true
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
### 2. Use in FastAPI
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
from fastapi import FastAPI, Depends
|
|
112
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
113
|
+
from sqlalchemy import text
|
|
114
|
+
from pgsqlasync2fast_fastapi import (
|
|
115
|
+
get_db_session,
|
|
116
|
+
startup_database,
|
|
117
|
+
shutdown_database
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
app = FastAPI()
|
|
121
|
+
|
|
122
|
+
@app.on_event("startup")
|
|
123
|
+
async def startup():
|
|
124
|
+
await startup_database()
|
|
125
|
+
|
|
126
|
+
@app.on_event("shutdown")
|
|
127
|
+
async def shutdown():
|
|
128
|
+
await shutdown_database()
|
|
129
|
+
|
|
130
|
+
@app.get("/users")
|
|
131
|
+
async def get_users(session: AsyncSession = Depends(get_db_session)):
|
|
132
|
+
result = await session.execute(text("SELECT * FROM users"))
|
|
133
|
+
users = result.fetchall()
|
|
134
|
+
return {"users": users}
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### 3. Use Multiple Databases
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
from functools import partial
|
|
141
|
+
from fastapi import Depends
|
|
142
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
143
|
+
from pgsqlasync2fast_fastapi import get_db_session
|
|
144
|
+
|
|
145
|
+
# Create dependency for business database
|
|
146
|
+
get_business_session = partial(get_db_session, connection_name="business")
|
|
147
|
+
|
|
148
|
+
@app.get("/business/data")
|
|
149
|
+
async def get_business_data(session: AsyncSession = Depends(get_business_session)):
|
|
150
|
+
result = await session.execute(text("SELECT * FROM business_data"))
|
|
151
|
+
return {"data": result.fetchall()}
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
### 4. Create Databases Programmatically
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
from pgsqlasync2fast_fastapi import create_database, database_exists
|
|
158
|
+
|
|
159
|
+
# Create a new database (requires a connection with is_superuser=true)
|
|
160
|
+
if not await database_exists("new_database"):
|
|
161
|
+
await create_database("new_database", owner="myuser")
|
|
162
|
+
print("Database created!")
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
## Configuration
|
|
166
|
+
|
|
167
|
+
### Environment Variables
|
|
168
|
+
|
|
169
|
+
All configuration is done through environment variables with the prefix `DB_`:
|
|
170
|
+
|
|
171
|
+
#### Connection Settings
|
|
172
|
+
|
|
173
|
+
```env
|
|
174
|
+
DB_CONNECTIONS__<NAME>__HOST=localhost # Database host
|
|
175
|
+
DB_CONNECTIONS__<NAME>__PORT=5432 # Database port
|
|
176
|
+
DB_CONNECTIONS__<NAME>__USERNAME=user # Database username
|
|
177
|
+
DB_CONNECTIONS__<NAME>__PASSWORD=pass # Database password
|
|
178
|
+
DB_CONNECTIONS__<NAME>__DATABASE=dbname # Database name
|
|
179
|
+
DB_CONNECTIONS__<NAME>__IS_SUPERUSER=false # Superuser privileges
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
#### Pool Settings (Optional)
|
|
183
|
+
|
|
184
|
+
```env
|
|
185
|
+
DB_CONNECTIONS__<NAME>__POOL_SIZE=5 # Connection pool size
|
|
186
|
+
DB_CONNECTIONS__<NAME>__MAX_OVERFLOW=10 # Max overflow connections
|
|
187
|
+
DB_CONNECTIONS__<NAME>__POOL_TIMEOUT=30 # Pool timeout in seconds
|
|
188
|
+
DB_CONNECTIONS__<NAME>__POOL_RECYCLE=3600 # Recycle connections after seconds
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
#### Global Settings
|
|
192
|
+
|
|
193
|
+
```env
|
|
194
|
+
DB_DEFAULT_CONNECTION=default # Default connection name
|
|
195
|
+
DB_ECHO=false # Global SQLAlchemy echo mode
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
## API Reference
|
|
199
|
+
|
|
200
|
+
### Dependencies
|
|
201
|
+
|
|
202
|
+
#### `get_db_session(connection_name: str = "default")`
|
|
203
|
+
|
|
204
|
+
FastAPI dependency that provides an async database session with automatic commit/rollback.
|
|
205
|
+
|
|
206
|
+
```python
|
|
207
|
+
@app.get("/items")
|
|
208
|
+
async def get_items(session: AsyncSession = Depends(get_db_session)):
|
|
209
|
+
result = await session.execute(text("SELECT * FROM items"))
|
|
210
|
+
return result.fetchall()
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
#### `get_db_engine(connection_name: str = "default")`
|
|
214
|
+
|
|
215
|
+
FastAPI dependency that provides the async engine for a connection.
|
|
216
|
+
|
|
217
|
+
```python
|
|
218
|
+
@app.get("/health")
|
|
219
|
+
async def health_check(engine: AsyncEngine = Depends(get_db_engine)):
|
|
220
|
+
async with engine.connect() as conn:
|
|
221
|
+
await conn.execute(text("SELECT 1"))
|
|
222
|
+
return {"status": "healthy"}
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
#### `get_db_manager()`
|
|
226
|
+
|
|
227
|
+
FastAPI dependency that provides the DatabaseManager singleton.
|
|
228
|
+
|
|
229
|
+
```python
|
|
230
|
+
@app.get("/connections")
|
|
231
|
+
async def list_connections(manager: DatabaseManager = Depends(get_db_manager)):
|
|
232
|
+
return {"connections": manager.list_connections()}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### Database Utilities
|
|
236
|
+
|
|
237
|
+
#### `create_database(database_name: str, owner: Optional[str] = None, connection_name: Optional[str] = None) -> bool`
|
|
238
|
+
|
|
239
|
+
Create a new database using a superuser connection.
|
|
240
|
+
|
|
241
|
+
```python
|
|
242
|
+
created = await create_database("my_new_db", owner="myuser")
|
|
243
|
+
if created:
|
|
244
|
+
print("Database created successfully!")
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
#### `database_exists(database_name: str, connection_name: Optional[str] = None) -> bool`
|
|
248
|
+
|
|
249
|
+
Check if a database exists.
|
|
250
|
+
|
|
251
|
+
```python
|
|
252
|
+
if await database_exists("my_db"):
|
|
253
|
+
print("Database exists!")
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
#### `drop_database(database_name: str, connection_name: Optional[str] = None, force: bool = False) -> bool`
|
|
257
|
+
|
|
258
|
+
Drop a database (requires superuser).
|
|
259
|
+
|
|
260
|
+
```python
|
|
261
|
+
dropped = await drop_database("old_db", force=True)
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
#### `list_databases(connection_name: Optional[str] = None) -> List[str]`
|
|
265
|
+
|
|
266
|
+
List all databases.
|
|
267
|
+
|
|
268
|
+
```python
|
|
269
|
+
databases = await list_databases()
|
|
270
|
+
for db in databases:
|
|
271
|
+
print(f" - {db}")
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
### Startup/Shutdown
|
|
275
|
+
|
|
276
|
+
#### `startup_database(config: Optional[DatabaseSettings] = None) -> DatabaseManager`
|
|
277
|
+
|
|
278
|
+
Initialize database connections on application startup.
|
|
279
|
+
|
|
280
|
+
```python
|
|
281
|
+
@app.on_event("startup")
|
|
282
|
+
async def startup():
|
|
283
|
+
await startup_database()
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
#### `shutdown_database() -> None`
|
|
287
|
+
|
|
288
|
+
Close all database connections on application shutdown.
|
|
289
|
+
|
|
290
|
+
```python
|
|
291
|
+
@app.on_event("shutdown")
|
|
292
|
+
async def shutdown():
|
|
293
|
+
await shutdown_database()
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
## Examples
|
|
297
|
+
|
|
298
|
+
See the `examples/` directory for complete working examples:
|
|
299
|
+
|
|
300
|
+
- `basic_usage.py` - Basic database connection and queries
|
|
301
|
+
- `multi_database.py` - Using multiple database connections
|
|
302
|
+
- `fastapi_integration.py` - Complete FastAPI application
|
|
303
|
+
- `database_creation.py` - Creating databases programmatically
|
|
304
|
+
|
|
305
|
+
## License
|
|
306
|
+
|
|
307
|
+
MIT License - see LICENSE file for details.
|
|
308
|
+
|
|
309
|
+
## Author
|
|
310
|
+
|
|
311
|
+
Angel Daniel Sanchez Castillo - angeldaniel.sanchezcastillo@gmail.com
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
# pgsqlasync2fast-fastapi
|
|
2
|
+
|
|
3
|
+
Simple and fast PostgreSQL async module for FastAPI with multi-database support and automatic database creation.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- ✅ **Multiple Database Connections**: Configure and manage multiple PostgreSQL databases
|
|
8
|
+
- ✅ **Async Support**: Built on SQLAlchemy 2.0+ async engine with asyncpg
|
|
9
|
+
- ✅ **Database Creation**: Automatic database creation with superuser support
|
|
10
|
+
- ✅ **FastAPI Integration**: Ready-to-use dependencies for seamless FastAPI integration
|
|
11
|
+
- ✅ **Connection Pooling**: Configurable connection pools per database
|
|
12
|
+
- ✅ **Health Checks**: Built-in connection health monitoring
|
|
13
|
+
- ✅ **Lazy Loading**: Engines created only when needed
|
|
14
|
+
- ✅ **Type Safe**: Full Pydantic settings with validation
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install pgsqlasync2fast-fastapi
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Quick Start
|
|
23
|
+
|
|
24
|
+
### 1. Configure your databases in `.env`
|
|
25
|
+
|
|
26
|
+
```env
|
|
27
|
+
# Default database connection
|
|
28
|
+
DB_CONNECTIONS__DEFAULT__HOST=localhost
|
|
29
|
+
DB_CONNECTIONS__DEFAULT__PORT=5432
|
|
30
|
+
DB_CONNECTIONS__DEFAULT__USERNAME=myuser
|
|
31
|
+
DB_CONNECTIONS__DEFAULT__PASSWORD=mypassword
|
|
32
|
+
DB_CONNECTIONS__DEFAULT__DATABASE=mydb
|
|
33
|
+
|
|
34
|
+
# Business database connection
|
|
35
|
+
DB_CONNECTIONS__BUSINESS__HOST=localhost
|
|
36
|
+
DB_CONNECTIONS__BUSINESS__PORT=5432
|
|
37
|
+
DB_CONNECTIONS__BUSINESS__USERNAME=business_user
|
|
38
|
+
DB_CONNECTIONS__BUSINESS__PASSWORD=business_password
|
|
39
|
+
DB_CONNECTIONS__BUSINESS__DATABASE=business_db
|
|
40
|
+
|
|
41
|
+
# Admin connection with superuser privileges
|
|
42
|
+
DB_CONNECTIONS__ADMIN__HOST=localhost
|
|
43
|
+
DB_CONNECTIONS__ADMIN__PORT=5432
|
|
44
|
+
DB_CONNECTIONS__ADMIN__USERNAME=postgres
|
|
45
|
+
DB_CONNECTIONS__ADMIN__PASSWORD=postgres_password
|
|
46
|
+
DB_CONNECTIONS__ADMIN__DATABASE=postgres
|
|
47
|
+
DB_CONNECTIONS__ADMIN__IS_SUPERUSER=true
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### 2. Use in FastAPI
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from fastapi import FastAPI, Depends
|
|
54
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
55
|
+
from sqlalchemy import text
|
|
56
|
+
from pgsqlasync2fast_fastapi import (
|
|
57
|
+
get_db_session,
|
|
58
|
+
startup_database,
|
|
59
|
+
shutdown_database
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
app = FastAPI()
|
|
63
|
+
|
|
64
|
+
@app.on_event("startup")
|
|
65
|
+
async def startup():
|
|
66
|
+
await startup_database()
|
|
67
|
+
|
|
68
|
+
@app.on_event("shutdown")
|
|
69
|
+
async def shutdown():
|
|
70
|
+
await shutdown_database()
|
|
71
|
+
|
|
72
|
+
@app.get("/users")
|
|
73
|
+
async def get_users(session: AsyncSession = Depends(get_db_session)):
|
|
74
|
+
result = await session.execute(text("SELECT * FROM users"))
|
|
75
|
+
users = result.fetchall()
|
|
76
|
+
return {"users": users}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### 3. Use Multiple Databases
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from functools import partial
|
|
83
|
+
from fastapi import Depends
|
|
84
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
85
|
+
from pgsqlasync2fast_fastapi import get_db_session
|
|
86
|
+
|
|
87
|
+
# Create dependency for business database
|
|
88
|
+
get_business_session = partial(get_db_session, connection_name="business")
|
|
89
|
+
|
|
90
|
+
@app.get("/business/data")
|
|
91
|
+
async def get_business_data(session: AsyncSession = Depends(get_business_session)):
|
|
92
|
+
result = await session.execute(text("SELECT * FROM business_data"))
|
|
93
|
+
return {"data": result.fetchall()}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### 4. Create Databases Programmatically
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
from pgsqlasync2fast_fastapi import create_database, database_exists
|
|
100
|
+
|
|
101
|
+
# Create a new database (requires a connection with is_superuser=true)
|
|
102
|
+
if not await database_exists("new_database"):
|
|
103
|
+
await create_database("new_database", owner="myuser")
|
|
104
|
+
print("Database created!")
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Configuration
|
|
108
|
+
|
|
109
|
+
### Environment Variables
|
|
110
|
+
|
|
111
|
+
All configuration is done through environment variables with the prefix `DB_`:
|
|
112
|
+
|
|
113
|
+
#### Connection Settings
|
|
114
|
+
|
|
115
|
+
```env
|
|
116
|
+
DB_CONNECTIONS__<NAME>__HOST=localhost # Database host
|
|
117
|
+
DB_CONNECTIONS__<NAME>__PORT=5432 # Database port
|
|
118
|
+
DB_CONNECTIONS__<NAME>__USERNAME=user # Database username
|
|
119
|
+
DB_CONNECTIONS__<NAME>__PASSWORD=pass # Database password
|
|
120
|
+
DB_CONNECTIONS__<NAME>__DATABASE=dbname # Database name
|
|
121
|
+
DB_CONNECTIONS__<NAME>__IS_SUPERUSER=false # Superuser privileges
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
#### Pool Settings (Optional)
|
|
125
|
+
|
|
126
|
+
```env
|
|
127
|
+
DB_CONNECTIONS__<NAME>__POOL_SIZE=5 # Connection pool size
|
|
128
|
+
DB_CONNECTIONS__<NAME>__MAX_OVERFLOW=10 # Max overflow connections
|
|
129
|
+
DB_CONNECTIONS__<NAME>__POOL_TIMEOUT=30 # Pool timeout in seconds
|
|
130
|
+
DB_CONNECTIONS__<NAME>__POOL_RECYCLE=3600 # Recycle connections after seconds
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
#### Global Settings
|
|
134
|
+
|
|
135
|
+
```env
|
|
136
|
+
DB_DEFAULT_CONNECTION=default # Default connection name
|
|
137
|
+
DB_ECHO=false # Global SQLAlchemy echo mode
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## API Reference
|
|
141
|
+
|
|
142
|
+
### Dependencies
|
|
143
|
+
|
|
144
|
+
#### `get_db_session(connection_name: str = "default")`
|
|
145
|
+
|
|
146
|
+
FastAPI dependency that provides an async database session with automatic commit/rollback.
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
@app.get("/items")
|
|
150
|
+
async def get_items(session: AsyncSession = Depends(get_db_session)):
|
|
151
|
+
result = await session.execute(text("SELECT * FROM items"))
|
|
152
|
+
return result.fetchall()
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
#### `get_db_engine(connection_name: str = "default")`
|
|
156
|
+
|
|
157
|
+
FastAPI dependency that provides the async engine for a connection.
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
@app.get("/health")
|
|
161
|
+
async def health_check(engine: AsyncEngine = Depends(get_db_engine)):
|
|
162
|
+
async with engine.connect() as conn:
|
|
163
|
+
await conn.execute(text("SELECT 1"))
|
|
164
|
+
return {"status": "healthy"}
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
#### `get_db_manager()`
|
|
168
|
+
|
|
169
|
+
FastAPI dependency that provides the DatabaseManager singleton.
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
@app.get("/connections")
|
|
173
|
+
async def list_connections(manager: DatabaseManager = Depends(get_db_manager)):
|
|
174
|
+
return {"connections": manager.list_connections()}
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### Database Utilities
|
|
178
|
+
|
|
179
|
+
#### `create_database(database_name: str, owner: Optional[str] = None, connection_name: Optional[str] = None) -> bool`
|
|
180
|
+
|
|
181
|
+
Create a new database using a superuser connection.
|
|
182
|
+
|
|
183
|
+
```python
|
|
184
|
+
created = await create_database("my_new_db", owner="myuser")
|
|
185
|
+
if created:
|
|
186
|
+
print("Database created successfully!")
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
#### `database_exists(database_name: str, connection_name: Optional[str] = None) -> bool`
|
|
190
|
+
|
|
191
|
+
Check if a database exists.
|
|
192
|
+
|
|
193
|
+
```python
|
|
194
|
+
if await database_exists("my_db"):
|
|
195
|
+
print("Database exists!")
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
#### `drop_database(database_name: str, connection_name: Optional[str] = None, force: bool = False) -> bool`
|
|
199
|
+
|
|
200
|
+
Drop a database (requires superuser).
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
dropped = await drop_database("old_db", force=True)
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
#### `list_databases(connection_name: Optional[str] = None) -> List[str]`
|
|
207
|
+
|
|
208
|
+
List all databases.
|
|
209
|
+
|
|
210
|
+
```python
|
|
211
|
+
databases = await list_databases()
|
|
212
|
+
for db in databases:
|
|
213
|
+
print(f" - {db}")
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
### Startup/Shutdown
|
|
217
|
+
|
|
218
|
+
#### `startup_database(config: Optional[DatabaseSettings] = None) -> DatabaseManager`
|
|
219
|
+
|
|
220
|
+
Initialize database connections on application startup.
|
|
221
|
+
|
|
222
|
+
```python
|
|
223
|
+
@app.on_event("startup")
|
|
224
|
+
async def startup():
|
|
225
|
+
await startup_database()
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
#### `shutdown_database() -> None`
|
|
229
|
+
|
|
230
|
+
Close all database connections on application shutdown.
|
|
231
|
+
|
|
232
|
+
```python
|
|
233
|
+
@app.on_event("shutdown")
|
|
234
|
+
async def shutdown():
|
|
235
|
+
await shutdown_database()
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
## Examples
|
|
239
|
+
|
|
240
|
+
See the `examples/` directory for complete working examples:
|
|
241
|
+
|
|
242
|
+
- `basic_usage.py` - Basic database connection and queries
|
|
243
|
+
- `multi_database.py` - Using multiple database connections
|
|
244
|
+
- `fastapi_integration.py` - Complete FastAPI application
|
|
245
|
+
- `database_creation.py` - Creating databases programmatically
|
|
246
|
+
|
|
247
|
+
## License
|
|
248
|
+
|
|
249
|
+
MIT License - see LICENSE file for details.
|
|
250
|
+
|
|
251
|
+
## Author
|
|
252
|
+
|
|
253
|
+
Angel Daniel Sanchez Castillo - angeldaniel.sanchezcastillo@gmail.com
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# ============================================
|
|
2
|
+
# PostgreSQL Database Configuration
|
|
3
|
+
# ============================================
|
|
4
|
+
|
|
5
|
+
# ===== Connection DEFAULT (principal) =====
|
|
6
|
+
# Esta es la conexión por defecto que se usará cuando no especifiques ninguna
|
|
7
|
+
DB_CONNECTIONS__DEFAULT__HOST=localhost
|
|
8
|
+
DB_CONNECTIONS__DEFAULT__PORT=5432
|
|
9
|
+
DB_CONNECTIONS__DEFAULT__USERNAME=myuser
|
|
10
|
+
DB_CONNECTIONS__DEFAULT__PASSWORD=mypassword
|
|
11
|
+
DB_CONNECTIONS__DEFAULT__DATABASE=mydb
|
|
12
|
+
DB_CONNECTIONS__DEFAULT__IS_SUPERUSER=false
|
|
13
|
+
|
|
14
|
+
# Pool settings (opcional, estos son los valores por defecto)
|
|
15
|
+
DB_CONNECTIONS__DEFAULT__POOL_SIZE=5
|
|
16
|
+
DB_CONNECTIONS__DEFAULT__MAX_OVERFLOW=10
|
|
17
|
+
DB_CONNECTIONS__DEFAULT__POOL_TIMEOUT=30
|
|
18
|
+
DB_CONNECTIONS__DEFAULT__POOL_RECYCLE=3600
|
|
19
|
+
|
|
20
|
+
# Echo mode para esta conexión (opcional)
|
|
21
|
+
DB_CONNECTIONS__DEFAULT__ECHO=false
|
|
22
|
+
|
|
23
|
+
# ===== Connection BUSINESS (ejemplo de segunda conexión) =====
|
|
24
|
+
# Para usar esta conexión, especifica connection_name="business" en tus dependencias
|
|
25
|
+
DB_CONNECTIONS__BUSINESS__HOST=localhost
|
|
26
|
+
DB_CONNECTIONS__BUSINESS__PORT=5432
|
|
27
|
+
DB_CONNECTIONS__BUSINESS__USERNAME=business_user
|
|
28
|
+
DB_CONNECTIONS__BUSINESS__PASSWORD=business_password
|
|
29
|
+
DB_CONNECTIONS__BUSINESS__DATABASE=business_db
|
|
30
|
+
DB_CONNECTIONS__BUSINESS__IS_SUPERUSER=false
|
|
31
|
+
|
|
32
|
+
# ===== Connection ADMIN (ejemplo con superusuario) =====
|
|
33
|
+
# Esta conexión tiene privilegios de superusuario para crear/eliminar bases de datos
|
|
34
|
+
DB_CONNECTIONS__ADMIN__HOST=localhost
|
|
35
|
+
DB_CONNECTIONS__ADMIN__PORT=5432
|
|
36
|
+
DB_CONNECTIONS__ADMIN__USERNAME=postgres
|
|
37
|
+
DB_CONNECTIONS__ADMIN__PASSWORD=postgres_password
|
|
38
|
+
DB_CONNECTIONS__ADMIN__DATABASE=postgres
|
|
39
|
+
DB_CONNECTIONS__ADMIN__IS_SUPERUSER=true
|
|
40
|
+
|
|
41
|
+
# ============================================
|
|
42
|
+
# General Settings
|
|
43
|
+
# ============================================
|
|
44
|
+
|
|
45
|
+
# Conexión por defecto cuando no se especifica ninguna
|
|
46
|
+
# Opciones: "default", "business", "admin", o cualquier otra que hayas configurado
|
|
47
|
+
DB_DEFAULT_CONNECTION=default
|
|
48
|
+
|
|
49
|
+
# Echo mode global (puede ser sobrescrito por cada conexión)
|
|
50
|
+
DB_ECHO=false
|