mdbq 3.11.8__py3-none-any.whl → 3.11.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mdbq/__version__.py CHANGED
@@ -1 +1 @@
1
- VERSION = '3.11.8'
1
+ VERSION = '3.11.9'
mdbq/log/mylogger.py CHANGED
@@ -247,7 +247,7 @@ class MyLogger:
247
247
  if isinstance(log_data.get('message'), str):
248
248
  log_data['message'] = log_data['message'].replace(field, '***')
249
249
 
250
- return json.dumps(log_data, ensure_ascii=False)
250
+ return json.dumps(log_data, ensure_ascii=False, default=str)
251
251
 
252
252
  formatter = StructuredFormatter()
253
253
 
@@ -114,7 +114,7 @@ class MySQLDeduplicator:
114
114
  )
115
115
 
116
116
  # 配置参数
117
- self.max_workers = max(1, min(max_workers, 20)) # 限制最大线程数
117
+ self.max_workers = min(max(1, max_workers), pool_size) # 限制最大线程数,不能超过连接池
118
118
  self.batch_size = batch_size
119
119
  self.skip_system_dbs = skip_system_dbs
120
120
  self.max_retries = max_retries
@@ -269,7 +269,8 @@ class MySQLDeduplicator:
269
269
  with conn.cursor() as cursor:
270
270
  cursor.execute(f"USE `{database}`")
271
271
  cursor.execute(sql)
272
- return [row[f'Tables_in_{database}'] for row in cursor.fetchall()]
272
+ # 严格过滤所有以'temp_'为前缀的表名(如temp_xxx、temp_xxx_dedup_...、temp_xxx_reorderid_...等)
273
+ return [row[f'Tables_in_{database}'] for row in cursor.fetchall() if not re.match(r'^temp_.*', row[f'Tables_in_{database}'])]
273
274
 
274
275
  @_retry_on_failure
275
276
  def _get_table_columns(self, database: str, table: str) -> List[str]:
@@ -328,46 +329,73 @@ class MySQLDeduplicator:
328
329
  if key in self._processing_tables:
329
330
  self._processing_tables.remove(key)
330
331
 
332
+ @_retry_on_failure
333
+ def _ensure_index(self, database: str, table: str, date_column: str) -> None:
334
+ """
335
+ 检查并为date_column自动创建索引(如果未存在)。
336
+ Args:
337
+ database (str): 数据库名。
338
+ table (str): 表名。
339
+ date_column (str): 需要检查的日期列名。
340
+ """
341
+ with self._get_connection() as conn:
342
+ with conn.cursor() as cursor:
343
+ # 检查索引是否已存在
344
+ cursor.execute(
345
+ """
346
+ SELECT COUNT(1) as idx_count FROM INFORMATION_SCHEMA.STATISTICS
347
+ WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = %s
348
+ """,
349
+ (database, table, date_column)
350
+ )
351
+ idx_count = cursor.fetchone()['idx_count']
352
+ if idx_count == 0:
353
+ # 自动创建索引
354
+ index_name = f"idx_{date_column}"
355
+ safe_index_name = self._make_safe_table_name(index_name, prefix='', suffix='', max_length=64)
356
+ try:
357
+ cursor.execute(f"CREATE INDEX `{safe_index_name}` ON `{database}`.`{table}` (`{date_column}`)")
358
+ conn.commit()
359
+ logger.info('已自动为date_column创建索引', {"库": database, "表": table, "date_column": date_column, "索引名": safe_index_name})
360
+ except Exception as e:
361
+ logger.error('自动创建date_column索引失败', {"库": database, "表": table, "date_column": date_column, "异常": str(e)})
362
+ else:
363
+ logger.debug('date_column已存在索引', {"库": database, "表": table, "date_column": date_column})
364
+
331
365
  def _deduplicate_table(
332
366
  self,
333
367
  database: str,
334
368
  table: str,
335
369
  columns: Optional[List[str]] = None,
336
- dry_run: bool = False
370
+ dry_run: bool = False,
371
+ use_python_dedup: bool = False
337
372
  ) -> Tuple[int, int]:
338
373
  """
339
374
  执行单表去重。
340
-
341
- Args:
342
- database (str): 数据库名。
343
- table (str): 表名。
344
- columns (Optional[List[str]]): 用于去重的列名列表(为None时使用所有列)。
345
- dry_run (bool): 是否为模拟运行(只统计不实际删除)。
346
- Returns:
347
- Tuple[int, int]: (重复组数, 实际删除行数)。
375
+ 支持按天分批处理(如果表包含date_column),否则全表去重。
376
+ 如果date_column在exclude_columns中,直接跳过该表。
377
+ 优化:分批删除时用主键、避免重复建/删临时表、并发处理每天。
348
378
  """
349
379
  if not self._acquire_table_lock(database, table):
350
380
  return (0, 0)
351
381
  temp_table = None
352
382
  try:
