Newer
Older
TIASDataHub / tests / catalog / test_migrate.py
"""マイグレーションの適用(testing.md 必須対象 8)."""

import re
import sqlite3
from pathlib import Path

import pytest

from tiasdata import catalog, kinds
from tiasdata.catalog import migrate
from tiasdata.catalog.migrate import Migration, MigrationResult
from tiasdata.datasets import freeze_version, load_definition, rebuild_manifest
from tiasdata.repo import RepoState


def _tables(conn: sqlite3.Connection) -> set[str]:
    rows = conn.execute(
        "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"
    )
    return {name for (name,) in rows}


def _schema(conn: sqlite3.Connection) -> list[tuple]:
    return conn.execute("SELECT type, name, sql FROM sqlite_master ORDER BY type, name").fetchall()


@pytest.mark.parametrize("series", ["catalog", "identity"])
def test_apply_to_empty_db_reaches_latest_version(tmp_path: Path, series: str) -> None:
    conn = catalog.connect(tmp_path / "db.sqlite", create=True)
    try:
        result = catalog.apply_migrations(conn, series)
        latest = catalog.latest_version(series)
        assert latest >= 1
        assert result == MigrationResult(0, latest)
        assert result.applied == latest
        assert conn.execute("PRAGMA user_version").fetchone()[0] == latest
        assert catalog.schema_version(conn) == latest
    finally:
        conn.close()


@pytest.mark.parametrize("series", ["catalog", "identity"])
def test_reapply_changes_nothing(tmp_path: Path, series: str) -> None:
    path = tmp_path / "db.sqlite"
    conn = catalog.connect(path, create=True)
    catalog.apply_migrations(conn, series)
    schema_before = _schema(conn)
    conn.close()

    # 別の接続から再適用しても何も変わらない
    conn = catalog.connect(path)
    try:
        result = catalog.apply_migrations(conn, series)
        latest = catalog.latest_version(series)
        assert result == MigrationResult(latest, latest)
        assert result.applied == 0
        assert _schema(conn) == schema_before
        assert conn.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
    finally:
        conn.close()


def test_reapply_keeps_kinds_rows_and_data(catalog_conn: sqlite3.Connection) -> None:
    catalog_conn.execute(
        "INSERT INTO subjects (subject_id, created_at) VALUES ('S000001', '2026-10-06T00:00:00Z')"
    )
    catalog_conn.commit()
    catalog.apply_migrations(catalog_conn, "catalog")
    assert catalog_conn.execute("SELECT COUNT(*) FROM kinds").fetchone()[0] == 10
    assert catalog_conn.execute("SELECT COUNT(*) FROM subjects").fetchone()[0] == 1


def test_catalog_and_identity_are_separate_series(tmp_path: Path) -> None:
    cat = catalog.connect(tmp_path / "catalog.sqlite", create=True)
    ident = catalog.connect(tmp_path / "identity.sqlite", create=True)
    try:
        catalog.apply_migrations(cat, "catalog")
        catalog.apply_migrations(ident, "identity")
        # 目録に対応表の表は無く,対応表に目録の表は無い
        assert "identity_map" not in _tables(cat)
        assert _tables(ident) == {"identity_map"}
    finally:
        cat.close()
        ident.close()


def test_db_newer_than_library_is_rejected(tmp_path: Path) -> None:
    conn = catalog.connect(tmp_path / "db.sqlite", create=True)
    try:
        catalog.apply_migrations(conn, "catalog")
        newer = catalog.latest_version("catalog") + 1
        conn.execute(f"PRAGMA user_version = {newer}")
        with pytest.raises(ValueError):
            catalog.apply_migrations(conn, "catalog")
        # 版は書き換わらない
        assert catalog.schema_version(conn) == newer
    finally:
        conn.close()


