File size: 2,009 Bytes
74bf532
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
Schema migration: add special_collection_score + special_collection_categories
columns to items table. Idempotent.
"""

import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy import inspect, text

from uraas.database import engine


def column_exists(table: str, column: str) -> bool:
    insp = inspect(engine)
    return column in {c["name"] for c in insp.get_columns(table)}


def main() -> int:
    print(
        "Migration: adding special_collection_score + special_collection_categories to items"
    )

    dialect = engine.dialect.name
    print(f"Dialect: {dialect}")

    statements = []
    if not column_exists("items", "special_collection_score"):
        statements.append(
            "ALTER TABLE items ADD COLUMN special_collection_score FLOAT DEFAULT 0.0"
        )
    else:
        print("  special_collection_score already present, skipping")

    if not column_exists("items", "special_collection_categories"):
        # TEXT for both sqlite + postgres
        statements.append(
            "ALTER TABLE items ADD COLUMN special_collection_categories TEXT"
        )
    else:
        print("  special_collection_categories already present, skipping")

    if not statements:
        print("Nothing to do.")
        return 0

    with engine.begin() as conn:
        for stmt in statements:
            print(f"  -> {stmt}")
            conn.execute(text(stmt))

    # Index on score so ORDER BY score DESC is fast
    try:
        with engine.begin() as conn:
            conn.execute(
                text(
                    "CREATE INDEX IF NOT EXISTS ix_items_special_collection_score "
                    "ON items (special_collection_score)"
                )
            )
            print("  -> index ix_items_special_collection_score ensured")
    except Exception as e:
        print(f"  (index creation skipped: {e})")

    print("Done.")
    return 0


if __name__ == "__main__":
    sys.exit(main())