353
- # 获取原始数据总量
354
- with self._get_connection() as conn:
355
- with conn.cursor() as cursor:
356
- logger.debug('执行SQL', {'sql': f'SELECT COUNT(*) as cnt FROM `{database}`.`{table}`'})
357
- cursor.execute(f"SELECT COUNT(*) as cnt FROM `{database}`.`{table}`")
358
- total_count_row = cursor.fetchone()
359
- total_count = total_count_row['cnt'] if total_count_row and 'cnt' in total_count_row else 0
360
- logger.info('执行', {"库": database, "表": table, "开始处理数据量": total_count, 'func': sys._getframe().f_code.co_name})
361
383
  # 获取实际列名
362
384
  all_columns = self._get_table_columns(database, table)
363
- logger.debug('获取表列', {'库': database, '表': table, 'all_columns': all_columns})
364
- # 检查是否需要按时间范围过滤
365
- use_time_filter = False
366
- time_col = self.date_column
367
385
  all_columns_lower = [col.lower() for col in all_columns]
368
- # 排除exclude_columns
369
386
  exclude_columns_lower = [col.lower() for col in getattr(self, 'exclude_columns', [])]
370
- # 统一列名小写做判断
387
+ time_col = self.date_column
388
+ time_col_lower = time_col.lower() if time_col else None
389
+ # 1. 跳过date_column在exclude_columns的情况
390
+ if time_col_lower and time_col_lower in exclude_columns_lower:
391
+ logger.warning('date_column在exclude_columns中,跳过该表', {"库": database, "表": table, "date_column": time_col, "exclude_columns": self.exclude_columns})
392
+ return (0, 0)
393
+ # 2. 判断表是否包含date_column
394
+ has_time_col = time_col_lower in all_columns_lower if time_col_lower else False
395
+ # 如果包含date_column,自动检查并创建索引
396
+ if has_time_col:
397
+ self._ensure_index(database, table, time_col)
398
+ # 3. 获取去重列
371
399
  use_columns = columns or all_columns
372
400
  use_columns = [col for col in use_columns if col.lower() in all_columns_lower and col.lower() not in exclude_columns_lower]
373
401
  invalid_columns = set([col for col in (columns or []) if col.lower() not in all_columns_lower])
@@ -376,81 +404,126 @@ class MySQLDeduplicator:
376
404
  if not use_columns:
377
405
  logger.error('没有有效的去重列', {"库": database, "表": table})
378
406
  return (0, 0)
379
- # 统一用反引号包裹
380
- column_list = ', '.join([f'`{col}`' for col in use_columns])
381
- temp_table = self._make_safe_table_name(table, prefix=f"temp_", suffix=f"_dedup_{os.getpid()}_{threading.get_ident()}")
382
407
  pk = self.primary_key
383
- # 主键判断也用小写
384
- if pk.lower() not in all_columns_lower and pk != 'id':
385
- logger.error('', {"不存在主键列": database, "表": table, "主键列不存在": pk})
386
- return (0, 0)
387
- # 找到实际主键名
388
408
  pk_real = next((c for c in all_columns if c.lower() == pk.lower()), pk)
