Repository navigation
Expand file tree
/
Copy pathimport_tool.py
More file actions
1879 lines (1591 loc) · 68.1 KB
/
Copy pathimport_tool.py
File metadata and controls
1879 lines (1591 loc) · 68.1 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
172
173
174
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
MySQL 数据导入工具 - 企业级数据导入解决方案
提供全面的企业级数据库数据导入功能,支持CSV、JSON、Excel、SQL等多种数据格式的高性能批量导入。
集成了智能数据验证、字段映射、事务管理、错误处理、重复检查和性能优化等完整的导入生态系统。
@fileoverview MySQL数据导入工具 - 企业级数据导入的完整解决方案
@author liyq
@version 1.0.0
@since 1.0.0
@updated 2025-09-25
@license MIT
"""
import asyncio
import csv
import io
import json
import re
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
import aiofiles
import openpyxl
from mysql_manager import MySQLManager
from type_utils import (
ImportOptions,
ImportResult,
ValidationResult,
FieldMapping,
ImportProgress,
DuplicateCacheItem,
CandidateKey,
MySQLMCPError,
ErrorCategory,
ErrorSeverity
)
from common_utils import TimeUtils
from logger import logger
from cache import CacheManager
from error_handler import safe_error as safe_error_handler
class MySQLImportTool:
"""
MySQL 数据导入工具类
企业级导入工具,集成了智能验证、字段映射、事务管理、
错误恢复等高级特性。支持CSV、JSON、Excel、SQL等多种数据格式的导入。
主要组件:
- 数据验证器:智能数据格式和类型验证
- 字段映射器:灵活的字段映射和转换
- 导入引擎:不同格式数据的专用导入器
- 事务管理器:确保数据一致性的事务控制
- 错误处理器:详细错误诊断和分类
"""
# 重复检查缓存
duplicate_cache: Dict[str, DuplicateCacheItem] = {}
# 默认缓存大小
max_cache_size: int = 10000
# 当前表格的候选键列表
current_candidate_keys: List[CandidateKey] = []
def __init__(self, mysql_manager: MySQLManager):
"""初始化导入工具"""
self.mysql_manager = mysql_manager
self.session_id = str(uuid.uuid4())
# 初始化缓存管理器
self.cache_manager = mysql_manager.cache_manager
# 注册内存跟踪
self._register_memory_tracking()
def _register_memory_tracking(self) -> None:
"""注册内存泄漏跟踪"""
# 这里可以添加内存跟踪逻辑
pass
async def import_from_csv(self, options: ImportOptions) -> ImportResult:
"""
从CSV文件导入数据
支持标准CSV格式和自定义分隔符,支持表头识别和字段映射。
提供数据验证、批量插入和错误处理等完整功能。
Args:
options: 导入选项配置
Returns:
包含导入结果的JSON格式数据
Raises:
MySQLMCPError: 当导入失败时抛出
"""
start_time = TimeUtils.now_in_milliseconds()
try:
# 发送开始进度事件
if options.with_progress:
initial_progress = self._create_progress(
0,
'fileReading',
'开始读取CSV文件...',
0,
0,
start_time
)
await self._emit_progress(initial_progress, options.file_path, 'csv')
# 验证输入参数
self._validate_import_options(options, 'csv')
# 读取CSV文件内容
file_content = await self._read_file_content(options.file_path, options.encoding or 'utf8')
# 发送文件读取完成进度
if options.with_progress:
progress = self._calculate_overall_progress(
{'fileReading': 30, 'dataParsing': 40, 'validation': 20, 'insertion': 10},
'fileReading',
100,
0,
0,
start_time,
f'CSV文件读取完成,大小: {(len(file_content.encode()) / 1024):.1f} KB'
)
await self._emit_progress(progress, options.file_path, 'csv')
# 发送开始解析进度
if options.with_progress:
progress = self._calculate_overall_progress(
{'fileReading': 30, 'dataParsing': 40, 'validation': 20, 'insertion': 10},
'dataParsing',
0,
0,
0,
start_time,
'开始解析CSV数据...'
)
await self._emit_progress(progress, options.file_path, 'csv')
# 解析CSV数据
csv_data = await self._parse_csv(file_content, {
'delimiter': options.delimiter or ',',
'quote': options.quote or '"',
'hasHeaders': options.has_headers is not False,
'encoding': options.encoding or 'utf8'
})
# 发送解析完成进度
if options.with_progress:
progress = self._calculate_overall_progress(
{'fileReading': 30, 'dataParsing': 40, 'validation': 20, 'insertion': 10},
'dataParsing',
100,
len(csv_data),
len(csv_data),
start_time,
f'CSV解析完成,共解析 {len(csv_data)} 行数据'
)
await self._emit_progress(progress, options.file_path, 'csv')
# 执行导入
result = await self._execute_import(options.table_name, csv_data, options)
return ImportResult(
success=True,
imported_rows=result['imported_rows'],
skipped_rows=result['skipped_rows'],
failed_rows=result['failed_rows'],
updated_rows=result['updated_rows'],
total_rows=len(csv_data),
duration=int(TimeUtils.get_duration_in_ms(start_time)),
batches_processed=result['batches_processed'],
file_path=options.file_path,
format='csv',
table_name=options.table_name
)
except Exception as error:
safe_error = self._safe_error(error, 'importFromCSV')
return ImportResult(
success=False,
imported_rows=0,
skipped_rows=0,
failed_rows=0,
updated_rows=0,
total_rows=0,
duration=int(TimeUtils.get_duration_in_ms(start_time)),
batches_processed=0,
file_path=options.file_path,
format='csv',
table_name=options.table_name,
error=safe_error.message
)
async def import_from_json(self, options: ImportOptions) -> ImportResult:
"""
从JSON文件导入数据
支持JSON数组和对象格式,支持嵌套数据结构的扁平化处理。
提供灵活的字段映射和数据转换功能。
Args:
options: 导入选项配置
Returns:
包含导入结果的JSON格式数据
Raises:
MySQLMCPError: 当导入失败时抛出
"""
start_time = TimeUtils.now_in_milliseconds()
try:
# 发送开始进度事件
if options.with_progress:
initial_progress = self._create_progress(
0,
'fileReading',
'开始读取JSON文件...',
0,
0,
start_time
)
await self._emit_progress(initial_progress, options.file_path, 'json')
# 验证输入参数
self._validate_import_options(options, 'json')
# 读取JSON文件内容
file_content = await self._read_file_content(options.file_path, options.encoding or 'utf8')
# 发送文件读取完成进度
if options.with_progress:
progress = self._calculate_overall_progress(
{'fileReading': 20, 'dataParsing': 60, 'validation': 15, 'insertion': 5},
'fileReading',
100,
0,
0,
start_time,
f'JSON文件读取完成,大小: {(len(file_content.encode()) / 1024):.1f} KB'
)
await self._emit_progress(progress, options.file_path, 'json')
# 发送开始解析进度
if options.with_progress:
progress = self._calculate_overall_progress(
{'fileReading': 20, 'dataParsing': 60, 'validation': 15, 'insertion': 5},
'dataParsing',
0,
0,
0,
start_time,
'开始解析JSON数据...'
)
await self._emit_progress(progress, options.file_path, 'json')
# 解析JSON数据
json_data = json.loads(file_content)
# 处理不同JSON格式
processed_data: List[Dict[str, Any]] = []
if isinstance(json_data, list):
processed_data = json_data
elif isinstance(json_data, dict):
# 如果是单个对象,转换为数组
processed_data = [json_data]
else:
raise MySQLMCPError(
'JSON文件必须包含对象数组或单个对象',
ErrorCategory.VALIDATION_ERROR,
ErrorSeverity.MEDIUM
)
# 扁平化嵌套数据(如果需要)
flatten_start_time = TimeUtils.now_in_milliseconds()
processed_data = [self._flatten_object(item) for item in processed_data]
flatten_time = TimeUtils.get_duration_in_ms(flatten_start_time)
# 发送解析完成进度
if options.with_progress:
progress = self._calculate_overall_progress(
{'fileReading': 20, 'dataParsing': 60, 'validation': 15, 'insertion': 5},
'dataParsing',
100,
len(processed_data),
len(processed_data),
start_time,
f'JSON解析完成,共解析 {len(processed_data)} 个对象 {f"(扁平化耗时: {flatten_time}ms)" if flatten_time > 0 else ""}'
)
await self._emit_progress(progress, options.file_path, 'json')
# 执行导入
result = await self._execute_import(options.table_name, processed_data, options)
return ImportResult(
success=True,
imported_rows=result['imported_rows'],
skipped_rows=result['skipped_rows'],
failed_rows=result['failed_rows'],
updated_rows=result['updated_rows'],
total_rows=len(processed_data),
duration=int(TimeUtils.get_duration_in_ms(start_time)),
batches_processed=result['batches_processed'],
file_path=options.file_path,
format='json',
table_name=options.table_name
)
except Exception as error:
safe_error = self._safe_error(error, 'importFromJSON')
return ImportResult(
success=False,
imported_rows=0,
skipped_rows=0,
failed_rows=0,
updated_rows=0,
total_rows=0,
duration=int(TimeUtils.get_duration_in_ms(start_time)),
batches_processed=0,
file_path=options.file_path,
format='json',
table_name=options.table_name,
error=safe_error.message
)
async def import_from_excel(self, options: ImportOptions) -> ImportResult:
"""
从Excel文件导入数据
支持多工作表Excel文件,支持样式保留和复杂数据类型处理。
提供工作表选择和字段映射等高级功能。
Args:
options: 导入选项配置
Returns:
包含导入结果的JSON格式数据
Raises:
MySQLMCPError: 当导入失败时抛出
"""
start_time = TimeUtils.now_in_milliseconds()
try:
# 发送开始进度事件
if options.with_progress:
initial_progress = self._create_progress(
0,
'fileReading',
'开始读取Excel文件...',
0,
0,
start_time
)
await self._emit_progress(initial_progress, options.file_path, 'excel')
# 验证输入参数
self._validate_import_options(options, 'excel')
# 发送开始加载进度
if options.with_progress:
progress = self._calculate_overall_progress(
{'fileReading': 40, 'dataParsing': 50, 'validation': 7, 'insertion': 3},
'fileReading',
10,
0,
0,
start_time,
'正在加载Excel工作簿...'
)
await self._emit_progress(progress, options.file_path, 'excel')
# 加载Excel文件
workbook = openpyxl.load_workbook(options.file_path, data_only=True)
# 发送加载完成进度
if options.with_progress:
progress = self._calculate_overall_progress(
{'fileReading': 40, 'dataParsing': 50, 'validation': 7, 'insertion': 3},
'fileReading',
100,
0,
0,
start_time,
'Excel文件加载完成,正在选择工作表...'
)
await self._emit_progress(progress, options.file_path, 'excel')
# 选择工作表
worksheet_name = options.sheet_name or workbook.sheetnames[0]
worksheet = workbook[worksheet_name]
if not worksheet:
raise MySQLMCPError(
f'工作表 \'{worksheet_name}\' 不存在',
ErrorCategory.VALIDATION_ERROR,
ErrorSeverity.MEDIUM
)
# 发送开始解析进度
if options.with_progress:
progress = self._calculate_overall_progress(
{'fileReading': 40, 'dataParsing': 50, 'validation': 7, 'insertion': 3},
'dataParsing',
0,
0,
0,
start_time,
'开始解析Excel数据...'
)
await self._emit_progress(progress, options.file_path, 'excel')
# 解析Excel数据
excel_data: List[Dict[str, Any]] = []
rows = list(worksheet.iter_rows(values_only=True))
if len(rows) == 0:
raise MySQLMCPError(
'Excel文件为空或不包含数据',
ErrorCategory.VALIDATION_ERROR,
ErrorSeverity.MEDIUM
)
# 处理表头
has_headers = options.has_headers is not False
headers: List[str] = []
if has_headers:
# 第一行作为表头
header_row = rows[0]
headers = [str(cell) if cell is not None else f"column_{i+1}" for i, cell in enumerate(header_row)]
else:
# 生成列名
first_data_row = rows[0]
headers = [f"column_{i+1}" for i in range(len(first_data_row))]
# 处理数据行
start_row_index = 1 if has_headers else 0
for row_idx in range(start_row_index, len(rows)):
row = rows[row_idx]
if not row:
continue
row_data: Dict[str, Any] = {}
for col_idx, cell_value in enumerate(row):
if col_idx < len(headers):
row_data[headers[col_idx]] = cell_value
excel_data.append(row_data)
# 执行导入
result = await self._execute_import(options.table_name, excel_data, options)
return ImportResult(
success=True,
imported_rows=result['imported_rows'],
skipped_rows=result['skipped_rows'],
failed_rows=result['failed_rows'],
updated_rows=result['updated_rows'],
total_rows=len(excel_data),
duration=int(TimeUtils.get_duration_in_ms(start_time)),
batches_processed=result['batches_processed'],
file_path=options.file_path,
format='excel',
table_name=options.table_name
)
except Exception as error:
safe_error = self._safe_error(error, 'importFromExcel')
return ImportResult(
success=False,
imported_rows=0,
skipped_rows=0,
failed_rows=0,
updated_rows=0,
total_rows=0,
duration=int(TimeUtils.get_duration_in_ms(start_time)),
batches_processed=0,
file_path=options.file_path,
format='excel',
table_name=options.table_name,
error=safe_error.message
)
async def import_from_sql(self, options: ImportOptions) -> ImportResult:
"""
从SQL文件导入数据
支持SQL脚本文件执行,支持事务管理和错误处理。
提供SQL语句解析和批量执行功能。
Args:
options: 导入选项配置
Returns:
包含导入结果的JSON格式数据
Raises:
MySQLMCPError: 当导入失败时抛出
"""
start_time = TimeUtils.now_in_milliseconds()
try:
# 发送开始进度事件
if options.with_progress:
initial_progress = self._create_progress(
0,
'fileReading',
'开始读取SQL文件...',
0,
0,
start_time
)
await self._emit_progress(initial_progress, options.file_path, 'sql')
# 验证输入参数
self._validate_import_options(options, 'sql')
# 读取SQL文件内容
file_content = await self._read_file_content(options.file_path, options.encoding or 'utf8')
# 发送文件读取完成进度
if options.with_progress:
progress = self._calculate_overall_progress(
{'fileReading': 20, 'dataParsing': 70, 'validation': 5, 'insertion': 5},
'fileReading',
100,
0,
0,
start_time,
f'SQL文件读取完成,大小: {(len(file_content.encode()) / 1024):.1f} KB'
)
await self._emit_progress(progress, options.file_path, 'sql')
# 发送开始解析进度
if options.with_progress:
progress = self._calculate_overall_progress(
{'fileReading': 20, 'dataParsing': 70, 'validation': 5, 'insertion': 5},
'dataParsing',
0,
0,
0,
start_time,
'开始解析SQL语句...'
)
await self._emit_progress(progress, options.file_path, 'sql')
# 解析SQL语句
parsing_start_time = TimeUtils.now_in_milliseconds()
sql_statements = self._parse_sql_statements(file_content)
parsing_time = TimeUtils.get_duration_in_ms(parsing_start_time)
# 发送解析完成进度
if options.with_progress:
progress = self._calculate_overall_progress(
{'fileReading': 20, 'dataParsing': 70, 'validation': 5, 'insertion': 5},
'dataParsing',
100,
len(sql_statements),
len(sql_statements),
start_time,
f'SQL解析完成,共解析 {len(sql_statements)} 条语句 (耗时: {parsing_time}ms)'
)
await self._emit_progress(progress, options.file_path, 'sql')
# 执行SQL语句
result = await self._execute_sql_statements(sql_statements, options)
return ImportResult(
success=True,
imported_rows=result['affected_rows'],
skipped_rows=0,
failed_rows=result['failed_statements'],
updated_rows=0,
total_rows=len(sql_statements),
duration=int(TimeUtils.get_duration_in_ms(start_time)),
batches_processed=1,
file_path=options.file_path,
format='sql',
table_name=options.table_name or 'multiple'
)
except Exception as error:
safe_error = self._safe_error(error, 'importFromSQL')
return ImportResult(
success=False,
imported_rows=0,
skipped_rows=0,
failed_rows=0,
updated_rows=0,
total_rows=0,
duration=int(TimeUtils.get_duration_in_ms(start_time)),
batches_processed=0,
file_path=options.file_path,
format='sql',
table_name=options.table_name or 'multiple',
error=safe_error.message
)
async def import_data(self, options: ImportOptions) -> ImportResult:
"""
通用导入方法 - 根据文件格式自动选择导入方式
Args:
options: 导入选项配置
Returns:
导入结果
"""
file_format = options.format or self._detect_file_format(options.file_path)
if file_format == 'csv':
return await self.import_from_csv(options)
elif file_format == 'json':
return await self.import_from_json(options)
elif file_format == 'excel':
return await self.import_from_excel(options)
elif file_format == 'sql':
return await self.import_from_sql(options)
else:
raise MySQLMCPError(
f'不支持的文件格式: {file_format}',
ErrorCategory.VALIDATION_ERROR,
ErrorSeverity.MEDIUM
)
async def validate_import(self, options: ImportOptions) -> ValidationResult:
"""
验证数据并生成预览
Args:
options: 导入选项配置
Returns:
验证结果
"""
try:
# 检测文件格式
file_format = options.format or self._detect_file_format(options.file_path)
# 读取文件样本
sample_data = await self._read_sample_data(options.file_path, file_format, 10)
# 验证表结构
table_schema = await self.mysql_manager.get_table_schema_cached(options.table_name)
# 验证字段映射
field_mapping = self._create_field_mapping(
options.field_mapping or {},
sample_data,
table_schema
)
# 验证数据类型和约束
validation_errors: List[str] = []
validation_warnings: List[str] = []
for row in sample_data:
validation = self._validate_data_row(row, field_mapping, table_schema)
validation_errors.extend(validation['errors'])
validation_warnings.extend(validation['warnings'])
return ValidationResult(
is_valid=len(validation_errors) == 0,
errors=list(set(validation_errors)),
warnings=list(set(validation_warnings)),
suggestions=self._generate_validation_suggestions(validation_errors, validation_warnings),
validated_rows=len(sample_data),
invalid_rows=len(validation_errors)
)
except Exception as error:
return ValidationResult(
is_valid=False,
errors=[str(error)],
warnings=[],
suggestions=['检查文件格式和表结构是否正确'],
validated_rows=0,
invalid_rows=1
)
# 辅助方法
def _validate_import_options(self, options: ImportOptions, file_format: str) -> None:
"""验证导入选项"""
if not options.table_name:
raise MySQLMCPError(
'必须指定目标表名',
ErrorCategory.VALIDATION_ERROR,
ErrorSeverity.MEDIUM
)
if not options.file_path:
raise MySQLMCPError(
'必须指定文件路径',
ErrorCategory.VALIDATION_ERROR,
ErrorSeverity.MEDIUM
)
# 格式特定验证
if file_format == 'csv':
if options.delimiter and len(options.delimiter) != 1:
raise MySQLMCPError(
'CSV分隔符必须是单个字符',
ErrorCategory.VALIDATION_ERROR,
ErrorSeverity.MEDIUM
)
elif file_format == 'excel':
if options.sheet_name and not isinstance(options.sheet_name, str):
raise MySQLMCPError(
'Excel工作表名称必须是字符串',
ErrorCategory.VALIDATION_ERROR,
ErrorSeverity.MEDIUM
)
async def _parse_csv(
self,
content: str,
options: Dict[str, Any]
) -> List[Dict[str, Any]]:
"""解析CSV数据"""
result: List[Dict[str, Any]] = []
# 使用StringIO处理内容
csv_reader = csv.reader(
io.StringIO(content),
delimiter=options['delimiter'],
quotechar=options['quote']
)
rows = list(csv_reader)
if len(rows) == 0:
return result
# 解析表头
headers: List[str] = []
if options['hasHeaders']:
headers = [str(cell) for cell in rows[0]]
# 解析数据行
start_index = 1 if options['hasHeaders'] else 0
for row in rows[start_index:]:
if not row:
continue
row_data: Dict[str, Any] = {}
if options['hasHeaders'] and headers:
# 使用表头作为键
for i, value in enumerate(row):
if i < len(headers):
row_data[headers[i]] = value
else:
# 生成列名
for i, value in enumerate(row):
row_data[f'column_{i + 1}'] = value
result.append(row_data)
return result
def _flatten_object(
self,
obj: Any,
prefix: str = '',
result: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""扁平化对象"""
if result is None:
result = {}
if not obj or not isinstance(obj, dict):
return result
for key, value in obj.items():
new_key = f"{prefix}_{key}" if prefix else key
if isinstance(value, dict) and value:
self._flatten_object(value, new_key, result)
else:
result[new_key] = value
return result
async def _read_file_content(self, file_path: str, encoding: str = 'utf8') -> str:
"""读取文件内容"""
async with aiofiles.open(file_path, 'r', encoding=encoding) as file:
return await file.read()
def _parse_sql_statements(self, content: str) -> List[str]:
"""解析SQL语句"""
statements: List[str] = []
current_statement = ''
in_quotes = False
quote_char = ''
for i, char in enumerate(content):
next_char = content[i + 1] if i + 1 < len(content) else ''
if not in_quotes and (char in ('"', "'")):
in_quotes = True
quote_char = char
elif in_quotes and char == quote_char and content[i - 1] != '\\':
in_quotes = False
elif not in_quotes and char == ';' and next_char and not next_char.isspace():
current_statement += char
statements.append(current_statement.strip())
current_statement = ''
continue
current_statement += char
# 添加最后一个语句(如果没有分号)
if current_statement.strip():
statements.append(current_statement.strip())
return [stmt for stmt in statements if stmt]
async def _execute_sql_statements(
self,
statements: List[str],
options: ImportOptions
) -> Dict[str, Any]:
"""执行SQL语句"""
total_affected_rows = 0
failed_statements = 0
if options.use_transaction:
# 使用事务批量执行
queries = [{'sql': sql, 'params': []} for sql in statements]
results = await self.mysql_manager.execute_batch_queries(queries)
total_affected_rows = sum(
r.get('affectedRows', 0) if isinstance(r, dict) else 0
for r in results
)
else:
# 逐条执行
for statement in statements:
try:
result = await self.mysql_manager.execute_query(statement)
if isinstance(result, dict) and 'affectedRows' in result:
total_affected_rows += result['affectedRows']
except Exception:
failed_statements += 1
return {
'affected_rows': total_affected_rows,
'failed_statements': failed_statements
}
def _detect_file_format(self, file_path: str) -> str:
"""检测文件格式"""
ext = Path(file_path).suffix.lower()
if ext == '.csv':
return 'csv'
elif ext == '.json':
return 'json'
elif ext in ('.xlsx', '.xls'):
return 'excel'
elif ext == '.sql':
return 'sql'
else:
raise MySQLMCPError(
f'无法检测文件格式: {ext}',
ErrorCategory.VALIDATION_ERROR,
ErrorSeverity.MEDIUM
)
async def _read_sample_data(
self,
file_path: str,
file_format: str,
sample_size: int
) -> List[Dict[str, Any]]:
"""读取样本数据"""
if file_format == 'csv':
content = await self._read_file_content(file_path)
csv_data = await self._parse_csv(content, {
'delimiter': ',',
'quote': '"',
'hasHeaders': True,
'encoding': 'utf8'
})
return csv_data[:sample_size]
elif file_format == 'json':
content = await self._read_file_content(file_path)
json_data = json.loads(content)
if isinstance(json_data, list):
return json_data[:sample_size]
else:
return [json_data]
elif file_format == 'excel':
workbook = openpyxl.load_workbook(file_path, data_only=True)
worksheet = workbook.active
sample_rows: List[Dict[str, Any]] = []
for row in worksheet.iter_rows(max_row=sample_size, values_only=True):
row_data: Dict[str, Any] = {}
for i, cell_value in enumerate(row):
row_data[f'column_{i+1}'] = cell_value
sample_rows.append(row_data)
return sample_rows
return []
def _create_field_mapping(
self,
user_mapping: Dict[str, str],
sample_data: List[Dict[str, Any]],
table_schema: Optional[List[Dict[str, Any]]]
) -> List[FieldMapping]:
"""创建字段映射"""
mappings: List[FieldMapping] = []
table_columns = table_schema or []
# 如果提供了用户映射,使用用户映射
if user_mapping:
for source_field, target_field in user_mapping.items():
column = next((col for col in table_columns if col.get('COLUMN_NAME') == target_field), None)
if column:
mappings.append(FieldMapping(
source_field=source_field,
target_field=target_field,
type_conversion='auto',
required=column.get('IS_NULLABLE') == 'NO'
))
else:
# 自动映射:使用相同的字段名
if sample_data:
source_fields = list(sample_data[0].keys())
for source_field in source_fields:
column = next((col for col in table_columns if col.get('COLUMN_NAME') == source_field), None)
if column:
mappings.append(FieldMapping(
source_field=source_field,
target_field=source_field,
type_conversion='auto',
required=column.get('IS_NULLABLE') == 'NO'
))
return mappings
def _validate_data_row(
self,
row: Dict[str, Any],
field_mapping: List[FieldMapping],
table_schema: Optional[List[Dict[str, Any]]]
) -> Dict[str, List[str]]:
"""验证数据行"""
errors: List[str] = []
warnings: List[str] = []
table_columns = table_schema or []
for mapping in field_mapping:
source_value = row.get(mapping.source_field)
column = next((col for col in table_columns if col.get('COLUMN_NAME') == mapping.target_field), None)
if not column:
errors.append(f'目标字段不存在: {mapping.target_field}')
continue
# 检查必填字段
if mapping.required and (source_value is None or source_value == ''):
errors.append(f'必填字段为空: {mapping.target_field}')
# 类型验证
if source_value is not None:
type_error = self._validate_data_type(source_value, column.get('DATA_TYPE', ''), mapping.target_field)
if type_error:
errors.append(type_error)
# 长度验证
if isinstance(source_value, str) and 'varchar' in column.get('DATA_TYPE', '').lower():
max_length_match = re.search(r'varchar\((\d+)\)', column.get('DATA_TYPE', ''))
if max_length_match:
max_length = int(max_length_match.group(1))
if len(source_value) > max_length:
errors.append(f'字段长度超过限制: {mapping.target_field} ({len(source_value)} > {max_length})')
return {'errors': errors, 'warnings': warnings}
def _validate_data_type(self, value: Any, column_type: str, field_name: str) -> Optional[str]:
"""验证数据类型"""
value_type = type(value).__name__
if 'int' in column_type.lower() and value_type != 'int' and not str(value).isdigit():
return f'字段类型不匹配: {field_name} 期望数字,得到 {value_type}'