cppackage 0.2.8__tar.gz → 0.2.9__tar.gz

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.
@@ -1,7 +1,7 @@
1
1
  import pymysql
2
2
  import time
3
3
  from pymysql import Error
4
-
4
+ import pandas as pd
5
5
  # 条件导入:支持直接运行和包模式
6
6
  try:
7
7
  from .config import get_db_config
@@ -109,7 +109,6 @@ def check_and_sync_columns(df ,table_name, database, max_new=5):
109
109
  db_cols = set(get_table_columns(table_name, database))
110
110
  # 新增字段
111
111
  new_cols = df_cols - db_cols
112
-
113
112
  # 缺失字段(减少的字段,不处理)
114
113
  missing_cols = db_cols - df_cols
115
114
  print("新增字段:", new_cols if new_cols else "无")
@@ -126,8 +125,122 @@ def check_and_sync_columns(df ,table_name, database, max_new=5):
126
125
  else:
127
126
  raise Exception(f"新增字段超过{max_new}个: {new_cols}")
128
127
  return True
129
-
130
-
128
+ # ===================== 通用查询重复记录函数(适配自定义索引) =====================
129
+ def find_duplicate_records(table_name, database, unique_index_fields, port=None):
130
+ """
131
+ 查询指定表中基于自定义唯一索引字段组合重复的记录
132
+ 参数:
133
+ table_name: 表名(必选)
134
+ database: 数据库名(必选)
135
+ unique_index_fields: 唯一索引字段列表(必选,如 ['begindate', 'enddate'])
136
+ port: 数据库端口(可选)
137
+ 返回:
138
+ DataFrame: 重复记录详情;None: 出错;空DataFrame: 无重复
139
+ """
140
+ # 核心校验:确保unique_index_fields是可迭代的非空列表
141
+ if not isinstance(unique_index_fields, list) or len(unique_index_fields) == 0:
142
+ print("错误:unique_index_fields 必须是非空列表!")
143
+ return None
144
+
145
+ fields_str = ",".join([f"`{field}`" for field in unique_index_fields])
146
+ group_by_str = ",".join([f"`{field}`" for field in unique_index_fields])
147
+
148
+ # 核心SQL:查询所有重复记录
149
+ sql = f"""
150
+ SELECT t.*
151
+ FROM `{table_name}` t
152
+ INNER JOIN (
153
+ SELECT {group_by_str}, COUNT(*) AS duplicate_count
154
+ FROM `{table_name}`
155
+ GROUP BY {group_by_str}
156
+ HAVING COUNT(*) > 1
157
+ ) dup ON {
158
+ " AND ".join([f"t.`{field}` = dup.`{field}`" for field in unique_index_fields])
159
+ }
160
+ ORDER BY {group_by_str}
161
+ """
162
+
163
+ try:
164
+ with _get_connection(database, port) as conn:
165
+ df_duplicates = pd.read_sql(sql, conn)
166
+ if df_duplicates.empty:
167
+ print(f"表 {table_name} 中无重复记录")
168
+ else:
169
+ print(f"发现 {len(df_duplicates)} 条重复记录({len(df_duplicates.drop_duplicates(subset=unique_index_fields))} 组重复组合)")
170
+ # 可选:保存重复记录到CSV
171
+ df_duplicates.to_csv(f"duplicate_records_{table_name}.csv", index=False, encoding="utf-8-sig")
172
+ print("重复记录已保存到 duplicate_records_{table_name}.csv")
173
+ return df_duplicates
174
+ except pymysql.MySQLError as e:
175
+ print("数据库查询失败:", e)
176
+ return None
177
+ except Exception as e:
178
+ print("未知错误:", e)
179
+ return None
180
+ # ===================== 删除重复记录函数(修复参数+调用逻辑) =====================
181
+ def delete_duplicate_records(table_name, database, unique_index_fields, port=None, keep_strategy="min_id"):
182
+ """
183
+ 删除重复记录,仅保留每组唯一值的一条记录
184
+ 参数:
185
+ table_name: 表名(必选)
186
+ database: 数据库名(必选)
187
+ unique_index_fields: 唯一索引字段列表(必选)
188
+ port: 数据库端口(可选)
189
+ keep_strategy: 保留策略(min_id/max_id)
190
+ 返回:
191
+ int: 删除的记录数;None: 出错;0: 无重复
192
+ """
193
+ # 1. 先调用修复后的find_duplicate_records查询重复数据
194
+ duplicate_df = find_duplicate_records(table_name, database, unique_index_fields, port)
195
+ if duplicate_df is None or duplicate_df.empty:
196
+ return 0
197
+
198
+ # 2. 构建删除SQL(核心逻辑)
199
+ group_by_str = ",".join([f"`{field}`" for field in unique_index_fields])
200
+ if keep_strategy == "min_id":
201
+ keep_condition = "MIN(`id`)"
202
+ elif keep_strategy == "max_id":
203
+ keep_condition = "MAX(`id`)"
204
+ else:
205
+ print(f"不支持的策略:{keep_strategy},默认使用min_id")
206
+ keep_condition = "MIN(`id`)"
207
+
208
+ delete_sql = f"""
209
+ DELETE t FROM `{table_name}` t
210
+ INNER JOIN (
211
+ SELECT {group_by_str}, {keep_condition} AS keep_id
212
+ FROM `{table_name}`
213
+ GROUP BY {group_by_str}
214
+ HAVING COUNT(*) > 1
215
+ ) dup ON {
216
+ " AND ".join([f"t.`{field}` = dup.`{field}`" for field in unique_index_fields])
217
+ }
218
+ WHERE t.`id` != dup.keep_id
219
+ """
220
+
221
+ try:
222
+ with _get_connection(database, port) as conn:
223
+ with conn.cursor() as cursor:
224
+ # 安全确认
225
+ print(f"\n⚠️ 即将删除表 {table_name} 的重复记录,保留策略:{keep_strategy}")
226
+ print("确认删除请按任意键,取消请关闭程序...")
227
+ input()
228
+
229
+ # 执行删除
230
+ affected_rows = cursor.execute(delete_sql)
231
+ conn.commit()
232
+ print(f"✅ 成功删除 {affected_rows} 条重复记录")
233
+ return affected_rows
234
+ except pymysql.MySQLError as e:
235
+ print("❌ 删除失败(数据库错误):", e)
236
+ if 'conn' in locals():
237
+ conn.rollback()
238
+ return None
239
+ except Exception as e:
240
+ print("❌ 删除失败(未知错误):", e)
241
+ if 'conn' in locals():
242
+ conn.rollback()
243
+ return None
131
244
  # ===================== DataFrame 入库 =====================
