MCPcopy
hub / github.com/PromtEngineer/localGPT / ChatDatabase

Class ChatDatabase

backend/database.py:7–637  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5from typing import List, Dict, Optional, Tuple
6
7class ChatDatabase:
8 def __init__(self, db_path: str = None):
9 if db_path is None:
10 # Auto-detect environment and set appropriate path
11 import os
12 if os.path.exists("/app"): # Docker environment
13 self.db_path = "/app/backend/chat_data.db"
14 else: # Local development environment
15 self.db_path = "backend/chat_data.db"
16 else:
17 self.db_path = db_path
18 self.init_database()
19
20 def init_database(self):
21 """Initialize the SQLite database with required tables"""
22 conn = sqlite3.connect(self.db_path)
23 cursor = conn.cursor()
24
25 # Enable foreign keys
26 conn.execute("PRAGMA foreign_keys = ON")
27
28 # Sessions table
29 conn.execute('''
30 CREATE TABLE IF NOT EXISTS sessions (
31 id TEXT PRIMARY KEY,
32 title TEXT NOT NULL,
33 created_at TEXT NOT NULL,
34 updated_at TEXT NOT NULL,
35 model_used TEXT NOT NULL,
36 message_count INTEGER DEFAULT 0
37 )
38 ''')
39
40 # Messages table
41 conn.execute('''
42 CREATE TABLE IF NOT EXISTS messages (
43 id TEXT PRIMARY KEY,
44 session_id TEXT NOT NULL,
45 content TEXT NOT NULL,
46 sender TEXT NOT NULL CHECK (sender IN ('user', 'assistant')),
47 timestamp TEXT NOT NULL,
48 metadata TEXT DEFAULT '{}',
49 FOREIGN KEY (session_id) REFERENCES sessions (id) ON DELETE CASCADE
50 )
51 ''')
52
53 # Create indexes for better performance
54 conn.execute('CREATE INDEX IF NOT EXISTS idx_messages_session_id ON messages(session_id)')
55 conn.execute('CREATE INDEX IF NOT EXISTS idx_messages_timestamp ON messages(timestamp)')
56 conn.execute('CREATE INDEX IF NOT EXISTS idx_sessions_updated_at ON sessions(updated_at)')
57
58 # Documents table
59 conn.execute('''
60 CREATE TABLE IF NOT EXISTS session_documents (
61 id INTEGER PRIMARY KEY AUTOINCREMENT,
62 session_id TEXT NOT NULL,
63 file_path TEXT NOT NULL,
64 indexed INTEGER DEFAULT 0,

Callers 4

__init__Method · 0.90
__init__Method · 0.90
api_server.pyFile · 0.90
database.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected