|
| 1 | +"""Add structured metadata indexes for entity frontmatter |
| 2 | +
|
| 3 | +Revision ID: d7e8f9a0b1c2 |
| 4 | +Revises: g9a0b3c4d5e6 |
| 5 | +Create Date: 2026-01-31 12:00:00.000000 |
| 6 | +
|
| 7 | +""" |
| 8 | + |
| 9 | +from typing import Sequence, Union |
| 10 | + |
| 11 | +import sqlalchemy as sa |
| 12 | +from alembic import op |
| 13 | +from sqlalchemy import text |
| 14 | + |
| 15 | + |
| 16 | +def column_exists(connection, table: str, column: str) -> bool: |
| 17 | + """Check if a column exists in a table (idempotent migration support).""" |
| 18 | + if connection.dialect.name == "postgresql": |
| 19 | + result = connection.execute( |
| 20 | + text( |
| 21 | + "SELECT 1 FROM information_schema.columns " |
| 22 | + "WHERE table_name = :table AND column_name = :column" |
| 23 | + ), |
| 24 | + {"table": table, "column": column}, |
| 25 | + ) |
| 26 | + return result.fetchone() is not None |
| 27 | + # SQLite |
| 28 | + result = connection.execute(text(f"PRAGMA table_info({table})")) |
| 29 | + columns = [row[1] for row in result] |
| 30 | + return column in columns |
| 31 | + |
| 32 | + |
| 33 | +def index_exists(connection, index_name: str) -> bool: |
| 34 | + """Check if an index exists (idempotent migration support).""" |
| 35 | + if connection.dialect.name == "postgresql": |
| 36 | + result = connection.execute( |
| 37 | + text("SELECT 1 FROM pg_indexes WHERE indexname = :index_name"), |
| 38 | + {"index_name": index_name}, |
| 39 | + ) |
| 40 | + return result.fetchone() is not None |
| 41 | + # SQLite |
| 42 | + result = connection.execute( |
| 43 | + text("SELECT 1 FROM sqlite_master WHERE type='index' AND name = :index_name"), |
| 44 | + {"index_name": index_name}, |
| 45 | + ) |
| 46 | + return result.fetchone() is not None |
| 47 | + |
| 48 | + |
| 49 | +# revision identifiers, used by Alembic. |
| 50 | +revision: str = "d7e8f9a0b1c2" |
| 51 | +down_revision: Union[str, None] = "6830751f5fb6" |
| 52 | +branch_labels: Union[str, Sequence[str], None] = None |
| 53 | +depends_on: Union[str, Sequence[str], None] = None |
| 54 | + |
| 55 | + |
| 56 | +def upgrade() -> None: |
| 57 | + """Add JSONB/GiN indexes for Postgres and generated columns for SQLite.""" |
| 58 | + connection = op.get_bind() |
| 59 | + dialect = connection.dialect.name |
| 60 | + |
| 61 | + if dialect == "postgresql": |
| 62 | + # Ensure JSONB for efficient indexing |
| 63 | + result = connection.execute( |
| 64 | + text( |
| 65 | + "SELECT data_type FROM information_schema.columns " |
| 66 | + "WHERE table_name = 'entity' AND column_name = 'entity_metadata'" |
| 67 | + ) |
| 68 | + ).fetchone() |
| 69 | + if result and result[0] != "jsonb": |
| 70 | + op.execute( |
| 71 | + "ALTER TABLE entity ALTER COLUMN entity_metadata " |
| 72 | + "TYPE jsonb USING entity_metadata::jsonb" |
| 73 | + ) |
| 74 | + |
| 75 | + # General JSONB GIN index |
| 76 | + op.execute( |
| 77 | + "CREATE INDEX IF NOT EXISTS idx_entity_metadata_gin " |
| 78 | + "ON entity USING GIN (entity_metadata jsonb_path_ops)" |
| 79 | + ) |
| 80 | + |
| 81 | + # Common field indexes |
| 82 | + op.execute( |
| 83 | + "CREATE INDEX IF NOT EXISTS idx_entity_tags_json " |
| 84 | + "ON entity USING GIN ((entity_metadata -> 'tags'))" |
| 85 | + ) |
| 86 | + op.execute( |
| 87 | + "CREATE INDEX IF NOT EXISTS idx_entity_frontmatter_type " |
| 88 | + "ON entity ((entity_metadata ->> 'type'))" |
| 89 | + ) |
| 90 | + op.execute( |
| 91 | + "CREATE INDEX IF NOT EXISTS idx_entity_frontmatter_status " |
| 92 | + "ON entity ((entity_metadata ->> 'status'))" |
| 93 | + ) |
| 94 | + return |
| 95 | + |
| 96 | + # SQLite: add generated columns for common frontmatter fields |
| 97 | + if not column_exists(connection, "entity", "tags_json"): |
| 98 | + op.add_column( |
| 99 | + "entity", |
| 100 | + sa.Column( |
| 101 | + "tags_json", |
| 102 | + sa.Text(), |
| 103 | + sa.Computed("json_extract(entity_metadata, '$.tags')", persisted=True), |
| 104 | + ), |
| 105 | + ) |
| 106 | + if not column_exists(connection, "entity", "frontmatter_status"): |
| 107 | + op.add_column( |
| 108 | + "entity", |
| 109 | + sa.Column( |
| 110 | + "frontmatter_status", |
| 111 | + sa.Text(), |
| 112 | + sa.Computed("json_extract(entity_metadata, '$.status')", persisted=True), |
| 113 | + ), |
| 114 | + ) |
| 115 | + if not column_exists(connection, "entity", "frontmatter_type"): |
| 116 | + op.add_column( |
| 117 | + "entity", |
| 118 | + sa.Column( |
| 119 | + "frontmatter_type", |
| 120 | + sa.Text(), |
| 121 | + sa.Computed("json_extract(entity_metadata, '$.type')", persisted=True), |
| 122 | + ), |
| 123 | + ) |
| 124 | + |
| 125 | + # Index generated columns |
| 126 | + if not index_exists(connection, "idx_entity_tags_json"): |
| 127 | + op.create_index("idx_entity_tags_json", "entity", ["tags_json"]) |
| 128 | + if not index_exists(connection, "idx_entity_frontmatter_status"): |
| 129 | + op.create_index("idx_entity_frontmatter_status", "entity", ["frontmatter_status"]) |
| 130 | + if not index_exists(connection, "idx_entity_frontmatter_type"): |
| 131 | + op.create_index("idx_entity_frontmatter_type", "entity", ["frontmatter_type"]) |
| 132 | + |
| 133 | + |
| 134 | +def downgrade() -> None: |
| 135 | + """Best-effort downgrade (drop indexes, revert JSONB on Postgres).""" |
| 136 | + connection = op.get_bind() |
| 137 | + dialect = connection.dialect.name |
| 138 | + |
| 139 | + if dialect == "postgresql": |
| 140 | + op.execute("DROP INDEX IF EXISTS idx_entity_frontmatter_status") |
| 141 | + op.execute("DROP INDEX IF EXISTS idx_entity_frontmatter_type") |
| 142 | + op.execute("DROP INDEX IF EXISTS idx_entity_tags_json") |
| 143 | + op.execute("DROP INDEX IF EXISTS idx_entity_metadata_gin") |
| 144 | + op.execute( |
| 145 | + "ALTER TABLE entity ALTER COLUMN entity_metadata TYPE json USING entity_metadata::json" |
| 146 | + ) |
| 147 | + return |
| 148 | + |
| 149 | + # SQLite: drop indexes (dropping generated columns requires table rebuild) |
| 150 | + op.execute("DROP INDEX IF EXISTS idx_entity_frontmatter_status") |
| 151 | + op.execute("DROP INDEX IF EXISTS idx_entity_frontmatter_type") |
| 152 | + op.execute("DROP INDEX IF EXISTS idx_entity_tags_json") |
0 commit comments