Repository navigation
Expand file tree
/
Copy pathdatabase.py
More file actions
343 lines (299 loc) · 11.8 KB
/
Copy pathdatabase.py
File metadata and controls
343 lines (299 loc) · 11.8 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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
"""Vera Web — MySQL veritabanı katmanı.
Uygulama açılışında veritabanını ve tabloları otomatik oluşturur.
"""
import mysql.connector
from mysql.connector import pooling
from werkzeug.security import generate_password_hash, check_password_hash
import config
_pool = None
# ─────────────────────────────────────────────────────────
# Kurulum
# ─────────────────────────────────────────────────────────
def init_db():
"""vera_db veritabanını ve tabloları yoksa oluşturur, bağlantı havuzunu kurar."""
# 1) Sunucuya (veritabanı seçmeden) bağlan ve veritabanını oluştur
server = mysql.connector.connect(
host=config.DB_HOST, port=config.DB_PORT,
user=config.DB_USER, password=config.DB_PASSWORD,
)
cur = server.cursor()
cur.execute(
f"CREATE DATABASE IF NOT EXISTS {config.DB_NAME} "
"CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
)
server.commit()
cur.close()
server.close()
# 2) Bağlantı havuzunu vera_db üzerinde kur
global _pool
_pool = pooling.MySQLConnectionPool(
pool_name="vera_pool", pool_size=8,
host=config.DB_HOST, port=config.DB_PORT,
user=config.DB_USER, password=config.DB_PASSWORD,
database=config.DB_NAME, charset="utf8mb4",
)
# 3) Tabloları oluştur
conn = _pool.get_connection()
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(80) NOT NULL,
email VARCHAR(160) NOT NULL UNIQUE,
password VARCHAR(255) NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# users tablosuna avatar sütunu (sonradan eklendi) — yoksa ekle
cur.execute("""
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = %s AND table_name = 'users' AND column_name = 'avatar'
""", (config.DB_NAME,))
if cur.fetchone()[0] == 0:
cur.execute("ALTER TABLE users ADD COLUMN avatar VARCHAR(500) DEFAULT NULL")
# users tablosuna google_id sütunu (Google ile Giriş için) — yoksa ekle
cur.execute("""
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = %s AND table_name = 'users' AND column_name = 'google_id'
""", (config.DB_NAME,))
if cur.fetchone()[0] == 0:
cur.execute("ALTER TABLE users ADD COLUMN google_id VARCHAR(64) DEFAULT NULL UNIQUE")
# eski kurulumlarda password NOT NULL olabilir — Google hesapları şifresiz olduğu için gevşet
cur.execute("""
SELECT IS_NULLABLE FROM information_schema.columns
WHERE table_schema = %s AND table_name = 'users' AND column_name = 'password'
""", (config.DB_NAME,))
row = cur.fetchone()
if row and row[0] == "NO":
cur.execute("ALTER TABLE users MODIFY COLUMN password VARCHAR(255) NULL")
cur.execute("""
CREATE TABLE IF NOT EXISTS conversations (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
title VARCHAR(255) DEFAULT 'Yeni sohbet',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS messages (
id INT AUTO_INCREMENT PRIMARY KEY,
conversation_id INT NOT NULL,
role ENUM('user','assistant') NOT NULL,
content MEDIUMTEXT,
media_path VARCHAR(500) DEFAULT NULL,
media_type VARCHAR(20) DEFAULT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (conversation_id) REFERENCES conversations(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# messages tablosuna reply_to sütunu (WhatsApp tarzı yanıt alıntısı) — yoksa ekle
cur.execute("""
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = %s AND table_name = 'messages' AND column_name = 'reply_to'
""", (config.DB_NAME,))
if cur.fetchone()[0] == 0:
cur.execute("ALTER TABLE messages ADD COLUMN reply_to VARCHAR(500) DEFAULT NULL")
conn.commit()
cur.close()
conn.close()
print("[DB] vera_db hazir - tablolar olusturuldu/dogrulandi.")
def _conn():
return _pool.get_connection()
# ─────────────────────────────────────────────────────────
# Kullanıcılar
# ─────────────────────────────────────────────────────────
def create_user(username, email, password):
"""Yeni kullanıcı oluşturur. Başarılıysa user_id döner, e-posta varsa None."""
conn = _conn()
cur = conn.cursor()
try:
cur.execute(
"INSERT INTO users (username, email, password) VALUES (%s, %s, %s)",
(username, email, generate_password_hash(password)),
)
conn.commit()
return cur.lastrowid
except mysql.connector.IntegrityError:
return None
finally:
cur.close()
conn.close()
def get_user_by_email(email):
conn = _conn()
cur = conn.cursor(dictionary=True)
cur.execute("SELECT * FROM users WHERE email = %s", (email,))
row = cur.fetchone()
cur.close()
conn.close()
return row
def verify_login(email, password):
"""E-posta + şifre doğruysa kullanıcı satırını döner, yoksa None."""
user = get_user_by_email(email)
if user and user["password"] and check_password_hash(user["password"], password):
return user
return None
# ─────────────────────────────────────────────────────────
# Google ile Giriş
# ─────────────────────────────────────────────────────────
def get_user_by_google_id(google_id):
conn = _conn()
cur = conn.cursor(dictionary=True)
cur.execute("SELECT * FROM users WHERE google_id = %s", (google_id,))
row = cur.fetchone()
cur.close()
conn.close()
return row
def create_google_user(username, email, google_id, avatar=None):
"""Google ile ilk kez giriş yapan kullanıcı için şifresiz hesap oluşturur."""
conn = _conn()
cur = conn.cursor()
try:
cur.execute(
"INSERT INTO users (username, email, password, google_id, avatar) "
"VALUES (%s, %s, NULL, %s, %s)",
(username[:80], email, google_id, avatar),
)
conn.commit()
return cur.lastrowid
except mysql.connector.IntegrityError:
return None
finally:
cur.close()
conn.close()
def link_google_account(user_id, google_id, avatar=None):
"""E-posta/şifre ile açılmış var olan bir hesaba Google kimliğini bağlar."""
conn = _conn()
cur = conn.cursor()
if avatar:
cur.execute(
"UPDATE users SET google_id = %s, avatar = %s WHERE id = %s",
(google_id, avatar, user_id),
)
else:
cur.execute("UPDATE users SET google_id = %s WHERE id = %s", (google_id, user_id))
conn.commit()
cur.close()
conn.close()
def get_user(user_id):
"""Profil için gereken alanları döner (şifre hariç)."""
conn = _conn()
cur = conn.cursor(dictionary=True)
cur.execute(
"SELECT id, username, email, avatar FROM users WHERE id = %s",
(user_id,),
)
row = cur.fetchone()
cur.close()
conn.close()
return row
def update_profile(user_id, username=None, avatar=None):
"""İsim ve/veya avatar günceller. avatar='' ise fotoğrafı kaldırır."""
fields, vals = [], []
if username:
fields.append("username = %s")
vals.append(username[:80])
if avatar is not None:
fields.append("avatar = %s")
vals.append(avatar or None)
if not fields:
return
vals.append(user_id)
conn = _conn()
cur = conn.cursor()
cur.execute(f"UPDATE users SET {', '.join(fields)} WHERE id = %s", vals)
conn.commit()
cur.close()
conn.close()
# ─────────────────────────────────────────────────────────
# Sohbetler
# ─────────────────────────────────────────────────────────
def create_conversation(user_id, title="Yeni sohbet"):
conn = _conn()
cur = conn.cursor()
cur.execute(
"INSERT INTO conversations (user_id, title) VALUES (%s, %s)",
(user_id, title),
)
conn.commit()
cid = cur.lastrowid
cur.close()
conn.close()
return cid
def list_conversations(user_id):
conn = _conn()
cur = conn.cursor(dictionary=True)
cur.execute(
"SELECT id, title, updated_at FROM conversations "
"WHERE user_id = %s ORDER BY updated_at DESC",
(user_id,),
)
rows = cur.fetchall()
cur.close()
conn.close()
return rows
def rename_conversation(conv_id, user_id, title):
conn = _conn()
cur = conn.cursor()
cur.execute(
"UPDATE conversations SET title = %s WHERE id = %s AND user_id = %s",
(title[:255], conv_id, user_id),
)
conn.commit()
cur.close()
conn.close()
def delete_conversation(conv_id, user_id):
conn = _conn()
cur = conn.cursor()
cur.execute(
"DELETE FROM conversations WHERE id = %s AND user_id = %s",
(conv_id, user_id),
)
conn.commit()
cur.close()
conn.close()
def owns_conversation(conv_id, user_id):
conn = _conn()
cur = conn.cursor()
cur.execute(
"SELECT 1 FROM conversations WHERE id = %s AND user_id = %s",
(conv_id, user_id),
)
ok = cur.fetchone() is not None
cur.close()
conn.close()
return ok
# ─────────────────────────────────────────────────────────
# Mesajlar
# ─────────────────────────────────────────────────────────
def add_message(conv_id, role, content, media_path=None, media_type=None, reply_to=None):
conn = _conn()
cur = conn.cursor()
cur.execute(
"INSERT INTO messages (conversation_id, role, content, media_path, media_type, reply_to) "
"VALUES (%s, %s, %s, %s, %s, %s)",
(conv_id, role, content, media_path, media_type, (reply_to or None)),
)
# sohbetin updated_at'ini tazele
cur.execute(
"UPDATE conversations SET updated_at = CURRENT_TIMESTAMP WHERE id = %s",
(conv_id,),
)
conn.commit()
mid = cur.lastrowid
cur.close()
conn.close()
return mid
def get_messages(conv_id):
conn = _conn()
cur = conn.cursor(dictionary=True)
cur.execute(
"SELECT role, content, media_path, media_type, reply_to, created_at "
"FROM messages WHERE conversation_id = %s ORDER BY id ASC",
(conv_id,),
)
rows = cur.fetchall()
cur.close()
conn.close()
return rows