132
245
 
133
246
  def update_datas(df, table_name, database):
@@ -135,7 +248,6 @@ def update_datas(df, table_name, database):
135
248
  conn = None
136
249
  for i in range(2):
137
250
  try:
138
- # 表结构校验,df为抓取数据表,db_cols为数据库现有字段
139
251
  conn = _get_connection(database)
140
252
  cursor = conn.cursor()
141
253
  cols = list(df.columns)
@@ -150,6 +262,7 @@ def update_datas(df, table_name, database):
150
262
  VALUES {values_str}
151
263
  ON DUPLICATE KEY UPDATE {update_clause}
152
264
  """
265
+ print(sql)
153
266
  data = [tuple(row) for row in df.values]
154
267
  flat_data = [v for row in data for v in row]
155
268
  cursor.execute(sql, flat_data)
@@ -161,6 +274,7 @@ def update_datas(df, table_name, database):
161
274
  conn.rollback()
162
275
  print("入库失败:", e)
163
276
  if '1054, "Unknown column' in str(e):
277
+ # 表结构校验,df为抓取数据表
164
278
  check_and_sync_columns(df,table_name,database)
165
279
  else:
166
280
  raise Exception(e)
@@ -0,0 +1,24 @@
1
+ from CPpackage.db.sql_model import find_duplicate_records,delete_duplicate_records
2
+ import os
3
+
4
+
5
+ if __name__ == "__main__":
6
+ # 配置你的参数
7
+ TABLE_NAME = "pinlei_hgjk" # 替换为实际表名
8
+ DATABASE_NAME = "shengyicanmou_copy" # 替换为实际数据库名
9
+ # 你的唯一索引字段列表(必须是列表类型!)
10
+ UNIQUE_FIELDS = ['begindate', 'enddate', 'value_l', 'sellerId', 'statDate', 'date_effect', 'store_id']
11
+ PORT = 3306 # 可选,默认从配置获取
12
+
13
+ # 第一步:查询重复记录
14
+ dup_df = find_duplicate_records(TABLE_NAME, DATABASE_NAME, UNIQUE_FIELDS, PORT)
15
+
16
+ # 第二步:确认有重复后删除
17
+ if dup_df is not None and not dup_df.empty:
18
+ delete_count = delete_duplicate_records(
19
+ table_name=TABLE_NAME,
20
+ database=DATABASE_NAME,
21
+ unique_index_fields=UNIQUE_FIELDS, # 必须传列表!
22
+ port=PORT,
23
+ keep_strategy="min_id"
24
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cppackage
3
- Version: 0.2.8
3
+ Version: 0.2.9
4
4
  Summary: 超品集团自用的Python包
5
5
  Home-page: https://github.com/example/CPpackage
6
6
  Author: team-数智组
@@ -14,6 +14,7 @@ CPpackage/core/__init__.py
14
14
  CPpackage/db/__init__.py
15
15
  CPpackage/db/config.py
16
16
  CPpackage/db/sql_model.py
17
+ CPpackage/db/test.py
17
18
  CPpackage/utils/__init__.py
18
19
  cppackage.egg-info/PKG-INFO
19
20
  cppackage.egg-info/SOURCES.txt
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cppackage
3
- Version: 0.2.8
3
+ Version: 0.2.9
4
4
  Summary: 超品集团自用的Python包
5
5
  Home-page: https://github.com/example/CPpackage
6
6
  Author: team-数智组
@@ -10,7 +10,7 @@ with open('readme.md', 'r', encoding='utf-8') as f:
10
10
  # 包的基本信息
11
11
  setup(
12
12
  name='cppackage',
13
- version='0.2.8',
13
+ version='0.2.9',
14
14
  description='超品集团自用的Python包',
15
15
  long_description=long_description,
16
16
  long_description_content_type='text/markdown',
File without changes
File without changes
File without changes
File without changes