1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#!/usr/bin/env python3
"""
Import test data into MySQL Shoplazza tables.
Reads SQL file generated by generate_test_data.py and imports into MySQL.
"""
import sys
import os
import argparse
from pathlib import Path
# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))
from utils.db_connector import create_db_connection, test_connection
def import_sql_file(db_engine, sql_file: str):
"""
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
21
|
Import SQL file into database using MySQL client (more reliable for large files).
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
22
23
|
Args:
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
24
|
db_engine: SQLAlchemy database engine (used to get connection info)
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
25
26
|
sql_file: Path to SQL file
"""
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
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
|
import subprocess
import os
from pathlib import Path
# Get connection info from engine URL
engine_url = str(db_engine.url)
# Parse: mysql+pymysql://user:pass@host:port/database
import re
match = re.match(r'mysql\+pymysql://([^:]+):([^@]+)@([^:]+):(\d+)/(.+)', engine_url)
if not match:
raise ValueError(f"Cannot parse database URL: {engine_url}")
username, password, host, port, database = match.groups()
# Use MySQL client to execute SQL file (more reliable)
sql_file_path = Path(sql_file).absolute()
# Build mysql command
mysql_cmd = [
'mysql',
f'-h{host}',
f'-P{port}',
f'-u{username}',
f'-p{password}',
database
]
print(f"Executing SQL file using MySQL client...")
print(f" File: {sql_file_path}")
print(f" Database: {host}:{port}/{database}")
try:
with open(sql_file_path, 'r', encoding='utf-8') as f:
result = subprocess.run(
mysql_cmd,
stdin=f,
capture_output=True,
text=True,
timeout=300 # 5 minute timeout
)
if result.returncode != 0:
error_msg = result.stderr or result.stdout
print(f"ERROR: MySQL execution failed")
print(f"Error output: {error_msg[:500]}")
raise Exception(f"MySQL execution failed: {error_msg[:200]}")
print("SQL file executed successfully")
return True
except FileNotFoundError:
# Fallback to SQLAlchemy if mysql client not available
print("MySQL client not found, falling back to SQLAlchemy...")
return import_sql_file_sqlalchemy(db_engine, sql_file)
except subprocess.TimeoutExpired:
raise Exception("SQL execution timed out after 5 minutes")
except Exception as e:
print(f"Error using MySQL client: {e}")
print("Falling back to SQLAlchemy...")
return import_sql_file_sqlalchemy(db_engine, sql_file)
def import_sql_file_sqlalchemy(db_engine, sql_file: str):
"""
Fallback method: Import SQL file using SQLAlchemy (for when mysql client unavailable).
"""
|
fb68a0ef
tangwang
配置优化
|
93
94
|
from sqlalchemy import text
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
95
96
97
|
with open(sql_file, 'r', encoding='utf-8') as f:
sql_content = f.read()
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
98
99
100
101
102
103
104
105
106
107
108
109
110
|
# Remove comment lines
lines = sql_content.split('\n')
cleaned_lines = []
for line in lines:
stripped = line.lstrip()
if stripped.startswith('--'):
continue
cleaned_lines.append(line)
sql_content = '\n'.join(cleaned_lines)
# Split by semicolon - but we need to handle strings properly
# Use a state machine to track string boundaries
|
a5a3856d
tangwang
店匠体系数据的搜索:mock da...
|
111
|
statements = []
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
112
|
current = []
|
a5a3856d
tangwang
店匠体系数据的搜索:mock da...
|
113
|
in_string = False
|
a5a3856d
tangwang
店匠体系数据的搜索:mock da...
|
114
|
i = 0
|
fb68a0ef
tangwang
配置优化
|
115
|
|
a5a3856d
tangwang
店匠体系数据的搜索:mock da...
|
116
117
118
|
while i < len(sql_content):
char = sql_content[i]
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
119
120
121
122
123
124
|
if char == "'":
# Check for escaped quote (two single quotes)
if i + 1 < len(sql_content) and sql_content[i+1] == "'":
current.append("''")
i += 1 # Skip next quote
elif not in_string:
|
a5a3856d
tangwang
店匠体系数据的搜索:mock da...
|
125
|
in_string = True
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
126
127
|
current.append(char)
else:
|
a5a3856d
tangwang
店匠体系数据的搜索:mock da...
|
128
|
in_string = False
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
129
130
131
|
current.append(char)
else:
current.append(char)
|
a5a3856d
tangwang
店匠体系数据的搜索:mock da...
|
132
|
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
133
|
# Split on semicolon only if not in string
|
a5a3856d
tangwang
店匠体系数据的搜索:mock da...
|
134
|
if char == ';' and not in_string:
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
135
136
|
stmt = ''.join(current).strip()
if stmt and stmt.upper().startswith('INSERT INTO'):
|
a5a3856d
tangwang
店匠体系数据的搜索:mock da...
|
137
|
statements.append(stmt)
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
138
|
current = []
|
a5a3856d
tangwang
店匠体系数据的搜索:mock da...
|
139
140
141
|
i += 1
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
142
143
144
145
|
# Handle last statement
if current:
stmt = ''.join(current).strip()
if stmt and stmt.upper().startswith('INSERT INTO'):
|
a5a3856d
tangwang
店匠体系数据的搜索:mock da...
|
146
|
statements.append(stmt)
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
147
|
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
148
|
print(f"Parsed {len(statements)} SQL statements")
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
149
150
|
print(f"Executing {len(statements)} SQL statements...")
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
151
152
153
154
155
|
# Use raw connection to avoid SQLAlchemy parameter parsing
raw_conn = db_engine.raw_connection()
try:
cursor = raw_conn.cursor()
try:
|
d586fd1f
tangwang
tenant=2测试数据灌入的字段修复
|
156
|
for i, statement in enumerate(statements, 1):
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
157
|
try:
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
158
159
160
161
|
# Execute raw SQL directly using pymysql cursor
cursor.execute(statement)
raw_conn.commit()
if i % 1000 == 0 or i == len(statements):
|
d586fd1f
tangwang
tenant=2测试数据灌入的字段修复
|
162
|
print(f" [{i}/{len(statements)}] Executed successfully")
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
163
164
|
except Exception as e:
print(f" [{i}/{len(statements)}] ERROR: {e}")
|
a5a3856d
tangwang
店匠体系数据的搜索:mock da...
|
165
166
167
|
error_start = max(0, statement.find('VALUES') - 100)
error_end = min(len(statement), error_start + 500)
print(f" Statement context: ...{statement[error_start:error_end]}...")
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
168
|
raise
|
8cff1628
tangwang
tenant2 1w测试数据 mo...
|
169
170
171
172
173
174
|
finally:
cursor.close()
finally:
raw_conn.close()
return True
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
|
def verify_import(db_engine, tenant_id: str):
"""
Verify imported data.
Args:
db_engine: SQLAlchemy database engine
tenant_id: Tenant ID to verify
"""
from sqlalchemy import text
with db_engine.connect() as conn:
# Count SPUs
result = conn.execute(text("SELECT COUNT(*) FROM shoplazza_product_spu WHERE tenant_id = :tenant_id"), {"tenant_id": tenant_id})
spu_count = result.scalar()
# Count SKUs
result = conn.execute(text("SELECT COUNT(*) FROM shoplazza_product_sku WHERE tenant_id = :tenant_id"), {"tenant_id": tenant_id})
sku_count = result.scalar()
print(f"\nVerification:")
print(f" SPUs: {spu_count}")
print(f" SKUs: {sku_count}")
return spu_count, sku_count
def main():
parser = argparse.ArgumentParser(description='Import test data into MySQL')
# Database connection
parser.add_argument('--db-host', required=True, help='MySQL host')
parser.add_argument('--db-port', type=int, default=3306, help='MySQL port (default: 3306)')
parser.add_argument('--db-database', required=True, help='MySQL database name')
parser.add_argument('--db-username', required=True, help='MySQL username')
parser.add_argument('--db-password', required=True, help='MySQL password')
# Import options
parser.add_argument('--sql-file', required=True, help='SQL file to import')
parser.add_argument('--tenant-id', help='Tenant ID to verify (optional)')
args = parser.parse_args()
print(f"Connecting to MySQL: {args.db_host}:{args.db_port}/{args.db_database}")
# Connect to database
try:
db_engine = create_db_connection(
host=args.db_host,
port=args.db_port,
database=args.db_database,
username=args.db_username,
password=args.db_password
)
except Exception as e:
print(f"ERROR: Failed to connect to MySQL: {e}")
return 1
# Test connection
if not test_connection(db_engine):
print("ERROR: Database connection test failed")
return 1
print("Database connection successful")
|
fb68a0ef
tangwang
配置优化
|
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
|
# Clean existing data if tenant_id provided
if args.tenant_id:
print(f"\nCleaning existing data for tenant_id: {args.tenant_id}")
from sqlalchemy import text
try:
with db_engine.connect() as conn:
# Delete SKUs first (foreign key constraint)
conn.execute(text(f"DELETE FROM shoplazza_product_sku WHERE tenant_id = '{args.tenant_id}'"))
# Delete SPUs
conn.execute(text(f"DELETE FROM shoplazza_product_spu WHERE tenant_id = '{args.tenant_id}'"))
conn.commit()
print("✓ Existing data cleaned")
except Exception as e:
print(f"⚠ Warning: Failed to clean existing data: {e}")
# Continue anyway
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
|
# Import SQL file
print(f"\nImporting SQL file: {args.sql_file}")
try:
import_sql_file(db_engine, args.sql_file)
print("Import completed successfully")
except Exception as e:
print(f"ERROR: Failed to import SQL file: {e}")
import traceback
traceback.print_exc()
return 1
# Verify import if tenant_id provided
if args.tenant_id:
verify_import(db_engine, args.tenant_id)
return 0
if __name__ == '__main__':
sys.exit(main())
|