def test_failed_migration_leaves_nothing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    # 1 ファイル目は正常,2 ファイル目は途中で失敗するマイグレーション
    good = Migration(1, "0001_good.sql", "CREATE TABLE a (x INTEGER);")
    bad = Migration(
        2,
        "0002_bad.sql",
        "CREATE TABLE b (x INTEGER);\nINSERT INTO a VALUES (1);\nTHIS IS NOT SQL;",
    )
    monkeypatch.setattr(migrate, "load_migrations", lambda series: [good, bad])

    conn = catalog.connect(tmp_path / "db.sqlite", create=True)
    try:
        with pytest.raises(sqlite3.Error):
            catalog.apply_migrations(conn, "catalog")
        # 失敗したファイルの変更は残らず,前のファイルまでは適用済み
        assert catalog.schema_version(conn) == 1
        assert _tables(conn) == {"a"}
        assert conn.execute("SELECT COUNT(*) FROM a").fetchone()[0] == 0
        assert not conn.in_transaction
    finally:
        conn.close()

    # 別の接続から見ても同じ(確定した内容だけが残っている)
    conn = catalog.connect(tmp_path / "db.sqlite")
    try:
        assert catalog.schema_version(conn) == 1
        assert _tables(conn) == {"a"}
    finally:
        conn.close()


