-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
53 lines (47 loc) · 1.54 KB
/
database.py
File metadata and controls
53 lines (47 loc) · 1.54 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# database.py
import asyncpg
from config import DATABASE_URI
async def init_database():
conn = await asyncpg.connect(DATABASE_URI)
await conn.execute('''
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
user_id BIGINT UNIQUE NOT NULL
);
''')
await conn.execute('''
CREATE TABLE IF NOT EXISTS groups (
id SERIAL PRIMARY KEY,
group_id BIGINT UNIQUE NOT NULL
);
''')
await conn.close()
async def add_user(user_id):
conn = await asyncpg.connect(DATABASE_URI)
await conn.execute('''
INSERT INTO users (user_id)
VALUES ($1)
ON CONFLICT (user_id) DO NOTHING;
''', user_id)
await conn.close()
async def add_group(group_id):
conn = await asyncpg.connect(DATABASE_URI)
await conn.execute('''
INSERT INTO groups (group_id)
VALUES ($1)
ON CONFLICT (group_id) DO NOTHING;
''', group_id)
await conn.close()
async def get_users():
conn = await asyncpg.connect(DATABASE_URI)
users = await conn.fetch('SELECT user_id FROM users;')
await conn.close()
return [user['user_id'] for user in users]
async def get_groups():
conn = await asyncpg.connect(DATABASE_URI)
groups = await conn.fetch('SELECT group_id FROM groups;')
await conn.close()
return [group['group_id'] for group in groups]
# Initialize the database when this module is imported
import asyncio
asyncio.get_event_loop().run_until_complete(init_database())