389
- # 构造where条件
390
- where_time = ''
391
- if use_time_filter:
392
- where_time = f"WHERE `{time_col}` >= '{self._dedup_start_date}' AND `{time_col}` <= '{self._dedup_end_date}'"
409
+ # 判断是否需要加日期区间条件
410
+ where_sql = ''
411
+ if has_time_col and self._dedup_start_date and self._dedup_end_date:
412
+ where_sql = f"t.`{time_col}` >= '{self._dedup_start_date}' AND t.`{time_col}` <= '{self._dedup_end_date}'"
413
+ # 获取原始数据总量(只统计区间内数据)
414
+ with self._get_connection() as conn:
415
+ with conn.cursor() as cursor:
416
+ count_where = f"WHERE `{time_col}` >= '{self._dedup_start_date}' AND `{time_col}` <= '{self._dedup_end_date}'" if has_time_col and self._dedup_start_date and self._dedup_end_date else ''
417
+ count_sql = f"SELECT COUNT(*) as cnt FROM `{database}`.`{table}` {count_where}"
418
+ logger.debug('执行SQL', {'sql': count_sql})
419
+ cursor.execute(count_sql)
420
+ total_count_row = cursor.fetchone()
421
+ total_count = total_count_row['cnt'] if total_count_row and 'cnt' in total_count_row else 0
422
+ logger.info('执行', {"库": database, "表": table, "开始处理数据量": total_count, 'func': sys._getframe().f_code.co_name})
423
+ column_list = ', '.join([f'`{col}`' for col in use_columns])
424
+
425
+ # 用Python查找重复
426
+ if use_python_dedup:
427
+ from collections import defaultdict
428
+ # 1. 拉取所有数据
429
+ select_cols = f'`{pk_real}`,' + ','.join([f'`{col}`' for col in use_columns])
430
+ select_where = f"WHERE `{time_col}` >= '{self._dedup_start_date}' AND `{time_col}` <= '{self._dedup_end_date}'" if has_time_col and self._dedup_start_date and self._dedup_end_date else ''
431
+ select_sql = f"SELECT {select_cols} FROM `{database}`.`{table}` {select_where}"
432
+ logger.debug('用Python查找重复,拉取数据SQL', {'sql': select_sql})
433
+ with self._get_connection() as conn:
434
+ with conn.cursor() as cursor:
435
+ cursor.execute(select_sql)
436
+ rows = cursor.fetchall()
437
+ # 2. 分组找重复
438
+ grouped = defaultdict(list)
439
+ for row in rows:
440
+ key = tuple(row[col] for col in use_columns)
441
+ grouped[key].append(row[pk_real])
442
+ # 3. 统计重复组和待删除id
443
+ dup_count = 0
444
+ del_ids = []
445
+ for ids in grouped.values():
446
+ if len(ids) > 1:
447
+ dup_count += 1
448
+ del_ids.extend(ids[1:]) # 只保留第一个
449
+ affected_rows = 0
450
+ if not dry_run and del_ids:
451
+ with self._get_connection() as conn:
452
+ with conn.cursor() as cursor:
453
+ for i in range(0, len(del_ids), self.batch_size):
454
+ batch = del_ids[i:i+self.batch_size]
455
+ del_ids_str = ','.join([str(i) for i in batch])
456
+ delete_sql = f"DELETE FROM `{database}`.`{table}` WHERE `{pk_real}` IN ({del_ids_str})"
457
+ logger.debug('用Python分批删除SQL', {'sql': delete_sql, 'ids': batch})
458
+ cursor.execute(delete_sql)
459
+ batch_deleted = cursor.rowcount
460
+ affected_rows += batch_deleted
461
+ conn.commit()
462
+ logger.info('用Python去重完成', {"库": database, "表": table, "数据量": total_count, "重复组数": dup_count, "实际删除": affected_rows, "去重模式": self.duplicate_keep_mode, "实际去重列": use_columns})
463
+ return (dup_count, affected_rows)
464
+ # SQL方式查找重复
465
+ temp_table = self._make_safe_table_name(table, prefix=f"temp_", suffix=f"_dedup_{os.getpid()}_{threading.get_ident()}")
466
+ drop_temp_sql = f"DROP TABLE IF EXISTS `{database}`.`{temp_table}`"
467
+ # 创建临时表时加where条件
468
+ create_temp_where = f"WHERE `{time_col}` >= '{self._dedup_start_date}' AND `{time_col}` <= '{self._dedup_end_date}'" if has_time_col and self._dedup_start_date and self._dedup_end_date else ''
393
469
  create_temp_sql = f"""
394
470
  CREATE TABLE `{database}`.`{temp_table}` AS
395
471
  SELECT MIN(`{pk_real}`) as `min_id`, {column_list}, COUNT(*) as `dup_count`
396
472
  FROM `{database}`.`{table}`
397
- {where_time}
473
+ {create_temp_where}
398
474
  GROUP BY {column_list}
399
475
  HAVING COUNT(*) > 1
400
476
  """
401
- drop_temp_sql = f"DROP TABLE IF EXISTS `{database}`.`{temp_table}`"
402
477
  with self._get_connection() as conn:
403
478
  with conn.cursor() as cursor:
404
479
  logger.debug('创建临时表SQL', {'sql': create_temp_sql})
405
480
  cursor.execute(create_temp_sql)
406
- logger.debug('统计临时表重复组SQL', {'sql': f'SELECT COUNT(*) as cnt FROM `{database}`.`{temp_table}`'})
407
481
  cursor.execute(f"SELECT COUNT(*) as cnt FROM `{database}`.`{temp_table}`")
408
482
  dup_count_row = cursor.fetchone()
409
483
  dup_count = dup_count_row['cnt'] if dup_count_row and 'cnt' in dup_count_row else 0
410
484
  if dup_count == 0:
411
- logger.info('没有重复数据', {"库": database, "表": table, "数据量": total_count, "时间范围": [self._dedup_start_date, self._dedup_end_date] if use_time_filter else None, "实际去重列": use_columns})
412
- logger.debug('删除临时表SQL', {'sql': drop_temp_sql})
485
+ logger.info('没有重复数据', {"库": database, "表": table, "数据量": total_count, "实际去重列": use_columns})
413
486
  cursor.execute(drop_temp_sql)
414
487
  conn.commit()
415
488
  return (0, 0)
416
489
  affected_rows = 0
417
490
  if not dry_run:
418
- # 分批删除,避免锁表
419
491
  while True:
