#!/usr/bin/env python3 """Run VLM queue migration""" import os import sys import re import psycopg2 from pathlib import Path def split_sql_statements(sql): """智能分割 SQL 语句(处理 PL/pgSQL 函数)""" statements = [] current = [] in_function = False in_dollar_quote = False dollar_tag = None lines = sql.split('\n') for line in lines: stripped = line.strip() # 跳过注释 if stripped.startswith('--'): continue # 检测函数开始 if re.search(r'\b(CREATE|CREATE OR REPLACE)\s+(FUNCTION|PROCEDURE)\b', stripped, re.IGNORECASE): in_function = True # 检测 dollar quote if in_function and '$$' in line: if not in_dollar_quote: in_dollar_quote = True dollar_tag = '$$' else: in_dollar_quote = False dollar_tag = None current.append(line) # 检测语句结束 if not in_function and stripped.endswith(';'): statements.append('\n'.join(current)) current = [] elif in_function and not in_dollar_quote and stripped.endswith(';'): # 函数结束 statements.append('\n'.join(current)) current = [] in_function = False # 添加最后一个语句 if current: statements.append('\n'.join(current)) return statements def main(): # 读取环境变量 database_url = os.environ.get('DATABASE_URL', 'postgres://accusys@localhost:5432/momentry') print(f"Connecting to database...") conn = psycopg2.connect(database_url) conn.autocommit = False cur = conn.cursor() # 读取迁移文件 migration_file = Path(__file__).parent.parent / 'migrations' / '20261011_vlm_queue.sql' print(f"Reading migration file: {migration_file}") with open(migration_file, 'r') as f: sql = f.read() # 智能分割 SQL 语句 print("Splitting SQL statements...") statements = split_sql_statements(sql) print(f" Found {len(statements)} statements\n") # 执行 SQL 语句 print("Running migration...") success_count = 0 skip_count = 0 error_count = 0 for i, statement in enumerate(statements): statement = statement.strip() if not statement: continue # 简化显示 first_line = statement.split('\n')[0].strip() if len(first_line) > 60: first_line = first_line[:60] + '...' try: cur.execute(statement) conn.commit() success_count += 1 print(f" ✓ Statement {i+1}: {first_line}") except psycopg2.Error as e: error_msg = str(e) conn.rollback() # 忽略"已存在"错误 if 'already exists' in error_msg or 'duplicate key' in error_msg: skip_count += 1 print(f" ⚠ Statement {i+1} skipped: {first_line}") else: error_count += 1 print(f" ✗ Statement {i+1} failed: {error_msg[:100]}") # 验证表创建 print("\nVerifying tables...") cur.execute(""" SELECT table_name FROM information_schema.tables WHERE table_name IN ('vlm_requests', 'vlm_dlq', 'vlm_consumer_offsets') ORDER BY table_name """) tables = [row[0] for row in cur.fetchall()] print(f" Tables created: {', '.join(tables) if tables else 'None'}") cur.close() conn.close() print(f"\n✅ Migration completed!") print(f" Success: {success_count}, Skipped: {skip_count}, Errors: {error_count}") if __name__ == '__main__': main()