migrate_to_sqlite.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. """把 DuckDB 基础属性库迁移到 SQLite。
  2. 用法(在仓库根目录):
  3. python -m points.migrate_to_sqlite --src db/wind104.duckdb --dst db/wind104.sqlite
  4. 迁移内容:
  5. - farm、turbine、signal、port 四张表
  6. - 所有索引
  7. - 验证行数一致
  8. SQLite 优势(对比 DuckDB):
  9. - Linux 服务器上更稳定(不会超时)
  10. - 内存占用更低
  11. - 并发控制更成熟(WAL 模式)
  12. - 文件锁在 NFS 上更可靠
  13. """
  14. import argparse
  15. import os
  16. import sqlite3
  17. import sys
  18. import time
  19. import duckdb
  20. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  21. # SQLite 的建表语句(从 DuckDB 的 DDL 适配过来)
  22. # 主要差异:
  23. # - varchar -> TEXT
  24. # - bigint -> INTEGER
  25. # - boolean -> INTEGER (0/1)
  26. SQLITE_DDL = [
  27. """CREATE TABLE IF NOT EXISTS farm(
  28. farm_id TEXT PRIMARY KEY,
  29. farm_name TEXT,
  30. farm_id_yk TEXT,
  31. note TEXT)""",
  32. """CREATE TABLE IF NOT EXISTS turbine(
  33. farm_id TEXT,
  34. wind_id TEXT,
  35. port INTEGER,
  36. machine_type TEXT,
  37. engine_code TEXT,
  38. mill_type_code TEXT,
  39. manufacturer_name TEXT,
  40. note TEXT,
  41. PRIMARY KEY(farm_id, wind_id))""",
  42. """CREATE TABLE IF NOT EXISTS signal(
  43. port INTEGER,
  44. common_addr INTEGER,
  45. obj_addr INTEGER,
  46. farm_id TEXT,
  47. wind_id TEXT,
  48. signal_id TEXT,
  49. signal_name_zh TEXT,
  50. signal_name TEXT,
  51. algo_signal TEXT,
  52. algo_pick TEXT,
  53. note TEXT,
  54. PRIMARY KEY(port, common_addr, obj_addr))""",
  55. """CREATE TABLE IF NOT EXISTS port(
  56. port INTEGER PRIMARY KEY,
  57. name TEXT,
  58. enabled INTEGER,
  59. note TEXT)""",
  60. 'CREATE INDEX IF NOT EXISTS signal_farm ON signal(farm_id, wind_id)',
  61. 'CREATE INDEX IF NOT EXISTS signal_algo ON signal(algo_signal)',
  62. ]
  63. def migrate(src_path, dst_path, wipe=False):
  64. """从 DuckDB 迁移到 SQLite。"""
  65. if not os.path.exists(src_path):
  66. print(f'源数据库不存在: {src_path}')
  67. return False
  68. if os.path.exists(dst_path) and not wipe:
  69. print(f'目标数据库已存在: {dst_path}')
  70. print('加 --wipe 覆盖重建')
  71. return False
  72. print(f'源: {src_path}')
  73. print(f'目标: {dst_path}')
  74. print()
  75. # 打开 DuckDB(只读)
  76. print('连接 DuckDB...')
  77. duck_conn = duckdb.connect(src_path, read_only=True)
  78. # 读取各表数据
  79. print('读取 DuckDB 数据...')
  80. tables = {}
  81. for table in ['farm', 'turbine', 'signal', 'port']:
  82. rows = duck_conn.execute(f'SELECT * FROM {table}').fetchall()
  83. cols = [desc[0] for desc in duck_conn.execute(f'SELECT * FROM {table} LIMIT 0').description]
  84. tables[table] = {'cols': cols, 'rows': rows}
  85. print(f' {table}: {len(rows)} 行')
  86. duck_conn.close()
  87. # 创建 SQLite
  88. print('\n创建 SQLite 数据库...')
  89. if wipe and os.path.exists(dst_path):
  90. os.remove(dst_path)
  91. sqlite_conn = sqlite3.connect(dst_path)
  92. sqlite_cursor = sqlite_conn.cursor()
  93. # 建表
  94. print('建表...')
  95. for ddl in SQLITE_DDL:
  96. sqlite_cursor.execute(ddl)
  97. sqlite_conn.commit()
  98. # 插入数据
  99. print('迁移数据...')
  100. t0 = time.time()
  101. for table, data in tables.items():
  102. cols = data['cols']
  103. rows = data['rows']
  104. if not rows:
  105. continue
  106. placeholders = ', '.join(['?'] * len(cols))
  107. col_names = ', '.join(cols)
  108. sql = f'INSERT INTO {table} ({col_names}) VALUES ({placeholders})'
  109. # 批量插入(每批 10000 行)
  110. batch_size = 10000
  111. for i in range(0, len(rows), batch_size):
  112. batch = rows[i:i + batch_size]
  113. sqlite_cursor.executemany(sql, batch)
  114. if i % 50000 == 0 and i > 0:
  115. print(f' {table}: 已插入 {i}/{len(rows)} 行')
  116. sqlite_conn.commit()
  117. print(f' {table}: 完成 {len(rows)} 行')
  118. # 验证
  119. print('\n验证数据...')
  120. all_match = True
  121. for table, data in tables.items():
  122. expected = len(data['rows'])
  123. sqlite_cursor.execute(f'SELECT COUNT(*) FROM {table}')
  124. actual = sqlite_cursor.fetchone()[0]
  125. match = 'OK' if expected == actual else 'FAIL'
  126. print(f' {table}: {match} {actual}/{expected}')
  127. if expected != actual:
  128. all_match = False
  129. sqlite_conn.close()
  130. elapsed = time.time() - t0
  131. print(f'\n迁移完成,耗时 {elapsed:.1f} 秒')
  132. if all_match:
  133. print('[OK] 所有表行数一致,迁移成功')
  134. print(f'\n下一步:')
  135. print(f' 1. 备份旧库: mv {src_path} {src_path}.bak')
  136. print(f' 2. 改配置文件指向新库(或改代码默认路径)')
  137. print(f' 3. 测试采集进程和网页')
  138. return True
  139. else:
  140. print('[FAIL] 行数不一致,迁移失败')
  141. return False
  142. def main():
  143. ap = argparse.ArgumentParser(description='DuckDB -> SQLite 迁移工具')
  144. ap.add_argument('--src', default=os.path.join(ROOT, 'db', 'wind104.duckdb'),
  145. help='源 DuckDB 文件路径')
  146. ap.add_argument('--dst', default=os.path.join(ROOT, 'db', 'wind104.sqlite'),
  147. help='目标 SQLite 文件路径')
  148. ap.add_argument('--wipe', action='store_true', help='覆盖已存在的目标文件')
  149. a = ap.parse_args()
  150. success = migrate(a.src, a.dst, a.wipe)
  151. return 0 if success else 1
  152. if __name__ == '__main__':
  153. sys.exit(main())