cppackage 0.2.7__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.
@@ -0,0 +1,285 @@
1
+ import pymysql
2
+ import time
3
+ from pymysql import Error
4
+ import pandas as pd
5
+ # 条件导入:支持直接运行和包模式
6
+ try:
7
+ from .config import get_db_config
8
+ except (ImportError, ValueError):
9
+ # 直接运行时失败,尝试绝对路径
10
+ import sys
11
+ import os
12
+ sys.path.insert(0, os.path.dirname(__file__))
13
+ from config import get_db_config
14
+
15
+
16
+ # ===================== 数据库连接 =====================
17
+
18
+ def _get_connection(database=None, port=None):
19
+ cfg = get_db_config()
20
+
21
+ db = database if database else cfg.get('database')
22
+ prt = port if port else cfg.get('port', 3306)
23
+
24
+ return pymysql.connect(
25
+ host=cfg.get('host'),
26
+ user=cfg.get('user'),
27
+ password=cfg.get('password'),
28
+ database=db,
29
+ port=prt,
30
+ charset="utf8mb4",
31
+ autocommit=False
32
+ )
33
+
34
+
35
+ # ===================== 查询操作 =====================
36
+
37
+ def sel_data(sql, params=None, port=None, database=None):
38
+
39
+ try:
40
+ with _get_connection(database, port) as conn:
41
+ with conn.cursor() as cursor:
42
+ cursor.execute(sql, params)
43
+ return cursor.fetchall()
44
+
45
+ except pymysql.MySQLError as e:
46
+ print("查询失败:", e)
47
+ return None
48
+
49
+ # ===================== 增量更新 =====================
50
+ def incremental_update(sql, values, port=None, database=None):
51
+ with _get_connection(database=database, port=port) as conn:
52
+ with conn.cursor() as cursor:
53
+ cursor.executemany(sql, values)
54
+ conn.commit()
55
+
56
+
57
+ # ===================== 删除操作 =====================
58
+ def del_data(sql, params=None, port=None, database=None):
59
+
60
+ try:
61
+ with _get_connection(database, port) as conn:
62
+ with conn.cursor() as cursor:
63
+ cursor.execute(sql, params)
64
+ conn.commit()
65
+
66
+ except pymysql.MySQLError as e:
67
+ print("删除失败:", e)
68
+
69
+
70
+ # ===================== 表结构管理 =====================
71
+
72
+ def get_table_columns(table_name, database):
73
+
74
+ sql = """
75
+ SELECT COLUMN_NAME
76
+ FROM INFORMATION_SCHEMA.COLUMNS
77
+ WHERE TABLE_SCHEMA=%s
78
+ AND TABLE_NAME=%s
79
+ ORDER BY ORDINAL_POSITION
80
+ """
81
+
82
+ with _get_connection(database) as conn:
83
+ with conn.cursor() as cursor:
84
+ cursor.execute(sql, (database, table_name))
85
+ return [row[0] for row in cursor.fetchall()]
86
+
87
+
88
+ def add_columns(table_name, database, columns):
89
+
90
+ with _get_connection(database) as conn:
91
+ with conn.cursor() as cursor:
92
+
93
+ for col in columns:
94
+ sql = f"""
95
+ ALTER TABLE `{table_name}`
96
+ ADD COLUMN `{col}` TEXT
97
+ """
98
+ cursor.execute(sql)
99
+ print(f"新增字段: {col}")
100
+
101
+ conn.commit()
102
+
103
+ # 表结构校验
104
+ def check_and_sync_columns(df ,table_name, database, max_new=5):
105
+
106
+ # df字段
107
+ df_cols = set(df.columns)
108
+ # 数据库字段
109
+ db_cols = set(get_table_columns(table_name, database))
110
+ # 新增字段
111
+ new_cols = df_cols - db_cols
112
+ # 缺失字段(减少的字段,不处理)
113
+ missing_cols = db_cols - df_cols
114
+ print("新增字段:", new_cols if new_cols else "无")
115
+ print("缺失字段(忽略):", missing_cols if missing_cols else "无")
116
+
117
+ # 最大新增字段限制
118
+ if len(db_cols) * 0.2 > max_new:
119
+ max_new = int(len(db_cols) *0.2)
120
+ # 自动补
121
+ if 0 < len(new_cols) <= max_new:
122
+ print("开始同步字段...")
123
+ add_columns(table_name, database, new_cols)
124
+ print("字段同步成功")
125
+ else:
126
+ raise Exception(f"新增字段超过{max_new}个: {new_cols}")
127
+ return True
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
244
+ # ===================== DataFrame 入库 =====================
245
+
246
+ def update_datas(df, table_name, database):
247
+
248
+ conn = None
249
+ for i in range(2):
250
+ try:
251
+ conn = _get_connection(database)
252
+ cursor = conn.cursor()
253
+ cols = list(df.columns)
254
+ col_str = ",".join([f"`{c}`" for c in cols])
255
+ value_tpl = "(" + ",".join(["%s"] * len(cols)) + ")"
256
+ values_str = ",".join([value_tpl] * len(df))
257
+ update_clause = ",".join(
258
+ [f"`{c}`=VALUES(`{c}`)" for c in cols if c != "id"]
259
+ )
260
+ sql = f"""
261
+ INSERT INTO `{table_name}` ({col_str})
262
+ VALUES {values_str}
263
+ ON DUPLICATE KEY UPDATE {update_clause}
264
+ """
265
+ print(sql)
266
+ data = [tuple(row) for row in df.values]
267
+ flat_data = [v for row in data for v in row]
268
+ cursor.execute(sql, flat_data)
269
+ conn.commit()
270
+ print(f"成功插入/更新 {cursor.rowcount} 条记录")
271
+ break
272
+ except Exception as e:
273
+ if conn:
274
+ conn.rollback()
275
+ print("入库失败:", e)
276
+ if '1054, "Unknown column' in str(e):
277
+ # 表结构校验,df为抓取数据表
278
+ check_and_sync_columns(df,table_name,database)
279
+ else:
280
+ raise Exception(e)
281
+ finally:
282
+ if conn:
283
+ conn.close()
284
+
285
+
@@ -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.7
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.7
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.7',
13
+ version='0.2.9',
14
14
  description='超品集团自用的Python包',
