final version, submitted to teacher
This commit is contained in:
40
web/db.py
40
web/db.py
@@ -1,5 +1,6 @@
|
||||
import sqlite3
|
||||
from flask import current_app as app
|
||||
import time
|
||||
|
||||
def get_db_connection():
|
||||
conn = sqlite3.connect('./static/db/db.sqlite')
|
||||
@@ -9,6 +10,21 @@ def get_db_connection():
|
||||
def dict_from_row(row):
|
||||
return {key: row[key] for key in row.keys()}
|
||||
|
||||
def execute_with_retry(conn, query, params=(), retries=5, delay=0.1):
|
||||
for attempt in range(retries):
|
||||
try:
|
||||
conn.execute(query, params)
|
||||
conn.commit()
|
||||
return
|
||||
except sqlite3.OperationalError as e:
|
||||
if "database is locked" in str(e):
|
||||
if attempt < retries - 1:
|
||||
time.sleep(delay)
|
||||
else:
|
||||
raise
|
||||
else:
|
||||
raise
|
||||
|
||||
def fetch_users(role_id):
|
||||
conn = get_db_connection()
|
||||
users = conn.execute('SELECT * FROM Zamestnanci WHERE Role_ID >= ?', (role_id,)).fetchall()
|
||||
@@ -73,29 +89,39 @@ def fetch_products():
|
||||
|
||||
def update_product(product_id, nazev, popis, momentalni_zasoba, minimalni_zasoba):
|
||||
conn = get_db_connection()
|
||||
conn.execute('''
|
||||
execute_with_retry(conn, '''
|
||||
UPDATE Produkty
|
||||
SET Nazev = ?, Popis = ?, Momentalni_Zasoba = ?, Minimalni_Zasoba = ?
|
||||
WHERE ID_Produktu = ?
|
||||
''', (nazev, popis, momentalni_zasoba, minimalni_zasoba, product_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def add_product_stock(product_id, quantity):
|
||||
conn = get_db_connection()
|
||||
conn.execute('''
|
||||
execute_with_retry(conn, '''
|
||||
UPDATE Produkty
|
||||
SET Momentalni_Zasoba = Momentalni_Zasoba + ?
|
||||
WHERE ID_Produktu = ?
|
||||
''', (quantity, product_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def create_product(nazev, popis, momentalni_zasoba, minimalni_zasoba):
|
||||
conn = get_db_connection()
|
||||
conn.execute('''
|
||||
execute_with_retry(conn, '''
|
||||
INSERT INTO Produkty (Nazev, Popis, Momentalni_Zasoba, Minimalni_Zasoba)
|
||||
VALUES (?, ?, ?, ?)
|
||||
''', (nazev, popis, momentalni_zasoba, minimalni_zasoba))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
conn.close()
|
||||
|
||||
def insert_used_products(repair_id, products):
|
||||
conn = get_db_connection()
|
||||
try:
|
||||
for product in products:
|
||||
product_id = product['id']
|
||||
quantity = product['quantity']
|
||||
app.logger.debug(f"Inserting product {product_id} with quantity {quantity} for repair {repair_id}")
|
||||
if quantity and int(quantity) > 0:
|
||||
execute_with_retry(conn, 'INSERT INTO Pouzite_Produkty (ID_Opravy, ID_Produktu, Pocet_Produktu) VALUES (?, ?, ?)',
|
||||
(repair_id, product_id, quantity))
|
||||
finally:
|
||||
conn.close()
|
||||
Reference in New Issue
Block a user