49 lines
1.9 KiB
Python
49 lines
1.9 KiB
Python
import sqlite3
|
|
from dataclasses import dataclass
|
|
from typing import Optional, List
|
|
|
|
@dataclass
|
|
class ParticipantModel:
|
|
conversation_id: Optional[int] = None
|
|
user_id: Optional[int] = None
|
|
joined_at: Optional[str] = None
|
|
|
|
class Participants:
|
|
def __init__(self, db_path="instance/app_database.db"):
|
|
self.db_path = db_path
|
|
self._create_tables()
|
|
|
|
def _create_tables(self):
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
cursor = conn.cursor()
|
|
cursor.execute("""
|
|
CREATE TABLE IF NOT EXISTS participants (
|
|
conversation_id INTEGER,
|
|
user_id INTEGER,
|
|
joined_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
PRIMARY KEY (conversation_id, user_id),
|
|
FOREIGN KEY (conversation_id) REFERENCES conversations(id) ON DELETE CASCADE,
|
|
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
);
|
|
""")
|
|
conn.commit()
|
|
|
|
def add_user(self, conversation_id: int, user_id: int):
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
conn.execute(
|
|
"INSERT OR IGNORE INTO participants (conversation_id, user_id) VALUES (?, ?)",
|
|
(conversation_id, user_id)
|
|
)
|
|
|
|
def get_conversation_members(self, conversation_id: int) -> List[int]:
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
cursor = conn.cursor()
|
|
cursor.execute("SELECT user_id FROM participants WHERE conversation_id = ?", (conversation_id,))
|
|
return [row[0] for row in cursor.fetchall()]
|
|
|
|
def remove_user(self, conversation_id: int, user_id: int):
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
conn.execute(
|
|
"DELETE FROM participants WHERE conversation_id = ? AND user_id = ?",
|
|
(conversation_id, user_id)
|
|
) |