-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
37 lines (28 loc) · 946 Bytes
/
database.py
File metadata and controls
37 lines (28 loc) · 946 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import os
import asyncpg
pool: asyncpg.Pool | None = None
async def connect() -> asyncpg.Pool:
global pool
database_url = os.getenv("DATABASE_URL", "")
if not database_url:
database_url = (
f"postgres://{os.getenv('PGUSER', 'postgres')}:{os.getenv('PGPASSWORD', '')}"
f"@{os.getenv('PGHOST', 'localhost')}:{os.getenv('PGPORT', '5432')}"
f"/{os.getenv('PGDATABASE', 'postgres')}"
)
pool = await asyncpg.create_pool(database_url)
return pool
async def migrate(db_pool: asyncpg.Pool) -> None:
await db_pool.execute("""
CREATE TABLE IF NOT EXISTS todos (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
completed BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
""")
async def close() -> None:
global pool
if pool:
await pool.close()
pool = None