Keeby-smilyai commited on
Commit
f77699b
·
verified ·
1 Parent(s): ac10df9

Update backend/database.py

Browse files
Files changed (1) hide show
  1. backend/database.py +126 -42
backend/database.py CHANGED
@@ -1,59 +1,143 @@
1
  # backend/database.py
2
  import sqlite3
3
- import hashlib
 
 
4
 
5
- DB_PATH = "code_agents_pro.db"
6
- PROJECT_ROOT = "./projects"
7
 
8
- def init_db():
9
- with sqlite3.connect(DB_PATH) as conn:
10
- cursor = conn.cursor()
11
- cursor.executescript("""
12
- CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT UNIQUE, password_hash TEXT);
13
- CREATE TABLE IF NOT EXISTS projects (id INTEGER PRIMARY KEY, user_id INTEGER, title TEXT, description TEXT, status TEXT DEFAULT 'queued', zip_path TEXT, logs TEXT DEFAULT '', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id));
14
- CREATE INDEX IF NOT EXISTS idx_user_status ON projects(user_id, status);
15
- """)
16
-
17
- def _db_execute(query, params=(), fetchone=False, fetchall=False, commit=False):
18
- try:
19
- with sqlite3.connect(DB_PATH) as conn:
20
- conn.row_factory = sqlite3.Row
21
- cursor = conn.cursor()
22
- cursor.execute(query, params)
23
- if commit:
24
- conn.commit()
25
- return cursor.lastrowid
26
- if fetchone:
27
- return cursor.fetchone()
28
- if fetchall:
29
- return cursor.fetchall()
30
- except sqlite3.Error as e:
31
- print(f"Database error: {e}")
32
- return None
33
-
34
- def hash_password(password):
35
- return hashlib.sha256(password.encode()).hexdigest()
36
 
37
- def verify_password(password, stored_hash):
38
- return hash_password(password) == stored_hash
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  def create_user(username, password):
 
 
 
 
 
 
 
 
 
41
  try:
42
- return _db_execute("INSERT INTO users (username, password_hash) VALUES (?, ?)", (username, hash_password(password)), commit=True)
 
 
43
  except sqlite3.IntegrityError:
44
  return None
 
 
45
 
46
  def get_user_by_username(username):
47
- return _db_execute("SELECT * FROM users WHERE username = ?", (username,), fetchone=True)
 
 
 
 
 
 
 
 
 
 
 
48
 
49
- def get_user_projects(user_id, limit=20):
50
- return _db_execute("SELECT * FROM projects WHERE user_id = ? ORDER BY created_at DESC LIMIT ?", (user_id, limit), fetchall=True)
 
51
 
52
- def create_project(user_id, title, description):
53
- return _db_execute("INSERT INTO projects (user_id, title, description) VALUES (?, ?, ?)", (user_id, title, description), commit=True)
 
 
 
 
 
 
 
 
54
 
