-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #128 from hotosm/feat/psycopg-pydantic
Replace encode/databases with psycopg & pydantic model validation
- Loading branch information
Showing
37 changed files
with
2,237 additions
and
2,347 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -43,7 +43,6 @@ db.sqlite3 | |
|
||
# ignore python environments | ||
venv | ||
fmtm-env | ||
|
||
# project related | ||
temp_webmaps/local_only | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,32 +1,73 @@ | ||
"""Config for the DTM database connection.""" | ||
|
||
from databases import Database | ||
from typing import AsyncGenerator | ||
from fastapi import Request | ||
from psycopg import Connection | ||
from psycopg_pool import AsyncConnectionPool | ||
from app.config import settings | ||
|
||
|
||
class DatabaseConnection: | ||
"""Manages database connection (sqlalchemy & encode databases)""" | ||
async def get_db_connection_pool() -> AsyncConnectionPool: | ||
"""Get the connection pool for psycopg.""" | ||
return AsyncConnectionPool(conninfo=settings.DTM_DB_URL.unicode_string()) | ||
|
||
def __init__(self): | ||
self.database = Database( | ||
settings.DTM_DB_URL.unicode_string(), | ||
min_size=5, | ||
max_size=20, | ||
) | ||
|
||
async def connect(self): | ||
"""Connect to the database.""" | ||
await self.database.connect() | ||
async def get_db(request: Request) -> AsyncGenerator[Connection, None]: | ||
"""Get a connection from the psycopg pool. | ||
async def disconnect(self): | ||
"""Disconnect from the database.""" | ||
await self.database.disconnect() | ||
Info on connections vs cursors: | ||
https://www.psycopg.org/psycopg3/docs/advanced/async.html | ||
Here we are getting a connection from the pool, which will be returned | ||
after the session ends / endpoint finishes processing. | ||
db_connection = DatabaseConnection() | ||
In summary: | ||
- Connection is created on endpoint call. | ||
- Cursors are used to execute commands throughout endpoint. | ||
Note it is possible to create multiple cursors from the connection, | ||
but all will be executed in the same db 'transaction'. | ||
- Connection is closed on endpoint finish. | ||
----------------------------------- | ||
To use the connection in endpoints: | ||
----------------------------------- | ||
async def get_db(): | ||
"""Get the encode database connection""" | ||
await db_connection.connect() | ||
yield db_connection.database | ||
@app.get("/something/") | ||
async def do_stuff(db = Depends(get_db)): | ||
async with db.cursor() as cursor: | ||
await cursor.execute("SELECT * FROM items") | ||
result = await cursor.fetchall() | ||
return result | ||
----------------------------------- | ||
Additionally, the connection could be passed through to a function to | ||
utilise the Pydantic model serialisation on the cursor: | ||
----------------------------------- | ||
from psycopg.rows import class_row | ||
async def get_user_by_id(db: Connection, id: int): | ||
async with conn.cursor(row_factory=class_row(User)) as cur: | ||
await cur.execute( | ||
''' | ||
SELECT id, first_name, last_name, dob | ||
FROM (VALUES | ||
(1, 'John', 'Doe', '2000-01-01'::date), | ||
(2, 'Jane', 'White', NULL) | ||
) AS data (id, first_name, last_name, dob) | ||
WHERE id = %(id)s; | ||
''', | ||
{"id": id}, | ||
) | ||
obj = await cur.fetchone() | ||
# reveal_type(obj) would return 'Optional[User]' here | ||
if not obj: | ||
raise KeyError(f"user {id} not found") | ||
# reveal_type(obj) would return 'User' here | ||
return obj | ||
""" | ||
async with request.app.state.db_pool.connection() as conn: | ||
yield conn |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
from typing import Annotated | ||
from fastapi import Depends, HTTPException, Path | ||
from psycopg import Connection | ||
from app.db import database | ||
from app.drones.drone_schemas import DbDrone | ||
from app.models.enums import HTTPStatus | ||
|
||
|
||
async def get_drone_by_id( | ||
drone_id: Annotated[ | ||
int, | ||
Path(description="Drone ID."), | ||
], | ||
db: Annotated[Connection, Depends(database.get_db)], | ||
) -> DbDrone: | ||
"""Get a single project by id.""" | ||
try: | ||
return await DbDrone.one(db, drone_id) | ||
except KeyError as e: | ||
raise HTTPException(status_code=HTTPStatus.NOT_FOUND) from e |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.