munch-ease-backend/persons/db.py

87 lines
1.8 KiB
Python
Raw Normal View History

2025-10-18 03:26:42 +00:00
from typing import AsyncIterator, ClassVar, List, Optional
2024-01-13 07:18:25 +00:00
from pydantic import BaseModel
2025-10-18 03:26:42 +00:00
2024-01-13 07:18:25 +00:00
class Person(BaseModel):
2025-10-18 03:26:42 +00:00
KEYS: ClassVar[List[str]] = ["id", "name"]
2024-05-17 09:09:03 +00:00
2024-05-20 10:09:57 +00:00
id: int = -1
2024-01-13 07:18:25 +00:00
name: str
2025-10-18 03:26:42 +00:00
2024-01-13 07:18:25 +00:00
async def create(conn):
2025-10-18 03:26:42 +00:00
await conn.execute(
"""
2024-01-13 08:44:07 +00:00
CREATE TABLE IF NOT EXISTS Person (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE
2025-10-18 03:26:42 +00:00
);"""
)
2024-04-25 02:03:30 +00:00
2024-05-13 03:59:46 +00:00
async def search_by_name(conn, name: str) -> AsyncIterator[Person]:
2025-10-18 03:26:42 +00:00
async with conn.execute(
"""
2024-05-04 04:22:19 +00:00
SELECT id, name
FROM Person
WHERE name LIKE ?
2025-10-18 03:26:42 +00:00
""",
(f"%{name}%",),
) as cursor:
2024-05-04 04:22:19 +00:00
async for row in cursor:
yield Person(id=row[0], name=row[1])
2025-10-18 03:26:42 +00:00
async def get_by_name(conn, name: str) -> Optional[Person]:
cursor = await conn.execute(
"""
2024-04-25 02:03:30 +00:00
SELECT id, name
FROM Person
WHERE name = ?
2025-10-18 03:26:42 +00:00
""",
(name,),
)
2024-04-25 02:03:30 +00:00
row = await cursor.fetchone()
if not row:
return None
return Person(id=row[0], name=row[1])
2024-01-13 07:18:25 +00:00
2025-10-18 03:26:42 +00:00
async def get_by_id(conn, id: int) -> Optional[Person]:
cursor = await conn.execute(
"""
2024-01-13 08:44:07 +00:00
SELECT id, name
FROM Person
WHERE id = ?
2025-10-18 03:26:42 +00:00
""",
(id,),
)
2024-01-13 08:44:07 +00:00
row = await cursor.fetchone()
if not row:
return None
return Person(id=row[0], name=row[1])
2025-10-18 03:26:42 +00:00
2024-05-13 03:59:46 +00:00
async def get_all(conn) -> AsyncIterator[Person]:
2025-10-18 03:26:42 +00:00
async with conn.execute(
"""
2024-01-13 08:44:07 +00:00
SELECT id, name
FROM Person
2025-10-18 03:26:42 +00:00
"""
) as cursor:
2024-01-13 08:44:07 +00:00
async for row in cursor:
yield Person(id=row[0], name=row[1])
2025-10-18 03:26:42 +00:00
2024-04-28 03:37:01 +00:00
async def insert_person(conn, person: Person) -> Person:
2025-10-18 03:26:42 +00:00
cursor = await conn.execute(
"""
2024-01-13 08:44:07 +00:00
INSERT INTO Person (name)
VALUES (?)
2025-10-18 03:26:42 +00:00
""",
(person.name,),
)
2024-01-13 08:44:07 +00:00
person.id = cursor.lastrowid
2025-10-18 03:26:42 +00:00
return person