feat(api+testing): select todos + testing

This commit is contained in:
2024-03-02 16:53:00 -05:00
parent 1a6469efa5
commit e92254cdaf
3 changed files with 83 additions and 1 deletions

View File

@@ -44,7 +44,25 @@ def generate_test_data() -> None:
sql.SQL(
"""
INSERT INTO todos (member_id, task)
VALUES (1, 'Test Task')
VALUES (1, 'Test Task 1')
"""
)
)
cur.execute(
sql.SQL(
"""
INSERT INTO todos (member_id, task)
VALUES (1, 'Test Task 2')
"""
)
)
cur.execute(
sql.SQL(
"""
INSERT INTO todos (member_id, task)
VALUES (1, 'Test Task 3')
"""
)
)

View File

@@ -0,0 +1,45 @@
from dataclasses import dataclass
from datetime import datetime
from psycopg import sql
from psycopg.rows import class_row
from psycopg_pool import AsyncConnectionPool
from pydantic import constr
@dataclass
class Todo:
complete: bool
due: datetime | None
id: int
task: constr(strip_whitespace=True, min_length=1) # type: ignore
async def select_todos(
db: AsyncConnectionPool, member_id: int, complete: bool | None = None
) -> list[Todo]:
async with db.connection() as conn:
async with conn.cursor(row_factory=class_row(Todo)) as curr:
if complete is None:
condition = sql.SQL("member_id = {}").format(sql.Literal(member_id))
else:
condition = sql.SQL("member_id = {} AND complete = {}").format(
sql.Literal(member_id), sql.Literal(complete)
)
query = sql.SQL(
"""
SELECT id, complete, due, task
FROM todos
WHERE {}
"""
).format(condition)
await curr.execute(
query,
)
todos = await curr.fetchall()
return todos