Files
solardb/client/models/applications.py
2025-09-17 10:39:58 +03:00

92 lines
3.3 KiB
Python

import sqlite3
import os
class DBApplications:
def __init__(self):
# Allow DB path override via env, default to /app/instance/dev.db inside container
default_path = os.getenv("DB_PATH", "instance/dev.db")
self.db_path = os.path.abspath(default_path)
os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
self.create_table()
def create_table(self):
with sqlite3.connect(self.db_path, check_same_thread=False) as conn:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS applications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
name TEXT NOT NULL UNIQUE,
access_code TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
status TEXT NOT NULL DEFAULT 'active'
);
""")
conn.commit()
def insert_application(self, user_id, name, access_code: str) -> bool:
try:
with sqlite3.connect(self.db_path, check_same_thread=False) as conn:
cursor = conn.cursor()
cursor.execute("""
INSERT INTO applications (user_id, name, access_code)
VALUES (?, ?, ?)
""", (user_id, name, access_code))
conn.commit()
return True
except sqlite3.IntegrityError:
return False
def get_application_by_id(self, id):
with sqlite3.connect(self.db_path, check_same_thread=False) as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT * FROM applications
WHERE id = ?
""", (id,))
row = cursor.fetchone()
if row:
return {
"id": row[0],
"user_id":row[1],
"name": row[2],
"access_code": row[3],
"created_at": row[4],
"status": row[5],
}
else:
return None
def get_applications(self, user_id):
with sqlite3.connect(self.db_path, check_same_thread=False) as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT * FROM applications
WHERE user_id = ?
""", (user_id,))
rows = cursor.fetchall()
all_rows = []
if rows:
for row in rows:
row = {
"id": row[0],
"user_id":row[1],
"name": row[2],
"access_code": row[3],
"created_at": row[4],
"status": row[5],
}
all_rows.append(row)
return all_rows
else:
return all_rows
def delete(self, id):
with sqlite3.connect(self.db_path, check_same_thread=False) as conn:
cursor = conn.cursor()
cursor.execute("""
DELETE FROM applications WHERE id = ?
""", (id,))
conn.commit()