From be72b5cbf3ecf1d84c015a84e0c8e6d898265116 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 13 Oct 2026 07:25:03 -0500 Subject: [PATCH] feat(api): add Alembic async migrations, initial schema, and database seed script - Initialize Alembic with async template and configure env.py with dynamic DATABASE_URL. - Add revision 001_initial_schema creating users, sculptures, check_ins, and tickets tables. - Add PostGIS GIST spatial index and pgvector HNSW cosine similarity index. - Implement api/src/api/database/seed.py with deterministic L2-normalized 1280-float vectors. - Seed initial user and 3 sculptures (La Novia Dulce, La Gata Ceremonial, La Gata Ilustrada). - Add unit tests verifying embedding properties, geographic bounds, and migration script callables. --- api/alembic.ini | 149 +++++++++++++++++++ api/alembic/README | 1 + api/alembic/env.py | 68 +++++++++ api/alembic/script.py.mako | 28 ++++ api/alembic/versions/001_initial_schema.py | 127 ++++++++++++++++ api/src/api/database/seed.py | 164 +++++++++++++++++++++ api/tests/unit/test_seed_and_migrations.py | 54 +++++++ 7 files changed, 591 insertions(+) create mode 100644 api/alembic.ini create mode 100644 api/alembic/README create mode 100644 api/alembic/env.py create mode 100644 api/alembic/script.py.mako create mode 100644 api/alembic/versions/001_initial_schema.py create mode 100644 api/src/api/database/seed.py create mode 100644 api/tests/unit/test_seed_and_migrations.py diff --git a/api/alembic.ini b/api/alembic.ini new file mode 100644 index 0000000..df80d65 --- /dev/null +++ b/api/alembic.ini @@ -0,0 +1,149 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts. +# this is typically a path given in POSIX (e.g. forward slashes) +# format, relative to the token %(here)s which refers to the location of this +# ini file +script_location = %(here)s/alembic + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s +# Or organize into date-based subdirectories (requires recursive_version_locations = true) +# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. for multiple paths, the path separator +# is defined by "path_separator" below. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the tzdata library which can be installed by adding +# `alembic[tz]` to the pip requirements. +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to /versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "path_separator" +# below. +# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions + +# path_separator; This indicates what character is used to split lists of file +# paths, including version_locations and prepend_sys_path within configparser +# files such as alembic.ini. +# The default rendered in new alembic.ini files is "os", which uses os.pathsep +# to provide os-dependent path splitting. +# +# Note that in order to support legacy alembic.ini files, this default does NOT +# take place if path_separator is not present in alembic.ini. If this +# option is omitted entirely, fallback logic is as follows: +# +# 1. Parsing of the version_locations option falls back to using the legacy +# "version_path_separator" key, which if absent then falls back to the legacy +# behavior of splitting on spaces and/or commas. +# 2. Parsing of the prepend_sys_path option falls back to the legacy +# behavior of splitting on spaces, commas, or colons. +# +# Valid values for path_separator are: +# +# path_separator = : +# path_separator = ; +# path_separator = space +# path_separator = newline +# +# Use os.pathsep. Default configuration used for new projects. +path_separator = os + + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# database URL. This is consumed by the user-maintained env.py script only. +# other means of configuring database URLs may be customized within the env.py +# file. +sqlalchemy.url = driver://user:pass@localhost/dbname + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module +# hooks = ruff +# ruff.type = module +# ruff.module = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Alternatively, use the exec runner to execute a binary found on your PATH +# hooks = ruff +# ruff.type = exec +# ruff.executable = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Logging configuration. This is also consumed by the user-maintained +# env.py script only. +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/api/alembic/README b/api/alembic/README new file mode 100644 index 0000000..e0d0858 --- /dev/null +++ b/api/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration with an async dbapi. \ No newline at end of file diff --git a/api/alembic/env.py b/api/alembic/env.py new file mode 100644 index 0000000..1b0d0cf --- /dev/null +++ b/api/alembic/env.py @@ -0,0 +1,68 @@ +import asyncio +from logging.config import fileConfig + +from sqlalchemy import pool +from sqlalchemy.engine import Connection +from sqlalchemy.ext.asyncio import create_async_engine + +import api.db_models # noqa: F401 +from alembic import context +from api.core.config import settings +from api.database.base import Base + +config = context.config + +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +target_metadata = Base.metadata + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode.""" + url = settings.DATABASE_URL + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + compare_type=True, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def do_run_migrations(connection: Connection) -> None: + context.configure( + connection=connection, + target_metadata=target_metadata, + compare_type=True, + ) + + with context.begin_transaction(): + context.run_migrations() + + +async def run_async_migrations() -> None: + """Run migrations in 'online' mode using the async engine.""" + connectable = create_async_engine( + settings.DATABASE_URL, + poolclass=pool.NullPool, + ) + + async with connectable.connect() as connection: + await connection.run_sync(do_run_migrations) + + await connectable.dispose() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode.""" + asyncio.run(run_async_migrations()) + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/api/alembic/script.py.mako b/api/alembic/script.py.mako new file mode 100644 index 0000000..1101630 --- /dev/null +++ b/api/alembic/script.py.mako @@ -0,0 +1,28 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + """Upgrade schema.""" + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + """Downgrade schema.""" + ${downgrades if downgrades else "pass"} diff --git a/api/alembic/versions/001_initial_schema.py b/api/alembic/versions/001_initial_schema.py new file mode 100644 index 0000000..f223e43 --- /dev/null +++ b/api/alembic/versions/001_initial_schema.py @@ -0,0 +1,127 @@ +"""initial schema with postgis and pgvector + +Revision ID: 001_initial_schema +Revises: +Create Date: 2026-10-13 07:05:00.000000 + +""" + +from collections.abc import Sequence + +import geoalchemy2 +import sqlalchemy as sa +from pgvector.sqlalchemy import Vector + +from alembic import op + +# revision identifiers, used by Alembic. +revision: str = "001_initial_schema" +down_revision: str | None = None +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + # 1. Enable required PostgreSQL extensions + op.execute("CREATE EXTENSION IF NOT EXISTS postgis;") + op.execute("CREATE EXTENSION IF NOT EXISTS vector;") + + # 2. Users table + op.create_table( + "users", + sa.Column("id", sa.UUID(), nullable=False), + sa.Column("name", sa.String(length=100), nullable=False), + sa.Column("email", sa.String(length=255), nullable=False), + sa.Column("trust_score", sa.Float(), nullable=False, server_default="0.5"), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index(op.f("ix_users_email"), "users", ["email"], unique=True) + + # 3. Sculptures table + op.create_table( + "sculptures", + sa.Column("id", sa.UUID(), nullable=False), + sa.Column("name", sa.String(length=255), nullable=False), + sa.Column("artist", sa.String(length=255), nullable=False), + sa.Column("year", sa.Integer(), nullable=False), + sa.Column("description", sa.Text(), nullable=True), + sa.Column("audio_url", sa.String(length=512), nullable=True), + sa.Column("unlocked_content", sa.Text(), nullable=True), + sa.Column("status", sa.String(length=50), nullable=False, server_default="on-site"), + sa.Column( + "location", + geoalchemy2.types.Geometry( + geometry_type="POINT", srid=4326, from_text="ST_GeomFromEWKT", name="geometry" + ), + nullable=False, + ), + sa.Column("embedding", Vector(1280), nullable=False), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False), + sa.PrimaryKeyConstraint("id"), + ) + + # Create HNSW index for vector cosine similarity + op.execute( + "CREATE INDEX idx_sculptures_embedding ON sculptures USING hnsw (embedding vector_cosine_ops);" + ) + + # 4. Check-ins table + op.create_table( + "check_ins", + sa.Column("id", sa.UUID(), nullable=False), + sa.Column("user_id", sa.UUID(), nullable=False), + sa.Column("sculpture_id", sa.UUID(), nullable=False), + sa.Column("captured_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("photo_url", sa.String(length=512), nullable=False), + sa.Column("similarity_score", sa.Float(), nullable=False), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(["sculpture_id"], ["sculptures.id"], ondelete="CASCADE"), + sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("user_id", "sculpture_id", name="uq_user_sculpture_checkin"), + ) + op.create_index(op.f("ix_check_ins_sculpture_id"), "check_ins", ["sculpture_id"], unique=False) + op.create_index(op.f("ix_check_ins_user_id"), "check_ins", ["user_id"], unique=False) + + # 5. Tickets table + op.create_table( + "tickets", + sa.Column("id", sa.UUID(), nullable=False), + sa.Column("reporter_id", sa.UUID(), nullable=False), + sa.Column("sculpture_id", sa.UUID(), nullable=False), + sa.Column("reported_status", sa.String(length=50), nullable=False), + sa.Column( + "location", + geoalchemy2.types.Geometry( + geometry_type="POINT", srid=4326, from_text="ST_GeomFromEWKT", name="geometry" + ), + nullable=False, + ), + sa.Column("photo_url", sa.String(length=512), nullable=True), + sa.Column("description", sa.Text(), nullable=True), + sa.Column("status", sa.String(length=50), nullable=False, server_default="pending"), + sa.Column("reporter_trust_score", sa.Float(), nullable=False), + sa.Column("notes", sa.String(length=300), nullable=True), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("resolved_at", sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(["sculpture_id"], ["sculptures.id"], ondelete="CASCADE"), + sa.ForeignKeyConstraint(["reporter_id"], ["users.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index(op.f("ix_tickets_reporter_id"), "tickets", ["reporter_id"], unique=False) + op.create_index(op.f("ix_tickets_sculpture_id"), "tickets", ["sculpture_id"], unique=False) + op.create_index( + "idx_tickets_sculpture_status", "tickets", ["sculpture_id", "status"], unique=False + ) + + +def downgrade() -> None: + op.drop_table("tickets") + op.drop_table("check_ins") + op.execute("DROP INDEX IF EXISTS idx_sculptures_embedding;") + op.drop_table("sculptures") + op.drop_index(op.f("ix_users_email"), table_name="users") + op.drop_table("users") diff --git a/api/src/api/database/seed.py b/api/src/api/database/seed.py new file mode 100644 index 0000000..effb5cf --- /dev/null +++ b/api/src/api/database/seed.py @@ -0,0 +1,164 @@ +import asyncio +import math +import random +import uuid +from collections.abc import Sequence + +from geoalchemy2.elements import WKTElement +from sqlalchemy.ext.asyncio import AsyncSession + +from api.database.session import AsyncSessionLocal +from api.db_models.sculpture import SculptureDB +from api.db_models.user import UserDB + + +def generate_normalized_embedding(seed_int: int, dimensions: int = 1280) -> list[float]: + """ + Generate a deterministic, L2-normalized float vector simulating MobileNetV2 output. + """ + rng = random.Random(seed_int) + raw_vals = [rng.gauss(0.0, 1.0) for _ in range(dimensions)] + magnitude = math.sqrt(sum(x * x for x in raw_vals)) + return [round(x / magnitude, 6) for x in raw_vals] + + +INITIAL_USER = { + "id": uuid.UUID("123e4567-e89b-12d3-a456-426614174000"), + "name": "Explorador Caleño", + "email": "explorer@cali.gov.co", + "trust_score": 0.85, +} + +INITIAL_SCULPTURES = [ + { + "id": uuid.UUID("234e5678-e89b-12d3-a456-426614174001"), + "name": "La Novia Dulce", + "artist": "Lorena Espitia", + "year": 2006, + "latitude": 3.450143, + "longitude": -76.533282, + "status": "on-site", + "description": ( + "Decorated with sweets and candies representing Cali's culinary traditions. " + "This bride is a homage to the traditional 'Macetas' given to godchildren every June." + ), + "unlocked_content": ( + "Cultural Oracle Insight: Lorena Espitia used bright fiberglass modeling to create a tactile sense " + "of Colombian sugar candies. The sculpture is traditionally positioned near the river to evoke " + "Cali's warm breeze carrying sweet aromas." + ), + "audio_url": "https://cdn.gatos.cali.gov.co/audio/novia_dulce.mp3", + "embedding_seed": 101, + }, + { + "id": uuid.UUID("234e5678-e89b-12d3-a456-426614174002"), + "name": "La Gata Ceremonial", + "artist": "José Horacio Martínez", + "year": 2006, + "latitude": 3.451600, + "longitude": -76.532600, + "status": "moved", + "description": ( + "A dark sculpture featuring intricate pre-Columbian gold patterns. " + "It represents the ancestral heritage, jaguar spirits, and mythological elements of Southwest Colombia." + ), + "unlocked_content": ( + "Cultural Oracle Insight: The gold motifs are inspired by Calima culture gold artifacts. " + "Its temporary relocation due to civic repairs on the Boulevard has triggered consensus recalculation, " + "verifying its new spot 150m north." + ), + "audio_url": "https://cdn.gatos.cali.gov.co/audio/gata_ceremonial.mp3", + "embedding_seed": 102, + }, + { + "id": uuid.UUID("234e5678-e89b-12d3-a456-426614174003"), + "name": "La Gata Ilustrada", + "artist": "Lucy Tejada", + "year": 2006, + "latitude": 3.450800, + "longitude": -76.532900, + "status": "on-site", + "description": ( + "Covered in birds, trees, and dreamlike childhood imagery by Lucy Tejada, " + "sister of master Hernando Tejada." + ), + "unlocked_content": ( + "Cultural Oracle Insight: Lucy Tejada painted this sculpture as a direct artistic dialogue " + "with her brother's bronze cat, symbolizing Cali's natural biodiversity and poetic innocence." + ), + "audio_url": "https://cdn.gatos.cali.gov.co/audio/gata_ilustrada.mp3", + "embedding_seed": 103, + }, +] + + +async def seed_data(session: AsyncSession) -> tuple[UserDB, Sequence[SculptureDB]]: + """ + Idempotently seed the baseline user and cat sculptures into the database. + """ + # 1. Seed user + user = await session.get(UserDB, INITIAL_USER["id"]) + if not user: + user = UserDB( + id=INITIAL_USER["id"], + name=INITIAL_USER["name"], + email=INITIAL_USER["email"], + trust_score=INITIAL_USER["trust_score"], + ) + session.add(user) + else: + user.name = INITIAL_USER["name"] + user.trust_score = INITIAL_USER["trust_score"] + + # 2. Seed sculptures + seeded_sculptures: list[SculptureDB] = [] + for item in INITIAL_SCULPTURES: + sculpture = await session.get(SculptureDB, item["id"]) + # PostGIS Point(Longitude Latitude) EPSG:4326 + point = WKTElement(f"POINT({item['longitude']} {item['latitude']})", srid=4326) + embedding = generate_normalized_embedding(item["embedding_seed"]) + + if not sculpture: + sculpture = SculptureDB( + id=item["id"], + name=item["name"], + artist=item["artist"], + year=item["year"], + description=item["description"], + audio_url=item["audio_url"], + unlocked_content=item["unlocked_content"], + status=item["status"], + location=point, + embedding=embedding, + ) + session.add(sculpture) + else: + sculpture.name = item["name"] + sculpture.artist = item["artist"] + sculpture.year = item["year"] + sculpture.description = item["description"] + sculpture.audio_url = item["audio_url"] + sculpture.unlocked_content = item["unlocked_content"] + sculpture.status = item["status"] + sculpture.location = point + sculpture.embedding = embedding + + seeded_sculptures.append(sculpture) + + await session.commit() + return user, seeded_sculptures + + +async def run_seed() -> None: + """CLI runner for database seeding.""" + print("🌱 Starting database seeding...") + async with AsyncSessionLocal() as session: + user, sculptures = await seed_data(session) + print(f"✅ User seeded: {user.name} ({user.email})") + for s in sculptures: + print(f"✅ Sculpture seeded: {s.name} by {s.artist} [{s.status}]") + print("🎉 Database seeding completed successfully!") + + +if __name__ == "__main__": + asyncio.run(run_seed()) diff --git a/api/tests/unit/test_seed_and_migrations.py b/api/tests/unit/test_seed_and_migrations.py new file mode 100644 index 0000000..af131f6 --- /dev/null +++ b/api/tests/unit/test_seed_and_migrations.py @@ -0,0 +1,54 @@ +import importlib.util +import math +from pathlib import Path + +from api.database.seed import INITIAL_SCULPTURES, INITIAL_USER, generate_normalized_embedding + + +def test_normalized_embedding_properties(): + vec = generate_normalized_embedding(seed_int=42, dimensions=1280) + assert len(vec) == 1280 + + # Verify L2 norm == 1.0 + l2_norm = math.sqrt(sum(x * x for x in vec)) + assert math.isclose(l2_norm, 1.0, rel_tol=1e-3) + + # Determinism + vec_repeat = generate_normalized_embedding(seed_int=42, dimensions=1280) + assert vec == vec_repeat + + +def test_initial_sculptures_data_validity(): + assert len(INITIAL_SCULPTURES) == 3 + + for item in INITIAL_SCULPTURES: + # Geographic bounds for Cali, Colombia + assert 3.30 <= item["latitude"] <= 3.60 + assert -76.60 <= item["longitude"] <= -76.40 + assert item["year"] >= 1996 + assert len(item["name"]) > 0 + assert len(item["artist"]) > 0 + assert item["status"] in ("on-site", "moved", "missing") + + +def test_initial_user_data_validity(): + assert "@" in INITIAL_USER["email"] + assert 0.0 <= INITIAL_USER["trust_score"] <= 1.0 + assert len(INITIAL_USER["name"]) > 0 + + +def test_migration_001_structure(): + migration_file = Path(__file__).parents[2] / "alembic" / "versions" / "001_initial_schema.py" + assert migration_file.is_file() + + spec = importlib.util.spec_from_file_location("migration_001", str(migration_file)) + assert spec is not None + assert spec.loader is not None + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + + assert hasattr(mod, "upgrade") + assert callable(mod.upgrade) + assert hasattr(mod, "downgrade") + assert callable(mod.downgrade) + assert mod.revision == "001_initial_schema"