"""Cloud schema guard (APPS_PLATFORM D-22): Alembic only, baseline = v1 production, no drift.""" import json import re import sqlite3 from pathlib import Path import pytest from alembic.autogenerate import compare_metadata from alembic.migration import MigrationContext from sqlalchemy import create_engine, text from schema import BASELINE, UnstampedDatabaseError, stamp_baseline, upgrade_to_head HERE = Path(__file__).resolve().parent V1_SQL = (HERE / "fixtures" / "v1_cloud_schema.sql").read_text(encoding="utf-8") def _v1_db(path: Path): con = sqlite3.connect(path) con.executescript(V1_SQL) con.execute("insert into sites (id, site_id, name, owner_name, contact_email, secret_key_hash, is_active, " "is_locked, license_expires_at, order_counter, menu_mode, menu_hours_en) values " "(1, 'site-1', 'Kopse', 'O', 'o@x', 'h', 1, 0, '2027-05-01 00:00:00', 7, 'order', 'old')") con.commit() con.close() return create_engine(f"sqlite:///{path.as_posix()}") def _shape(path): con = sqlite3.connect(path) tables = {t: sorted((r[1], r[2].upper(), r[3]) for r in con.execute(f'pragma table_info("{t}")')) for (t,) in con.execute("select name from sqlite_master where type='table' " "and name not in ('alembic_version', 'sqlite_sequence')")} idx = sorted(r[0] for r in con.execute("select name from sqlite_master where type='index' and name not like 'sqlite_%'")) con.close() return tables, idx def test_baseline_equals_v1_production_schema(tmp_path): from schema import alembic_config from alembic import command eng = create_engine(f"sqlite:///{(tmp_path / 'b.db').as_posix()}") with eng.begin() as conn: command.upgrade(alembic_config(conn), BASELINE) eng.dispose() con = sqlite3.connect(tmp_path / "v1.db") con.executescript(V1_SQL) con.close() assert _shape(tmp_path / "b.db") == _shape(tmp_path / "v1.db") def test_unstamped_v1_db_is_refused(tmp_path): eng = _v1_db(tmp_path / "prod.db") with pytest.raises(UnstampedDatabaseError): upgrade_to_head(eng) def test_stamp_then_upgrade_a_v1_db(tmp_path): # the cutover procedure eng = _v1_db(tmp_path / "prod.db") stamp_baseline(eng) upgrade_to_head(eng) with eng.connect() as conn: site = conn.execute(text("select site_id, order_counter, modules from sites")).one() presets = conn.execute(text("select name from plan_presets")).scalars().all() cols = [r[1] for r in conn.execute(text("pragma table_info(sites)"))] eng.dispose() assert site[0] == "site-1" and site[1] == 7 # data kept mods = json.loads(site[2]) assert {"ordering", "waiter_app", "kds", "connect_menu"} <= set(mods) assert mods["kds"] == {"limits": {"devices": None}} # v1 had no KDS limit assert presets == ["Everything (v1 sites)"] assert "menu_hours_en" not in cols def test_no_drift_between_models_and_migrations(tmp_path): from database import Base import models.all # noqa: F401 eng = create_engine(f"sqlite:///{(tmp_path / 'd.db').as_posix()}") upgrade_to_head(eng) with eng.connect() as conn: diff = compare_metadata(MigrationContext.configure(conn, opts={"compare_type": True}), Base.metadata) eng.dispose() assert diff == [], "\n".join(map(str, diff)) def test_nothing_calls_create_all(): root = HERE.parent bad = [p.relative_to(root).as_posix() for p in root.rglob("*.py") if not p.relative_to(root).as_posix().startswith(("tests/", "migrations/")) and re.search(r"\.create_all\(", p.read_text(encoding="utf-8", errors="ignore"))] assert bad == [] def test_0003_keeps_orders_gives_tokens_and_refs_per_site(tmp_path): """Existing online orders survive the table rebuild, get a tracking token, and two sites may now both have ORD-0001 (plan phase 3S, S.2).""" from schema import alembic_config from alembic import command import sqlalchemy as sa eng = create_engine(f"sqlite:///{(tmp_path / 'c.db').as_posix()}") with eng.begin() as conn: command.upgrade(alembic_config(conn), "0002_v2_licensing") for sid in (1, 2): conn.execute(text("insert into sites (id, site_id, name, owner_name, contact_email, secret_key_hash, is_active, " "license_expires_at, created_at, order_counter, menu_mode) " "values (:i, :s, 'S', 'O', 'o@x', 'x', 1, '2027-01-01', '2026-01-01', 1, 'order')"), {"i": sid, "s": f"site-{sid}"}) conn.execute(text("insert into online_orders (site_id, public_ref, order_type, customer_name, items_json, subtotal, " "delivery_fee, total, status, synced_to_local) values (1, 'ORD-0001', 'dine_in', 'A', '[]', 1, 0, 1, 'delivered', 1)")) upgrade_to_head(eng) with eng.begin() as conn: row = conn.execute(text("select public_ref, tracking_token from online_orders")).one() assert row[0] == "ORD-0001" and row[1] conn.execute(text("insert into online_orders (site_id, public_ref, order_type, customer_name, items_json, subtotal, " "delivery_fee, total, status, synced_to_local) values (2, 'ORD-0001', 'dine_in', 'B', '[]', 1, 0, 1, 'delivered', 0)")) with pytest.raises(sa.exc.IntegrityError): with conn.begin_nested(): conn.execute(text("insert into online_orders (site_id, public_ref, order_type, customer_name, items_json, subtotal, " "delivery_fee, total, status, synced_to_local) values (2, 'ORD-0001', 'dine_in', 'C', '[]', 1, 0, 1, 'delivered', 0)")) idx = {i["name"] for i in sa.inspect(conn).get_indexes("online_orders")} eng.dispose() assert {"ix_online_orders_site_id", "ix_online_orders_status"} <= idx