Update utils/database.py
Browse files- utils/database.py +16 -10
utils/database.py
CHANGED
|
@@ -28,6 +28,10 @@ import io
|
|
| 28 |
import tempfile
|
| 29 |
from sqlite3 import Error
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
def create_connection(db_file):
|
| 33 |
"""
|
|
@@ -40,7 +44,7 @@ def create_connection(db_file):
|
|
| 40 |
"""
|
| 41 |
conn = None
|
| 42 |
try:
|
| 43 |
-
conn = sqlite3.connect(db_file)
|
| 44 |
return conn
|
| 45 |
except Error as e:
|
| 46 |
st.error("Failed to connect to database. Please try again or contact support.")
|
|
@@ -133,9 +137,10 @@ def get_documents(conn):
|
|
| 133 |
tuple: (list of document contents, list of document names).
|
| 134 |
"""
|
| 135 |
try:
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
|
|
|
| 139 |
|
| 140 |
if not results:
|
| 141 |
return [], []
|
|
@@ -163,12 +168,13 @@ def insert_document(conn, name, content):
|
|
| 163 |
int: ID of the inserted document, or None if insertion failed.
|
| 164 |
"""
|
| 165 |
try:
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
|
|
|
| 172 |
|
| 173 |
except Error as e:
|
| 174 |
st.error(f"Error inserting document: {e}")
|
|
|
|
| 28 |
import tempfile
|
| 29 |
from sqlite3 import Error
|
| 30 |
|
| 31 |
+
from threading import Lock
|
| 32 |
+
|
| 33 |
+
# Create a lock for database connection
|
| 34 |
+
conn_lock = Lock()
|
| 35 |
|
| 36 |
def create_connection(db_file):
|
| 37 |
"""
|
|
|
|
| 44 |
"""
|
| 45 |
conn = None
|
| 46 |
try:
|
| 47 |
+
conn = sqlite3.connect(db_file, check_same_thread=False)
|
| 48 |
return conn
|
| 49 |
except Error as e:
|
| 50 |
st.error("Failed to connect to database. Please try again or contact support.")
|
|
|
|
| 137 |
tuple: (list of document contents, list of document names).
|
| 138 |
"""
|
| 139 |
try:
|
| 140 |
+
with conn_lock:
|
| 141 |
+
cursor = conn.cursor()
|
| 142 |
+
cursor.execute("SELECT content, name FROM documents")
|
| 143 |
+
results = cursor.fetchall()
|
| 144 |
|
| 145 |
if not results:
|
| 146 |
return [], []
|
|
|
|
| 168 |
int: ID of the inserted document, or None if insertion failed.
|
| 169 |
"""
|
| 170 |
try:
|
| 171 |
+
with conn_lock:
|
| 172 |
+
cursor = conn.cursor()
|
| 173 |
+
sql = '''INSERT INTO documents (name, content)
|
| 174 |
+
VALUES (?, ?)'''
|
| 175 |
+
cursor.execute(sql, (name, content))
|
| 176 |
+
conn.commit()
|
| 177 |
+
return cursor.lastrowid
|
| 178 |
|
| 179 |
except Error as e:
|
| 180 |
st.error(f"Error inserting document: {e}")
|