55
- def update_project_status(project_id, status, logs=None, zip_path=None):
56
- _db_execute("UPDATE projects SET status=?, logs=COALESCE(?, logs), zip_path=COALESCE(?, zip_path) WHERE id=?", (status, logs, zip_path, project_id), commit=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
  def get_project(project_id):
59
- return _db_execute("SELECT * FROM projects WHERE id = ?", (project_id,), fetchone=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # backend/database.py
2
  import sqlite3
3
+ import bcrypt
4
+ import os
5
+ import time
6
 
7
+ DATABASE_PATH = 'data.db'
 
8
 
9
+ def get_db_connection():
10
+ """Establishes a connection to the SQLite database."""
11
+ conn = sqlite3.connect(DATABASE_PATH)
12
+ return conn
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ def init_db():
15
+ """
16
+ Initializes the database by creating the necessary tables.
17
+ This function should be called once on application startup.
18
+ """
19
+ conn = get_db_connection()
20
+ c = conn.cursor()
21
+
22
+ # Users table
23
+ c.execute("""
24
+ CREATE TABLE IF NOT EXISTS users (
25
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
26
+ username TEXT UNIQUE NOT NULL,
27
+ password_hash TEXT NOT NULL
28
+ )
29
+ """)
30
+
31
+ # Projects table
32
+ c.execute("""
33
+ CREATE TABLE IF NOT EXISTS projects (
34
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
35
+ user_id INTEGER NOT NULL,
36
+ title TEXT NOT NULL,
37
+ prompt TEXT NOT NULL,
38
+ status TEXT NOT NULL,
39
+ created_at INTEGER NOT NULL,
40
+ logs TEXT,
41
+ zip_path TEXT,
42
+ FOREIGN KEY (user_id) REFERENCES users (id)
43
+ )
44
+ """)
45
+
46
+ conn.commit()
47
+ conn.close()
48
 
49
  def create_user(username, password):
50
+ """
51
+ Creates a new user in the database.
52
+ Returns the user ID or None if the username is already taken.
53
+ """
54
+ conn = get_db_connection()
55
+ c = conn.cursor()
56
+
57
+ hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
58
+
59
  try:
60
+ c.execute("INSERT INTO users (username, password_hash) VALUES (?, ?)", (username, hashed_password))
61
+ conn.commit()
62
+ return c.lastrowid
63
  except sqlite3.IntegrityError:
64
  return None
65
+ finally:
66
+ conn.close()
67
 
68
  def get_user_by_username(username):
69
+ """Fetches a user by their username."""
70
+ conn = get_db_connection()
71
+ c = conn.cursor()
72
+ c.execute("SELECT * FROM users WHERE username = ?", (username,))
73
+ user = c.fetchone()
74
+ conn.close()
75
+
76
+ if user:
77
+ columns = [desc[0] for desc in c.description]
78
+ return dict(zip(columns, user))
79
+
80
+ return None
81
 
82
+ def verify_password(password, password_hash):
83
+ """Verifies a password against its hash."""
84
+ return bcrypt.checkpw(password.encode('utf-8'), password_hash.encode('utf-8'))
85
 
86
+ def create_project(user_id, title, prompt):
87
+ """Creates a new project record and returns its ID."""
88
+ conn = get_db_connection()
89
+ c = conn.cursor()
90
+ c.execute("INSERT INTO projects (user_id, title, prompt, status, created_at) VALUES (?, ?, ?, ?, ?)",
91
+ (user_id, title, prompt, "queued", int(time.time())))
92
+ project_id = c.lastrowid
93
+ conn.commit()
94
+ conn.close()
95
+ return project_id
96
 
97
+ def get_user_projects(user_id):
98
+ """Retrieves all projects for a given user, ordered by creation date."""
99
+ conn = get_db_connection()
100
+ c = conn.cursor()
101
+ c.execute("SELECT * FROM projects WHERE user_id = ? ORDER BY created_at DESC", (user_id,))
102
+ projects = c.fetchall()
103
+ conn.close()
104
+
105
+ project_list = []
106
+ if projects:
107
+ columns = [desc[0] for desc in c.description]
108
+ for project in projects:
109
+ project_list.append(dict(zip(columns, project)))
110
+
111
+ return project_list
112
 
113
  def get_project(project_id):
114
+ """
115
+ Fetches a single project record by its unique ID.
116
+ This function is used by the front end for live log updates.
117
+ """
118
+ conn = get_db_connection()
119
+ c = conn.cursor()
120
+ c.execute("SELECT * FROM projects WHERE id = ?", (project_id,))
121
+ project = c.fetchone()
122
+ conn.close()
123
+
124
+ if project:
125
+ columns = [desc[0] for desc in c.description]
126
+ return dict(zip(columns, project))
127
+
128
+ return None
129
+
130
+ def update_project_status(project_id, status, logs=None, zip_path=None):
131
+ """Updates the status and optional logs/zip path for a project."""
132
+ conn = get_db_connection()
133
+ c = conn.cursor()
134
+
135
+ if logs is not None and zip_path is not None:
136
+ c.execute("UPDATE projects SET status = ?, logs = ?, zip_path = ? WHERE id = ?", (status, logs, zip_path, project_id))
137
+ elif logs is not None:
138
+ c.execute("UPDATE projects SET status = ?, logs = ? WHERE id = ?", (status, logs, project_id))
139
+ else:
140
+ c.execute("UPDATE projects SET status = ? WHERE id = ?", (status, project_id))
141
+
142
+ conn.commit()
143
+ conn.close()