db init and migration, graceful

This commit is contained in:
grove5_admin committed 2026-05-01 15:32:16 -07:00
1 parent 1e91a43407
commit f5e4527b4b
2 files changed
+49 -43

No files matched your search

+7 -17
View File
@@ -258,20 +258,10 @@ INSERT OR IGNORE INTO schema_version (version, description)
VALUES (1, 'Initial schema — runs, payloads, sweep_points, baselines, anomalies, co2e_calibration'); VALUES (1, 'Initial schema — runs, payloads, sweep_points, baselines, anomalies, co2e_calibration');
-- ── Migration: v2 — raw ADC columns ────────────────────────────────────── -- ── Migration: v2 — raw ADC columns ──────────────────────────────────────
-- Add raw ADC columns for time-series storage and future reprocessing. -- adc_temp, adc_hum, adc_pres added to payloads.
-- Only runs if schema_version v2 hasn't been recorded yet. -- adc_gas_res, gas_range added to sweep_points.
--
INSERT OR IGNORE INTO schema_version (version, description) -- Migration is applied by init_db() in storage.py using PRAGMA table_info
VALUES (2, 'Add raw ADC columns: adc_temp, adc_hum, adc_pres, adc_gas_res, gas_range'); -- checks rather than ALTER TABLE here — ALTER TABLE on a fresh DB (which
-- already has these columns from CREATE TABLE above) would error with
-- Apply migration only if we just inserted v2 (rows_affected check would be better in Python, -- "duplicate column name". See storage.py for the migration code.
-- but here we use the fact that INSERT OR IGNORE returns 0 changes if already exists)
-- Note: These ALTER TABLE statements only run on databases created before v2.
-- Fresh installs already have these columns from the CREATE TABLE statements above.
ALTER TABLE payloads ADD COLUMN adc_temp INTEGER;
ALTER TABLE payloads ADD COLUMN adc_hum INTEGER;
ALTER TABLE payloads ADD COLUMN adc_pres INTEGER;
ALTER TABLE sweep_points ADD COLUMN adc_gas_res INTEGER;
ALTER TABLE sweep_points ADD COLUMN gas_range INTEGER;
+42 -26
View File
@@ -48,41 +48,57 @@ DB_PATH = Path(__file__).parent / "cultivar.db"
async def init_db(db_path: Path = DB_PATH) -> aiosqlite.Connection: async def init_db(db_path: Path = DB_PATH) -> aiosqlite.Connection:
""" """
Open the database, apply schema, return connection. Open the database, apply base schema, run any pending migrations, return connection.
Safe to call on every startup — all statements use CREATE IF NOT EXISTS. Safe to call on every startup — CREATE TABLE uses IF NOT EXISTS throughout.
Migrations are applied in Python using PRAGMA table_info() checks rather than
ALTER TABLE in schema.sql, because ALTER TABLE on a fresh DB (which already has
the columns from CREATE TABLE) would raise "duplicate column name".
""" """
db = await aiosqlite.connect(db_path) db = await aiosqlite.connect(db_path)
db.row_factory = aiosqlite.Row db.row_factory = aiosqlite.Row
# Check current schema version before applying migrations # Apply base schema (CREATE TABLE IF NOT EXISTS + v1 version record).
current_version = 0 # schema.sql must not contain any ALTER TABLE statements — those live here.
try: await db.executescript(SCHEMA_PATH.read_text())
async with db.execute("SELECT MAX(version) as v FROM schema_version") as cur:
row = await cur.fetchone()
current_version = row['v'] or 0
except Exception:
# schema_version doesn't exist yet (fresh database)
current_version = 0
# Apply schema - filter out v2 migration if already applied or on fresh DB
schema = SCHEMA_PATH.read_text()
if current_version >= 2 or current_version == 0:
# Remove v2 migration ALTER TABLE statements (lines after v2 INSERT)
# - Version >= 2: migration already applied
# - Version == 0: fresh database, CREATE TABLE already has the columns
migration_start = schema.find('-- ── Migration: v2')
if migration_start > 0:
schema = schema[:migration_start]
schema += "\n-- v2 migration not needed, skipping ALTER TABLE statements\n"
await db.executescript(schema)
await db.commit() await db.commit()
# Verify final schema version # Determine the current schema version after base schema is applied.
async with db.execute("SELECT MAX(version) as v FROM schema_version") as cur: async with db.execute("SELECT MAX(version) as v FROM schema_version") as cur:
row = await cur.fetchone() row = await cur.fetchone()
log.info(f"Database ready — schema version {row['v']} at {db_path}") current_version = row['v'] or 0
# ── Migration: v2 ────────────────────────────────────────────────────────
# Adds raw ADC columns to payloads and sweep_points.
# Fresh DBs already have these columns (they're in CREATE TABLE); v1 DBs
# do not. We check with PRAGMA rather than catching a duplicate-column error
# so the intent is explicit and the error path is never needed.
if current_version < 2:
async with db.execute("PRAGMA table_info(payloads)") as cur:
rows = await cur.fetchall()
payload_cols = {row['name'] for row in rows}
if 'adc_temp' not in payload_cols:
await db.execute("ALTER TABLE payloads ADD COLUMN adc_temp INTEGER")
await db.execute("ALTER TABLE payloads ADD COLUMN adc_hum INTEGER")
await db.execute("ALTER TABLE payloads ADD COLUMN adc_pres INTEGER")
async with db.execute("PRAGMA table_info(sweep_points)") as cur:
rows = await cur.fetchall()
sweep_cols = {row['name'] for row in rows}
if 'adc_gas_res' not in sweep_cols:
await db.execute("ALTER TABLE sweep_points ADD COLUMN adc_gas_res INTEGER")
await db.execute("ALTER TABLE sweep_points ADD COLUMN gas_range INTEGER")
await db.execute(
"INSERT OR IGNORE INTO schema_version (version, description) VALUES (?, ?)",
(2, 'Add raw ADC columns: adc_temp, adc_hum, adc_pres, adc_gas_res, gas_range'),
)
await db.commit()
current_version = 2
log.info(f"Database ready — schema version {current_version} at {db_path}")
return db return db