420
- if self.duplicate_keep_mode == 'remove_all':
421
- # 删除所有重复组的所有记录
422
- delete_dup_sql = f"""
423
- DELETE FROM `{database}`.`{table}`
424
- WHERE ({', '.join([f'`{col}`' for col in use_columns])}) IN (
425
- SELECT {column_list} FROM `{database}`.`{temp_table}`
426
- ) {'AND' if use_time_filter else ''} {f'`{time_col}` >= \'{self._dedup_start_date}\' AND `{time_col}` <= \'{self._dedup_end_date}\'' if use_time_filter else ''}
427
- LIMIT {self.batch_size}
428
- """
429
- else:
430
- # 修正:只删除重复组中不是min_id的行,唯一数据不动
431
- delete_dup_sql = f"""
432
- DELETE FROM `{database}`.`{table}` t
433
- WHERE EXISTS (
434
- SELECT 1 FROM `{database}`.`{temp_table}` tmp
435
- WHERE
436
- {' AND '.join([f't.`{col}` <=> tmp.`{col}`' for col in use_columns])}
437
- AND t.`{pk_real}` <> tmp.`min_id`
438
- )
439
- {'AND' if use_time_filter else ''} {f't.`{time_col}` >= \'{self._dedup_start_date}\' AND t.`{time_col}` <= \'{self._dedup_end_date}\'' if use_time_filter else ''}
440
- LIMIT {self.batch_size}
441
- """
442
- logger.debug('执行删除重复数据SQL', {'sql': delete_dup_sql})
443
- cursor.execute(delete_dup_sql)
492
+ where_clauses = []
493
+ if self.duplicate_keep_mode == 'keep_one':
494
+ where_clauses.append(f"t.`{pk_real}` <> tmp.`min_id`")
495
+ if where_sql.strip():
496
+ where_clauses.append(where_sql.strip())
497
+ where_full = "WHERE " + " AND ".join(where_clauses) if where_clauses else ""
498
+ find_dup_ids_sql = f"""
499
+ SELECT t.`{pk_real}` as del_id
500
+ FROM `{database}`.`{table}` t
501
+ JOIN `{database}`.`{temp_table}` tmp
502
+ ON {' AND '.join([f't.`{col}` <=> tmp.`{col}`' for col in use_columns])}
503
+ {where_full}
504
+ LIMIT {self.batch_size}
505
+ """
506
+ logger.debug('查找待删除重复id SQL', {'sql': find_dup_ids_sql})
507
+ cursor.execute(find_dup_ids_sql)
508
+ del_ids = [row['del_id'] for row in cursor.fetchall()]
509
+ if not del_ids:
510
+ break
511
+ del_ids_str = ','.join([str(i) for i in del_ids])
512
+ delete_sql = f"DELETE FROM `{database}`.`{table}` WHERE `{pk_real}` IN ({del_ids_str})"
513
+ logger.debug('按id批量删除SQL', {'sql': delete_sql, 'ids': del_ids})
514
+ cursor.execute(delete_sql)
444
515
  batch_deleted = cursor.rowcount
445
516
  affected_rows += batch_deleted
446
517
  conn.commit()
518
+ if batch_deleted == 0:
519
+ logger.warning('检测到未能删除任何数据,强制跳出循环,防止假死', {"库": database, "表": table})
520
+ break
447
521
  if batch_deleted < self.batch_size:
448
522
  break
449
- logger.info('操作删除', {"库": database, "表": table, "数据量": total_count, "重复组数": dup_count, "实际删除": affected_rows, "时间范围": [self._dedup_start_date, self._dedup_end_date] if use_time_filter else None, "实际去重列": use_columns, "去重模式": self.duplicate_keep_mode})
523
+ logger.info('操作删除', {"库": database, "表": table, "数据量": total_count, "重复组数": dup_count, "实际删除": affected_rows, "去重模式": self.duplicate_keep_mode, "实际去重列": use_columns})
450
524
  else:
451
- logger.debug('dry_run模式,不执行删除', {"库": database, "表": table, "重复组数": dup_count, "时间范围": [self._dedup_start_date, self._dedup_end_date] if use_time_filter else None})
525
+ logger.debug('dry_run模式,不执行删除', {"库": database, "表": table, "重复组数": dup_count})
452
526
  affected_rows = 0
453
- logger.debug('删除临时表SQL', {'sql': drop_temp_sql})
454
527
  cursor.execute(drop_temp_sql)
455
528
  conn.commit()
456
529
  return (dup_count, affected_rows)
@@ -475,7 +548,9 @@ class MySQLDeduplicator:
475
548
  database: str,
476
549
  table: str,
477
550
  columns: Optional[List[str]] = None,
478
- dry_run: bool = False
551
+ dry_run: bool = False,
552
+ reorder_id: bool = False,
553
+ use_python_dedup: bool = True
479
554
  ) -> Tuple[int, int]:
480
555
  """
481
556
  对指定表进行去重。
@@ -485,6 +560,8 @@ class MySQLDeduplicator:
485
560
  table (str): 表名。
486
561
  columns (Optional[List[str]]): 用于去重的列名列表(为None时使用所有列)。
487
562
  dry_run (bool): 是否为模拟运行(只统计不实际删除)。
563
+ reorder_id (bool): 去重后是否重排id。
564
+ use_python_dedup (bool): 是否用Python查找重复id。
488
565
  Returns:
489
566
  Tuple[int, int]: (重复组数, 实际删除行数)。
490
567
  """
