port mod app

This commit is contained in:
2025-06-30 22:13:12 +03:00
parent 453aeff95a
commit c22aa1036f
8 changed files with 80 additions and 41 deletions

View File

@ -4,13 +4,12 @@ from flask import current_app
class DB:
def __init__(self):
self._transaction_depth = 0
self._connection = None
@contextmanager
def _get_connection(self):
if self._connection and self._transaction_depth > 0:
if self._connection:
yield self._connection
return
@ -21,48 +20,24 @@ class DB:
try:
yield conn
finally:
if self._transaction_depth == 0:
conn.close()
conn.close()
@contextmanager
def transaction(self):
"""Transaction context."""
self.begin()
tr_connection = sqlite3.connect(current_app.config["DB_PATH"])
tr_connection.row_factory = sqlite3.Row
tr_connection.execute("PRAGMA FOREIGN_KEYS = 1")
tr_connection.execute("BEGIN")
try:
yield
self.commit()
tr_connection.execute("COMMIT")
except Exception:
self.rollback()
tr_connection.execute("ROLLBACK")
raise
def begin(self):
"""Begins a new transaction."""
if self._transaction_depth == 0:
if not self._connection:
self._connection = sqlite3.connect(current_app.config["DB_PATH"])
self._connection.row_factory = sqlite3.Row
self._connection.execute("PRAGMA FOREIGN_KEYS = 1")
self._connection.execute("BEGIN")
self._transaction_depth += 1
def commit(self):
"""Commits the current transaction."""
if self._transaction_depth > 0:
self._transaction_depth -= 1
if self._transaction_depth == 0:
self._connection.commit()
def rollback(self):
"""Rolls back the current transaction."""
if self._transaction_depth > 0:
self._transaction_depth = 0
self._connection.rollback()
def query(self, sql, *args):
"""Executes a query and returns a list of dictionaries."""
with self._get_connection() as conn:
@ -209,6 +184,13 @@ class Model:
return result["c"] if result else 0
@classmethod
def select(cls, sel = "*"):
qb = db.QueryBuilder(cls.table).select(sel)
result = qb.all()
return result if result else []
def update(self, data):
qb = db.QueryBuilder(self.table)\
.where({"id": self._data["id"]})