sync_data.py
5.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import pymysql
import sqlite3
import os
import schedule
import time
import datetime
# 数据库配置
MYSQL_CONFIG = {
'host': '192.168.3.222',
'port': 3308,
'user': 'os_user',
'password': 'os#123',
'database': 'scrm_account',
'charset': 'utf8mb4'
}
# 获取当前脚本所在目录,确保数据库文件在同级目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
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. 每 12 小时运行一次
schedule.every(12).hours.do(sync_task)
print("定时任务已启动,每 12 小时同步一次。按 Ctrl+C 停止。")
while True:
schedule.run_pending()
time.sleep(60) # 每分钟检查一次任务状态
if __name__ == "__main__":
run_scheduler()