-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
68 lines (62 loc) · 1.83 KB
/
Copy pathdb.py
File metadata and controls
68 lines (62 loc) · 1.83 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import sqlite3
import os
from datetime import datetime
DB_PATH = "db/data.db"
os.makedirs("db", exist_ok=True)
def get_connection():
return sqlite3.connect(DB_PATH)
def init_db():
conn = get_connection()
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
original TEXT,
summary TEXT,
tags TEXT,
sentiment TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
conn.close()
def save_history(user_id, original, summary, tags, sentiment):
conn = get_connection()
cur = conn.cursor()
cur.execute("""
INSERT INTO history (user_id, original, summary, tags, sentiment)
VALUES (?, ?, ?, ?, ?)
""", (user_id, original, summary, tags, sentiment))
conn.commit()
conn.close()
def get_user_history(user_id, limit=20):
conn = get_connection()
cur = conn.cursor()
cur.execute("""
SELECT original, summary, tags, sentiment, created_at
FROM history
WHERE user_id = ?
ORDER BY created_at DESC
LIMIT ?
""", (user_id, limit))
rows = cur.fetchall()
conn.close()
return rows
def enforce_history_limit(user_id, max_entries=20):
conn = get_connection()
cur = conn.cursor()
cur.execute("SELECT COUNT(*) FROM history WHERE user_id = ?", (user_id,))
count = cur.fetchone()[0]
if count >= max_entries:
to_delete = count - max_entries + 1
cur.execute("""
DELETE FROM history
WHERE id IN (
SELECT id FROM history WHERE user_id = ?
ORDER BY created_at ASC
LIMIT ?
)
""", (user_id, to_delete))
conn.commit()
conn.close()