def test_failed_first_migration_leaves_empty_db(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    bad = Migration(1, "0001_bad.sql", "CREATE TABLE a (x INTEGER);\nTHIS IS NOT SQL;")
    monkeypatch.setattr(migrate, "load_migrations", lambda series: [bad])
    conn = catalog.connect(tmp_path / "db.sqlite", create=True)
    try:
        with pytest.raises(sqlite3.Error):
            catalog.apply_migrations(conn, "catalog")
        assert catalog.schema_version(conn) == 0
        assert _tables(conn) == set()
    finally:
        conn.close()


@pytest.mark.parametrize("series", ["catalog", "identity"])
def test_bundled_migrations_are_numbered_from_one(series: str) -> None:
    migrations = migrate.load_migrations(series)
    assert [m.version for m in migrations] == list(range(1, len(migrations) + 1))
    assert catalog.latest_version(series) == len(migrations)


@pytest.mark.parametrize("series", ["catalog", "identity"])
def test_bundled_migrations_do_not_manage_transaction_or_version(series: str) -> None:
    # apply_migrations() が BEGIN・COMMIT・user_version を付けるため,ファイル側に書かない
    for m in migrate.load_migrations(series):
        code = "\n".join(
            line for line in m.sql.splitlines() if not line.lstrip().startswith("--")
        ).upper()
        assert "USER_VERSION" not in code, m.name
        # トリガ本体の BEGIN … END; は対象外(トランザクションの文だけを見る)
        pattern = (
            r"^\s*(BEGIN(\s+(DEFERRED|IMMEDIATE|EXCLUSIVE))?(\s+TRANSACTION)?"
            r"|COMMIT(\s+TRANSACTION)?|END\s+TRANSACTION|ROLLBACK)\s*;"
        )
        assert re.search(pattern, code, re.M) is None, m.name


# ---------------------------------------------------------------------------
# catalog/0002: 所見の種類 review(2026-10-08 のユーザー判断)
# ---------------------------------------------------------------------------
def _review_kind(conn: sqlite3.Connection) -> tuple | None:
    return conn.execute(
        "SELECT kind, category, value_schema_version FROM kinds WHERE kind = 'review'"
    ).fetchone()


def test_catalog_latest_version_includes_review_kind() -> None:
    names = [m.name for m in migrate.load_migrations("catalog")]
    assert len(names) >= 2
    assert names[1].startswith("0002_")


def test_review_kind_from_empty_db(tmp_path: Path) -> None:
    # 0 → 最新: review は annotation・value_schema_version=1
    conn = catalog.connect(tmp_path / "db.sqlite", create=True)
    try:
        result = catalog.apply_migrations(conn, "catalog")
        assert result.before == 0
        assert result.after == catalog.latest_version("catalog")
        assert _review_kind(conn) == ("review", "annotation", 1)
    finally:
        conn.close()


def test_review_kind_from_version_1_keeps_existing_rows(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    # 1 → 最新: 研究室 PC の目録(0001 だけ適用・取り込み済み)に 0002 を足す
    path = tmp_path / "db.sqlite"
    first_only = migrate.load_migrations("catalog")[:1]
    with monkeypatch.context() as m:
        m.setattr(migrate, "load_migrations", lambda series: first_only)
        conn = catalog.connect(path, create=True)
        catalog.apply_migrations(conn, "catalog")
        assert catalog.schema_version(conn) == 1
        assert _review_kind(conn) is None
        conn.execute(
            "INSERT INTO subjects (subject_id, created_at)"
            " VALUES ('S000001', '2026-10-06T00:00:00Z')"
        )
        conn.execute("INSERT INTO captures (capture_id, subject_id) VALUES ('C000001', 'S000001')")
        conn.execute(
            "INSERT INTO annotations (kind, capture_id, value, source, created_at) VALUES"
            " ('tongue_color', 'C000001', '{\"label\":\"red\",\"severity\":\"mild\"}', 'x',"
            " '2026-10-06T00:00:00Z')"
        )
        conn.commit()
        kinds_before = conn.execute("SELECT * FROM kinds ORDER BY kind").fetchall()
        conn.close()

    conn = catalog.connect(path)
    try:
        result = catalog.apply_migrations(conn, "catalog")
        latest = catalog.latest_version("catalog")
        assert result == MigrationResult(1, latest)
        assert catalog.schema_version(conn) == latest
        assert _review_kind(conn) == ("review", "annotation", 1)
        # 0002 以降で足した種類のほかは,もとの行のまま
        kinds_after = conn.execute(
            "SELECT * FROM kinds WHERE kind NOT IN"
            " ('review', 'deeptias_features', 'deeptias_output_file', 'tongue_color_rounds',"
            " 'tongue_color_first_round') ORDER BY kind"
        )
        assert kinds_after.fetchall() == kinds_before
        assert conn.execute("SELECT COUNT(*) FROM subjects").fetchone()[0] == 1
        assert conn.execute("SELECT COUNT(*) FROM captures").fetchone()[0] == 1
        assert conn.execute("SELECT COUNT(*) FROM annotations").fetchone()[0] == 1
        # review の所見を付けられる(外部キー kinds を満たす)
        conn.execute(
            "INSERT INTO annotations (kind, capture_id, value, source, created_at) VALUES"
            " ('review', 'C000001', '{}', 'review_list', '2026-10-08T00:00:00Z')"
        )
        conn.commit()
        assert conn.execute("PRAGMA integrity_check").fetchone()[0] == "ok"

        # 再適用しても review の行は 1 つのまま
        again = catalog.apply_migrations(conn, "catalog")
        assert again.applied == 0
        assert conn.execute("SELECT COUNT(*) FROM kinds WHERE kind = 'review'").fetchone()[0] == 1
    finally:
        conn.close()


# ---------------------------------------------------------------------------
# catalog/0003: 所見の種類 deeptias_features(SPEC_02「kinds」)
# ---------------------------------------------------------------------------
_DATA_TABLES = (
    "subjects",
    "captures",
    "assets",
    "annotations",
    "derivations",
    "derivation_outputs",
    "datasets",
    "dataset_versions",
    "dataset_members",
    "dataset_member_annotations",
    "deliveries",
)


def _dump_tables(conn: sqlite3.Connection) -> dict[str, list[tuple]]:
    return {t: conn.execute(f"SELECT * FROM {t} ORDER BY 1, 2").fetchall() for t in _DATA_TABLES}


def _at_version_2_with_frozen_version(path: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
    # 研究室 PC の目録(0002 まで適用・取り込み済み・版あり)と同じ状態を作る
    first_two = migrate.load_migrations("catalog")[:2]
    with monkeypatch.context() as m:
        m.setattr(migrate, "load_migrations", lambda series: first_two)
        conn = catalog.connect(path, create=True)
        catalog.apply_migrations(conn, "catalog")
    assert catalog.schema_version(conn) == 2
    sha = "a" * 64
    conn.execute(
        "INSERT INTO subjects (subject_id, created_at) VALUES ('S000001', '2026-10-06T00:00:00Z')"
    )
    conn.execute("INSERT INTO captures (capture_id, subject_id) VALUES ('C000001', 'S000001')")
    conn.execute(
        "INSERT INTO assets (sha256, kind, capture_id, ext, size_bytes, source, source_name,"
        " registered_at) VALUES (?, 'tongue_crop_masked', 'C000001', 'png', 10, 'src', 'x/1.png',"
        " '2026-10-06T00:00:00Z')",
        (sha,),
    )
    for kind, value in (
        ("tongue_color", '{"label":"red","severity":"mild"}'),
        ("review", '{"reason":"r","resolve":"r","since":"2026-10-08","numbers":[1]}'),
    ):
        conn.execute(
            "INSERT INTO annotations (kind, capture_id, value, source, created_at)"
            " VALUES (?, 'C000001', ?, 'x', '2026-10-06T00:00:00Z')",
            (kind, value),
        )
    conn.commit()

    definition = (
        'name = "tongue_color"\ndescription = "d"\n[select]\n'
        'asset_kind = "tongue_crop_masked"\nrequire = ["tongue_color"]\n'
        '[columns]\ntongue_color = ["label", "severity"]\n'
    )
    directory = tmp_path / "datasets"
    directory.mkdir()
    (directory / "tongue_color.toml").write_bytes(definition.encode())
    freeze_version(
        conn,
        load_definition(directory, "tongue_color"),
        repo_state=RepoState(commit="0" * 40, uncommitted=0),
    )
    return conn


def test_deeptias_kind_from_version_2_keeps_existing_rows(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    path = tmp_path / "db.sqlite"
    conn = _at_version_2_with_frozen_version(path, monkeypatch, tmp_path)
    data_before = _dump_tables(conn)
    assert all(data_before[t] for t in ("annotations", "dataset_versions", "dataset_members"))
    kinds_before = conn.execute("SELECT * FROM kinds ORDER BY kind").fetchall()
    manifest_before = rebuild_manifest(conn, "tongue_color", 1)
    assert conn.execute("SELECT 1 FROM kinds WHERE kind = 'deeptias_features'").fetchone() is None
    conn.close()

    conn = catalog.connect(path)
    try:
        latest = catalog.latest_version("catalog")
        assert latest >= 3
        assert catalog.apply_migrations(conn, "catalog") == MigrationResult(2, latest)

        # 既存の行はすべてそのまま(凍結した版を含む)
        assert _dump_tables(conn) == data_before
        kinds_after = conn.execute(
            "SELECT * FROM kinds WHERE kind NOT IN"
            " ('deeptias_features', 'deeptias_output_file', 'tongue_color_rounds',"
            " 'tongue_color_first_round') ORDER BY kind"
        ).fetchall()
        assert kinds_after == kinds_before
        assert rebuild_manifest(conn, "tongue_color", 1) == manifest_before

        row = conn.execute(
            "SELECT category, value_schema_version FROM kinds WHERE kind = 'deeptias_features'"
        ).fetchone()
        assert row == ("annotation", 1)

        # 所見を付けられる(外部キー kinds を満たす)
        conn.execute(
            "INSERT INTO annotations (kind, capture_id, value, source, created_at) VALUES"
            " ('deeptias_features', 'C000001', '{}', 'deeptias_output_folder',"
            " '2026-10-31T00:00:00Z')"
        )
        conn.commit()
        assert conn.execute("PRAGMA integrity_check").fetchone()[0] == "ok"

        # 再適用しても行は 1 つのまま
        assert catalog.apply_migrations(conn, "catalog").applied == 0
        count = conn.execute("SELECT COUNT(*) FROM kinds WHERE kind = 'deeptias_features'")
        assert count.fetchone()[0] == 1
    finally:
        conn.close()


def test_deeptias_kind_from_empty_db(tmp_path: Path) -> None:
    conn = catalog.connect(tmp_path / "db.sqlite", create=True)
    try:
        catalog.apply_migrations(conn, "catalog")
        row = conn.execute(
            "SELECT category, value_schema_version FROM kinds WHERE kind = 'deeptias_features'"
        ).fetchone()
        assert row == ("annotation", 1)
    finally:
        conn.close()


# ---------------------------------------------------------------------------
# catalog/0004: DeepTIAS の出力全体と舌色ラベルの 3 回分(SPEC_02「kinds」「derivations」)
# ---------------------------------------------------------------------------
def _at_version_3_with_frozen_version_and_derivation(
    path: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> sqlite3.Connection:
    # 研究室 PC の目録(0003 まで適用・版あり・由来あり)と同じ状態を作る
    conn = _at_version_2_with_frozen_version(path, monkeypatch, tmp_path)
    first_three = migrate.load_migrations("catalog")[:3]
    with monkeypatch.context() as m:
        m.setattr(migrate, "load_migrations", lambda series: first_three)
        catalog.apply_migrations(conn, "catalog")
    assert catalog.schema_version(conn) == 3
    conn.execute(
        "INSERT INTO derivations (tool, tool_version, mode, note)"
        " VALUES ('DeepTIAS', 'unknown', 'Image&Calib', 'old')"
    )
    conn.execute(
        "INSERT INTO derivation_outputs (derivation_id, sha256, role) VALUES (1, ?, 'cropped')",
        ("a" * 64,),
    )
    conn.commit()
    return conn


def test_outputs_and_rounds_from_version_3_keep_existing_rows(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    path = tmp_path / "db.sqlite"
    conn = _at_version_3_with_frozen_version_and_derivation(path, monkeypatch, tmp_path)
    tables = [t for t in _DATA_TABLES if t != "derivations"]
    data_before = {t: conn.execute(f"SELECT * FROM {t} ORDER BY 1, 2").fetchall() for t in tables}
    derivations_before = conn.execute("SELECT * FROM derivations").fetchall()
    assert derivations_before
    kinds_before = conn.execute("SELECT * FROM kinds ORDER BY kind").fetchall()
    manifest_before = rebuild_manifest(conn, "tongue_color", 1)
    conn.close()

    conn = catalog.connect(path)
    try:
        latest = catalog.latest_version("catalog")
        assert latest >= 4
        assert catalog.apply_migrations(conn, "catalog") == MigrationResult(3, latest)

        assert {
            t: conn.execute(f"SELECT * FROM {t} ORDER BY 1, 2").fetchall() for t in tables
        } == data_before
        # 既存の由来は同じ値のままで,足した列は NULL
        columns = [row[1] for row in conn.execute("PRAGMA table_info(derivations)")]
        assert "capture_id" in columns
        names = [c for c in columns if c != "capture_id"]
        assert conn.execute(f"SELECT {', '.join(names)} FROM derivations").fetchall() == (
            derivations_before
        )
        assert conn.execute("SELECT capture_id FROM derivations").fetchall() == [(None,)]

        kinds_after = conn.execute(
            "SELECT * FROM kinds WHERE kind NOT IN"
            " ('deeptias_output_file', 'tongue_color_rounds', 'tongue_color_first_round')"
            " ORDER BY kind"
        ).fetchall()
        assert kinds_after == kinds_before
        assert rebuild_manifest(conn, "tongue_color", 1) == manifest_before
        assert conn.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
        assert conn.execute("PRAGMA foreign_key_check").fetchall() == []

        assert catalog.apply_migrations(conn, "catalog").applied == 0
    finally:
        conn.close()


def test_outputs_and_rounds_kinds(catalog_conn: sqlite3.Connection) -> None:
    rows = catalog_conn.execute(
        "SELECT kind, category, value_schema_version FROM kinds"
        " WHERE kind IN ('deeptias_output_file', 'tongue_color_rounds') ORDER BY kind"
    ).fetchall()
    assert rows == [
        ("deeptias_output_file", "asset", None),
        ("tongue_color_rounds", "annotation", 1),
    ]


def test_derivations_capture_id_has_foreign_key_and_index(
    catalog_conn: sqlite3.Connection,
) -> None:
    foreign_keys = catalog_conn.execute("PRAGMA foreign_key_list(derivations)").fetchall()
    assert [(row[2], row[3], row[4]) for row in foreign_keys] == [
        ("captures", "capture_id", "capture_id")
    ]
    indexed = [
        catalog_conn.execute(f"PRAGMA index_info({name})").fetchall()
        for (_, name, *_rest) in catalog_conn.execute("PRAGMA index_list(derivations)").fetchall()
    ]
    assert any([row[2] for row in columns] == ["capture_id"] for columns in indexed)
    # 無い撮影は指せない
    with pytest.raises(sqlite3.IntegrityError):
        catalog_conn.execute(
            "INSERT INTO derivations (tool, tool_version, capture_id) VALUES ('t', 'v', 'C999999')"
        )


# ---------------------------------------------------------------------------
# catalog/0005: 舌色の 1 回目のラベル(SPEC_02「kinds」)
# ---------------------------------------------------------------------------
_FIRST_ROUND_KIND = "tongue_color_first_round"


def _first_round_kind_row(conn: sqlite3.Connection) -> tuple | None:
    return conn.execute(
        "SELECT category, value_schema_version FROM kinds WHERE kind = ?", (_FIRST_ROUND_KIND,)
    ).fetchone()


def test_first_round_kind_from_empty_db(catalog_conn: sqlite3.Connection) -> None:
    assert _first_round_kind_row(catalog_conn) == ("annotation", 1)


def test_first_round_kind_from_version_4_keeps_existing_rows(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    # 研究室 PC の目録(0004 まで適用・版あり・由来あり)に 0005 を足す
    path = tmp_path / "db.sqlite"
    conn = _at_version_3_with_frozen_version_and_derivation(path, monkeypatch, tmp_path)
    first_four = migrate.load_migrations("catalog")[:4]
    with monkeypatch.context() as m:
        m.setattr(migrate, "load_migrations", lambda series: first_four)
        catalog.apply_migrations(conn, "catalog")
    assert catalog.schema_version(conn) == 4
    assert _first_round_kind_row(conn) is None
    conn.execute(
        "INSERT INTO annotations (kind, capture_id, value, source, created_at) VALUES"
        " ('tongue_color_rounds', 'C000001', '{\"rounds\":[null,null,null]}',"
        " 'namiki_label_xlsx', '2026-11-01T00:00:00Z')"
    )
    conn.commit()
    data_before = _dump_tables(conn)
    assert all(data_before[t] for t in ("annotations", "dataset_versions", "dataset_members"))
    assert data_before["derivations"]
    kinds_before = conn.execute("SELECT * FROM kinds ORDER BY kind").fetchall()
    manifest_before = rebuild_manifest(conn, "tongue_color", 1)
    conn.close()

    conn = catalog.connect(path)
    try:
        latest = catalog.latest_version("catalog")
        assert latest >= 5
        assert catalog.apply_migrations(conn, "catalog") == MigrationResult(4, latest)

        # 既存の行はすべてそのまま(凍結した版・所見・由来を含む).足すのは kinds の 1 行だけ
        assert _dump_tables(conn) == data_before
        kinds_after = conn.execute(
            "SELECT * FROM kinds WHERE kind != ? ORDER BY kind", (_FIRST_ROUND_KIND,)
        ).fetchall()
        assert kinds_after == kinds_before
        assert rebuild_manifest(conn, "tongue_color", 1) == manifest_before
        assert _first_round_kind_row(conn) == ("annotation", 1)

        # 所見を付けられる(外部キー kinds を満たす)
        conn.execute(
            "INSERT INTO annotations (kind, capture_id, value, source, created_at) VALUES"
            " (?, 'C000001', '{\"label\":\"red\",\"level\":1}', 'namiki_first_round_xlsx',"
            " '2026-11-02T00:00:00Z')",
            (_FIRST_ROUND_KIND,),
        )
        conn.commit()
        assert conn.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
        assert conn.execute("PRAGMA foreign_key_check").fetchall() == []

        # 再適用しても行は 1 つのまま
        assert catalog.apply_migrations(conn, "catalog").applied == 0
        count = conn.execute("SELECT COUNT(*) FROM kinds WHERE kind = ?", (_FIRST_ROUND_KIND,))
        assert count.fetchone()[0] == 1
    finally:
        conn.close()


def test_every_annotation_kind_has_a_value_type(catalog_conn: sqlite3.Connection) -> None:
    # 種類の行と値の型は同時に足す(coding-style.md「マイグレーション」)
    rows = catalog_conn.execute("SELECT kind FROM kinds WHERE category = 'annotation'").fetchall()
    assert {kind for (kind,) in rows} == set(kinds.ANNOTATION_VALUE_TYPES)