@@ -495,9 +572,17 @@ class MySQLDeduplicator:
495
572
  if not self._check_table_exists(database, table):
496
573
  logger.warning('表不存在', {"库": database, "表": table, "warning": "跳过"})
497
574
  return (0, 0)
498
- logger.info('单表开始', {"库": database, "表": table, "参数": {"指定去重列": columns, "模拟运行": dry_run, '排除列': self.exclude_columns}})
499
- result = self._deduplicate_table(database, table, columns, dry_run)
575
+ logger.info('单表开始', {"库": database, "表": table, "参数": {"指定去重列": columns, "模拟运行": dry_run, '排除列': self.exclude_columns, 'use_python_dedup': use_python_dedup}})
576
+ result = self._deduplicate_table(database, table, columns, dry_run, use_python_dedup)
500
577
  logger.info('单表完成', {"库": database, "表": table, "结果[重复, 删除]": result})
578
+ # 自动重排id列(仅当有实际删除时且reorder_id为True)
579
+ dup_count, affected_rows = result
580
+ if reorder_id and affected_rows > 0:
581
+ try:
582
+ reorder_ok = self.reorder_id_column(database, table, id_column=self.primary_key, dry_run=dry_run)
583
+ logger.info('自动重排id列完成', {"库": database, "表": table, "结果": reorder_ok})
584
+ except Exception as e:
585
+ logger.error('自动重排id列异常', {"库": database, "表": table, "异常": str(e)})
501
586
  return result
502
587
  except Exception as e:
503
588
  logger.error('发生全局错误', {"库": database, "表": table, 'func': sys._getframe().f_code.co_name, "发生全局错误": str(e)})
@@ -509,7 +594,9 @@ class MySQLDeduplicator:
509
594
  tables: Optional[List[str]] = None,
510
595
  columns_map: Optional[Dict[str, List[str]]] = None,
511
596
  dry_run: bool = False,
512
- parallel: bool = False
597
+ parallel: bool = False,
598
+ reorder_id: bool = False,
599
+ use_python_dedup: bool = True
513
600
  ) -> Dict[str, Tuple[int, int]]:
514
601
  """
515
602
  对指定数据库的所有表进行去重。
@@ -520,6 +607,8 @@ class MySQLDeduplicator:
520
607
  columns_map (Optional[Dict[str, List[str]]]): 各表使用的去重列 {表名: [列名]}。
521
608
  dry_run (bool): 是否为模拟运行。
522
609
  parallel (bool): 是否并行处理。
610
+ reorder_id (bool): 去重后是否重排id。
611
+ use_python_dedup (bool): 是否用Python查找重复id。
523
612
  Returns:
524
613
  Dict[str, Tuple[int, int]]: {表名: (重复组数, 实际删除行数)}。
525
614
  """
@@ -548,7 +637,7 @@ class MySQLDeduplicator:
548
637
  logger.debug('提交表去重任务', {'库': database, '表': table, 'columns': columns})
549
638
  futures[executor.submit(
550
639
  self.deduplicate_table,
551
- database, table, columns, dry_run
640
+ database, table, columns, dry_run, reorder_id, True
552
641
  )] = table
553
642
  for future in concurrent.futures.as_completed(futures):
554
643
  table = futures[future]
@@ -564,7 +653,7 @@ class MySQLDeduplicator:
564
653
  for table in target_tables:
565
654
  columns = columns_map.get(table) if columns_map else None
566
655
  dup_count, affected_rows = self.deduplicate_table(
567
- database, table, columns, dry_run
656
+ database, table, columns, dry_run, reorder_id, True
568
657
  )
569
658
  results[table] = (dup_count, affected_rows)
570
659
  total_dup = sum(r[0] for r in results.values())
@@ -581,7 +670,9 @@ class MySQLDeduplicator:
581
670
  tables_map: Optional[Dict[str, List[str]]] = None,
582
671
  columns_map: Optional[Dict[str, Dict[str, List[str]]]] = None,
583
672
  dry_run: bool = False,
584
- parallel: bool = False
673
+ parallel: bool = False,
674
+ reorder_id: bool = False,
675
+ use_python_dedup: bool = True
585
676
  ) -> Dict[str, Dict[str, Tuple[int, int]]]:
586
677
  """
587
678
  对所有数据库进行去重。
@@ -592,6 +683,8 @@ class MySQLDeduplicator:
592
683
  columns_map (Optional[Dict[str, Dict[str, List[str]]]]): 指定每个表去重时使用的列,格式为 {数据库名: {表名: [列名, ...]}}。如果为 None,则使用所有列。
593
684
  dry_run (bool): 是否为模拟运行模式。为 True 时只统计重复行数,不实际删除。
594
685
  parallel (bool): 是否并行处理多个数据库。为 True 时使用线程池并发处理。
686
+ reorder_id (bool): 去重后是否重排id。
687
+ use_python_dedup (bool): 是否用Python查找重复id。
595
688
  Returns:
596
689
  Dict[str, Dict[str, Tuple[int, int]]]: 嵌套字典,格式为 {数据库名: {表名: (重复组数, 实际删除行数)}}。
597
690
  """
