s2v / core /database.py
diwash-barla1's picture
Initial commit with clean history
aa642ce
Raw
History Blame Contribute Delete
2.68 kB
# code/database.py
import sqlite3
from contextlib import contextmanager
# हम constants फाइल से पाथ और लॉक इम्पोर्ट कर रहे हैं
from core.constants import DATABASE_FILE, GLOBAL_DB_LOCK
@contextmanager
def get_db_cursor():
conn = sqlite3.connect(DATABASE_FILE, check_same_thread=False)
conn.row_factory = sqlite3.Row
try:
yield conn
conn.commit()
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
def init_db():
with GLOBAL_DB_LOCK:
with get_db_cursor() as conn:
conn.execute('CREATE TABLE IF NOT EXISTS tasks (id TEXT PRIMARY KEY, status TEXT NOT NULL, progress INTEGER NOT NULL, log TEXT, output_filename TEXT)')
def create_task(task_id):
log_message = "मिशन शुरू हो रहा...\n"
with GLOBAL_DB_LOCK:
with get_db_cursor() as conn:
conn.execute('INSERT INTO tasks (id, status, progress, log) VALUES (?, ?, ?, ?)', (task_id, 'processing', 0, log_message))
def get_task(task_id):
with GLOBAL_DB_LOCK:
with get_db_cursor() as conn:
return conn.execute('SELECT * FROM tasks WHERE id = ?', (task_id,)).fetchone()
def update_task_log(task_id, message, progress):
with GLOBAL_DB_LOCK:
with get_db_cursor() as conn:
# First fetch current log
current_row = conn.execute('SELECT log FROM tasks WHERE id = ?', (task_id,)).fetchone()
if not current_row: return # Task not found
current_log = current_row['log']
new_log = current_log + message + "\n"
conn.execute('UPDATE tasks SET log = ?, progress = ? WHERE id = ?', (new_log, progress, task_id))
def update_task_final_status(task_id, status, error_message=None, output_filename=None):
with GLOBAL_DB_LOCK:
with get_db_cursor() as conn:
current_row = conn.execute('SELECT log FROM tasks WHERE id = ?', (task_id,)).fetchone()
if not current_row: return
current_log = current_row['log']
if status == 'error':
final_log = current_log + f"\n\n🚨 FATAL ERROR: {error_message}"
conn.execute('UPDATE tasks SET status = ?, log = ? WHERE id = ?', (status, final_log, task_id))
elif status == 'complete':
final_log = current_log + "\n🎉 मिशन पूरा हुआ!"
conn.execute('UPDATE tasks SET status = ?, progress = ?, output_filename = ?, log = ? WHERE id = ?', (status, 100, output_filename, final_log, task_id))