| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183 |
- """把 DuckDB 基础属性库迁移到 SQLite。
- 用法(在仓库根目录):
- python -m points.migrate_to_sqlite --src db/wind104.duckdb --dst db/wind104.sqlite
- 迁移内容:
- - farm、turbine、signal、port 四张表
- - 所有索引
- - 验证行数一致
- SQLite 优势(对比 DuckDB):
- - Linux 服务器上更稳定(不会超时)
- - 内存占用更低
- - 并发控制更成熟(WAL 模式)
- - 文件锁在 NFS 上更可靠
- """
- import argparse
- import os
- import sqlite3
- import sys
- import time
- import duckdb
- ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- # SQLite 的建表语句(从 DuckDB 的 DDL 适配过来)
- # 主要差异:
- # - varchar -> TEXT
- # - bigint -> INTEGER
- # - boolean -> INTEGER (0/1)
- SQLITE_DDL = [
- """CREATE TABLE IF NOT EXISTS farm(
- farm_id TEXT PRIMARY KEY,
- farm_name TEXT,
- farm_id_yk TEXT,
- note TEXT)""",
- """CREATE TABLE IF NOT EXISTS turbine(
- farm_id TEXT,
- wind_id TEXT,
- port INTEGER,
- machine_type TEXT,
- engine_code TEXT,
- mill_type_code TEXT,
- manufacturer_name TEXT,
- note TEXT,
- PRIMARY KEY(farm_id, wind_id))""",
- """CREATE TABLE IF NOT EXISTS signal(
- port INTEGER,
- common_addr INTEGER,
- obj_addr INTEGER,
- farm_id TEXT,
- wind_id TEXT,
- signal_id TEXT,
- signal_name_zh TEXT,
- signal_name TEXT,
- algo_signal TEXT,
- algo_pick TEXT,
- note TEXT,
- PRIMARY KEY(port, common_addr, obj_addr))""",
- """CREATE TABLE IF NOT EXISTS port(
- port INTEGER PRIMARY KEY,
- name TEXT,
- enabled INTEGER,
- note TEXT)""",
- 'CREATE INDEX IF NOT EXISTS signal_farm ON signal(farm_id, wind_id)',
- 'CREATE INDEX IF NOT EXISTS signal_algo ON signal(algo_signal)',
- ]
- def migrate(src_path, dst_path, wipe=False):
- """从 DuckDB 迁移到 SQLite。"""
- if not os.path.exists(src_path):
- print(f'源数据库不存在: {src_path}')
- return False
- if os.path.exists(dst_path) and not wipe:
- print(f'目标数据库已存在: {dst_path}')
- print('加 --wipe 覆盖重建')
- return False
- print(f'源: {src_path}')
- print(f'目标: {dst_path}')
- print()
- # 打开 DuckDB(只读)
- print('连接 DuckDB...')
- duck_conn = duckdb.connect(src_path, read_only=True)
- # 读取各表数据
- print('读取 DuckDB 数据...')
- tables = {}
- for table in ['farm', 'turbine', 'signal', 'port']:
- rows = duck_conn.execute(f'SELECT * FROM {table}').fetchall()
- cols = [desc[0] for desc in duck_conn.execute(f'SELECT * FROM {table} LIMIT 0').description]
- tables[table] = {'cols': cols, 'rows': rows}
- print(f' {table}: {len(rows)} 行')
- duck_conn.close()
- # 创建 SQLite
- print('\n创建 SQLite 数据库...')
- if wipe and os.path.exists(dst_path):
- os.remove(dst_path)
- sqlite_conn = sqlite3.connect(dst_path)
- sqlite_cursor = sqlite_conn.cursor()
- # 建表
- print('建表...')
- for ddl in SQLITE_DDL:
- sqlite_cursor.execute(ddl)
- sqlite_conn.commit()
- # 插入数据
- print('迁移数据...')
- t0 = time.time()
- for table, data in tables.items():
- cols = data['cols']
- rows = data['rows']
- if not rows:
- continue
- placeholders = ', '.join(['?'] * len(cols))
- col_names = ', '.join(cols)
- sql = f'INSERT INTO {table} ({col_names}) VALUES ({placeholders})'
- # 批量插入(每批 10000 行)
- batch_size = 10000
- for i in range(0, len(rows), batch_size):
- batch = rows[i:i + batch_size]
- sqlite_cursor.executemany(sql, batch)
- if i % 50000 == 0 and i > 0:
- print(f' {table}: 已插入 {i}/{len(rows)} 行')
- sqlite_conn.commit()
- print(f' {table}: 完成 {len(rows)} 行')
- # 验证
- print('\n验证数据...')
- all_match = True
- for table, data in tables.items():
- expected = len(data['rows'])
- sqlite_cursor.execute(f'SELECT COUNT(*) FROM {table}')
- actual = sqlite_cursor.fetchone()[0]
- match = 'OK' if expected == actual else 'FAIL'
- print(f' {table}: {match} {actual}/{expected}')
- if expected != actual:
- all_match = False
- sqlite_conn.close()
- elapsed = time.time() - t0
- print(f'\n迁移完成,耗时 {elapsed:.1f} 秒')
- if all_match:
- print('[OK] 所有表行数一致,迁移成功')
- print(f'\n下一步:')
- print(f' 1. 备份旧库: mv {src_path} {src_path}.bak')
- print(f' 2. 改配置文件指向新库(或改代码默认路径)')
- print(f' 3. 测试采集进程和网页')
- return True
- else:
- print('[FAIL] 行数不一致,迁移失败')
- return False
- def main():
- ap = argparse.ArgumentParser(description='DuckDB -> SQLite 迁移工具')
- ap.add_argument('--src', default=os.path.join(ROOT, 'db', 'wind104.duckdb'),
- help='源 DuckDB 文件路径')
- ap.add_argument('--dst', default=os.path.join(ROOT, 'db', 'wind104.sqlite'),
- help='目标 SQLite 文件路径')
- ap.add_argument('--wipe', action='store_true', help='覆盖已存在的目标文件')
- a = ap.parse_args()
- success = migrate(a.src, a.dst, a.wipe)
- return 0 if success else 1
- if __name__ == '__main__':
- sys.exit(main())
|