@@ -603,7 +696,7 @@ class MySQLDeduplicator:
603
696
  if not target_dbs:
604
697
  logger.warning('没有可处理的数据库')
605
698
  return all_results
606
- logger.info('全局开始', {"数据库数量": len(target_dbs), "数据库列表": target_dbs, "参数": {"模拟运行": dry_run, "并行处理": parallel, '排除列': self.exclude_columns}})
699
+ logger.info('全局开始', {"数据库数量": len(target_dbs), "数据库列表": target_dbs, "参数": {"模拟运行": dry_run, "并行处理": parallel, '排除列': self.exclude_columns, 'use_python_dedup': use_python_dedup}})
607
700
  if parallel and self.max_workers > 1:
608
701
  # 使用线程池并行处理多个数据库
609
702
  with concurrent.futures.ThreadPoolExecutor(
@@ -615,7 +708,7 @@ class MySQLDeduplicator:
615
708
  db_columns_map = columns_map.get(db) if columns_map else None
616
709
  futures[executor.submit(
617
710
  self.deduplicate_database,
618
- db, tables, db_columns_map, dry_run, False
711
+ db, tables, db_columns_map, dry_run, False, reorder_id, True
619
712
  )] = db
620
713
  for future in concurrent.futures.as_completed(futures):
621
714
  db = futures[future]
@@ -631,7 +724,7 @@ class MySQLDeduplicator:
631
724
  tables = tables_map.get(db) if tables_map else None
632
725
  db_columns_map = columns_map.get(db) if columns_map else None
633
726
  db_results = self.deduplicate_database(
634
- db, tables, db_columns_map, dry_run, parallel
727
+ db, tables, db_columns_map, dry_run, parallel, reorder_id, True
635
728
  )
636
729
  all_results[db] = db_results
637
730
  total_dup = sum(
@@ -806,7 +899,7 @@ class MySQLDeduplicator:
806
899
  with conn.cursor() as cursor:
807
900
  cursor.execute(f"SHOW CREATE TABLE {table_quoted}")
808
901
  create_table_sql = cursor.fetchone()['Create Table']
809
- logger.info('开始id重排', {"库": database, "表": table, "重排列": id_column, "dry_run": dry_run, "DDL警告": "MySQL DDL操作不可回滚,建议提前备份!"})
902
+ logger.info('开始id重排', {"库": database, "表": table, "重排列": id_column, "试运行": dry_run, "DDL警告": "MySQL DDL操作不可回滚,建议提前备份!"})
810
903
  if dry_run:
811
904
  logger.info('dry_run模式,打印原表结构', {"库": database, "表": table, "建表语句": create_table_sql})
812
905
  return True
@@ -933,17 +1026,19 @@ def main():
933
1026
  username='root',
934
1027
  password='pwd',
935
1028
  host='localhost',
936
- port=3306
1029
+ port=3306,
1030
+ date_range=['2025-05-27', '2025-05-28'],
1031
+ exclude_tables={'推广数据2': ['地域报表_城市_2025_05_copy1', '主体报表_2025_copy1']}
937
1032
  )
938
1033
 
939
1034
  # 全库去重(单线程)
940
- deduplicator.deduplicate_all(dry_run=False, parallel=True)
1035
+ deduplicator.deduplicate_all(dry_run=False, parallel=True, reorder_id=True)
941
1036
 
942
1037
  # # 指定数据库去重(多线程)
943
- # deduplicator.deduplicate_database('my_db', dry_run=False, parallel=False)
1038
+ # deduplicator.deduplicate_database('my_db', dry_run=False, parallel=False, reorder_id=False)
944
1039
 
945
1040
  # # 指定表去重(使用特定列)
946
- # deduplicator.deduplicate_table('my_db', 'my_table', columns=['name', 'date'], dry_run=False)
1041
+ # deduplicator.deduplicate_table('my_db', 'my_table', columns=['name', 'date'], dry_run=False, reorder_id=False)
947
1042
 
948
1043
  # # 重排id列
949
1044
  # deduplicator.reorder_id_column('my_db', 'my_table', 'id', dry_run=False, auto_drop_backup=True)
mdbq/mysql/uploader.py CHANGED
@@ -428,6 +428,7 @@ class MySQLUploader:
428
428
  if idx_col in set_typ:
429
429
  safe_idx_col = self._validate_identifier(idx_col)
430
430
  index_defs.append(f"INDEX `idx_{safe_idx_col}` (`{safe_idx_col}`)")
431
+ index_defs = list(set(index_defs))
431
432
  index_sql = (',' + ','.join(index_defs)) if index_defs else ''
432
433
  sql = f"""
433
434
  CREATE TABLE IF NOT EXISTS `{db_name}`.`{table_name}` (
@@ -593,6 +594,34 @@ class MySQLUploader:
593
594
  logger.error('无法获取表列信息', {'库': db_name, '表': table_name, '错误': str(e)})
594
595
  raise
595
596
 
597
+ def _ensure_index(self, db_name: str, table_name: str, column: str):
598
+ """
599
+ 确保某列有索引,如果没有则创建。
600
+ """
601
+ db_name = self._validate_identifier(db_name)
602
+ table_name = self._validate_identifier(table_name)
603
+ column = self._validate_identifier(column)
604
+ # 检查索引是否已存在
605
+ sql_check = '''
606
+ SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS
607
+ WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = %s
608
+ '''
609
+ sql_create = f'ALTER TABLE `{db_name}`.`{table_name}` ADD INDEX `idx_{column}` (`{column}`)'
610
+ try:
611
+ with self._get_connection() as conn:
612
+ with conn.cursor() as cursor:
613
+ cursor.execute(sql_check, (db_name, table_name, column))
614
+ exists = cursor.fetchone()
615
+ if exists and list(exists.values())[0] > 0:
616
+ logger.debug('索引已存在', {'库': db_name, '表': table_name, '列': column})
617
+ return
618
+ cursor.execute(sql_create)
619
+ conn.commit()
620
+ logger.info('已为列创建索引', {'库': db_name, '表': table_name, '列': column})
621
+ except Exception as e:
622
+ logger.error('创建索引失败', {'库': db_name, '表': table_name, '列': column, '错误': str(e)})
623
+ raise
624
+
596
625
  def _upload_to_table(
597
626
  self,
598
627
  db_name: str,
@@ -646,6 +675,13 @@ class MySQLUploader:
646
675
  })
647
676
  raise ValueError(f"列不存在: `{col}` -> `{db_name}`.`{table_name}`")
648
677
 
678
+ # 确保分表参考字段为索引
679
+ if date_column and date_column in table_columns:
680
+ try:
681
+ self._ensure_index(db_name, table_name, date_column)
682
+ except Exception as e:
683
+ logger.warning('分表参考字段索引创建失败', {'库': db_name, '表': table_name, '列': date_column, '错误': str(e)})
684
+
649
685
  # 插入数据
650
686
  self._insert_data(
651
687
  db_name, table_name, data, set_typ,
@@ -868,7 +904,7 @@ class MySQLUploader:
868
904
  :param duplicate_columns: 用于检查重复的列,可选
869
905
  :param allow_null: 是否允许空值,默认为False
870
906
  :param partition_by: 分表方式('year'、'month'、'None'),可选
871
- :param partition_date_column: 用于分表的日期列名,默认为'日期'
907
+ :param partition_date_column: 用于分表的日期列名,默认为'日期', 默认会添加为索引
872
908
  :param auto_create: 表不存在时是否自动创建,默认为True
873
909
  :param indexes: 需要创建索引的列列表,可选
874
910
  :param update_on_duplicate: 遇到重复数据时是否更新旧数据,默认为False
@@ -977,6 +1013,12 @@ class MySQLUploader:
977
1013
  allow_null, auto_create, partition_date_column,
978
1014
  indexes, batch_id, update_on_duplicate, transaction_mode
979
1015
  )
1016
+ # 确保分表参考字段为索引
1017
+ if partition_date_column in filtered_set_typ:
1018
+ try:
1019
+ self._ensure_index(db_name, part_table, partition_date_column)
1020
+ except Exception as e:
1021
+ logger.warning('分表参考字段索引创建失败', {'库': db_name, '表': part_table, '列': partition_date_column, '错误': str(e)})
980
1022
  except Exception as e:
981
1023
  logger.error('分表上传异常', {
982
1024
  '库': db_name,
@@ -995,6 +1037,12 @@ class MySQLUploader:
995
1037
  allow_null, auto_create, partition_date_column,
996
1038
  indexes, batch_id, update_on_duplicate, transaction_mode
997
1039
  )
1040
+ # 确保分表参考字段为索引
1041
+ if partition_date_column in filtered_set_typ:
1042
+ try:
1043
+ self._ensure_index(db_name, table_name, partition_date_column)
1044
+ except Exception as e:
1045
+ logger.warning('分表参考字段索引创建失败', {'库': db_name, '表': table_name, '列': partition_date_column, '错误': str(e)})
998
1046
 
999
1047
  success_flag = True
1000
1048
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: mdbq
3
- Version: 3.11.8
3
+ Version: 3.11.9
4
4
  Home-page: https://pypi.org/project/mdbq
5
5
  Author: xigua,
6
6
  Author-email: 2587125111@qq.com
@@ -1,17 +1,17 @@
1
1
  mdbq/__init__.py,sha256=Il5Q9ATdX8yXqVxtP_nYqUhExzxPC_qk_WXQ_4h0exg,16
2
- mdbq/__version__.py,sha256=JqV56ilza72jpkf_fztVtAdeSmcdPr0BmGGo9FFjGrA,18
2
+ mdbq/__version__.py,sha256=PDdrWyCY8MR3t82c_RzSF6lAB6oCcZdWveXkX7AvIIQ,18
3
3
  mdbq/aggregation/__init__.py,sha256=EeDqX2Aml6SPx8363J-v1lz0EcZtgwIBYyCJV6CcEDU,40
4
4
  mdbq/aggregation/query_data.py,sha256=nxL8hSy8yI1QLlqnkTNHHQSxRfo-6WKL5OA-N4xLB7c,179832
5
5
  mdbq/config/__init__.py,sha256=jso1oHcy6cJEfa7udS_9uO5X6kZLoPBF8l3wCYmr5dM,18
6
6
  mdbq/config/config.py,sha256=eaTfrfXQ65xLqjr5I8-HkZd_jEY1JkGinEgv3TSLeoQ,3170
7
7
  mdbq/log/__init__.py,sha256=Mpbrav0s0ifLL7lVDAuePEi1hJKiSHhxcv1byBKDl5E,15
8
- mdbq/log/mylogger.py,sha256=HuxLBCXjm6fZrxYE0rdpUCz359WGeqOX0vvg9jTuRY4,24126
8
+ mdbq/log/mylogger.py,sha256=Crw6LwVo3I3IUbzIETu8f46Quza3CTCh-qYf4edbBPo,24139
9
9
  mdbq/log/spider_logging.py,sha256=-ozWWEGm3HVv604ozs_OOvVwumjokmUPwbaodesUrPY,1664
10
10
  mdbq/mysql/__init__.py,sha256=A_DPJyAoEvTSFojiI2e94zP0FKtCkkwKP1kYUCSyQzo,11
11
- mdbq/mysql/deduplicator.py,sha256=Znmjn4sI1Mj2koSPTDojFwg_1MTgk3GZTFZyhSRwn7s,46746
11
+ mdbq/mysql/deduplicator.py,sha256=G7hdIO6rDLBNo1jSm6PbmPAzzfdN2jZFP4BnLhO02Mo,52970
12
12
  mdbq/mysql/mysql.py,sha256=Kjpi-LL00WQUmTTOfhEBsNrmo4-4kFFJzrHbVKfqiBE,56770
13
13
  mdbq/mysql/s_query.py,sha256=dlnrVJ3-Vp1Suv9CNbPxyYSRqRJUHjOpF39tb2F-wBc,10190
14
- mdbq/mysql/uploader.py,sha256=LxPlAfSNhQbLu-or4wxa-vLjCw5_PIN3ZVoksWUJazQ,61701
14
+ mdbq/mysql/uploader.py,sha256=8Px_W2bYOr1wQgMXMK0DggNiuE6a6Ul4BlJake8LSo8,64469
15
15
  mdbq/other/__init__.py,sha256=jso1oHcy6cJEfa7udS_9uO5X6kZLoPBF8l3wCYmr5dM,18
16
16
  mdbq/other/download_sku_picture.py,sha256=YU8DxKMXbdeE1OOKEA848WVp62jYHw5O4tXTjUdq9H0,44832
17
17
  mdbq/other/otk.py,sha256=iclBIFbQbhlqzUbcMMoePXBpcP1eZ06ZtjnhcA_EbmE,7241
@@ -24,7 +24,7 @@ mdbq/redis/__init__.py,sha256=YtgBlVSMDphtpwYX248wGge1x-Ex_mMufz4-8W0XRmA,12
24
24
  mdbq/redis/getredis.py,sha256=YHgCKO8mEsslwet33K5tGss-nrDDwPnOSlhA9iBu0jY,24078
25
25
  mdbq/spider/__init__.py,sha256=RBMFXGy_jd1HXZhngB2T2XTvJqki8P_Fr-pBcwijnew,18
26
26
  mdbq/spider/aikucun.py,sha256=cqK-JRd_DHbToC7hyo83m8o97NZkJFqmB2xBtr6aAVU,20961
27
- mdbq-3.11.8.dist-info/METADATA,sha256=EJtaHsIzWmcB9hTRg1NZeDd55Zez0lu6FPD_ZQB9nMw,364
28
- mdbq-3.11.8.dist-info/WHEEL,sha256=jB7zZ3N9hIM9adW7qlTAyycLYW9npaWKLRzaoVcLKcM,91
29
- mdbq-3.11.8.dist-info/top_level.txt,sha256=2FQ-uLnCSB-OwFiWntzmwosW3X2Xqsg0ewh1axsaylA,5
30
- mdbq-3.11.8.dist-info/RECORD,,
27
+ mdbq-3.11.9.dist-info/METADATA,sha256=djSbJHNSHuyh2So6ia5CluTggpZ4REj9jxhO9vwOeKw,364
28
+ mdbq-3.11.9.dist-info/WHEEL,sha256=jB7zZ3N9hIM9adW7qlTAyycLYW9npaWKLRzaoVcLKcM,91
29
+ mdbq-3.11.9.dist-info/top_level.txt,sha256=2FQ-uLnCSB-OwFiWntzmwosW3X2Xqsg0ewh1axsaylA,5
30
+ mdbq-3.11.9.dist-info/RECORD,,
File without changes