15
15
  long_description=long_description,
16
16
  long_description_content_type='text/markdown',
@@ -1,172 +0,0 @@
1
- import pymysql
2
- import time
3
- from pymysql import Error
4
-
5
- # 条件导入:支持直接运行和包模式
6
- try:
7
- from .config import get_db_config
8
- except (ImportError, ValueError):
9
- # 直接运行时失败,尝试绝对路径
10
- import sys
11
- import os
12
- sys.path.insert(0, os.path.dirname(__file__))
13
- from config import get_db_config
14
-
15
-
16
- # ===================== 数据库连接 =====================
17
-
18
- def _get_connection(database=None, port=None):
19
- cfg = get_db_config()
20
-
21
- db = database if database else cfg.get('database')
22
- prt = port if port else cfg.get('port', 3306)
23
-
24
- return pymysql.connect(
25
- host=cfg.get('host'),
26
- user=cfg.get('user'),
27
- password=cfg.get('password'),
28
- database=db,
29
- port=prt,
30
- charset="utf8mb4",
31
- autocommit=False
32
- )
33
-
34
-
35
- # ===================== 查询操作 =====================
36
-
37
- def sel_data(sql, params=None, port=None, database=None):
38
-
39
- try:
40
- with _get_connection(database, port) as conn:
41
- with conn.cursor() as cursor:
42
- cursor.execute(sql, params)
43
- return cursor.fetchall()
44
-
45
- except pymysql.MySQLError as e:
46
- print("查询失败:", e)
47
- return None
48
-
49
- # ===================== 增量更新 =====================
50
- def incremental_update(sql, values, port=None, database=None):
51
- with _get_connection(database=database, port=port) as conn:
52
- with conn.cursor() as cursor:
53
- cursor.executemany(sql, values)
54
- conn.commit()
55
-
56
-
57
- # ===================== 删除操作 =====================
58
- def del_data(sql, params=None, port=None, database=None):
59
-
60
- try:
61
- with _get_connection(database, port) as conn:
62
- with conn.cursor() as cursor:
63
- cursor.execute(sql, params)
64
- conn.commit()
65
-
66
- except pymysql.MySQLError as e:
67
- print("删除失败:", e)
68
-
69
-
70
- # ===================== 表结构管理 =====================
71
-
72
- def get_table_columns(table_name, database):
73
-
74
- sql = """
75
- SELECT COLUMN_NAME
76
- FROM INFORMATION_SCHEMA.COLUMNS
77
- WHERE TABLE_SCHEMA=%s
78
- AND TABLE_NAME=%s
79
- ORDER BY ORDINAL_POSITION
80
- """
81
-
82
- with _get_connection(database) as conn:
83
- with conn.cursor() as cursor:
84
- cursor.execute(sql, (database, table_name))
85
- return [row[0] for row in cursor.fetchall()]
86
-
87
-
88
- def add_columns(table_name, database, columns):
89
-
90
- with _get_connection(database) as conn:
91
- with conn.cursor() as cursor:
92
-
93
- for col in columns:
94
- sql = f"""
95
- ALTER TABLE `{table_name}`
96
- ADD COLUMN `{col}` TEXT
97
- """
98
- cursor.execute(sql)
99
- print(f"新增字段: {col}")
100
-
101
- conn.commit()
102
-
103
- # 表结构校验
104
- def check_and_sync_columns(df ,table_name, database, max_new=5):
105
-
106
- # df字段
107
- df_cols = set(df.columns)
108
- # 数据库字段
109
- db_cols = set(get_table_columns(table_name, database))
110
- # 新增字段
111
- new_cols = df_cols - db_cols
112
-
113
- # 缺失字段(减少的字段,不处理)
114
- missing_cols = db_cols - df_cols
115
- print("新增字段:", new_cols if new_cols else "无")
116
- print("缺失字段(忽略):", missing_cols if missing_cols else "无")
117
-
118
- # 超限
119
- if len(new_cols) > max_new:
120
- raise Exception(f"新增字段超过{max_new}个: {new_cols}")
121
-
122
- # 自动补
123
- if 0 < len(new_cols) <= max_new:
124
-
125
- print("开始同步字段...")
126
- add_columns(table_name, database, new_cols)
127
- print("字段同步成功")
128
-
129
- return True
130
-
131
-
132
- # ===================== DataFrame 入库 =====================
133
-
134
- def update_datas(df, table_name, database):
135
-
136
- conn = None
137
- for i in range(2):
138
- try:
139
- # 表结构校验,df为抓取数据表,db_cols为数据库现有字段
140
- conn = _get_connection(database)
141
- cursor = conn.cursor()
142
- cols = list(df.columns)
143
- col_str = ",".join([f"`{c}`" for c in cols])
144
- value_tpl = "(" + ",".join(["%s"] * len(cols)) + ")"
145
- values_str = ",".join([value_tpl] * len(df))
146
- update_clause = ",".join(
147
- [f"`{c}`=VALUES(`{c}`)" for c in cols if c != "id"]
148
- )
149
- sql = f"""
150
- INSERT INTO `{table_name}` ({col_str})
151
- VALUES {values_str}
152
- ON DUPLICATE KEY UPDATE {update_clause}
153
- """
154
- data = [tuple(row) for row in df.values]
155
- flat_data = [v for row in data for v in row]
156
- cursor.execute(sql, flat_data)
157
- conn.commit()
158
- print(f"成功插入/更新 {cursor.rowcount} 条记录")
159
- break
160
- except Exception as e:
161
- if conn:
162
- conn.rollback()
163
- print("入库失败:", e)
164
- if '1054, "Unknown column' in str(e):
165
- check_and_sync_columns(df,table_name,database)
166
- else:
167
- raise Exception(e)
168
- finally:
169
- if conn:
170
- conn.close()
171
-
172
-
File without changes
File without changes
File without changes
File without changes