example_usage.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. """
  2. 数据库模块使用示例
  3. 展示如何使用数据库连接、操作和迁移功能
  4. """
  5. import os
  6. from datetime import datetime
  7. from backend.modules.database import (
  8. DatabaseConnection, DatabaseOperations, DatabaseMigration,
  9. User, ImageRecord, ProcessRecord, SystemConfig
  10. )
  11. from backend.utils.logger_config import setup_logger
  12. from typing import Optional, Any
  13. import json
  14. logger = setup_logger(__name__)
  15. def example_database_usage():
  16. """数据库使用示例"""
  17. # 1. 初始化数据库
  18. print("=== 初始化数据库 ===")
  19. migration = DatabaseMigration()
  20. if migration.init_database():
  21. print("数据库初始化成功")
  22. else:
  23. print("数据库初始化失败")
  24. return
  25. # 2. 创建数据库操作实例
  26. db_ops = DatabaseOperations()
  27. # 3. 用户管理示例
  28. print("\n=== 用户管理示例 ===")
  29. # 创建用户(需 password_hash,无 email)
  30. user = db_ops.create_user(
  31. username="test_user", # 用户名
  32. password_hash="hash123", # 示例 hash
  33. is_admin=False
  34. )
  35. print(f"创建用户: {user['username']}, ID: {user['id']}")
  36. # 查询用户
  37. found_user = db_ops.get_user_by_username("test_user")
  38. print(f"查询用户: {found_user['username'] if found_user else '未找到'}")
  39. # 4. 图片记录示例
  40. print("\n=== 图片记录示例 ===")
  41. # 创建图片记录(face)
  42. image_record = db_ops.create_image_record(
  43. user_id=user['id'],
  44. image_type="face",
  45. original_filename="face.jpg",
  46. stored_path="/data/images/face_001.jpg",
  47. file_size=1024000,
  48. image_hash=None
  49. )
  50. print(f"创建图片记录: {image_record['id']}")
  51. # 查询用户图片
  52. user_images = db_ops.get_user_images(user['id'], image_type="face")
  53. print(f"用户图片数量: {user_images['total']}")
  54. # 5. 处理记录示例
  55. print("\n=== 处理记录示例 ===")
  56. # 创建服装图片记录
  57. cloth_image = db_ops.create_image_record(
  58. user_id=user['id'],
  59. image_type="cloth",
  60. original_filename="cloth.jpg",
  61. stored_path="/data/images/cloth_001.jpg",
  62. file_size=2048000,
  63. image_hash=None
  64. )
  65. # 创建结果图片记录(必须先创建 result_image)
  66. result_image = db_ops.create_image_record(
  67. user_id=user['id'],
  68. image_type="result",
  69. original_filename="result.jpg",
  70. stored_path="/data/images/result_001.jpg",
  71. file_size=1536000,
  72. image_hash=None
  73. )
  74. # 创建AI换脸处理记录(需 result_image_id)
  75. process_record = db_ops.create_process_record(
  76. user_id=user['id'],
  77. face_image_id=image_record['id'],
  78. cloth_image_id=cloth_image['id'],
  79. result_image_id=result_image['id'],
  80. generated_text="美丽的海边风景,阳光明媚,心情愉悦"
  81. )
  82. print(f"创建AI换脸处理记录: {process_record['id']}")
  83. # 6. 系统配置示例
  84. print("\n=== 系统配置示例 ===")
  85. # 设置配置
  86. db_ops.set_config(
  87. "max_image_size",
  88. 10485760, # 10MB
  89. config_type="int",
  90. config_description="最大图片文件大小(字节)"
  91. )
  92. db_ops.set_config(
  93. "allowed_image_formats",
  94. ["jpg", "png", "gif"],
  95. config_type="json",
  96. config_description="允许的图片格式"
  97. )
  98. # 获取配置
  99. max_size = db_ops.get_config("max_image_size")
  100. allowed_formats = db_ops.get_config("allowed_image_formats")
  101. print(f"最大图片大小: {max_size['config_value']} 字节")
  102. print(f"允许的格式: {allowed_formats['config_value']}")
  103. # 7. 统计信息示例
  104. print("\n=== 统计信息示例 ===")
  105. stats = db_ops.get_statistics()
  106. print(f"总用户数: {stats['total_users']}")
  107. print(f"活跃用户数: {stats['active_users']}")
  108. print(f"总图片数: {stats['face_images']}")
  109. print(f"总处理数: {stats['total_processes']}")
  110. print(f"总服装图片数: {stats['cloth_images']}")
  111. print(f"总结果图片数: {stats['result_images']}")
  112. # 8. 数据库健康检查
  113. print("\n=== 数据库健康检查 ===")
  114. health = migration.check_database_health()
  115. print(f"状态: {health['status']}")
  116. print(f"当前版本: {health['current_version']}")
  117. print(f"总迁移数: {health['total_migrations']}")
  118. print(f"待执行迁移: {health['pending_migrations']}")
  119. if health['errors']:
  120. print(f"错误: {health['errors']}")
  121. def example_migration_usage():
  122. """数据库迁移示例"""
  123. print("\n=== 数据库迁移示例 ===")
  124. migration = DatabaseMigration()
  125. # 创建迁移文件
  126. migration_file = migration.create_migration(
  127. version="1.2.0",
  128. description="添加任务类型和提示词字段",
  129. up_sql="""
  130. ALTER TABLE process_records ADD COLUMN task_type TEXT;
  131. ALTER TABLE process_records ADD COLUMN prompt TEXT;
  132. """,
  133. down_sql="""
  134. CREATE TABLE process_records_backup AS
  135. SELECT id, user_id, face_image_id, cloth_image_id, result_image_id,
  136. generated_text, status, completed_at
  137. FROM process_records;
  138. DROP TABLE process_records;
  139. ALTER TABLE process_records_backup RENAME TO process_records;
  140. """
  141. )
  142. print(f"创建迁移文件: {migration_file}")
  143. # 执行迁移
  144. if migration.migrate_up():
  145. print("迁移执行成功")
  146. else:
  147. print("迁移执行失败")
  148. # 执行迁移回滚(回滚到 1.0.0 版本)
  149. # if migration.migrate_down("1.0.0"):
  150. # print("迁移回滚成功")
  151. # else:
  152. # print("迁移回滚失败")
  153. # 执行健康检查
  154. health = migration.check_database_health()
  155. print(f"状态: {health['status']}")
  156. print(f"当前版本: {health['current_version']}")
  157. print(f"总迁移数: {health['total_migrations']}")
  158. print(f"待执行迁移: {health['pending_migrations']}")
  159. if health['errors']:
  160. print(f"错误: {health['errors']}")
  161. if __name__ == "__main__":
  162. # 运行示例
  163. # example_database_usage()
  164. example_migration_usage()