-
Notifications
You must be signed in to change notification settings - Fork 1
/
db_operations.py
94 lines (79 loc) · 2.5 KB
/
db_operations.py
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import sqlite3
import threading
from datetime import datetime
thread_local = threading.local()
def get_db_connection():
if not hasattr(thread_local, "connection"):
thread_local.connection = sqlite3.connect(database="messages.db", check_same_thread=False)
return thread_local.connection
def initialize_database():
conn = get_db_connection()
c = conn.cursor()
c.execute(
"""CREATE TABLE IF NOT EXISTS message (
id INTEGER PRIMARY KEY AUTOINCREMENT,
message_id INTEGER NOT NULL,
sender TEXT NOT NULL,
sender_short_name TEXT NOT NULL,
sender_long_name TEXT NOT NULL,
reply_id INTEGER NOT NULL,
channel INTEGER NOT NULL,
date TEXT NOT NULL,
content TEXT NOT NULL
);"""
)
c.execute(
"""CREATE TABLE IF NOT EXISTS channels (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
url TEXT NOT NULL
);"""
)
conn.commit()
print("Database schema initialized.")
def add_channel(name, url):
conn = get_db_connection()
c = conn.cursor()
c.execute("INSERT INTO channels (name, url) VALUES (?, ?)", (name, url))
conn.commit()
def get_channels():
conn = get_db_connection()
c = conn.cursor()
c.execute("SELECT name, url FROM channels")
return c.fetchall()
def add_message(
message_id,
sender_id,
sender_short_name,
sender_long_name,
reply_id,
channel,
content,
):
conn = get_db_connection()
c = conn.cursor()
date = datetime.now().strftime("%Y-%m-%d %H:%M")
c.execute(
"INSERT INTO message (message_id, sender, sender_short_name, sender_long_name, reply_id, "
"channel, date, content) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
(
message_id,
sender_id,
sender_short_name,
sender_long_name,
reply_id,
channel,
date,
content,
),
)
return conn.commit()
def get_messages(top: int = 5):
conn = get_db_connection()
c = conn.cursor()
c.execute(
"SELECT id, sender_short_name, sender_long_name, date, channel, "
"content FROM message ORDER BY date DESC LIMIT ?",
(top,),
)
return c.fetchall()