"""Adding a column to a database that already exists. There is no Alembic here: ``_ensure_model_columns`` diffs each model against the live table and ``ADD COLUMN``s what is missing. That covers the only kind of change made so far, but it has a sharp edge — SQLite fills an added column with NULL unless the statement carries a DEFAULT. ``User.token_version`` is where that edge would have cut: existing rows would have come back NULL, every token's version check would have failed against it, and the upgrade would have signed out every user on every install. So the helper now renders a DEFAULT for scalar defaults, and this file pins that behaviour against a genuinely old-shaped table. """ from __future__ import annotations import pytest from sqlalchemy import create_engine, inspect, text @pytest.fixture def legacy_db(tmp_path, monkeypatch): """A database whose ``user`` table predates ``token_version``.""" import database import models # noqa: F401 — populates SQLModel.metadata db_file = tmp_path / "legacy.db" engine = create_engine(f"sqlite:///{db_file}") with engine.begin() as conn: conn.execute( text( """ CREATE TABLE user ( id INTEGER NOT NULL PRIMARY KEY, username VARCHAR NOT NULL, hashed_password VARCHAR NOT NULL, role VARCHAR NOT NULL, is_active BOOLEAN NOT NULL, created_at DATETIME NOT NULL ) """ ) ) conn.execute( text( "INSERT INTO user (id, username, hashed_password, role, is_active," " created_at) VALUES (1, 'olduser', 'x', 'admin', 1, '2026-01-01')" ) ) monkeypatch.setattr(database, "engine", engine) return engine def test_the_new_column_is_added_and_backfilled(legacy_db): import database assert "token_version" not in {c["name"] for c in inspect(legacy_db).get_columns("user")} database._ensure_model_columns() columns = {c["name"]: c for c in inspect(legacy_db).get_columns("user")} assert "token_version" in columns with legacy_db.begin() as conn: value = conn.execute(text("SELECT token_version FROM user WHERE id = 1")).scalar() assert value == 1, "existing rows must be backfilled, not left NULL" def test_the_existing_row_survives_untouched(legacy_db): import database database._ensure_model_columns() with legacy_db.begin() as conn: row = conn.execute(text("SELECT username, role FROM user WHERE id = 1")).one() assert row.username == "olduser" assert row.role == "admin" def test_running_it_twice_changes_nothing(legacy_db): import database database._ensure_model_columns() database._ensure_model_columns() # must not raise "duplicate column name" with legacy_db.begin() as conn: assert conn.execute(text("SELECT token_version FROM user")).scalar() == 1 @pytest.mark.parametrize( "value,expected", [ (1, "1"), (0, "0"), (True, "1"), (False, "0"), ("user", "'user'"), ("it's", "'it''s'"), # quotes escaped, not injected ], ) def test_default_literals_are_rendered_and_escaped(value, expected): from sqlalchemy import Column, Integer import database column = Column("c", Integer, default=value) assert database._default_literal(column) == expected def test_callable_defaults_have_no_literal(): """``default_factory`` (a timestamp, say) has no fixed value to backfill — such a column is added nullable, as before.""" from sqlalchemy import Column, DateTime import database from models.user import User assert database._default_literal(Column("c", DateTime, default=lambda: 1)) is None assert database._default_literal(User.__table__.columns["created_at"]) is None def test_the_live_schema_matches_the_models(db): """Belt and braces on the real database the rest of the suite uses.""" from sqlmodel import SQLModel import database inspector = inspect(database.engine) for table_name, table in SQLModel.metadata.tables.items(): live = {c["name"] for c in inspector.get_columns(table_name)} missing = {c.name for c in table.columns} - live assert not missing, f"{table_name} is missing {missing}"