"""Migration script to add public-booking-link slug support to properties. Idempotent (safe to run multiple times): - Adds `slug` (VARCHAR, nullable) and `list_on_landing` (BOOLEAN NOT NULL DEFAULT 0) columns to `properties` if missing. - Creates a UNIQUE INDEX on `slug` if missing. - Backfills NULL slugs deterministically from each property's name. """ import sys import os # Add backend to path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from sqlalchemy import inspect, text from app.core.slug import generate_unique_slug from app.db.session import SessionLocal, engine from app.models.property import Property SLUG_INDEX_NAME = "ix_properties_slug_unique" def migrate() -> None: """Run migration to add slug + list_on_landing support to properties.""" inspector = inspect(engine) columns = [col["name"] for col in inspector.get_columns("properties")] print("Starting property slug migration...") with engine.connect() as conn: if "slug" not in columns: print("1. Adding slug column to properties...") conn.execute(text("ALTER TABLE properties ADD COLUMN slug VARCHAR")) conn.commit() print(" Column added.") else: print("1. slug column already exists.") if "list_on_landing" not in columns: print("2. Adding list_on_landing column to properties...") conn.execute( text("ALTER TABLE properties ADD COLUMN list_on_landing BOOLEAN DEFAULT 0 NOT NULL") ) conn.commit() print(" Column added.") else: print("2. list_on_landing column already exists.") # Recompute indexes after potentially adding the slug column. inspector = inspect(engine) index_names = {ix["name"] for ix in inspector.get_indexes("properties")} if SLUG_INDEX_NAME not in index_names: print("3. Creating unique index on slug...") with engine.connect() as conn: conn.execute( text(f"CREATE UNIQUE INDEX {SLUG_INDEX_NAME} ON properties (slug)") ) conn.commit() print(" Index created.") else: print("3. Unique index on slug already exists.") # Backfill: deterministic unique slug for every property missing one. print("4. Backfilling missing slugs...") db = SessionLocal() try: properties_without_slug = ( db.query(Property) .filter(Property.slug.is_(None)) .order_by(Property.id) .all() ) for prop in properties_without_slug: prop.slug = generate_unique_slug(db, prop.name, exclude_id=prop.id) db.flush() db.commit() print(f" Backfilled {len(properties_without_slug)} propert(y/ies).") except Exception: db.rollback() raise finally: db.close() print("Migration completed successfully!") if __name__ == "__main__": migrate()