Hfzune commited on
Commit
6db335b
·
verified ·
1 Parent(s): e419ba3

Create db/models.py

Browse files
Files changed (1) hide show
  1. db/models.py +279 -0
db/models.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import secrets
3
+ import sqlite3
4
+ import logging
5
+ from datetime import datetime, timezone
6
+
7
+ from db.init import get_conn
8
+
9
+ log = logging.getLogger("db.models")
10
+
11
+
12
+ def now_iso():
13
+ return datetime.now(timezone.utc).isoformat()
14
+
15
+
16
+ # ---------------- Users ----------------
17
+
18
+ def get_user(user_id: int):
19
+ with get_conn() as conn:
20
+ row = conn.execute(
21
+ "SELECT * FROM users WHERE user_id = ?", (user_id,)
22
+ ).fetchone()
23
+ return dict(row) if row else None
24
+
25
+
26
+ def upsert_user(user_id: int, username: str = None, first_name: str = None):
27
+ with get_conn() as conn:
28
+ existing = conn.execute(
29
+ "SELECT user_id FROM users WHERE user_id = ?", (user_id,)
30
+ ).fetchone()
31
+ if existing:
32
+ conn.execute(
33
+ "UPDATE users SET username=?, first_name=?, last_seen=? WHERE user_id=?",
34
+ (username, first_name, now_iso(), user_id),
35
+ )
36
+ else:
37
+ conn.execute(
38
+ """INSERT INTO users(user_id, username, first_name, created_at, last_seen)
39
+ VALUES (?, ?, ?, ?, ?)""",
40
+ (user_id, username, first_name, now_iso(), now_iso()),
41
+ )
42
+
43
+
44
+ def bind_token(user_id: int, token: str) -> bool:
45
+ with get_conn() as conn:
46
+ # token must exist and be unassigned (or already bound to this user)
47
+ row = conn.execute(
48
+ "SELECT * FROM tokens WHERE token = ?", (token,)
49
+ ).fetchone()
50
+ if not row:
51
+ return False
52
+ if not row["is_active"]:
53
+ return False
54
+ if row["assigned_to"] not in (None, user_id):
55
+ return False
56
+
57
+ conn.execute(
58
+ "UPDATE tokens SET assigned_to=? WHERE token=?", (user_id, token)
59
+ )
60
+ conn.execute(
61
+ "UPDATE users SET token=?, is_active=1 WHERE user_id=?",
62
+ (token, user_id),
63
+ )
64
+ return True
65
+
66
+
67
+ def user_has_valid_token(user_id: int) -> bool:
68
+ with get_conn() as conn:
69
+ row = conn.execute(
70
+ """SELECT u.is_active AS u_active, t.is_active AS t_active
71
+ FROM users u LEFT JOIN tokens t ON u.token = t.token
72
+ WHERE u.user_id = ?""",
73
+ (user_id,),
74
+ ).fetchone()
75
+ if not row:
76
+ return False
77
+ return bool(row["u_active"]) and bool(row["t_active"])
78
+
79
+
80
+ def revoke_user(user_id: int):
81
+ with get_conn() as conn:
82
+ conn.execute("UPDATE users SET is_active=0 WHERE user_id=?", (user_id,))
83
+ conn.execute(
84
+ "UPDATE tokens SET is_active=0 WHERE assigned_to=?", (user_id,)
85
+ )
86
+
87
+
88
+ def delete_user(user_id: int):
89
+ with get_conn() as conn:
90
+ conn.execute("DELETE FROM conversations WHERE user_id=?", (user_id,))
91
+ conn.execute("DELETE FROM users WHERE user_id=?", (user_id,))
92
+ conn.execute(
93
+ "UPDATE tokens SET assigned_to=NULL, is_active=0 WHERE assigned_to=?",
94
+ (user_id,),
95
+ )
96
+
97
+
98
+ def increment_user_turns(user_id: int):
99
+ with get_conn() as conn:
100
+ conn.execute(
101
+ "UPDATE users SET total_turns = total_turns + 1 WHERE user_id=?",
102
+ (user_id,),
103
+ )
104
+
105
+
106
+ # ---------------- Tokens ----------------
107
+
108
+ def generate_token(assigned_to: int = None) -> str:
109
+ tok = secrets.token_urlsafe(24)
110
+ with get_conn() as conn:
111
+ conn.execute(
112
+ """INSERT INTO tokens(token, assigned_to, created_at)
113
+ VALUES (?, ?, ?)""",
114
+ (tok, assigned_to, now_iso()),
115
+ )
116
+ if assigned_to is not None:
117
+ conn.execute(
118
+ "UPDATE users SET token=?, is_active=1 WHERE user_id=?",
119
+ (tok, assigned_to),
120
+ )
121
+ return tok
122
+
123
+
124
+ def list_tokens():
125
+ with get_conn() as conn:
126
+ rows = conn.execute(
127
+ "SELECT * FROM tokens ORDER BY created_at DESC"
128
+ ).fetchall()
129
+ return [dict(r) for r in rows]
130
+
131
+
132
+ def revoke_token(token: str):
133
+ with get_conn() as conn:
134
+ conn.execute("UPDATE tokens SET is_active=0 WHERE token=?", (token,))
135
+ conn.execute(
136
+ "UPDATE users SET is_active=0 WHERE token=?", (token,)
137
+ )
138
+
139
+
140
+ def reassign_token(token: str, new_user_id: int):
141
+ with get_conn() as conn:
142
+ conn.execute(
143
+ "UPDATE tokens SET assigned_to=? WHERE token=?", (new_user_id, token)
144
+ )
145
+ conn.execute(
146
+ "UPDATE users SET token=?, is_active=1 WHERE user_id=?",
147
+ (token, new_user_id),
148
+ )
149
+
150
+
151
+ def bump_token_use(token: str):
152
+ with get_conn() as conn:
153
+ conn.execute(
154
+ """UPDATE tokens SET turns_used = turns_used + 1,
155
+ last_used = ?
156
+ WHERE token = ?""",
157
+ (now_iso(), token),
158
+ )
159
+
160
+
161
+ # ---------------- Conversations ----------------
162
+
163
+ def add_message(user_id: int, role: str, content: str,
164
+ latency_ms: int = None, gpu_time_ms: int = None):
165
+ with get_conn() as conn:
166
+ conn.execute(
167
+ """INSERT INTO conversations
168
+ (user_id, role, content, timestamp, latency_ms, gpu_time_ms)
169
+ VALUES (?, ?, ?, ?, ?, ?)""",
170
+ (user_id, role, content, now_iso(), latency_ms, gpu_time_ms),
171
+ )
172
+
173
+
174
+ def get_history(user_id: int, limit_turns: int = 6):
175
+ """Return last N turns (2*N messages) in chronological order."""
176
+ with get_conn() as conn:
177
+ rows = conn.execute(
178
+ """SELECT role, content FROM conversations
179
+ WHERE user_id = ?
180
+ ORDER BY id DESC LIMIT ?""",
181
+ (user_id, limit_turns * 2),
182
+ ).fetchall()
183
+ rows = list(reversed(rows))
184
+ return [{"role": r["role"], "content": r["content"]} for r in rows]
185
+
186
+
187
+ def clear_history(user_id: int):
188
+ with get_conn() as conn:
189
+ conn.execute("DELETE FROM conversations WHERE user_id=?", (user_id,))
190
+
191
+
192
+ def list_users():
193
+ with get_conn() as conn:
194
+ rows = conn.execute(
195
+ "SELECT * FROM users ORDER BY created_at DESC"
196
+ ).fetchall()
197
+ return [dict(r) for r in rows]
198
+
199
+
200
+ def list_conversations(user_id: int = None, limit: int = 500):
201
+ with get_conn() as conn:
202
+ if user_id:
203
+ rows = conn.execute(
204
+ """SELECT * FROM conversations WHERE user_id=?
205
+ ORDER BY id DESC LIMIT ?""",
206
+ (user_id, limit),
207
+ ).fetchall()
208
+ else:
209
+ rows = conn.execute(
210
+ "SELECT * FROM conversations ORDER BY id DESC LIMIT ?",
211
+ (limit,),
212
+ ).fetchall()
213
+ return [dict(r) for r in rows]
214
+
215
+
216
+ def stats():
217
+ with get_conn() as conn:
218
+ total_users = conn.execute("SELECT COUNT(*) c FROM users").fetchone()["c"]
219
+ active_users = conn.execute(
220
+ "SELECT COUNT(*) c FROM users WHERE is_active=1"
221
+ ).fetchone()["c"]
222
+ total_msgs = conn.execute(
223
+ "SELECT COUNT(*) c FROM conversations"
224
+ ).fetchone()["c"]
225
+ today = datetime.now(timezone.utc).date().isoformat()
226
+ today_msgs = conn.execute(
227
+ "SELECT COUNT(*) c FROM conversations WHERE timestamp LIKE ?",
228
+ (today + "%",),
229
+ ).fetchone()["c"]
230
+ return {
231
+ "total_users": total_users,
232
+ "active_users": active_users,
233
+ "total_messages": total_msgs,
234
+ "messages_today": today_msgs,
235
+ }
236
+
237
+
238
+ # ---------------- Settings ----------------
239
+
240
+ def get_setting(key: str, default=None):
241
+ with get_conn() as conn:
242
+ row = conn.execute(
243
+ "SELECT value FROM settings WHERE key=?", (key,)
244
+ ).fetchone()
245
+ return row["value"] if row else default
246
+
247
+
248
+ def set_setting(key: str, value: str):
249
+ with get_conn() as conn:
250
+ conn.execute(
251
+ "INSERT INTO settings(key, value) VALUES (?, ?) "
252
+ "ON CONFLICT(key) DO UPDATE SET value=excluded.value",
253
+ (key, str(value)),
254
+ )
255
+
256
+
257
+ def all_settings():
258
+ with get_conn() as conn:
259
+ rows = conn.execute("SELECT key, value FROM settings").fetchall()
260
+ return {r["key"]: r["value"] for r in rows}
261
+
262
+
263
+ # ---------------- GPU log ----------------
264
+
265
+ def log_gpu(user_id: int, duration_ms: int, status: str):
266
+ with get_conn() as conn:
267
+ conn.execute(
268
+ """INSERT INTO gpu_log(user_id, timestamp, duration_ms, status)
269
+ VALUES (?, ?, ?, ?)""",
270
+ (user_id, now_iso(), duration_ms, status),
271
+ )
272
+
273
+
274
+ def recent_gpu_log(limit: int = 50):
275
+ with get_conn() as conn:
276
+ rows = conn.execute(
277
+ "SELECT * FROM gpu_log ORDER BY id DESC LIMIT ?", (limit,)
278
+ ).fetchall()
279
+ return [dict(r) for r in rows]