sync_data.py 6.34 KB
import pymysql
try:
    import sqlite3
except ImportError:
    # 兼容某些 Linux 环境下 Python 缺少 _sqlite3 模块的问题
    try:
        from pysqlite3 import dbapi2 as sqlite3
    except ImportError:
        raise ImportError("系统缺少 sqlite3 且未安装 pysqlite3-binary。请运行: pip3.10 install pysqlite3-binary")
import os
import schedule
import time
import datetime
import configparser

# 获取当前脚本所在目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_PATH = os.path.join(BASE_DIR, 'config.ini')

# 读取配置文件
config = configparser.ConfigParser()
config.read(CONFIG_PATH, encoding='utf-8')

# 数据库配置
MYSQL_CONFIG = {
    'host': config.get('mysql', 'host'),
    'port': config.getint('mysql', 'port'),
    'user': config.get('mysql', 'user'),
    'password': config.get('mysql', 'password'),
    'database': config.get('mysql', 'database'),
    'charset': config.get('mysql', 'charset')
}

# 获取定时任务间隔
SYNC_INTERVAL = config.getint('sync', 'interval_hours', fallback=12)

# SQLite 数据库文件路径
SQLITE_DB_PATH = os.path.join(BASE_DIR, 'merchants_fts.db')

def preprocess_text(text):
    """在每个字符间添加空格,支持 FTS5 间隙匹配"""
    if not text: return ""
    return " ".join(list(str(text).replace(" ", "")))

def init_sqlite():
    """初始化 SQLite 表结构"""
    conn = sqlite3.connect(SQLITE_DB_PATH)
    cursor = conn.cursor()
    try:
        # 1. 初始化 FTS 表
        # 使用 UNINDEXED 标记 merchantNo,以便可以通过它进行删除操作
        cursor.execute("""
            CREATE VIRTUAL TABLE IF NOT EXISTS merchants USING fts5(
                merchantNo UNINDEXED, 
                name
            );
        """)
        
        # 2. 初始化元数据表用于存储上次同步时间
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS sync_metadata (
                id INTEGER PRIMARY KEY,
                last_sync_time DATETIME,
                table_name TEXT UNIQUE
            );
        """)
        
        # 初始化一条记录,如果不存在
        cursor.execute("""
            INSERT OR IGNORE INTO sync_metadata (id, last_sync_time, table_name) 
            VALUES (1, '1970-01-01 00:00:00', 'platform_merchant');
        """)
        
        conn.commit()
    finally:
        conn.close()

def get_last_sync_time():
    """获取上次同步的时间"""
    conn = sqlite3.connect(SQLITE_DB_PATH)
    cursor = conn.cursor()
    try:
        cursor.execute("SELECT last_sync_time FROM sync_metadata WHERE table_name = 'platform_merchant'")
        row = cursor.fetchone()
        return row[0] if row else '1970-01-01 00:00:00'
    finally:
        conn.close()

def update_last_sync_time(new_time):
    """更新上次同步的时间"""
    conn = sqlite3.connect(SQLITE_DB_PATH)
    cursor = conn.cursor()
    try:
        cursor.execute("""
            UPDATE sync_metadata 
            SET last_sync_time = ? 
            WHERE table_name = 'platform_merchant'
        """, (new_time,))
        conn.commit()
    finally:
        conn.close()

def sync_task():
    """执行同步任务的主函数(增量同步)"""
    print(f"[{datetime.datetime.now()}] 开始执行同步任务...")
    
    # 确保表已初始化
    init_sqlite()
    
    last_sync_time = get_last_sync_time()
    print(f"上次同步时间: {last_sync_time}")

    # 建立 SQLite 连接
    sqlite_conn = sqlite3.connect(SQLITE_DB_PATH)
    sqlite_cursor = sqlite_conn.cursor()
    
    try:
        # 1. 从 MySQL 读取增量数据
        mysql_conn = pymysql.connect(**MYSQL_CONFIG)
        try:
            with mysql_conn.cursor() as mysql_cursor:
                # 按照 updated_time 排序,方便最后更新 last_sync_time
                sql = """
                    SELECT merchantNo, merchant_name, updated_time 
                    FROM platform_merchant 
                    WHERE updated_time > %s
                    ORDER BY updated_time ASC
                """
                mysql_cursor.execute(sql, (last_sync_time,))
                rows = mysql_cursor.fetchall()
                
                if not rows:
                    print(f"[{datetime.datetime.now()}] 没有新数据,跳过同步。")
                    return

                print(f"从 MySQL 读取到 {len(rows)} 条新增/更新记录。")

                # 2. 增量同步到 SQLite
                # 对于 FTS5 表,我们先根据 merchantNo 删除旧记录(如果有),再插入新记录
                # 这样可以保证数据唯一性且能够更新
                
                count = 0
                max_updated_time = last_sync_time
                
                for m_no, m_name, updated_time in rows:
                    # 删除旧记录
                    sqlite_cursor.execute("DELETE FROM merchants WHERE merchantNo = ?;", (m_no,))
                    
                    # 插入新记录
                    sqlite_cursor.execute("INSERT INTO merchants (merchantNo, name) VALUES (?, ?);", 
                                       (m_no, preprocess_text(m_name)))
                    
                    # 记录最大的更新时间
                    if updated_time and str(updated_time) > str(max_updated_time):
                        max_updated_time = str(updated_time)
                    
                    count += 1
                
                sqlite_conn.commit()
                
                # 3. 更新同步元数据
                update_last_sync_time(max_updated_time)
                
                print(f"[{datetime.datetime.now()}] 同步成功!共处理 {count} 条数据,最新同步时间更新为 {max_updated_time}。")
        finally:
            mysql_conn.close()

    except Exception as e:
        print(f"[{datetime.datetime.now()}] 同步失败: {e}")
        import traceback
        traceback.print_exc()
    finally:
        sqlite_conn.close()

def run_scheduler():
    """设置并运行定时器"""
    # 1. 启动时立即运行一次
    sync_task()
    
    # 2. 每隔指定时间运行一次
    schedule.every(SYNC_INTERVAL).hours.do(sync_task)
    
    print(f"定时任务已启动,每 {SYNC_INTERVAL} 小时同步一次。按 Ctrl+C 停止。")
    while True:
        schedule.run_pending()
        time.sleep(60) # 每分钟检查一次任务状态

if __name__ == "__main__":
    run_scheduler()