Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

66.7 KB
Raw Blame
"""Tests for SQLite target connector."""

from __future__ import annotations

import logging
import sqlite3
import struct
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Annotated, Any, Iterator, cast

import numpy as np
import pytest
from numpy.typing import NDArray

import cocoindex as coco
from cocoindex._internal.context_keys import ContextProvider
from cocoindex.connectorkits import statediff, target
from cocoindex.connectors import sqlite
from cocoindex.resources.schema import VectorSchema

from tests import common

SQLITE_DB = coco.ContextKey[sqlite.ManagedConnection]("sqlite_test_db")


# =============================================================================
# Check for sqlite-vec availability
# =============================================================================

try:
    import sqlite_vec  # type: ignore[import-not-found]  # noqa: F401

    HAS_SQLITE_VEC = True
except ImportError:
    HAS_SQLITE_VEC = False

requires_sqlite_vec = pytest.mark.skipif(
    not HAS_SQLITE_VEC, reason="sqlite-vec is not installed"
)


# =============================================================================
# Test utilities
# =============================================================================


def read_table_data(
    managed_conn: sqlite.ManagedConnection, table_name: str
) -> list[dict[str, Any]]:
    """Read all rows from a table as a list of dicts."""
    with managed_conn.readonly() as conn:
        conn.row_factory = sqlite3.Row
        cursor = conn.execute(f'SELECT * FROM "{table_name}"')
        return [dict(row) for row in cursor.fetchall()]


def table_exists(managed_conn: sqlite.ManagedConnection, table_name: str) -> bool:
    """Check if a table exists."""
    with managed_conn.readonly() as conn:
        cursor = conn.execute(
            "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
            (table_name,),
        )
        return cursor.fetchone() is not None


def get_table_columns(
    managed_conn: sqlite.ManagedConnection, table_name: str
) -> dict[str, str]:
    """Get column names and types for a table."""
    with managed_conn.readonly() as conn:
        cursor = conn.execute(f'PRAGMA table_info("{table_name}")')
        return {row[1]: row[2] for row in cursor.fetchall()}


def get_table_sql(managed_conn: sqlite.ManagedConnection, table_name: str) -> str:
    """Get the CREATE TABLE statement of a table."""
    with managed_conn.readonly() as conn:
        row = conn.execute(
            "SELECT sql FROM sqlite_master WHERE type='table' AND name=?",
            (table_name,),
        ).fetchone()
    assert row is not None
    return str(row[0])


def get_column_notnull(
    managed_conn: sqlite.ManagedConnection, table_name: str, column_name: str
) -> bool:
    """Whether a column is declared NOT NULL."""
    with managed_conn.readonly() as conn:
        for row in conn.execute(f'PRAGMA table_info("{table_name}")'):
            if row[1] == column_name:
                return bool(row[3])
    raise AssertionError(f"column {column_name!r} not found in table {table_name!r}")


def decode_vector(blob: bytes, dim: int) -> list[float]:
    """Decode a sqlite-vec vector blob to a list of floats."""
    return list(struct.unpack(f"{dim}f", blob))


def make_test_env(
    managed_conn: sqlite.ManagedConnection, env_name: str
) -> coco.Environment:
    """Create a test environment with the SQLite connection provided."""
    ctx = ContextProvider()
    ctx.provide(SQLITE_DB, managed_conn)
    settings = coco.Settings.from_env(
        db_path=common.get_env_db_path(f"connectors__test_sqlite_target__{env_name}")
    )
    return coco.Environment(settings, context_provider=ctx)


# =============================================================================
# Test fixtures
# =============================================================================


@pytest.fixture
def sqlite_db() -> Iterator[tuple[sqlite.ManagedConnection, Path]]:
    """Create a temporary SQLite database."""
    with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as f:
        db_path = Path(f.name)

    managed_conn = sqlite.connect(db_path)
    yield managed_conn, db_path
    managed_conn.close()
    db_path.unlink(missing_ok=True)


# =============================================================================
# Row types for testing
# =============================================================================


@dataclass
class SimpleRow:
    id: str
    name: str
    value: int


@dataclass
class ExtendedRow:
    id: str
    name: str
    value: int
    extra: str


@dataclass
class NullableIntValueRow:
    id: str
    name: str
    value: int | None


@dataclass
class NullableStrValueRow:
    id: str
    name: str
    value: str | None


@dataclass
class CollatedNameRow:
    id: str
    name: Annotated[str, sqlite.SqliteType("TEXT COLLATE NOCASE")]


@dataclass
class NoValueRow:
    id: str
    name: str


# =============================================================================
# Source data (global state for tests)
# =============================================================================

_source_rows: list[Any] = []
_row_type: type = SimpleRow
_table_name: str = "test_table"


# =============================================================================
# App functions
# =============================================================================


async def declare_table_and_rows() -> None:
    """Declare table and rows from global source data."""
    table = await coco.use_mount(
        coco.component_subpath("setup", "table"),
        sqlite.declare_table_target,
        SQLITE_DB,
        _table_name,
        await sqlite.TableSchema.from_class(_row_type, primary_key=["id"]),
    )

    for row in _source_rows:
        table.declare_row(row=row)


# =============================================================================
# Non-vector test cases
# =============================================================================


