"""Seed the "Aliyun Bailian (DashScope)" API key provider. Revision ID: 075 Revises: 074 Create Date: 2026-04-27 The provider catalog is admin-managed via /admin/assets/api-keys, so the admin can rename or deactivate this row freely. The seed only fires if no provider whose (lower-cased) name contains "bailian" already exists, to avoid clobbering an admin's customized row across re-runs / forks. Idempotent: safe to re-run. """ from __future__ import annotations import sqlalchemy as sa from alembic import op revision = "075" down_revision = "074" branch_labels = None depends_on = None def _table_exists(bind, name: str) -> bool: return bind.execute( sa.text( "SELECT 1 FROM information_schema.TABLES " "WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :n", ), {"n": name}, ).scalar() is not None def upgrade() -> None: bind = op.get_bind() if not _table_exists(bind, "api_key_providers"): return existing = bind.execute(sa.text( "SELECT id FROM api_key_providers " "WHERE LOWER(name) LIKE '%bailian%' " " OR LOWER(name) LIKE '%dashscope%' " " OR LOWER(name) LIKE '%百炼%' " "LIMIT 1" )).fetchone() if existing: return new_id = bind.execute(sa.text("SELECT UUID()")).scalar() bind.execute(sa.text( "INSERT INTO api_key_providers " "(id, name, description, is_active, sort_order, created_at, updated_at) " "VALUES (:id, :n, :d, 1, 50, NOW(), NOW())" ), { "id": new_id, "n": "Aliyun Bailian (DashScope)", "d": ( "阿里云百炼 / DashScope. Approval auto-grants a dedicated RAM " "sub-user with AliyunBailianFullAccess + AccessKey/Secret. " "Use the AK/SK with the DashScope SDK in RAM-auth mode " "(or log in to Bailian console as that RAM user to mint a " "personal API key). Workspace + applications + usage are " "synced into Helix nightly via bailian.workspace_sync." ), }) def downgrade() -> None: bind = op.get_bind() if not _table_exists(bind, "api_key_providers"): return # Only delete if no assignments reference it (otherwise leave alone # to avoid breaking historical request rows). bind.execute(sa.text( "DELETE FROM api_key_providers " "WHERE name = 'Aliyun Bailian (DashScope)' " "AND NOT EXISTS (" " SELECT 1 FROM api_key_assignments " " WHERE api_key_assignments.provider_id = api_key_providers.id" ")" ))