munch-ease-backend/persons/db.py

56 lines
1.5 KiB
Python
Raw Normal View History

2024-01-13 07:18:25 +00:00
from pydantic import BaseModel
2024-04-25 02:03:30 +00:00
from typing import List
2024-01-13 07:18:25 +00:00
class Person(BaseModel):
id: int
name: str
async def create(conn):
2024-01-13 08:44:07 +00:00
await conn.execute('''
CREATE TABLE IF NOT EXISTS Person (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE
);''')
2024-04-25 02:03:30 +00:00
await insert(conn, Person(id=0, name='Jacob'))
await insert(conn, Person(id=0, name='Ellie'))
await insert(conn, Person(id=0, name='Ryan'))
await insert(conn, Person(id=0, name='Chris'))
async def get_by_name(conn, name: str) -> Person:
cursor = await conn.execute('''
SELECT id, name
FROM Person
WHERE name = ?
''', (name,))
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
2024-01-13 08:44:07 +00:00
async def get_by_id(conn, id: int) -> Person:
cursor = await conn.execute('''
SELECT id, name
FROM Person
WHERE id = ?
''', (id,))
row = await cursor.fetchone()
if not row:
return None
return Person(id=row[0], name=row[1])
async def get_all(conn) -> List[Person]:
async with conn.execute('''
SELECT id, name
FROM Person
''') as cursor:
async for row in cursor:
yield Person(id=row[0], name=row[1])
async def insert(conn, person: Person) -> Person:
cursor = await conn.execute('''
INSERT INTO Person (name)
VALUES (?)
''', (person.name,))
person.id = cursor.lastrowid
return person