diff --git a/gateway/docs/schema-051-rollout.md b/gateway/docs/schema-051-rollout.md new file mode 100644 index 000000000..98457c2ba --- /dev/null +++ b/gateway/docs/schema-051-rollout.md @@ -0,0 +1,25 @@ +# Schema 051: SQLite boolean defaults and rollback boundary + +Migration `051_sqlite_boolean_defaults` revises +`050_demo_key_first_used` (the api-chain port, PR #234). PR #61 must merge +after PR #234. +On SQLite it repairs legacy text booleans in refresh tokens, human approvals, +and permits, then replaces their text defaults with integer false defaults. +PostgreSQL schema and data are unchanged. + +## Compatibility release before migration + +Before an authorized rollout, confirm the database revision, back up the +database, and qualify a 051-capable recovery image. Rehearse the migration on +a copy of any SQLite database created before the corrected 022 and 023 +migrations, including existing rows and inserts that omit these columns. +The application requires its packaged Alembic head, so an older image cannot +restart after the database reaches 051. + +## Rollback after activation + +SQLite downgrade raises `sqlite_boolean_defaults_downgrade_unsupported` +instead of marking a database downgraded while retaining corrected values +and defaults. Recover with a 051-capable image and the database at 051. +Returning to an older packaged head requires a separately reviewed migration +and compatibility plan. diff --git a/gateway/migrations/versions/022_refresh_tokens.py b/gateway/migrations/versions/022_refresh_tokens.py index a39a7c013..7dc7d2aca 100644 --- a/gateway/migrations/versions/022_refresh_tokens.py +++ b/gateway/migrations/versions/022_refresh_tokens.py @@ -23,7 +23,9 @@ def upgrade() -> None: "refresh_tokens", sa.Column("jti", sa.String(length=64), nullable=False), sa.Column("wallet_id", sa.String(length=50), nullable=False), - sa.Column("revoked", sa.Boolean(), nullable=False, server_default="false"), + # sa.false() renders as 0 on SQLite and false on PostgreSQL. The string + # "false" is stored as text on SQLite and reads back as true. + sa.Column("revoked", sa.Boolean(), nullable=False, server_default=sa.false()), sa.Column("created_at", sa.DateTime(), nullable=False), sa.Column("expires_at", sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(["wallet_id"], ["wallets.wallet_id"]), diff --git a/gateway/migrations/versions/023_human_approval_gate.py b/gateway/migrations/versions/023_human_approval_gate.py index 6a2fdb051..36d17c27f 100644 --- a/gateway/migrations/versions/023_human_approval_gate.py +++ b/gateway/migrations/versions/023_human_approval_gate.py @@ -28,11 +28,13 @@ def upgrade() -> None: op.add_column( "permits", + # sa.false() renders as 0 on SQLite and false on PostgreSQL. The string + # "false" is stored as text on SQLite and reads back as true. sa.Column( "requires_human_approval", sa.Boolean(), nullable=False, - server_default="false", + server_default=sa.false(), ), ) @@ -46,7 +48,7 @@ def upgrade() -> None: sa.Column( "status", sa.String(length=16), nullable=False, server_default="pending" ), - sa.Column("simulated", sa.Boolean(), nullable=False, server_default="false"), + sa.Column("simulated", sa.Boolean(), nullable=False, server_default=sa.false()), sa.Column("sentinel_action_id", sa.String(length=64), nullable=True), sa.Column("requested_at", sa.DateTime(), nullable=False), sa.Column("expires_at", sa.DateTime(), nullable=False), diff --git a/gateway/migrations/versions/024_human_approval_hardening.py b/gateway/migrations/versions/024_human_approval_hardening.py index 6b2080f08..81716c57f 100644 --- a/gateway/migrations/versions/024_human_approval_hardening.py +++ b/gateway/migrations/versions/024_human_approval_hardening.py @@ -8,14 +8,16 @@ reloaded approval reject an invoke that reused the same idempotency key with different arguments or a different current price. -2. Repair ``permits.requires_human_approval`` on SQLite. Migration 023 added - the column with ``server_default="false"`` — a plain string that SQLite - stores as the *text* ``'false'`` and then reads back through SQLAlchemy's - non-native Boolean as ``True`` (``bool("false")``). Every permit that - existed before 023 therefore reports ``requires_human_approval=True`` and - fails signature verification (the flag enters the signed payload only when - true). Postgres parses ``'false'`` as boolean false, so it is unaffected; - the repair runs on SQLite only, normalizing any non-0/1 value back to 0. +2. Repair text booleans on SQLite. Migrations 022 and 023 added + ``refresh_tokens.revoked``, ``permits.requires_human_approval``, and + ``human_approvals.simulated`` with the string server default ``"false"``. + SQLite stores that as the text ``'false'``. SQLAlchemy then reads any + non-empty text as true, so a live refresh token looks revoked, a permit + looks like it requires human approval (and fails signature verification, + because the flag enters the signed payload only when true), and a real + approval looks simulated. Postgres parses ``'false'`` as boolean false, so + it is unaffected. The repair runs on SQLite only and rewrites the known + text values in the correct direction. Unexpected text is left alone. Revision ID: 024_human_approval_hardening Revises: 023_human_approval_gate @@ -40,25 +42,30 @@ def upgrade() -> None: bind = op.get_bind() if bind.dialect.name == "sqlite": - # Existing rows backfilled by 023 hold the text 'false'. Repair only - # the known text booleans, in the correct direction, so an unexpected - # value is never silently downgraded to "approval not required" (that - # would remove a control rather than restore one). 023's server_default - # can only produce 'false', but the 'true' side is handled defensively. - op.execute( - sa.text( - "UPDATE permits SET requires_human_approval = 0 " - "WHERE typeof(requires_human_approval) = 'text' " - "AND lower(requires_human_approval) IN ('false', 'f', '0', 'no')" + # Rows created under the old string default hold the text 'false'. + # Repair only the known text booleans, in the correct direction, so an + # unexpected value is never silently turned into "not set". The old + # server default can only produce 'false', but the 'true' side is + # handled so a real true is not left as text. + for table, column in ( + ("permits", "requires_human_approval"), + ("human_approvals", "simulated"), + ("refresh_tokens", "revoked"), + ): + op.execute( + sa.text( + f"UPDATE {table} SET {column} = 0 " + f"WHERE typeof({column}) = 'text' " + f"AND lower({column}) IN ('false', 'f', '0', 'no')" + ) ) - ) - op.execute( - sa.text( - "UPDATE permits SET requires_human_approval = 1 " - "WHERE typeof(requires_human_approval) = 'text' " - "AND lower(requires_human_approval) IN ('true', 't', '1', 'yes')" + op.execute( + sa.text( + f"UPDATE {table} SET {column} = 1 " + f"WHERE typeof({column}) = 'text' " + f"AND lower({column}) IN ('true', 't', '1', 'yes')" + ) ) - ) def downgrade() -> None: diff --git a/gateway/migrations/versions/051_sqlite_boolean_defaults.py b/gateway/migrations/versions/051_sqlite_boolean_defaults.py new file mode 100644 index 000000000..48e10bbb9 --- /dev/null +++ b/gateway/migrations/versions/051_sqlite_boolean_defaults.py @@ -0,0 +1,50 @@ +"""Repair legacy SQLite text booleans and replace their text defaults. + +Revision ID: 051_sqlite_boolean_defaults +Revises: 050_demo_key_first_used +""" + +from alembic import op +import sqlalchemy as sa + +revision: str = "051_sqlite_boolean_defaults" +down_revision: str = "050_demo_key_first_used" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + if op.get_bind().dialect.name != "sqlite": + return + + for table, column in ( + ("refresh_tokens", "revoked"), + ("human_approvals", "simulated"), + ("permits", "requires_human_approval"), + ): + op.execute( + sa.text( + f"UPDATE {table} SET {column} = 0 " + f"WHERE typeof({column}) = 'text' " + f"AND lower({column}) IN ('false', 'f', '0', 'no')" + ) + ) + op.execute( + sa.text( + f"UPDATE {table} SET {column} = 1 " + f"WHERE typeof({column}) = 'text' " + f"AND lower({column}) IN ('true', 't', '1', 'yes')" + ) + ) + with op.batch_alter_table(table) as batch_op: + batch_op.alter_column( + column, + existing_type=sa.Boolean(), + existing_nullable=False, + server_default=sa.false(), + ) + + +def downgrade() -> None: + if op.get_bind().dialect.name == "sqlite": + raise RuntimeError("sqlite_boolean_defaults_downgrade_unsupported") diff --git a/gateway/tests/test_action_migrations.py b/gateway/tests/test_action_migrations.py index 70257346b..bab9e443e 100644 --- a/gateway/tests/test_action_migrations.py +++ b/gateway/tests/test_action_migrations.py @@ -89,7 +89,9 @@ def migrate(url, revision, direction="upgrade"): def test_action_migration_retains_legacy_and_blocks_authority_loss( tmp_path, start_revision, authority ): - head_revision = current_head_revision() + # Exercise the 042 downgrade without crossing the irreversible SQLite + # boolean repair in later migrations. + head_revision = "044_receipt_resolutions" path = tmp_path / "migration.sqlite" url = f"sqlite+aiosqlite:///{path}" result = migrate(url, "040_permit_repeat_window") @@ -121,7 +123,7 @@ def test_action_migration_retains_legacy_and_blocks_authority_loss( ("",), ("w",), ] - result = migrate(url, "head") + result = migrate(url, head_revision) assert result.returncode == 0, result.stderr with sqlite3.connect(path) as db: assert db.execute("SELECT version_num FROM alembic_version").fetchone() == ( diff --git a/gateway/tests/test_migrations.py b/gateway/tests/test_migrations.py index ce12ba793..1e3e1b2bc 100644 --- a/gateway/tests/test_migrations.py +++ b/gateway/tests/test_migrations.py @@ -784,7 +784,7 @@ def test_041_scrubs_legacy_plaintext_owner_keys_from_content_tables( Rows whose owner_key is a known wallet id (what the factory routers write now) keep their owner, and an already-blank row stays blank. The rows are - inserted at head and the scrub is exercised by stepping back to 040 and + inserted at 044 and the scrub is exercised by stepping back to 040 and forward again, which also pins that the downgrade is a no-op (the scrubbed values were credentials and are unrecoverable) and the upgrade idempotent. """ @@ -796,7 +796,7 @@ def test_041_scrubs_legacy_plaintext_owner_keys_from_content_tables( monkeypatch.setenv("DATABASE_URL", async_url) config = Config("alembic.ini") - command.upgrade(config, "head") + command.upgrade(config, "044_receipt_resolutions") asyncio.set_event_loop(asyncio.new_event_loop()) engine = create_engine(sync_url) @@ -872,7 +872,7 @@ def owners() -> tuple[dict, dict]: command.downgrade(config, "040_permit_repeat_window") asyncio.set_event_loop(asyncio.new_event_loop()) - command.upgrade(config, "head") + command.upgrade(config, "044_receipt_resolutions") asyncio.set_event_loop(asyncio.new_event_loop()) pipelines, campaigns = owners() @@ -883,6 +883,6 @@ def owners() -> tuple[dict, dict]: # Idempotent: a second pass changes nothing. command.downgrade(config, "040_permit_repeat_window") asyncio.set_event_loop(asyncio.new_event_loop()) - command.upgrade(config, "head") + command.upgrade(config, "044_receipt_resolutions") asyncio.set_event_loop(asyncio.new_event_loop()) assert owners() == (pipelines, campaigns) diff --git a/gateway/tests/test_sqlite_boolean_defaults.py b/gateway/tests/test_sqlite_boolean_defaults.py new file mode 100644 index 000000000..f68415170 --- /dev/null +++ b/gateway/tests/test_sqlite_boolean_defaults.py @@ -0,0 +1,237 @@ +"""SQLite boolean columns created as false must stay false. + +refresh_tokens.revoked, permits.requires_human_approval, and +human_approvals.simulated are read through SQLAlchemy. On SQLite the text +value 'false' is read as true. These tests cover a fresh upgrade, where an +omitted column must store an integer false, and an upgrade through 024, +where text 'false' becomes false and text 'true' stays true. +""" + +from __future__ import annotations + +import asyncio +import sqlite3 + +from alembic import command +from alembic.config import Config +from sqlalchemy import Boolean, Column, MetaData, String, Table, create_engine, select + + +def _upgrade(monkeypatch, db_path, revision: str) -> None: + monkeypatch.setenv("DATABASE_URL", f"sqlite+aiosqlite:///{db_path}") + command.upgrade(Config("alembic.ini"), revision) + asyncio.set_event_loop(asyncio.new_event_loop()) + + +def _seed_wallet_and_key(db_path) -> None: + connection = sqlite3.connect(db_path) + connection.execute( + """ + INSERT INTO wallets ( + wallet_id, wallet_type, owner_key, balance, lifetime_credits, + lifetime_debits, daily_spent, auto_refill, status + ) VALUES ('w-bool', 'agent', '', 0, 0, 0, 0, 0, 'active') + """ + ) + connection.execute( + """ + INSERT INTO signing_keys (key_id, alg, public_key_b64, status) + VALUES ('k-bool', 'Ed25519', 'public', 'active') + """ + ) + connection.commit() + connection.close() + + +def _insert_permit(db_path, permit_id: str, *, approval_sql: str | None) -> None: + approval_column = "" + approval_value = "" + if approval_sql is not None: + approval_column = ", requires_human_approval" + approval_value = f", {approval_sql}" + connection = sqlite3.connect(db_path) + connection.execute( + f""" + INSERT INTO permits ( + permit_id, issuer_wallet_id, subject_wallet_id, scopes_json, + allowed_tools_json, max_credits, expires_at, nonce, status, + signature, key_id, issued_at{approval_column} + ) VALUES ( + ?, 'w-bool', 'w-bool', '[]', '[]', 10, '2030-01-01 00:00:00', + ?, 'active', 'sig', 'k-bool', '2026-01-01 00:00:00'{approval_value} + ) + """, + (permit_id, f"nonce-{permit_id}"), + ) + connection.commit() + connection.close() + + +def _read_bool(db_path, table: str, column: str, key_column: str, key: str): + engine = create_engine(f"sqlite:///{db_path}") + reflected = Table( + table, + MetaData(), + Column(key_column, String, primary_key=True), + Column(column, Boolean), + ) + with engine.connect() as connection: + value = connection.execute( + select(reflected.c[column]).where(reflected.c[key_column] == key) + ).scalar_one() + engine.dispose() + return value + + +def _typeof(db_path, table: str, column: str, key_column: str, key: str) -> str: + connection = sqlite3.connect(db_path) + row = connection.execute( + f"SELECT typeof({column}) FROM {table} WHERE {key_column} = ?", + (key,), + ).fetchone() + connection.close() + return row[0] + + +def test_024_repairs_every_text_false_boolean(tmp_path, monkeypatch): + """Text 'false' on the three string-default booleans must become false.""" + db_path = tmp_path / "boolean-repair.db" + _upgrade(monkeypatch, db_path, "023_human_approval_gate") + _seed_wallet_and_key(db_path) + _insert_permit(db_path, "p-text", approval_sql="'false'") + _insert_permit(db_path, "p-true", approval_sql="'true'") + connection = sqlite3.connect(db_path) + connection.execute( + """ + INSERT INTO refresh_tokens (jti, wallet_id, revoked, created_at, expires_at) + VALUES ('j-text', 'w-bool', 'false', '2026-01-01', '2026-02-01') + """ + ) + connection.execute( + """ + INSERT INTO refresh_tokens (jti, wallet_id, revoked, created_at, expires_at) + VALUES ('j-true', 'w-bool', 'true', '2026-01-01', '2026-02-01') + """ + ) + connection.execute( + """ + INSERT INTO human_approvals ( + approval_id, wallet_id, permit_id, tool, idempotency_key, + simulated, requested_at, expires_at + ) VALUES ( + 'a-text', 'w-bool', 'p-text', 'tool', 'idem-text', + 'false', '2026-01-01', '2026-02-01' + ) + """ + ) + connection.execute( + """ + INSERT INTO human_approvals ( + approval_id, wallet_id, permit_id, tool, idempotency_key, + simulated, requested_at, expires_at + ) VALUES ( + 'a-true', 'w-bool', 'p-true', 'tool', 'idem-true', + 'true', '2026-01-01', '2026-02-01' + ) + """ + ) + connection.commit() + connection.close() + + assert ( + _read_bool(db_path, "permits", "requires_human_approval", "permit_id", "p-text") + is True + ) + assert _read_bool(db_path, "refresh_tokens", "revoked", "jti", "j-text") is True + assert ( + _read_bool(db_path, "human_approvals", "simulated", "approval_id", "a-text") + is True + ) + + _upgrade(monkeypatch, db_path, "024_human_approval_hardening") + + assert ( + _read_bool(db_path, "permits", "requires_human_approval", "permit_id", "p-text") + is False + ) + assert _read_bool(db_path, "refresh_tokens", "revoked", "jti", "j-text") is False + assert ( + _read_bool(db_path, "human_approvals", "simulated", "approval_id", "a-text") + is False + ) + assert ( + _read_bool(db_path, "permits", "requires_human_approval", "permit_id", "p-true") + is True + ) + assert _read_bool(db_path, "refresh_tokens", "revoked", "jti", "j-true") is True + assert ( + _read_bool(db_path, "human_approvals", "simulated", "approval_id", "a-true") + is True + ) + assert ( + _typeof(db_path, "permits", "requires_human_approval", "permit_id", "p-text") + == "integer" + ) + assert _typeof(db_path, "refresh_tokens", "revoked", "jti", "j-text") == "integer" + assert ( + _typeof(db_path, "human_approvals", "simulated", "approval_id", "a-text") + == "integer" + ) + + +def test_head_omitted_boolean_defaults_read_as_false(tmp_path, monkeypatch): + """An omitted boolean must stay false after later migrations.""" + db_path = tmp_path / "boolean-default.db" + _upgrade(monkeypatch, db_path, "head") + _seed_wallet_and_key(db_path) + _insert_permit(db_path, "p-default", approval_sql=None) + connection = sqlite3.connect(db_path) + connection.execute( + """ + INSERT INTO refresh_tokens (jti, wallet_id, created_at, expires_at) + VALUES ('j-default', 'w-bool', '2026-01-01', '2026-02-01') + """ + ) + connection.execute( + """ + INSERT INTO human_approvals ( + approval_id, wallet_id, permit_id, tool, idempotency_key, + requested_at, expires_at + ) VALUES ( + 'a-default', 'w-bool', 'p-default', 'tool', 'idem-default', + '2026-01-01', '2026-02-01' + ) + """ + ) + connection.commit() + connection.close() + + reads = { + "requires_human_approval": _read_bool( + db_path, "permits", "requires_human_approval", "permit_id", "p-default" + ), + "allow_identical_repeats": _read_bool( + db_path, "permits", "allow_identical_repeats", "permit_id", "p-default" + ), + "revoked": _read_bool(db_path, "refresh_tokens", "revoked", "jti", "j-default"), + "simulated": _read_bool( + db_path, "human_approvals", "simulated", "approval_id", "a-default" + ), + } + assert reads == { + "requires_human_approval": False, + "allow_identical_repeats": False, + "revoked": False, + "simulated": False, + } + assert ( + _typeof(db_path, "permits", "requires_human_approval", "permit_id", "p-default") + == "integer" + ) + assert ( + _typeof(db_path, "refresh_tokens", "revoked", "jti", "j-default") == "integer" + ) + assert ( + _typeof(db_path, "human_approvals", "simulated", "approval_id", "a-default") + == "integer" + ) diff --git a/gateway/tests/test_sqlite_legacy_boolean_defaults.py b/gateway/tests/test_sqlite_legacy_boolean_defaults.py new file mode 100644 index 000000000..0b958858b --- /dev/null +++ b/gateway/tests/test_sqlite_legacy_boolean_defaults.py @@ -0,0 +1,148 @@ +"""Legacy SQLite defaults remain safe after upgrading an existing database.""" + +import asyncio +import sqlite3 + +from alembic import command +from alembic.config import Config +from alembic.script import ScriptDirectory +import pytest + + +_COLUMNS = ( + ("refresh_tokens", "revoked"), + ("human_approvals", "simulated"), + ("permits", "requires_human_approval"), +) + + +def _upgrade(monkeypatch, db_path, revision): + monkeypatch.setenv("DATABASE_URL", f"sqlite+aiosqlite:///{db_path}") + command.upgrade(Config("alembic.ini"), revision) + asyncio.set_event_loop(asyncio.new_event_loop()) + + +def _defaults(connection): + return { + (table, column): next( + row[4] + for row in connection.execute(f"PRAGMA table_info({table})") + if row[1] == column + ) + for table, column in _COLUMNS + } + + +def test_upgrade_repairs_legacy_sqlite_defaults(tmp_path, monkeypatch): + script = ScriptDirectory.from_config(Config("alembic.ini")) + assert script.get_heads() == ["051_sqlite_boolean_defaults"] + assert script.get_revision("051_sqlite_boolean_defaults").down_revision == ( + "050_demo_key_first_used" + ) + + db_path = tmp_path / "legacy-defaults.db" + _upgrade(monkeypatch, db_path, "023_human_approval_gate") + + # Reproduce the schema defaults emitted by the original 022 and 023. + with sqlite3.connect(db_path) as connection: + connection.execute("PRAGMA writable_schema = ON") + for table, column in _COLUMNS: + old = f"{column} BOOLEAN DEFAULT 0 NOT NULL" + new = f"{column} BOOLEAN DEFAULT 'false' NOT NULL" + connection.execute( + "UPDATE sqlite_master SET sql = replace(sql, ?, ?) " + "WHERE type = 'table' AND name = ?", + (old, new, table), + ) + assert connection.execute("SELECT changes()").fetchone()[0] == 1 + connection.execute("PRAGMA writable_schema = OFF") + schema_version = connection.execute("PRAGMA schema_version").fetchone()[0] + connection.execute(f"PRAGMA schema_version = {schema_version + 1}") + + _upgrade(monkeypatch, db_path, "044_receipt_resolutions") + with sqlite3.connect(db_path) as connection: + assert set(_defaults(connection).values()) == {"'false'"} + connection.execute( + "INSERT INTO wallets (wallet_id, wallet_type, owner_key, balance, " + "lifetime_credits, lifetime_debits, daily_spent, auto_refill, status) " + "VALUES ('w-legacy', 'agent', '', 0, 0, 0, 0, 0, 'active')" + ) + connection.execute( + "INSERT INTO signing_keys (key_id, alg, public_key_b64, status) " + "VALUES ('k-legacy', 'Ed25519', 'public', 'active')" + ) + connection.executemany( + "INSERT INTO permits (permit_id, issuer_wallet_id, subject_wallet_id, " + "scopes_json, allowed_tools_json, max_credits, expires_at, nonce, " + "status, signature, key_id) VALUES (?, 'w-legacy', 'w-legacy', " + "'[]', '[]', 1, '2030-01-01', ?, 'active', 'sig', 'k-legacy')", + (("p-default", "n-default"), ("p-true", "n-true")), + ) + connection.executemany( + "INSERT INTO refresh_tokens (jti, wallet_id, created_at, expires_at) " + "VALUES (?, 'w-legacy', '2026-01-01', '2026-02-01')", + (("j-default",), ("j-true",)), + ) + connection.executemany( + "INSERT INTO human_approvals (approval_id, wallet_id, permit_id, " + "tool, idempotency_key, requested_at, expires_at) " + "VALUES (?, 'w-legacy', ?, 'tool', ?, '2026-01-01', '2026-02-01')", + ( + ("a-default", "p-default", "idem-default"), + ("a-true", "p-true", "idem-true"), + ), + ) + for table, column, key in ( + ("refresh_tokens", "revoked", "jti"), + ("human_approvals", "simulated", "approval_id"), + ("permits", "requires_human_approval", "permit_id"), + ): + connection.execute( + f"UPDATE {table} SET {column} = 'true' WHERE {key} LIKE '%-true'" + ) + assert connection.execute( + f"SELECT {column}, typeof({column}) FROM {table} ORDER BY {key}" + ).fetchall() == [("false", "text"), ("true", "text")] + indexes = { + table: { + row[1:] for row in connection.execute(f"PRAGMA index_list({table})") + } + for table, _ in _COLUMNS + } + foreign_keys = { + table: { + row[2:] + for row in connection.execute(f"PRAGMA foreign_key_list({table})") + } + for table, _ in _COLUMNS + } + + _upgrade(monkeypatch, db_path, "head") + with sqlite3.connect(db_path) as connection: + assert set(_defaults(connection).values()) == {"0"} + for table, column, key in ( + ("refresh_tokens", "revoked", "jti"), + ("human_approvals", "simulated", "approval_id"), + ("permits", "requires_human_approval", "permit_id"), + ): + assert connection.execute( + f"SELECT {column}, typeof({column}) FROM {table} ORDER BY {key}" + ).fetchall() == [(0, "integer"), (1, "integer")] + assert { + row[1:] for row in connection.execute(f"PRAGMA index_list({table})") + } == indexes[table] + assert { + row[2:] + for row in connection.execute(f"PRAGMA foreign_key_list({table})") + } == foreign_keys[table] + + with pytest.raises( + RuntimeError, match="sqlite_boolean_defaults_downgrade_unsupported" + ): + command.downgrade(Config("alembic.ini"), "050_demo_key_first_used") + asyncio.set_event_loop(asyncio.new_event_loop()) + with sqlite3.connect(db_path) as connection: + assert connection.execute( + "SELECT version_num FROM alembic_version" + ).fetchone() == ("051_sqlite_boolean_defaults",) + assert set(_defaults(connection).values()) == {"0"}