Add database.py with connection, schema application and default seeding

This commit is contained in:
ai-bot committed 2026-11-14 12:03:26 +00:00
1 parent 8ad8cc506c
commit 3d06beb53a
1 file changed
+129
+129
View File
@@ -0,0 +1,129 @@
"""Database connection, schema application and default seeding.
The DDL lives in schema.sql next to this file and is the only schema source.
"""
import os
import sqlite3
from pathlib import Path
SCHEMA_VERSION = 1
SCHEMA_FILE = Path(__file__).resolve().parent / "schema.sql"
DEFAULT_DATABASE_PATH = "data/skuld.sqlite3"
# Settings of docs/spec.md section 4.1, with their defaults.
SETTING_DEFAULTS = {
"tax_rate_percent": "22",
"lot_method": "FIFO",
"wealth_tax_enabled": "0",
"wealth_tax_threshold_ore": "0",
"wealth_tax_rate_percent": "0",
"deduct_admin_costs": "0",
"year_end_price_source": "Skatteetaten",
}
# The published BTC year-end rates of docs/spec.md section 5.3, in ore per BTC.
# The date is the 1 January of the year the rate belongs to.
SEED_PRICES = (
("2021-01-01", 24731891),
("2022-01-01", 40846955),
("2023-01-01", 16283143),
("2024-01-01", 43548647),
("2025-01-01", 106037489),
("2026-01-01", 88120606),
)
def database_path():
"""Return the database path: DATABASE_PATH, or the development default."""
return os.environ.get("DATABASE_PATH") or DEFAULT_DATABASE_PATH
def connect(path=None):
"""Open a connection with foreign keys on and WAL journaling."""
resolved = path or database_path()
if resolved != ":memory:":
Path(resolved).expanduser().resolve().parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(resolved)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
conn.execute("PRAGMA journal_mode = WAL")
return conn
def apply_schema(conn=None):
"""Apply schema.sql and record the schema version. Idempotent."""
own = conn is None
if own:
conn = connect()
try:
conn.executescript(SCHEMA_FILE.read_text(encoding="utf-8"))
row = conn.execute("SELECT version FROM schema_version").fetchone()
if row is None:
conn.execute(
"INSERT INTO schema_version (version) VALUES (?)", (SCHEMA_VERSION,)
)
elif row["version"] != SCHEMA_VERSION:
conn.execute(
"UPDATE schema_version SET version = ?", (SCHEMA_VERSION,)
)
conn.commit()
finally:
if own:
conn.close()
def seed_defaults(conn=None):
"""Insert the default settings and the seeded rates. Idempotent."""
own = conn is None
if own:
conn = connect()
try:
for key, value in SETTING_DEFAULTS.items():
conn.execute(
"INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", (key, value)
)
for date, nok_per_btc_ore in SEED_PRICES:
conn.execute(
"INSERT OR IGNORE INTO prices (asset, date, nok_per_btc_ore, source)"
" VALUES ('BTC', ?, ?, ?)",
(date, nok_per_btc_ore, SETTING_DEFAULTS["year_end_price_source"]),
)
conn.commit()
finally:
if own:
conn.close()
def get_setting(key):
"""Return one setting value, or None when the key is unknown."""
conn = connect()
try:
row = conn.execute("SELECT value FROM settings WHERE key = ?", (key,)).fetchone()
finally:
conn.close()
return row["value"] if row else None
def set_setting(key, value):
"""Store one setting value."""
conn = connect()
try:
conn.execute(
"INSERT INTO settings (key, value) VALUES (?, ?)"
" ON CONFLICT(key) DO UPDATE SET value = excluded.value",
(key, str(value)),
)
conn.commit()
finally:
conn.close()
def all_settings():
"""Return every setting as a plain dict."""
conn = connect()
try:
rows = conn.execute("SELECT key, value FROM settings").fetchall()
finally:
conn.close()
return {row["key"]: row["value"] for row in rows}