Commit 9891df4c by imwangxiaozhou

feat(sync): 实现增量同步并添加元数据管理

- 将全量同步改为基于 updated_time 的增量同步,提高同步效率
- 新增 sync_metadata 表用于记录上次同步时间
- 添加初始化函数确保表结构正确创建
- 改进错误处理,添加异常追踪信息
1 parent de07e250
No preview for this file type
...@@ -24,39 +24,133 @@ def preprocess_text(text): ...@@ -24,39 +24,133 @@ def preprocess_text(text):
if not text: return "" if not text: return ""
return " ".join(list(str(text).replace(" ", ""))) 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(): def sync_task():
"""执行同步任务的主函数""" """执行同步任务的主函数(增量同步)"""
print(f"[{datetime.datetime.now()}] 开始执行同步任务...") print(f"[{datetime.datetime.now()}] 开始执行同步任务...")
# 确保表已初始化
init_sqlite()
last_sync_time = get_last_sync_time()
print(f"上次同步时间: {last_sync_time}")
# 建立 SQLite 连接 # 建立 SQLite 连接
# 如果表不存在则创建,如果存在则清空重写(全量同步)
sqlite_conn = sqlite3.connect(SQLITE_DB_PATH) sqlite_conn = sqlite3.connect(SQLITE_DB_PATH)
sqlite_cursor = sqlite_conn.cursor() sqlite_cursor = sqlite_conn.cursor()
try: try:
# 1. 初始化 SQLite 表结构 # 1. 从 MySQL 读取增量数据
sqlite_cursor.execute("DROP TABLE IF EXISTS merchants;")
sqlite_cursor.execute("CREATE VIRTUAL TABLE merchants USING fts5(merchantNo UNINDEXED, name);")
# 2. 从 MySQL 读取数据
mysql_conn = pymysql.connect(**MYSQL_CONFIG) mysql_conn = pymysql.connect(**MYSQL_CONFIG)
try: try:
with mysql_conn.cursor() as mysql_cursor: with mysql_conn.cursor() as mysql_cursor:
sql = "SELECT merchantNo, merchant_name FROM platform_merchant" # 按照 updated_time 排序,方便最后更新 last_sync_time
mysql_cursor.execute(sql) 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() rows = mysql_cursor.fetchall()
print(f"从 MySQL 读取到 {len(rows)} 条记录。")
if not rows:
print(f"[{datetime.datetime.now()}] 没有新数据,跳过同步。")
return
print(f"从 MySQL 读取到 {len(rows)} 条新增/更新记录。")
# 3. 批量同步到 SQLite # 2. 增量同步到 SQLite
batch_data = [(m_no, preprocess_text(m_name)) for m_no, m_name in rows] # 对于 FTS5 表,我们先根据 merchantNo 删除旧记录(如果有),再插入新记录
sqlite_cursor.executemany("INSERT INTO merchants (merchantNo, name) VALUES (?, ?);", batch_data) # 这样可以保证数据唯一性且能够更新
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() sqlite_conn.commit()
print(f"[{datetime.datetime.now()}] 同步成功!共写入 {len(rows)} 条数据。")
# 3. 更新同步元数据
update_last_sync_time(max_updated_time)
print(f"[{datetime.datetime.now()}] 同步成功!共处理 {count} 条数据,最新同步时间更新为 {max_updated_time}。")
finally: finally:
mysql_conn.close() mysql_conn.close()
except Exception as e: except Exception as e:
print(f"[{datetime.datetime.now()}] 同步失败: {e}") print(f"[{datetime.datetime.now()}] 同步失败: {e}")
import traceback
traceback.print_exc()
finally: finally:
sqlite_conn.close() sqlite_conn.close()
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!