2025-11-04 05:17:27 +01:00
|
|
|
import time
|
|
|
|
|
|
2025-11-04 08:09:12 +01:00
|
|
|
|
2025-11-04 05:17:27 +01:00
|
|
|
def db_set(key, value, db_conn):
|
|
|
|
|
if not db_conn:
|
|
|
|
|
return {"status": "error", "error": "Database not initialized"}
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
cursor = db_conn.cursor()
|
2025-11-04 08:09:12 +01:00
|
|
|
cursor.execute(
|
|
|
|
|
"""INSERT OR REPLACE INTO kv_store (key, value, timestamp)
|
|
|
|
|
VALUES (?, ?, ?)""",
|
|
|
|
|
(key, value, time.time()),
|
|
|
|
|
)
|
2025-11-04 05:17:27 +01:00
|
|
|
db_conn.commit()
|
|
|
|
|
return {"status": "success", "message": f"Set {key}"}
|
|
|
|
|
except Exception as e:
|
|
|
|
|
return {"status": "error", "error": str(e)}
|
|
|
|
|
|
2025-11-04 08:09:12 +01:00
|
|
|
|
2025-11-04 05:17:27 +01:00
|
|
|
def db_get(key, db_conn):
|
|
|
|
|
if not db_conn:
|
|
|
|
|
return {"status": "error", "error": "Database not initialized"}
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
cursor = db_conn.cursor()
|
|
|
|
|
cursor.execute("SELECT value FROM kv_store WHERE key = ?", (key,))
|
|
|
|
|
result = cursor.fetchone()
|
|
|
|
|
if result:
|
|
|
|
|
return {"status": "success", "value": result[0]}
|
|
|
|
|
else:
|
|
|
|
|
return {"status": "error", "error": "Key not found"}
|
|
|
|
|
except Exception as e:
|
|
|
|
|
return {"status": "error", "error": str(e)}
|
|
|
|
|
|
2025-11-04 08:09:12 +01:00
|
|
|
|
2025-11-04 05:17:27 +01:00
|
|
|
def db_query(query, db_conn):
|
|
|
|
|
if not db_conn:
|
|
|
|
|
return {"status": "error", "error": "Database not initialized"}
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
cursor = db_conn.cursor()
|
|
|
|
|
cursor.execute(query)
|
|
|
|
|
|
2025-11-04 08:09:12 +01:00
|
|
|
if query.strip().upper().startswith("SELECT"):
|
2025-11-04 05:17:27 +01:00
|
|
|
results = cursor.fetchall()
|
2025-11-04 08:09:12 +01:00
|
|
|
columns = (
|
|
|
|
|
[desc[0] for desc in cursor.description] if cursor.description else []
|
|
|
|
|
)
|
2025-11-04 05:17:27 +01:00
|
|
|
return {"status": "success", "columns": columns, "rows": results}
|
|
|
|
|
else:
|
|
|
|
|
db_conn.commit()
|
|
|
|
|
return {"status": "success", "rows_affected": cursor.rowcount}
|
|
|
|
|
except Exception as e:
|
|
|
|
|
return {"status": "error", "error": str(e)}
|