add_tingwu_comments.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. """
  4. 通义听悟任务表字段注释添加脚本
  5. 执行 SQL 迁移文件: 038_add_tingwu_task_comments.sql
  6. """
  7. import os
  8. import sys
  9. import psycopg2
  10. from pathlib import Path
  11. # 添加项目根目录到 Python 路径
  12. project_root = Path(__file__).parent.parent
  13. sys.path.insert(0, str(project_root))
  14. from dotenv import load_dotenv
  15. # 加载环境变量
  16. env_path = project_root / '.env'
  17. load_dotenv(env_path)
  18. def get_db_connection():
  19. """获取数据库连接"""
  20. return psycopg2.connect(
  21. host=os.getenv('DB_HOST', 'localhost'),
  22. port=int(os.getenv('DB_PORT', 5432)),
  23. user=os.getenv('DB_USER', 'postgres'),
  24. password=os.getenv('DB_PASSWORD'),
  25. database=os.getenv('DB_NAME', 'model_square')
  26. )
  27. def execute_migration():
  28. """执行迁移脚本"""
  29. migration_file = project_root / 'migrations' / '038_add_tingwu_task_comments.sql'
  30. if not migration_file.exists():
  31. print(f"❌ 迁移文件不存在: {migration_file}")
  32. return False
  33. print(f"📄 读取迁移文件: {migration_file}")
  34. with open(migration_file, 'r', encoding='utf-8') as f:
  35. sql_content = f.read()
  36. print("🔗 连接数据库...")
  37. conn = get_db_connection()
  38. cursor = conn.cursor()
  39. try:
  40. print("🚀 执行迁移...")
  41. cursor.execute(sql_content)
  42. conn.commit()
  43. print("✅ 迁移执行成功!")
  44. # 验证注释是否添加成功
  45. print("\n📊 验证字段注释...")
  46. cursor.execute("""
  47. SELECT
  48. col.column_name,
  49. pgd.description
  50. FROM pg_catalog.pg_statio_all_tables AS st
  51. INNER JOIN pg_catalog.pg_description pgd ON (
  52. pgd.objoid = st.relid
  53. )
  54. INNER JOIN information_schema.columns col ON (
  55. pgd.objsubid = col.ordinal_position
  56. AND col.table_schema = st.schemaname
  57. AND col.table_name = st.relname
  58. )
  59. WHERE st.schemaname = 'aigcspace'
  60. AND st.relname = 'tingwu_task'
  61. ORDER BY col.ordinal_position
  62. LIMIT 10;
  63. """)
  64. results = cursor.fetchall()
  65. if results:
  66. print("\n前10个字段的注释:")
  67. for column_name, description in results:
  68. print(f" • {column_name}: {description}")
  69. else:
  70. print("⚠️ 未查询到字段注释,可能需要检查")
  71. return True
  72. except Exception as e:
  73. conn.rollback()
  74. print(f"❌ 迁移执行失败: {str(e)}")
  75. return False
  76. finally:
  77. cursor.close()
  78. conn.close()
  79. def main():
  80. """主函数"""
  81. print("=" * 60)
  82. print("通义听悟任务表字段注释添加")
  83. print("=" * 60)
  84. print()
  85. success = execute_migration()
  86. print()
  87. print("=" * 60)
  88. if success:
  89. print("✅ 所有操作完成")
  90. print()
  91. print("📝 注释说明:")
  92. print(" - 表注释: aigcspace.tingwu_task")
  93. print(" - 字段注释: 53个字段")
  94. print(" - 索引说明: 5个索引")
  95. print()
  96. print("🔍 查看注释:")
  97. print(" psql -d model_square -c \"\\d+ aigcspace.tingwu_task\"")
  98. else:
  99. print("❌ 操作失败,请检查错误信息")
  100. print("=" * 60)
  101. if __name__ == '__main__':
  102. main()