Skip to content

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

fix(sqlite): fail a column type change whose DROP fails (#2798)

Leoyac1d884daefc
diff --git a/python/cocoindex/connectors/sqlite/_target.py b/python/cocoindex/connectors/sqlite/_target.py
index 824e4000..26343376 100644
--- a/python/cocoindex/connectors/sqlite/_target.py
+++ b/python/cocoindex/connectors/sqlite/_target.py
@@ -13,6 +13,7 @@ from __future__ import annotations
import datetime
import decimal
import json
+import logging
import re
import sqlite3
import uuid
@@ -63,6 +64,8 @@ ValueEncoder = Callable[[Any], Any]
_VEC_EXTENSION = "sqlite-vec"
+_logger = logging.getLogger(__name__)
+
@dataclass
class ManagedConnection:
@@ -790,6 +793,34 @@ def _create_table(
conn.execute(sql)
+class _ColumnShape(NamedTuple):
+ type: str # Upper-cased: SQLite reports standard type names upper-cased.
+ not_null: bool
+
+
+def _column_shape(
+ conn: sqlite3.Connection, table_name: str, col_name: str
+) -> _ColumnShape | None:
+ """Return the shape of a column, or None if it is absent."""
+ qualified_name = _qualified_table_name(table_name)
+ for row in conn.execute(f"PRAGMA table_info({qualified_name})"):
+ if row[1] == col_name:
+ return _ColumnShape(str(row[2]).upper(), bool(row[3]))
+ return None
+
+
+def _has_shape(actual: _ColumnShape, col: ColumnDef) -> bool:
+ """Whether `actual` (from PRAGMA table_info) has `col`'s type and nullability.
+
+ PRAGMA table_info reports only the type name: for a declared type that also
+ carries COLLATE, DEFAULT, CHECK and so on, it reports the words before them.
+ """
+ declared = col.type.strip().upper()
+ return actual.not_null == (not col.nullable) and (
+ declared == actual.type or declared.startswith(actual.type + " ")
+ )
+
+
def _apply_column_actions(
conn: sqlite3.Connection,
table_name: str,
@@ -821,9 +852,26 @@ def _apply_column_actions(
# SQLite 3.35.0+ supports DROP COLUMN
try:
conn.execute(f'ALTER TABLE {qualified_name} DROP COLUMN "{col_name}"')
- except sqlite3.OperationalError:
- # Older SQLite doesn't support DROP COLUMN - silently skip
- pass
+ except sqlite3.OperationalError as e:
+ leftover = _column_shape(conn, table_name, col_name)
+ if leftover is None:
+ continue # Already gone, as desired.
+ if leftover.not_null:
+ # Every row write would fail on the leftover, and once this
+ # delete is recorded no later run retries it.
+ raise RuntimeError(
+ f"Failed to drop NOT NULL column {col_name!r} from SQLite "
+ f"table {table_name!r}: {e}"
+ ) from e
+ # A nullable leftover (SQLite < 3.35, or an index references the
+ # column) is harmless: rows just leave it NULL.
+ _logger.warning(
+ "SQLite target: could not drop removed column %r from table %r, "
+ "left in place as unused: %s",
+ col_name,
+ table_name,
+ e,
+ )
continue
desired_col = non_pk_col_by_name.get(col_name)
@@ -832,45 +880,38 @@ def _apply_column_actions(
# it as a no-op here; "delete" should have been emitted.
continue
- if action in ("insert", "upsert"):
- # SQLite supports ADD COLUMN
- nullable = "" if desired_col.nullable else " NOT NULL"
- try:
- conn.execute(
- f"ALTER TABLE {qualified_name} "
- f'ADD COLUMN "{col_name}" {desired_col.type}{nullable}'
- )
- except sqlite3.OperationalError as e:
- # Only ignore if column already exists (e.g. upsert / idempotent re-run)
- if "duplicate column name" in str(e).lower():
- pass
- else:
- raise RuntimeError(
- f"Failed to add column {col_name!r} to SQLite table {table_name!r}: {e}"
- ) from e
- continue
-
- if action == "replace":
- # SQLite doesn't support ALTER COLUMN TYPE directly.
- # For type changes, attempt to drop and re-add column.
+ # insert / upsert / replace: bring the column to the desired shape.
+ actual = _column_shape(conn, table_name, col_name)
+ if actual is not None:
+ if action != "replace" and _has_shape(actual, desired_col):
+ # Already in place: an idempotent re-run, or a full reprocess.
+ continue
+ # SQLite has no ALTER COLUMN TYPE: drop, then re-add. A `replace`
+ # always rebuilds, since PRAGMA can't show a change to COLLATE,
+ # DEFAULT or CHECK. A failed DROP (an index references the column, or
+ # SQLite < 3.35) fails the action, unless the column already has the
+ # desired shape (changed out of band); otherwise the new shape would
+ # be recorded while the table keeps the old one.
try:
conn.execute(f'ALTER TABLE {qualified_name} DROP COLUMN "{col_name}"')
- except sqlite3.OperationalError:
- pass
- nullable = "" if desired_col.nullable else " NOT NULL"
- try:
- conn.execute(
- f"ALTER TABLE {qualified_name} "
- f'ADD COLUMN "{col_name}" {desired_col.type}{nullable}'
- )
except sqlite3.OperationalError as e:
- if "duplicate column name" in str(e).lower():
- pass
- else:
- raise RuntimeError(
- f"Failed to replace column {col_name!r} in SQLite table {table_name!r}: {e}"
- ) from e
- continue
+ if _has_shape(actual, desired_col):
+ continue
+ raise RuntimeError(
+ f"Failed to change the shape of column {col_name!r} in SQLite "
+ f"table {table_name!r} from {actual} to type "
+ f"{desired_col.type!r}, nullable={desired_col.nullable}: {e}"
+ ) from e
+ nullable = "" if desired_col.nullable else " NOT NULL"
+ try:
+ conn.execute(
+ f"ALTER TABLE {qualified_name} "
+ f'ADD COLUMN "{col_name}" {desired_col.type}{nullable}'
+ )
+ except sqlite3.OperationalError as e:
+ raise RuntimeError(
+ f"Failed to add column {col_name!r} to SQLite table {table_name!r}: {e}"
+ ) from e
def _row_handler(
diff --git a/python/tests/connectors/test_sqlite_target.py b/python/tests/connectors/test_sqlite_target.py
index 97bdc74d..d85637bc 100644
--- a/python/tests/connectors/test_sqlite_target.py
+++ b/python/tests/connectors/test_sqlite_target.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import logging
import sqlite3
import struct
import tempfile
@@ -74,6 +75,28 @@ def get_table_columns(
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))
@@ -128,6 +151,32 @@ class ExtendedRow:
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)
# =============================================================================
@@ -1566,10 +1615,375 @@ def test_unsupported_sqlite_migration_raises_error(
_table_name = old_table_name
-def test_duplicate_column_error_is_ignored_on_idempotent_rerun(
+def test_column_type_change_blocked_by_index_raises_and_retries(
sqlite_db: tuple[sqlite.ManagedConnection, Path],
) -> None:
- """Test that duplicate column errors are safely ignored during idempotent ADD COLUMN execution."""
+ """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"
@@ -1589,8 +2003,92 @@ def test_duplicate_column_error_is_ignored_on_idempotent_rerun(
# 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:
- # Should not raise an exception because 'duplicate column name' is caught and ignored
+ # 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"