def test_create_table_and_insert_rows(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test creating a table and inserting rows."""
    managed_conn, _ = sqlite_db
    global _source_rows, _row_type, _table_name

    _source_rows = []
    _row_type = SimpleRow
    _table_name = "test_create"

    test_env = make_test_env(managed_conn, "test_create_table_and_insert_rows")

    app = coco.App(
        coco.AppConfig(name="test_create_table_and_insert", environment=test_env),
        declare_table_and_rows,
    )

    # Insert initial data
    _source_rows = [
        SimpleRow(id="1", name="Alice", value=100),
        SimpleRow(id="2", name="Bob", value=200),
    ]
    app.update_blocking()

    assert table_exists(managed_conn, _table_name)
    data = read_table_data(managed_conn, _table_name)
    assert len(data) == 2
    assert {"id": "1", "name": "Alice", "value": 100} in data
    assert {"id": "2", "name": "Bob", "value": 200} in data

    # Insert more data
    _source_rows.append(SimpleRow(id="3", name="Charlie", value=300))
    app.update_blocking()

    data = read_table_data(managed_conn, _table_name)
    assert len(data) == 3
    assert {"id": "3", "name": "Charlie", "value": 300} in data


def test_update_row(sqlite_db: tuple[sqlite.ManagedConnection, Path]) -> None:
    """Test updating an existing row."""
    managed_conn, _ = sqlite_db
    global _source_rows, _row_type, _table_name

    _source_rows = []
    _row_type = SimpleRow
    _table_name = "test_update"

    test_env = make_test_env(managed_conn, "test_update_row")

    app = coco.App(
        coco.AppConfig(name="test_update_row", environment=test_env),
        declare_table_and_rows,
    )

    # Insert initial data
    _source_rows = [
        SimpleRow(id="1", name="Alice", value=100),
        SimpleRow(id="2", name="Bob", value=200),
    ]
    app.update_blocking()

    data = read_table_data(managed_conn, _table_name)
    assert len(data) == 2

    # Update a row
    _source_rows = [
        SimpleRow(id="1", name="Alice Updated", value=150),
        SimpleRow(id="2", name="Bob", value=200),
    ]
    app.update_blocking()

    data = read_table_data(managed_conn, _table_name)
    assert len(data) == 2
    assert {"id": "1", "name": "Alice Updated", "value": 150} in data
    assert {"id": "2", "name": "Bob", "value": 200} in data


def test_delete_row(sqlite_db: tuple[sqlite.ManagedConnection, Path]) -> None:
    """Test deleting a row."""
    managed_conn, _ = sqlite_db
    global _source_rows, _row_type, _table_name

    _source_rows = []
    _row_type = SimpleRow
    _table_name = "test_delete"

    test_env = make_test_env(managed_conn, "test_delete_row")

    app = coco.App(
        coco.AppConfig(name="test_delete_row", environment=test_env),
        declare_table_and_rows,
    )

    # Insert initial data
    _source_rows = [
        SimpleRow(id="1", name="Alice", value=100),
        SimpleRow(id="2", name="Bob", value=200),
        SimpleRow(id="3", name="Charlie", value=300),
    ]
    app.update_blocking()

    data = read_table_data(managed_conn, _table_name)
    assert len(data) == 3

    # Delete a row
    _source_rows = [
        SimpleRow(id="1", name="Alice", value=100),
        SimpleRow(id="3", name="Charlie", value=300),
    ]
    app.update_blocking()

    data = read_table_data(managed_conn, _table_name)
    assert len(data) == 2
    assert {"id": "1", "name": "Alice", "value": 100} in data
    assert {"id": "3", "name": "Charlie", "value": 300} in data
    # Bob should be deleted
    assert not any(row["id"] == "2" for row in data)


def test_dataclass_row_null_primary_key_raises(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test dataclass rows cannot declare NULL primary keys."""
    managed_conn, _ = sqlite_db
    global _source_rows, _row_type, _table_name

    old_source_rows = _source_rows
    old_row_type = _row_type
    old_table_name = _table_name
    try:
        _row_type = SimpleRow
        _table_name = "test_dataclass_null_pk"
        _source_rows = [SimpleRow(id=cast(Any, None), name="No id", value=1)]

        test_env = make_test_env(
            managed_conn, "test_dataclass_row_null_primary_key_raises"
        )
        app = coco.App(
            coco.AppConfig(
                name="test_dataclass_row_null_primary_key_raises",
                environment=test_env,
            ),
            declare_table_and_rows,
        )

        with pytest.raises(
            ValueError, match="SQLite primary key column 'id' cannot be None"
        ):
            app.update_blocking()
    finally:
        _source_rows = old_source_rows
        _row_type = old_row_type
        _table_name = old_table_name


def test_different_schema_types(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test creating tables with different schema types (dataclass with different columns)."""
    managed_conn, _ = sqlite_db

    extended_rows: list[ExtendedRow] = []

    test_env = make_test_env(managed_conn, "test_different_schema_types")

    async def declare_extended_table() -> None:
        table = await coco.use_mount(
            coco.component_subpath("setup", "table"),
            sqlite.declare_table_target,
            SQLITE_DB,
            "extended_table",
            await sqlite.TableSchema.from_class(ExtendedRow, primary_key=["id"]),
        )
        for row in extended_rows:
            table.declare_row(row=row)

    app = coco.App(
        coco.AppConfig(name="test_different_schema_types", environment=test_env),
        declare_extended_table,
    )

    extended_rows.extend(
        [
            ExtendedRow(id="1", name="Alice", value=100, extra="extra_data"),
            ExtendedRow(id="2", name="Bob", value=200, extra="more_data"),
        ]
    )
    app.update_blocking()

    columns = get_table_columns(managed_conn, "extended_table")
    assert "extra" in columns

    data = read_table_data(managed_conn, "extended_table")
    assert len(data) == 2
    assert {"id": "1", "name": "Alice", "value": 100, "extra": "extra_data"} in data
    assert {"id": "2", "name": "Bob", "value": 200, "extra": "more_data"} in data


def test_drop_table(sqlite_db: tuple[sqlite.ManagedConnection, Path]) -> None:
    """Test dropping a table when no longer declared."""
    managed_conn, _ = sqlite_db
    global _source_rows, _row_type, _table_name

    _source_rows = []
    _row_type = SimpleRow
    _table_name = "test_drop"

    test_env = make_test_env(managed_conn, "test_drop_table")

    async def declare_table_conditionally() -> None:
        if _source_rows:  # Only declare if there are rows
            table = await coco.use_mount(
                coco.component_subpath("setup", "table"),
                sqlite.declare_table_target,
                SQLITE_DB,
                _table_name,
                await sqlite.TableSchema.from_class(_row_type, primary_key=["id"]),
            )
            for row in _source_rows:
                table.declare_row(row=row)

    app = coco.App(
        coco.AppConfig(name="test_drop_table", environment=test_env),
        declare_table_conditionally,
    )

    # Create table with data
    _source_rows = [SimpleRow(id="1", name="Alice", value=100)]
    app.update_blocking()

    assert table_exists(managed_conn, _table_name)

    # Remove all rows (table should be dropped)
    _source_rows = []
    app.update_blocking()

    assert not table_exists(managed_conn, _table_name)


def test_no_change_optimization(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that unchanged data doesn't cause unnecessary updates."""
    managed_conn, _ = sqlite_db
    global _source_rows, _row_type, _table_name

    _source_rows = []
    _row_type = SimpleRow
    _table_name = "test_no_change"

    test_env = make_test_env(managed_conn, "test_no_change_optimization")

    app = coco.App(
        coco.AppConfig(name="test_no_change", environment=test_env),
        declare_table_and_rows,
    )

    # Insert initial data
    _source_rows = [
        SimpleRow(id="1", name="Alice", value=100),
        SimpleRow(id="2", name="Bob", value=200),
    ]
    app.update_blocking()

    data1 = read_table_data(managed_conn, _table_name)
    assert len(data1) == 2

    # Run update again with same data - should be a no-op
    app.update_blocking()

    data2 = read_table_data(managed_conn, _table_name)
    assert data1 == data2


def _planned_actions(actions: list[Any] | None) -> dict[Any, Any]:
    """Planned preview actions: ``("table", name) -> main action`` and
    ``("row", key) -> value`` (``None``: delete)."""
    assert actions is not None
    plan: dict[Any, Any] = {}
    for action in actions:
        if isinstance(action, sqlite._target._TableAction):
            plan[("table", action.key.table_name)] = action.main_action
        else:
            assert isinstance(action, sqlite._target._RowAction)
            plan[("row", action.key)] = action.value
    assert len(plan) == len(actions)
    return plan


def test_preview_rows(sqlite_db: tuple[sqlite.ManagedConnection, Path]) -> None:
    """Preview plans the table and its rows without creating either."""
    managed_conn, _ = sqlite_db
    global _source_rows, _row_type, _table_name

    _source_rows = []
    _row_type = SimpleRow
    _table_name = "test_preview"

    test_env = make_test_env(managed_conn, "test_preview_rows")

    app = coco.App(
        coco.AppConfig(name="test_preview_rows", environment=test_env),
        declare_table_and_rows,
    )

    # The table's action and one per row; nothing is created.
    _source_rows = [
        SimpleRow(id="1", name="Alice", value=100),
        SimpleRow(id="2", name="Bob", value=200),
    ]
    actions = app.update_blocking(preview=True)
    assert _planned_actions(actions) == {
        ("table", _table_name): "insert",
        ("row", ("1",)): {"id": "1", "name": "Alice", "value": 100},
        ("row", ("2",)): {"id": "2", "name": "Bob", "value": 200},
    }
    assert not table_exists(managed_conn, _table_name)

    app.update_blocking()
    assert len(read_table_data(managed_conn, _table_name)) == 2

    # Against the applied state: the table's action (no change of its own),
    # row 2 changed and row 3 added; row 1 is unchanged; the container action is still
    # listed. Nothing is applied.
    _source_rows = [
        SimpleRow(id="1", name="Alice", value=100),
        SimpleRow(id="2", name="Bob", value=250),
        SimpleRow(id="3", name="Charlie", value=300),
    ]
    actions = app.update_blocking(preview=True)
    assert _planned_actions(actions) == {
        ("table", _table_name): None,
        ("row", ("2",)): {"id": "2", "name": "Bob", "value": 250},
        ("row", ("3",)): {"id": "3", "name": "Charlie", "value": 300},
    }
    data = read_table_data(managed_conn, _table_name)
    assert len(data) == 2
    assert {"id": "2", "name": "Bob", "value": 200} in data

    app.update_blocking()
    data = read_table_data(managed_conn, _table_name)
    assert len(data) == 3
    assert {"id": "2", "name": "Bob", "value": 250} in data


def test_multiple_tables(sqlite_db: tuple[sqlite.ManagedConnection, Path]) -> None:
    """Test managing multiple tables in the same database."""
    managed_conn, _ = sqlite_db

    table1_rows: list[SimpleRow] = []
    table2_rows: list[SimpleRow] = []

    test_env = make_test_env(managed_conn, "test_multiple_tables")

    async def declare_multiple_tables() -> None:
        schema = await sqlite.TableSchema.from_class(SimpleRow, primary_key=["id"])

        table1 = await coco.use_mount(
            coco.component_subpath("setup", "table1"),
            sqlite.declare_table_target,
            SQLITE_DB,
            "users",
            schema,
        )

        table2 = await coco.use_mount(
            coco.component_subpath("setup", "table2"),
            sqlite.declare_table_target,
            SQLITE_DB,
            "products",
            schema,
        )

        for row in table1_rows:
            table1.declare_row(row=row)

        for row in table2_rows:
            table2.declare_row(row=row)

    app = coco.App(
        coco.AppConfig(name="test_multiple_tables", environment=test_env),
        declare_multiple_tables,
    )

    # Insert data into both tables
    table1_rows.extend(
        [
            SimpleRow(id="u1", name="User1", value=1),
            SimpleRow(id="u2", name="User2", value=2),
        ]
    )
    table2_rows.extend(
        [
            SimpleRow(id="p1", name="Product1", value=100),
            SimpleRow(id="p2", name="Product2", value=200),
        ]
    )
    app.update_blocking()

    assert table_exists(managed_conn, "users")
    assert table_exists(managed_conn, "products")

    users_data = read_table_data(managed_conn, "users")
    products_data = read_table_data(managed_conn, "products")

    assert len(users_data) == 2
    assert len(products_data) == 2


def test_dict_rows(sqlite_db: tuple[sqlite.ManagedConnection, Path]) -> None:
    """Test using dict rows instead of dataclass rows."""
    managed_conn, _ = sqlite_db

    dict_rows: list[dict[str, Any]] = []

    test_env = make_test_env(managed_conn, "test_dict_rows")

    async def declare_dict_table() -> None:
        table = await coco.use_mount(
            coco.component_subpath("setup", "table"),
            sqlite.declare_table_target,
            SQLITE_DB,
            "dict_table",
            sqlite.TableSchema(
                {
                    "id": sqlite.ColumnDef(type="TEXT", nullable=False),
                    "name": sqlite.ColumnDef(type="TEXT"),
                    "count": sqlite.ColumnDef(type="INTEGER"),
                },
                primary_key=["id"],
            ),
        )

        for row in dict_rows:
            table.declare_row(row=row)

    app = coco.App(
        coco.AppConfig(name="test_dict_rows", environment=test_env),
        declare_dict_table,
    )

    dict_rows.extend(
        [
            {"id": "1", "name": "Item1", "count": 10},
            {"id": "2", "name": "Item2", "count": 20},
        ]
    )
    app.update_blocking()

    data = read_table_data(managed_conn, "dict_table")
    assert len(data) == 2
    assert {"id": "1", "name": "Item1", "count": 10} in data


def test_dict_row_missing_primary_key_raises(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test dict rows missing primary keys are rejected."""
    managed_conn, _ = sqlite_db

    dict_rows: list[dict[str, Any]] = []

    test_env = make_test_env(managed_conn, "test_dict_row_missing_primary_key_raises")

    async def declare_dict_table() -> None:
        table = await coco.use_mount(
            coco.component_subpath("setup", "table"),
            sqlite.declare_table_target,
            SQLITE_DB,
            "dict_missing_pk",
            sqlite.TableSchema(
                {
                    "id": sqlite.ColumnDef(type="TEXT", nullable=False),
                    "name": sqlite.ColumnDef(type="TEXT"),
                    "count": sqlite.ColumnDef(type="INTEGER"),
                },
                primary_key=["id"],
            ),
        )

        for row in dict_rows:
            table.declare_row(row=row)

    app = coco.App(
        coco.AppConfig(
            name="test_dict_row_missing_primary_key_raises", environment=test_env
        ),
        declare_dict_table,
    )

    dict_rows.extend([{"name": "Item1", "count": 1}])
    with pytest.raises(
        ValueError, match="SQLite row is missing primary key column 'id'"
    ):
        app.update_blocking()


def test_dict_row_null_primary_key_raises(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test dict rows with NULL primary keys are rejected."""
    managed_conn, _ = sqlite_db

    dict_rows: list[dict[str, Any]] = []

    test_env = make_test_env(managed_conn, "test_dict_row_null_primary_key_raises")

    async def declare_dict_table() -> None:
        table = await coco.use_mount(
            coco.component_subpath("setup", "table"),
            sqlite.declare_table_target,
            SQLITE_DB,
            "dict_null_pk",
            sqlite.TableSchema(
                {
                    "id": sqlite.ColumnDef(type="TEXT", nullable=False),
                    "name": sqlite.ColumnDef(type="TEXT"),
                    "count": sqlite.ColumnDef(type="INTEGER"),
                },
                primary_key=["id"],
            ),
        )

        for row in dict_rows:
            table.declare_row(row=row)

    app = coco.App(
        coco.AppConfig(
            name="test_dict_row_null_primary_key_raises", environment=test_env
        ),
        declare_dict_table,
    )

    dict_rows.extend([{"id": None, "name": "Item1", "count": 1}])
    with pytest.raises(
        ValueError, match="SQLite primary key column 'id' cannot be None"
    ):
        app.update_blocking()


def test_dict_row_missing_nullable_non_key_writes_null(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test missing nullable non-key dict fields are written as NULL."""
    managed_conn, _ = sqlite_db

    dict_rows: list[dict[str, Any]] = []

    test_env = make_test_env(
        managed_conn, "test_dict_row_missing_nullable_non_key_writes_null"
    )

    async def declare_dict_table() -> None:
        table = await coco.use_mount(
            coco.component_subpath("setup", "table"),
            sqlite.declare_table_target,
            SQLITE_DB,
            "dict_missing_nullable",
            sqlite.TableSchema(
                {
                    "id": sqlite.ColumnDef(type="TEXT", nullable=False),
                    "name": sqlite.ColumnDef(type="TEXT"),
                    "count": sqlite.ColumnDef(type="INTEGER"),
                },
                primary_key=["id"],
            ),
        )

        for row in dict_rows:
            table.declare_row(row=row)

    app = coco.App(
        coco.AppConfig(
            name="test_dict_row_missing_nullable_non_key_writes_null",
            environment=test_env,
        ),
        declare_dict_table,
    )

    dict_rows.extend([{"id": "1", "name": "Item1"}])
    app.update_blocking()

    assert read_table_data(managed_conn, "dict_missing_nullable") == [
        {"id": "1", "name": "Item1", "count": None}
    ]


def test_user_managed_table(sqlite_db: tuple[sqlite.ManagedConnection, Path]) -> None:
    """Test user-managed table (CocoIndex only manages rows, not DDL)."""
    managed_conn, _ = sqlite_db

    # Pre-create the table manually
    with managed_conn.transaction() as conn:
        conn.execute("""
            CREATE TABLE user_managed (
                id TEXT PRIMARY KEY,
                name TEXT,
                value INTEGER
            )
        """)

    user_rows: list[SimpleRow] = []

    test_env = make_test_env(managed_conn, "test_user_managed_table")

    async def declare_user_managed_rows() -> None:
        table: sqlite.TableTarget[SimpleRow] = await coco.use_mount(
            coco.component_subpath("setup", "table"),
            sqlite.declare_table_target,
            SQLITE_DB,
            "user_managed",
            await sqlite.TableSchema.from_class(SimpleRow, primary_key=["id"]),
            managed_by=target.ManagedBy.USER,
        )

        for row in user_rows:
            table.declare_row(row=row)

    app = coco.App(
        coco.AppConfig(name="test_user_managed", environment=test_env),
        declare_user_managed_rows,
    )

    # Insert rows
    user_rows.extend(
        [
            SimpleRow(id="1", name="Alice", value=100),
        ]
    )
    app.update_blocking()

    data = read_table_data(managed_conn, "user_managed")
    assert len(data) == 1

    # Clear rows - table should remain (user-managed)
    user_rows.clear()
    app.update_blocking()

    # Table should still exist
    assert table_exists(managed_conn, "user_managed")
    # But rows should be deleted
    data = read_table_data(managed_conn, "user_managed")
    assert len(data) == 0


# =============================================================================
# Virtual table tests
# =============================================================================


@requires_sqlite_vec
def test_vec0_virtual_table_basic(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test creating a basic vec0 virtual table with vectors."""
    managed_conn, _ = sqlite_db

    @dataclass
    class Vec0Row:
        id: int
        content: str
        embedding: Annotated[
            NDArray[np.float32], VectorSchema(dtype=np.dtype(np.float32), size=4)
        ]

    rows: list[Vec0Row] = []

    test_env = make_test_env(managed_conn, "test_vec0_virtual_table_basic")

    async def declare_vec0_table() -> None:
        table = await coco.use_mount(
            coco.component_subpath("setup", "table"),
            sqlite.declare_table_target,
            SQLITE_DB,
            table_name="vec0_docs",
            table_schema=await sqlite.TableSchema.from_class(
                Vec0Row,
                primary_key=["id"],
            ),
            virtual_table_def=sqlite.Vec0TableDef(),
        )

        for row in rows:
            table.declare_row(row=row)

    app = coco.App(
        coco.AppConfig(name="Vec0BasicTest", environment=test_env),
        declare_vec0_table,
    )

    # Insert initial rows
    rows = [
        Vec0Row(
            id=1,
            content="Doc 1",
            embedding=np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32),
        ),
        Vec0Row(
            id=2,
            content="Doc 2",
            embedding=np.array([5.0, 6.0, 7.0, 8.0], dtype=np.float32),
        ),
    ]
    app.update_blocking()

    # Verify table was created as virtual table
    with managed_conn.readonly() as conn:
        cursor = conn.execute(
            "SELECT sql FROM sqlite_master WHERE type='table' AND name='vec0_docs'"
        )
        sql = cursor.fetchone()[0]
        assert "VIRTUAL TABLE" in sql
        assert "USING vec0" in sql

    # Verify data and decode vectors
    data = read_table_data(managed_conn, "vec0_docs")
    assert len(data) == 2

    doc1 = next(row for row in data if row["id"] == 1)
    assert doc1["content"] == "Doc 1"
    vector1 = decode_vector(doc1["embedding"], 4)
    assert vector1 == pytest.approx([1.0, 2.0, 3.0, 4.0])

    doc2 = next(row for row in data if row["id"] == 2)
    assert doc2["content"] == "Doc 2"
    vector2 = decode_vector(doc2["embedding"], 4)
    assert vector2 == pytest.approx([5.0, 6.0, 7.0, 8.0])

    # Test update
    rows[0] = Vec0Row(
        id=1,
        content="Updated Doc 1",
        embedding=np.array([9.0, 9.0, 9.0, 9.0], dtype=np.float32),
    )
    app.update_blocking()

    data = read_table_data(managed_conn, "vec0_docs")
    assert len(data) == 2
    doc1 = next(row for row in data if row["id"] == 1)
    assert doc1["content"] == "Updated Doc 1"
    vector1 = decode_vector(doc1["embedding"], 4)
    assert vector1 == pytest.approx([9.0, 9.0, 9.0, 9.0])

    # Test delete
    rows.pop(0)  # Remove doc1
    app.update_blocking()

    data = read_table_data(managed_conn, "vec0_docs")
    assert len(data) == 1
    assert data[0]["id"] == 2


@requires_sqlite_vec
def test_vec0_with_partition_keys(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test vec0 virtual table with partition keys."""
    managed_conn, _ = sqlite_db

    @dataclass
    class Vec0PartitionedRow:
        id: int
        year: int
        content: str
        embedding: Annotated[
            NDArray[np.float32], VectorSchema(dtype=np.dtype(np.float32), size=2)
        ]

    rows: list[Vec0PartitionedRow] = []

    test_env = make_test_env(managed_conn, "test_vec0_with_partition_keys")

    async def declare_partitioned_table() -> None:
        table = await coco.use_mount(
            coco.component_subpath("setup", "table"),
            sqlite.declare_table_target,
            SQLITE_DB,
            table_name="vec0_partitioned",
            table_schema=await sqlite.TableSchema.from_class(
                Vec0PartitionedRow,
                primary_key=["id"],
            ),
            virtual_table_def=sqlite.Vec0TableDef(
                partition_key_columns=["year"],
            ),
        )

        for row in rows:
            table.declare_row(row=row)

    app = coco.App(
        coco.AppConfig(name="Vec0PartitionTest", environment=test_env),
        declare_partitioned_table,
    )

    rows = [
        Vec0PartitionedRow(
            id=1,
            year=2024,
            content="Old doc",
            embedding=np.array([1.0, 2.0], dtype=np.float32),
        ),
        Vec0PartitionedRow(
            id=2,
            year=2025,
            content="New doc",
            embedding=np.array([3.0, 4.0], dtype=np.float32),
        ),
    ]
    app.update_blocking()

    # Verify CREATE statement includes partition key
    with managed_conn.readonly() as conn:
        cursor = conn.execute(
            "SELECT sql FROM sqlite_master WHERE type='table' AND name='vec0_partitioned'"
        )
        sql = cursor.fetchone()[0]
        assert "partition key" in sql.lower()

    data = read_table_data(managed_conn, "vec0_partitioned")
    assert len(data) == 2


@requires_sqlite_vec
def test_vec0_with_auxiliary_columns(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test vec0 virtual table with auxiliary columns."""
    managed_conn, _ = sqlite_db

    @dataclass
    class Vec0AuxRow:
        id: int
        content: str
        metadata: str  # Auxiliary column
        embedding: Annotated[
            NDArray[np.float32], VectorSchema(dtype=np.dtype(np.float32), size=2)
        ]

    rows: list[Vec0AuxRow] = []

    test_env = make_test_env(managed_conn, "test_vec0_with_auxiliary_columns")

    async def declare_aux_table() -> None:
        table = await coco.use_mount(
            coco.component_subpath("setup", "table"),
            sqlite.declare_table_target,
            SQLITE_DB,
            table_name="vec0_with_aux",
            table_schema=await sqlite.TableSchema.from_class(
                Vec0AuxRow,
                primary_key=["id"],
            ),
            virtual_table_def=sqlite.Vec0TableDef(
                auxiliary_columns=["metadata"],
            ),
        )

        for row in rows:
            table.declare_row(row=row)

    app = coco.App(
        coco.AppConfig(name="Vec0AuxTest", environment=test_env),
        declare_aux_table,
    )

    rows = [
        Vec0AuxRow(
            id=1,
            content="Doc",
            metadata="extra info",
            embedding=np.array([1.0, 2.0], dtype=np.float32),
        ),
    ]
    app.update_blocking()

    # Verify CREATE statement includes + prefix for auxiliary column
    with managed_conn.readonly() as conn:
        cursor = conn.execute(
            "SELECT sql FROM sqlite_master WHERE type='table' AND name='vec0_with_aux'"
        )
        sql = cursor.fetchone()[0]
        assert "+metadata" in sql

    data = read_table_data(managed_conn, "vec0_with_aux")
    assert len(data) == 1
    assert data[0]["metadata"] == "extra info"


@requires_sqlite_vec
def test_vec0_schema_change_forces_recreate(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that schema changes to vec0 virtual tables trigger DROP+CREATE."""
    managed_conn, _ = sqlite_db

    @dataclass
    class Vec0RowV1:
        id: int
        content: str
        embedding: Annotated[
            NDArray[np.float32], VectorSchema(dtype=np.dtype(np.float32), size=2)
        ]

    @dataclass
    class Vec0RowV2:
        id: int
        content: str
        new_field: str  # Added column
        embedding: Annotated[
            NDArray[np.float32], VectorSchema(dtype=np.dtype(np.float32), size=2)
        ]

    row_schema: type[Vec0RowV1] | type[Vec0RowV2] = Vec0RowV1
    rows: list[Vec0RowV1 | Vec0RowV2] = []

    test_env = make_test_env(managed_conn, "test_vec0_schema_change_forces_recreate")

    async def declare_evolving_table() -> None:
        table = await coco.use_mount(
            coco.component_subpath("setup", "table"),
            sqlite.declare_table_target,
            SQLITE_DB,
            table_name="vec0_evolving",
            table_schema=await sqlite.TableSchema.from_class(
                row_schema,
                primary_key=["id"],
            ),
            virtual_table_def=sqlite.Vec0TableDef(),
        )

        for row in rows:
            table.declare_row(row=row)

    app = coco.App(
        coco.AppConfig(name="Vec0SchemaChangeTest", environment=test_env),
        declare_evolving_table,
    )

    # Initial schema
    rows = [
        Vec0RowV1(
            id=1, content="Doc 1", embedding=np.array([1.0, 2.0], dtype=np.float32)
        ),
    ]
    app.update_blocking()

    columns = get_table_columns(managed_conn, "vec0_evolving")
    assert "new_field" not in columns

    # Change schema (add column) - should trigger DROP+CREATE
    row_schema = Vec0RowV2
    rows = [
        Vec0RowV2(
            id=1,
            content="Doc 1",
            new_field="value",
            embedding=np.array([1.0, 2.0], dtype=np.float32),
        ),
    ]
    app.update_blocking()

    # Verify new column exists
    columns = get_table_columns(managed_conn, "vec0_evolving")
    assert "new_field" in columns

    data = read_table_data(managed_conn, "vec0_evolving")
    assert len(data) == 1
    assert data[0]["new_field"] == "value"


@requires_sqlite_vec
def test_vec0_without_vector_column_raises_error(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that vec0 table without vector columns raises validation error."""
    managed_conn, _ = sqlite_db

    @dataclass
    class NoVectorRow:
        id: int
        content: str

    test_env = make_test_env(
        managed_conn, "test_vec0_without_vector_column_raises_error"
    )

    async def declare_invalid_table() -> None:
        sqlite.declare_table_target(
            SQLITE_DB,
            table_name="vec0_invalid",
            table_schema=await sqlite.TableSchema.from_class(
                NoVectorRow,
                primary_key=["id"],
            ),
            virtual_table_def=sqlite.Vec0TableDef(),
        )

    app = coco.App(
        coco.AppConfig(name="Vec0NoVectorTest", environment=test_env),
        declare_invalid_table,
    )

    with pytest.raises(
        ValueError, match="require at least one float\\[N\\] vector column"
    ):
        app.update_blocking()


@requires_sqlite_vec
def test_vec0_with_composite_pk_raises_error(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that vec0 table with composite primary key raises validation error."""
    managed_conn, _ = sqlite_db

    @dataclass
    class CompositePkRow:
        id1: int
        id2: int
        embedding: Annotated[
            NDArray[np.float32], VectorSchema(dtype=np.dtype(np.float32), size=2)
        ]

    test_env = make_test_env(managed_conn, "test_vec0_with_composite_pk_raises_error")

    async def declare_invalid_table() -> None:
        sqlite.declare_table_target(
            SQLITE_DB,
            table_name="vec0_composite_pk",
            table_schema=await sqlite.TableSchema.from_class(
                CompositePkRow,
                primary_key=["id1", "id2"],
            ),
            virtual_table_def=sqlite.Vec0TableDef(),
        )

    app = coco.App(
        coco.AppConfig(name="Vec0CompositePkTest", environment=test_env),
        declare_invalid_table,
    )

    with pytest.raises(ValueError, match="require exactly one primary key column"):
        app.update_blocking()


@requires_sqlite_vec
def test_vec0_with_non_integer_pk_raises_error(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that vec0 table with non-integer primary key raises validation error."""
    managed_conn, _ = sqlite_db

    @dataclass
    class StringPkRow:
        id: str
        embedding: Annotated[
            NDArray[np.float32], VectorSchema(dtype=np.dtype(np.float32), size=2)
        ]

    test_env = make_test_env(managed_conn, "test_vec0_with_non_integer_pk_raises_error")

    async def declare_invalid_table() -> None:
        sqlite.declare_table_target(
            SQLITE_DB,
            table_name="vec0_string_pk",
            table_schema=await sqlite.TableSchema.from_class(
                StringPkRow,
                primary_key=["id"],
            ),
            virtual_table_def=sqlite.Vec0TableDef(),
        )

    app = coco.App(
        coco.AppConfig(name="Vec0StringPkTest", environment=test_env),
        declare_invalid_table,
    )

    with pytest.raises(ValueError, match="require INTEGER primary key"):
        app.update_blocking()


@requires_sqlite_vec
def test_vec0_without_extension_raises_error(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that vec0 table without sqlite-vec extension raises error."""
    # Create a new connection without loading vec extension
    _, db_path = sqlite_db
    managed_conn_no_vec = sqlite.connect(str(db_path), load_vec=False)

    @dataclass
    class Vec0Row:
        id: int
        embedding: Annotated[
            NDArray[np.float32], VectorSchema(dtype=np.dtype(np.float32), size=2)
        ]

    test_env = make_test_env(
        managed_conn_no_vec, "test_vec0_without_extension_raises_error"
    )

    async def declare_table_without_ext() -> None:
        sqlite.declare_table_target(
            SQLITE_DB,
            table_name="vec0_needs_ext",
            table_schema=await sqlite.TableSchema.from_class(
                Vec0Row,
                primary_key=["id"],
            ),
            virtual_table_def=sqlite.Vec0TableDef(),
        )

    app = coco.App(
        coco.AppConfig(name="Vec0NoExtTest", environment=test_env),
        declare_table_without_ext,
    )

    with pytest.raises(RuntimeError, match="sqlite-vec extension must be loaded"):
        app.update_blocking()

    managed_conn_no_vec.close()


@requires_sqlite_vec
def test_vec0_invalid_partition_key_raises_error(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that vec0 table with invalid partition key column raises error."""
    managed_conn, _ = sqlite_db

    @dataclass
    class Vec0Row:
        id: int
        embedding: Annotated[
            NDArray[np.float32], VectorSchema(dtype=np.dtype(np.float32), size=2)
        ]

    test_env = make_test_env(
        managed_conn, "test_vec0_invalid_partition_key_raises_error"
    )

    async def declare_invalid_table() -> None:
        sqlite.declare_table_target(
            SQLITE_DB,
            table_name="vec0_bad_partition",
            table_schema=await sqlite.TableSchema.from_class(
                Vec0Row,
                primary_key=["id"],
            ),
            virtual_table_def=sqlite.Vec0TableDef(
                partition_key_columns=["nonexistent_column"],
            ),
        )

    app = coco.App(
        coco.AppConfig(name="Vec0BadPartitionTest", environment=test_env),
        declare_invalid_table,
    )

    with pytest.raises(ValueError, match="Partition key columns not in schema"):
        app.update_blocking()


@requires_sqlite_vec
def test_vec0_invalid_auxiliary_column_raises_error(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that vec0 table with invalid auxiliary column raises error."""
    managed_conn, _ = sqlite_db

    @dataclass
    class Vec0Row:
        id: int
        embedding: Annotated[
            NDArray[np.float32], VectorSchema(dtype=np.dtype(np.float32), size=2)
        ]

    test_env = make_test_env(
        managed_conn, "test_vec0_invalid_auxiliary_column_raises_error"
    )

    async def declare_invalid_table() -> None:
        sqlite.declare_table_target(
            SQLITE_DB,
            table_name="vec0_bad_aux",
            table_schema=await sqlite.TableSchema.from_class(
                Vec0Row,
                primary_key=["id"],
            ),
            virtual_table_def=sqlite.Vec0TableDef(
                auxiliary_columns=["nonexistent_column"],
            ),
        )

    app = coco.App(
        coco.AppConfig(name="Vec0BadAuxTest", environment=test_env),
        declare_invalid_table,
    )

    with pytest.raises(ValueError, match="Auxiliary columns not in schema"):
        app.update_blocking()


@requires_sqlite_vec
def test_vec0_with_column_overrides(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test vec0 virtual table with VectorSchema in column_overrides."""
    managed_conn, _ = sqlite_db

    explicit_vector_schema = VectorSchema(dtype=np.dtype(np.float32), size=3)

    @dataclass
    class Vec0OverrideRow:
        id: int
        data: str
        vec: NDArray[np.float32]  # No annotation, use column_overrides

    rows: list[Vec0OverrideRow] = []

    test_env = make_test_env(managed_conn, "test_vec0_with_column_overrides")

    async def declare_vec0_override_table() -> None:
        table = await coco.use_mount(
            coco.component_subpath("setup", "table"),
            sqlite.declare_table_target,
            SQLITE_DB,
            table_name="vec0_overrides",
            table_schema=await sqlite.TableSchema.from_class(
                Vec0OverrideRow,
                primary_key=["id"],
                column_overrides={"vec": explicit_vector_schema},
            ),
            virtual_table_def=sqlite.Vec0TableDef(),
        )

        for row in rows:
            table.declare_row(row=row)

    app = coco.App(
        coco.AppConfig(name="Vec0OverrideTest", environment=test_env),
        declare_vec0_override_table,
    )

    rows = [
        Vec0OverrideRow(
            id=1,
            data="test data",
            vec=np.array([0.1, 0.2, 0.3], dtype=np.float32),
        ),
    ]
    app.update_blocking()

    data = read_table_data(managed_conn, "vec0_overrides")
    assert len(data) == 1
    row = data[0]
    assert row["data"] == "test data"
    vector = decode_vector(row["vec"], 3)
    assert vector == pytest.approx([0.1, 0.2, 0.3])


@requires_sqlite_vec
def test_regular_table_vs_vec0_switch(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test switching between regular table and vec0 virtual table triggers recreation."""
    managed_conn, _ = sqlite_db

    @dataclass
    class VectorRow:
        id: int
        content: str
        embedding: Annotated[
            NDArray[np.float32], VectorSchema(dtype=np.dtype(np.float32), size=2)
        ]

    use_virtual = False
    rows: list[VectorRow] = []

    test_env = make_test_env(managed_conn, "test_regular_table_vs_vec0_switch")

    async def declare_table() -> None:
        table = await coco.use_mount(
            coco.component_subpath("setup", "table"),
            sqlite.declare_table_target,
            SQLITE_DB,
            table_name="switchable",
            table_schema=await sqlite.TableSchema.from_class(
                VectorRow,
                primary_key=["id"],
            ),
            virtual_table_def=sqlite.Vec0TableDef() if use_virtual else None,
        )

        for row in rows:
            table.declare_row(row=row)

    app = coco.App(
        coco.AppConfig(name="SwitchTest", environment=test_env),
        declare_table,
    )

    # Start with regular table
    rows = [
        VectorRow(
            id=1, content="Doc", embedding=np.array([1.0, 2.0], dtype=np.float32)
        ),
    ]
    app.update_blocking()

    # Verify it's a regular table
    with managed_conn.readonly() as conn:
        cursor = conn.execute(
            "SELECT sql FROM sqlite_master WHERE type='table' AND name='switchable'"
        )
        sql = cursor.fetchone()[0]
        assert "VIRTUAL TABLE" not in sql

    # Switch to virtual table
    use_virtual = True
    app.update_blocking()

    # Verify it's now a virtual table
    with managed_conn.readonly() as conn:
        cursor = conn.execute(
            "SELECT sql FROM sqlite_master WHERE type='table' AND name='switchable'"
        )
        sql = cursor.fetchone()[0]
        assert "VIRTUAL TABLE" in sql
        assert "USING vec0" in sql

    # Switching table types (regular <-> virtual) triggers DROP+CREATE, which
    # marks child targets as destructively invalidated. The engine therefore
    # re-declares all rows, so the data is preserved after re-processing.
    data = read_table_data(managed_conn, "switchable")
    assert len(data) == 1
    assert data[0]["id"] == 1


def test_unsupported_sqlite_migration_raises_error(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that attempting an invalid SQLite migration (adding NOT NULL column without DEFAULT to a populated table) raises RuntimeError loudly instead of silently swallowing the failure."""
    managed_conn, _ = sqlite_db
    global _source_rows, _row_type, _table_name

    old_source_rows = _source_rows
    old_row_type = _row_type
    old_table_name = _table_name
    try:
        _source_rows = [SimpleRow(id="1", name="Alice", value=100)]
        _row_type = SimpleRow
        _table_name = "test_alter_non_nullable_raises"

        test_env = make_test_env(
            managed_conn, "test_unsupported_sqlite_migration_raises_error"
        )

        async def declare_dynamic_schema() -> None:
            table = await coco.use_mount(
                coco.component_subpath("setup", "table"),
                sqlite.declare_table_target,
                SQLITE_DB,
                _table_name,
                await sqlite.TableSchema.from_class(_row_type, primary_key=["id"]),
            )
            for row in _source_rows:
                table.declare_row(row=row)

        app = coco.App(
            coco.AppConfig(
                name="test_unsupported_sqlite_migration_raises_error",
                environment=test_env,
            ),
            declare_dynamic_schema,
        )

        # Initial update creates table with SimpleRow and inserts data
        app.update_blocking()
        assert table_exists(managed_conn, _table_name)
        assert "extra" not in get_table_columns(managed_conn, _table_name)

        # Update schema to ExtendedRow (adds 'extra' column which is NOT NULL)
        _row_type = ExtendedRow
        _source_rows = [
            ExtendedRow(id="1", name="Alice", value=100, extra="new_field"),
        ]

        # SQLite rejects adding NOT NULL column without DEFAULT to a populated table.
        # This MUST fail loudly with RuntimeError instead of silently proceeding.
        with pytest.raises(RuntimeError, match="Failed to add column 'extra'"):
            app.update_blocking()

        # Database schema must remain consistent (unaltered)
        cols = get_table_columns(managed_conn, _table_name)
        assert "extra" not in cols
    finally:
        _source_rows = old_source_rows
        _row_type = old_row_type
        _table_name = old_table_name


def test_column_type_change_blocked_by_index_raises_and_retries(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that a column type change whose DROP COLUMN fails raises instead of keeping the old type silently, and is retried once the blocker is gone."""
    managed_conn, _ = sqlite_db
    global _source_rows, _row_type, _table_name

    old_source_rows = _source_rows
    old_row_type = _row_type
    old_table_name = _table_name
    try:
        _source_rows = [NullableIntValueRow(id="1", name="Alice", value=100)]
        _row_type = NullableIntValueRow
        _table_name = "test_type_change_blocked_by_index"

        test_env = make_test_env(
            managed_conn, "test_column_type_change_blocked_by_index_raises_and_retries"
        )

        async def declare_dynamic_schema() -> None:
            table = await coco.use_mount(
                coco.component_subpath("setup", "table"),
                sqlite.declare_table_target,
                SQLITE_DB,
                _table_name,
                await sqlite.TableSchema.from_class(_row_type, primary_key=["id"]),
            )
            for row in _source_rows:
                table.declare_row(row=row)

        app = coco.App(
            coco.AppConfig(
                name="test_column_type_change_blocked_by_index_raises_and_retries",
                environment=test_env,
            ),
            declare_dynamic_schema,
        )

        # Initial update creates the column as INTEGER.
        app.update_blocking()
        assert get_table_columns(managed_conn, _table_name)["value"] == "INTEGER"

        # SQLite cannot drop a column that an index references.
        with managed_conn.transaction() as conn:
            conn.execute(f'CREATE INDEX idx_value ON "{_table_name}" ("value")')

        # Changing the type to TEXT must fail loudly instead of recording the new
        # type while the table keeps the old one.
        _row_type = NullableStrValueRow
        _source_rows = [NullableStrValueRow(id="1", name="Alice", value="100")]
        with pytest.raises(
            RuntimeError, match="Failed to change the shape of column 'value'"
        ):
            app.update_blocking()

        # Nothing was half-applied: the column is still INTEGER.
        assert get_table_columns(managed_conn, _table_name)["value"] == "INTEGER"

        # The failed run recorded nothing, so the next run retries the change
        # rather than treating it as applied.
        with pytest.raises(
            RuntimeError, match="Failed to change the shape of column 'value'"
        ):
            app.update_blocking()
        assert get_table_columns(managed_conn, _table_name)["value"] == "INTEGER"

        # Once the blocking index is gone, the change applies and the value is
        # preserved through the drop/re-add.
        with managed_conn.transaction() as conn:
            conn.execute("DROP INDEX idx_value")
        app.update_blocking()

        assert get_table_columns(managed_conn, _table_name)["value"] == "TEXT"
        data = read_table_data(managed_conn, _table_name)
        assert data == [{"id": "1", "name": "Alice", "value": "100"}]
    finally:
        _source_rows = old_source_rows
        _row_type = old_row_type
        _table_name = old_table_name


def test_column_nullability_change_blocked_by_index_raises_and_retries(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that a nullable-only change is protected as well, since the tracking record carries nullability too."""
    managed_conn, _ = sqlite_db
    global _source_rows, _row_type, _table_name

    old_source_rows = _source_rows
    old_row_type = _row_type
    old_table_name = _table_name
    try:
        _source_rows = [SimpleRow(id="1", name="Alice", value=100)]
        _row_type = SimpleRow
        _table_name = "test_nullability_change_blocked_by_index"

        app_name = "test_column_nullability_change_blocked_by_index_raises_and_retries"
        app = coco.App(
            coco.AppConfig(
                name=app_name, environment=make_test_env(managed_conn, app_name)
            ),
            declare_table_and_rows,
        )

        # The initial schema declares value as INTEGER NOT NULL.
        app.update_blocking()
        assert get_table_columns(managed_conn, _table_name)["value"] == "INTEGER"
        assert get_column_notnull(managed_conn, _table_name, "value") is True

        # SQLite cannot drop a column that an index references.
        with managed_conn.transaction() as conn:
            conn.execute(f'CREATE INDEX idx_value ON "{_table_name}" ("value")')

        # Only the nullability changes, so the declared type still matches the
        # desired one. Accepting the blocked replace on the type alone would
        # record nullable while the column stays NOT NULL.
        _row_type = NullableIntValueRow
        _source_rows = [NullableIntValueRow(id="1", name="Alice", value=100)]
        with pytest.raises(
            RuntimeError, match="Failed to change the shape of column 'value'"
        ):
            app.update_blocking()

        # Nothing was half-applied: the column is still NOT NULL.
        assert get_column_notnull(managed_conn, _table_name, "value") is True

        # No tracking record was committed, so the change is retried.
        with pytest.raises(
            RuntimeError, match="Failed to change the shape of column 'value'"
        ):
            app.update_blocking()
        assert get_column_notnull(managed_conn, _table_name, "value") is True
    finally:
        _source_rows = old_source_rows
        _row_type = old_row_type
        _table_name = old_table_name


def test_column_type_change_already_applied_is_accepted(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that a blocked replace is accepted when the column already has the desired shape."""
    managed_conn, _ = sqlite_db
    global _source_rows, _row_type, _table_name

    old_source_rows = _source_rows
    old_row_type = _row_type
    old_table_name = _table_name
    try:
        _source_rows = [NullableIntValueRow(id="1", name="Alice", value=100)]
        _row_type = NullableIntValueRow
        _table_name = "test_type_change_already_applied"

        app_name = "test_column_type_change_already_applied_is_accepted"
        app = coco.App(
            coco.AppConfig(
                name=app_name, environment=make_test_env(managed_conn, app_name)
            ),
            declare_table_and_rows,
        )

        app.update_blocking()
        assert get_table_columns(managed_conn, _table_name)["value"] == "INTEGER"

        # Bring the column to the desired shape out of band, then pin it with an
        # index so the replace's DROP COLUMN still fails.
        with managed_conn.transaction() as conn:
            conn.execute(f'ALTER TABLE "{_table_name}" DROP COLUMN "value"')
            conn.execute(f'ALTER TABLE "{_table_name}" ADD COLUMN "value" TEXT')
            conn.execute(f'CREATE INDEX idx_value ON "{_table_name}" ("value")')

        _row_type = NullableStrValueRow
        _source_rows = [NullableStrValueRow(id="1", name="Alice", value="100")]
        app.update_blocking()

        assert get_table_columns(managed_conn, _table_name)["value"] == "TEXT"
        assert get_column_notnull(managed_conn, _table_name, "value") is False
        data = read_table_data(managed_conn, _table_name)
        assert data == [{"id": "1", "name": "Alice", "value": "100"}]
    finally:
        _source_rows = old_source_rows
        _row_type = old_row_type
        _table_name = old_table_name


def test_dropped_not_null_column_that_cannot_be_dropped_raises(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that a removed NOT NULL column an index pins fails the run, and succeeds once the index is gone."""
    managed_conn, _ = sqlite_db
    global _source_rows, _row_type, _table_name

    old_source_rows = _source_rows
    old_row_type = _row_type
    old_table_name = _table_name
    try:
        _source_rows = [SimpleRow(id="1", name="Alice", value=100)]
        _row_type = SimpleRow
        _table_name = "test_dropped_not_null_column_blocked_by_index"

        app_name = "test_dropped_not_null_column_that_cannot_be_dropped_raises"
        app = coco.App(
            coco.AppConfig(
                name=app_name, environment=make_test_env(managed_conn, app_name)
            ),
            declare_table_and_rows,
        )

        app.update_blocking()
        assert get_column_notnull(managed_conn, _table_name, "value") is True

        with managed_conn.transaction() as conn:
            conn.execute(f'CREATE INDEX idx_value ON "{_table_name}" ("value")')

        # Every row write would fail on the leftover NOT NULL column, so failing
        # the run lets the next one retry the DROP.
        _row_type = NoValueRow
        _source_rows = [NoValueRow(id="1", name="Alice")]
        with pytest.raises(
            RuntimeError, match="Failed to drop NOT NULL column 'value'"
        ):
            app.update_blocking()

        # Nothing was half-applied: the column is still there.
        assert "value" in get_table_columns(managed_conn, _table_name)

        # The failed run recorded nothing, so the next run retries.
        with pytest.raises(
            RuntimeError, match="Failed to drop NOT NULL column 'value'"
        ):
            app.update_blocking()
        assert "value" in get_table_columns(managed_conn, _table_name)

        # Once the blocking index is gone, the column is dropped and the data is
        # preserved.
        with managed_conn.transaction() as conn:
            conn.execute("DROP INDEX idx_value")
        app.update_blocking()

        assert "value" not in get_table_columns(managed_conn, _table_name)
        assert read_table_data(managed_conn, _table_name) == [
            {"id": "1", "name": "Alice"}
        ]
    finally:
        _source_rows = old_source_rows
        _row_type = old_row_type
        _table_name = old_table_name


def test_dropped_nullable_column_that_cannot_be_dropped_warns(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
    caplog: pytest.LogCaptureFixture,
) -> None:
    """Test that a removed nullable column an index pins is left in place with a warning naming it."""
    managed_conn, _ = sqlite_db
    global _source_rows, _row_type, _table_name

    old_source_rows = _source_rows
    old_row_type = _row_type
    old_table_name = _table_name
    try:
        _source_rows = [NullableIntValueRow(id="1", name="Alice", value=100)]
        _row_type = NullableIntValueRow
        _table_name = "test_dropped_nullable_column_blocked_by_index"

        app_name = "test_dropped_nullable_column_that_cannot_be_dropped_warns"
        app = coco.App(
            coco.AppConfig(
                name=app_name, environment=make_test_env(managed_conn, app_name)
            ),
            declare_table_and_rows,
        )

        app.update_blocking()
        assert get_column_notnull(managed_conn, _table_name, "value") is False

        with managed_conn.transaction() as conn:
            conn.execute(f'CREATE INDEX idx_value ON "{_table_name}" ("value")')

        # A nullable leftover is harmless: rows just leave it NULL.
        _row_type = NoValueRow
        _source_rows = [NoValueRow(id="1", name="Alice")]
        with caplog.at_level(logging.WARNING):
            app.update_blocking()

        warnings = [
            record.getMessage()
            for record in caplog.records
            if "could not drop removed column" in record.getMessage()
        ]
        assert len(warnings) == 1
        assert "'value'" in warnings[0]
        assert repr(_table_name) in warnings[0]

        # The DROP was tolerated, so the column is still there.
        assert "value" in get_table_columns(managed_conn, _table_name)
    finally:
        _source_rows = old_source_rows
        _row_type = old_row_type
        _table_name = old_table_name


def test_readded_column_after_blocked_drop_raises_until_index_is_dropped(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that re-adding a column whose DROP was blocked applies the new type once the index is gone."""
    managed_conn, _ = sqlite_db
    global _source_rows, _row_type, _table_name

    old_source_rows = _source_rows
    old_row_type = _row_type
    old_table_name = _table_name
    try:
        _source_rows = [NullableIntValueRow(id="1", name="Alice", value=100)]
        _row_type = NullableIntValueRow
        _table_name = "test_readded_column_after_blocked_drop"

        app_name = (
            "test_readded_column_after_blocked_drop_raises_until_index_is_dropped"
        )
        app = coco.App(
            coco.AppConfig(
                name=app_name, environment=make_test_env(managed_conn, app_name)
            ),
            declare_table_and_rows,
        )

        app.update_blocking()
        assert get_table_columns(managed_conn, _table_name)["value"] == "INTEGER"

        with managed_conn.transaction() as conn:
            conn.execute(f'CREATE INDEX idx_value ON "{_table_name}" ("value")')

        # Removing the column is only a warning for a nullable leftover.
        _row_type = NoValueRow
        _source_rows = [NoValueRow(id="1", name="Alice")]
        app.update_blocking()
        assert "value" in get_table_columns(managed_conn, _table_name)

        # Re-adding it as TEXT is an insert. The leftover INTEGER column blocks
        # the DROP, so the run fails instead of recording TEXT while the table
        # keeps INTEGER.
        _row_type = NullableStrValueRow
        _source_rows = [NullableStrValueRow(id="1", name="Alice", value="100")]
        with pytest.raises(
            RuntimeError, match="Failed to change the shape of column 'value'"
        ):
            app.update_blocking()
        assert get_table_columns(managed_conn, _table_name)["value"] == "INTEGER"

        # Once the index is gone, the insert converges to TEXT.
        with managed_conn.transaction() as conn:
            conn.execute("DROP INDEX idx_value")
        app.update_blocking()

        assert get_table_columns(managed_conn, _table_name)["value"] == "TEXT"
        assert read_table_data(managed_conn, _table_name) == [
            {"id": "1", "name": "Alice", "value": "100"}
        ]
    finally:
        _source_rows = old_source_rows
        _row_type = old_row_type
        _table_name = old_table_name


def test_existing_column_is_kept_on_idempotent_rerun(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that an insert for a column that already has the shape is skipped."""
    managed_conn, _ = sqlite_db
    table_name = "test_duplicate_col"

    schema = sqlite.TableSchema(
        columns={
            "id": sqlite.ColumnDef(type="TEXT", nullable=False),
            "col1": sqlite.ColumnDef(type="TEXT", nullable=True),
        },
        primary_key=["id"],
    )

    with managed_conn.transaction() as conn:
        sqlite._target._create_table(
            conn, table_name, schema, if_not_exists=True, has_vec_extension=False
        )

    # Manually call _apply_column_actions with action 'insert' for col1 (which already exists)
    column_actions: dict[str, statediff.DiffAction] = {"col:col1": "insert"}
    with managed_conn.transaction() as conn:
        # No-op: the shape check sees col1 already has the desired shape.
        sqlite._target._apply_column_actions(conn, table_name, schema, column_actions)

    cols = get_table_columns(managed_conn, table_name)
    assert "col1" in cols


def test_full_reprocess_keeps_a_column_whose_type_carries_a_constraint(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that a full reprocess leaves a column whose declared type carries a constraint alone.

    PRAGMA table_info reports only the type name, so `TEXT COLLATE NOCASE` has
    to compare equal to the reported `TEXT`; otherwise every full reprocess drops
    and re-adds the column, and the re-add fails with NOT NULL once the table has
    rows.
    """
    managed_conn, _ = sqlite_db
    global _source_rows, _row_type, _table_name

    old_source_rows = _source_rows
    old_row_type = _row_type
    old_table_name = _table_name
    try:
        _source_rows = [CollatedNameRow(id="1", name="Alice")]
        _row_type = CollatedNameRow
        _table_name = "test_collated_name_full_reprocess"

        app_name = "test_full_reprocess_keeps_a_column_whose_type_carries_a_constraint"
        app = coco.App(
            coco.AppConfig(
                name=app_name, environment=make_test_env(managed_conn, app_name)
            ),
            declare_table_and_rows,
        )

        app.update_blocking()
        assert get_table_columns(managed_conn, _table_name)["name"] == "TEXT"
        assert get_column_notnull(managed_conn, _table_name, "name") is True

        app.update_blocking(full_reprocess=True)
        app.update_blocking(full_reprocess=True)

        assert get_table_columns(managed_conn, _table_name)["name"] == "TEXT"
        assert get_column_notnull(managed_conn, _table_name, "name") is True
        assert read_table_data(managed_conn, _table_name) == [
            {"id": "1", "name": "Alice"}
        ]
    finally:
        _source_rows = old_source_rows
        _row_type = old_row_type
        _table_name = old_table_name


def test_replace_rebuilds_a_column_to_drop_its_constraint(
    sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
    """Test that a replace rebuilds the column, since PRAGMA can't show a lost constraint."""
    managed_conn, _ = sqlite_db
    table_name = "test_drop_collation"
    collated = sqlite.TableSchema(
        columns={
            "id": sqlite.ColumnDef(type="TEXT", nullable=False),
            "name": sqlite.ColumnDef(type="TEXT COLLATE NOCASE", nullable=True),
        },
        primary_key=["id"],
    )
    plain = sqlite.TableSchema(
        columns={
            "id": sqlite.ColumnDef(type="TEXT", nullable=False),
            "name": sqlite.ColumnDef(type="TEXT", nullable=True),
        },
        primary_key=["id"],
    )

    with managed_conn.transaction() as conn:
        sqlite._target._create_table(
            conn, table_name, collated, if_not_exists=True, has_vec_extension=False
        )
    assert "COLLATE" in get_table_sql(managed_conn, table_name)

    # PRAGMA reports plain TEXT for the collated column, so a shape check alone
    # would skip this replace and keep the collation while recording plain TEXT.
    column_actions: dict[str, statediff.DiffAction] = {"col:name": "replace"}
    with managed_conn.transaction() as conn:
        sqlite._target._apply_column_actions(conn, table_name, plain, column_actions)

    assert "COLLATE" not in get_table_sql(managed_conn, table_name)
    assert get_table_columns(managed_conn, table_name)["name"] == "TEXT"