27 lines
607 B
Python
27 lines
607 B
Python
import sqlite3
|
|
from contextlib import contextmanager
|
|
from config import DATABASE_PATH
|
|
from pathlib import Path
|
|
|
|
|
|
def get_connection() -> sqlite3.Connection:
|
|
Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True)
|
|
conn = sqlite3.connect(DATABASE_PATH)
|
|
conn.row_factory = sqlite3.Row
|
|
conn.execute("PRAGMA journal_mode=WAL")
|
|
conn.execute("PRAGMA foreign_keys=ON")
|
|
return conn
|
|
|
|
|
|
@contextmanager
|
|
def get_db():
|
|
conn = get_connection()
|
|
try:
|
|
yield conn
|
|
conn.commit()
|
|
except Exception:
|
|
conn.rollback()
|
|
raise
|
|
finally:
|
|
conn.close()
|