mysqlclient-client 1.0.0__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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 doctorgu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,296 @@
1
+ Metadata-Version: 2.4
2
+ Name: mysqlclient-client
3
+ Version: 1.0.0
4
+ Summary: MySQL helper function to run MySQL query with #if support
5
+ Author-email: Gu Park <doctorgu@kakao.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 doctorgu
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: homepage, https://github.com/doctorgu/mysqlclient-client
29
+ Project-URL: repository, https://github.com/doctorgu/mysqlclient-client
30
+ Project-URL: documentation, https://github.com/doctorgu/mysqlclient-client
31
+ Keywords: mysqlclient client,mysqlclient helper,mysql helper
32
+ Requires-Python: >=3.11
33
+ Description-Content-Type: text/markdown
34
+ License-File: LICENSE
35
+ Requires-Dist: mysqlclient
36
+ Requires-Dist: pyhumps
37
+ Requires-Dist: typing-extensions
38
+ Requires-Dist: python-dotenv
39
+ Requires-Dist: pydantic-settings
40
+ Requires-Dist: Flask
41
+ Requires-Dist: PyYAML
42
+ Requires-Dist: ruff
43
+ Provides-Extra: test
44
+ Requires-Dist: pytest; extra == "test"
45
+ Requires-Dist: pytest-cov; extra == "test"
46
+ Requires-Dist: pytest-env; extra == "test"
47
+ Requires-Dist: pytest-mock; extra == "test"
48
+ Requires-Dist: pytest-asyncio; extra == "test"
49
+ Requires-Dist: build; extra == "test"
50
+ Dynamic: license-file
51
+
52
+ # MysqlclientClient — Modern MySQL Helper for Python
53
+
54
+ A lightweight, opinionated wrapper around **mysqlclient** (`MySQLdb`) with built-in support for:
55
+
56
+ - Connection pooling (`minconn` / `maxconn`)
57
+ - Query dictionary management
58
+ - Conditional SQL (`#if` / `#elif` / `#endif`)
59
+ - Bilingual column aliases (`en|ko`)
60
+ - Simple transaction handling via context manager
61
+ - Safe parameter binding (`%(param)s` syntax)
62
+ - Streaming CSV export support
63
+
64
+ > Successor-friendly alternative to raw mysqlclient with better developer experience.
65
+
66
+ ## Installation
67
+
68
+ ```bash
69
+ pip install mysqlclient-client
70
+ ```
71
+
72
+ > Note: `mysqlclient-client` is a custom helper class. See full source in repository.
73
+
74
+ ## Quick Start
75
+
76
+ ### 1. Define Queries
77
+
78
+ YAML format in `queries` folder (or dictionary):
79
+
80
+ ```yaml
81
+ - name: read_user_id_all
82
+ value: |
83
+ SELECT user_id
84
+ FROM t_user
85
+
86
+ - name: upsert_user
87
+ value: |
88
+ INSERT INTO t_user
89
+ (
90
+ user_id, user_name, user_rank
91
+ )
92
+ VALUES
93
+ (
94
+ %(user_id)s, %(user_name)s, %(user_rank)s
95
+ )
96
+ ON DUPLICATE KEY UPDATE
97
+ user_name = %(user_name)s,
98
+ user_rank = %(user_rank)s,
99
+ update_time = CURRENT_TIMESTAMP
100
+ ```
101
+
102
+ ### 2. Configure Database Connection
103
+
104
+ ```python
105
+ from mysqlclient_client.settings import Settings
106
+
107
+ db_settings = Settings(
108
+ host="127.0.0.1",
109
+ port=3306,
110
+ database="test",
111
+ user="root",
112
+ password="password",
113
+ minconn=3,
114
+ maxconn=10,
115
+ connect_timeout=5,
116
+ use_en_ko_column_alias=True,
117
+ use_conditional=True,
118
+ all_query=qry_dic,
119
+ before_read_execute=lambda qry_key, params, qry_str, qry_with_value: print(
120
+ f'READ_ROWS_START, QRY_KEY: "{qry_key}", QRY_WITH_VALUE: {qry_with_value}'
121
+ ),
122
+ after_read_execute=lambda qry_key, duration: print(
123
+ f'READ_ROWS_END, QRY_KEY: "{qry_key}", DURATION: {duration}'
124
+ ),
125
+ before_update_execute=lambda qry_key, params, params_out, qry_str, qry_with_value: (
126
+ print(f'UPDATES_START, QRY_KEY: "{qry_key}", QRY_WITH_VALUE: {qry_with_value}')
127
+ ),
128
+ after_update_execute=lambda qry_key, row_count, params_out, duration: print(
129
+ f'UPDATES_END, QRY_KEY: "{qry_key}", DURATION: {duration}'
130
+ ),
131
+ )
132
+ ```
133
+
134
+ ### 3. Basic Usage
135
+
136
+ ```python
137
+ from mysqlclient_client.client import Client
138
+
139
+ db = Client(db_settings=db_settings)
140
+
141
+ # Read single row
142
+ row = db.read_row("read_user_id_all", {})
143
+ print(row) # {'user_id': 'gildong.hong'}
144
+
145
+ # Read all rows
146
+ rows = db.read_rows("read_user_id_all", {})
147
+ print(rows[:2])
148
+ ```
149
+
150
+ ## Create / Update / Delete Operations
151
+
152
+ ### `update()` — Single CUD Statement
153
+
154
+ Returns affected row count:
155
+
156
+ ```python
157
+ affected = db.update(
158
+ "upsert_user", {"user_id": "gildong.hong", "user_name": "홍길동", "user_rank": 1}
159
+ )
160
+ print("Affected rows:", affected) # 1
161
+ ```
162
+
163
+ ### Capture Output Parameters
164
+
165
+ ```python
166
+ params_out = {"user_name": "", "user_rank": 0}
167
+ db.update(
168
+ "upsert_user",
169
+ {"user_id": "gildong.hong", "user_name": "홍길동", "user_rank": 1},
170
+ params_out=params_out,
171
+ )
172
+ print("Returned name:", params_out["user_name"], params_out["user_rank"])
173
+ ```
174
+
175
+ ### `updates()` — Batch Execution
176
+
177
+ ```python
178
+ batch = [
179
+ ("upsert_user", {"user_id": "sunja.kim", "user_name": "김순자", "user_rank": 2}),
180
+ ("upsert_user", {"user_id": "malja.kim", "user_name": "김말자", "user_rank": 3}),
181
+ ]
182
+
183
+ results = db.updates(batch)
184
+ print("Batch results:", results) # [1, 1]
185
+ ```
186
+
187
+ ## Transaction Support with `with`
188
+
189
+ Automatically commits on success, rolls back on exception:
190
+
191
+ ```python
192
+ with Client(db_settings=db_settings) as db:
193
+ new_id = "youngja.lee"
194
+ db.update("upsert_user", {"user_id": new_id, "user_name": "이영자", "user_rank": 4})
195
+ db.update("delete_user", {"user_id": new_id})
196
+ print("Committed successfully")
197
+ ```
198
+
199
+ ## Partially return CSV
200
+
201
+ Read rows partially and return immediately to client to show progress:
202
+
203
+ ```python
204
+ # Flask
205
+ @app.route("/read-csv-partial")
206
+ def read_csv_partial():
207
+ """read csv partial"""
208
+
209
+ db_client = Client(db_settings=db_settings)
210
+ filename = f"{datetime.now(UTC).strftime('%Y%m%d%H%M%S')}.csv"
211
+
212
+ return Response(
213
+ db_client.read_csv_partial("read_csv_partial", {}),
214
+ mimetype="text/csv",
215
+ headers={
216
+ "Access-Control-Expose-Headers": "Content-Disposition",
217
+ "Content-Disposition": f'attachment; filename="{filename}"',
218
+ "Cache-Control": "no-cache, no-store, must-revalidate",
219
+ "Pragma": "no-cache",
220
+ "Expires": "0",
221
+ "X-Accel-Buffering": "no",
222
+ "Transfer-Encoding": "chunked",
223
+ },
224
+ )
225
+ ```
226
+
227
+ ## Bilingual Column Aliases (English ↔ Korean)
228
+
229
+ Enabled when `use_en_ko_column_alias=True` and `en` not omitted:
230
+
231
+ ```yaml
232
+ - name: read_user_alias
233
+ value: |
234
+ SELECT user_id "Id|아이디", user_name "Name|이름", user_rank "Rank|순위"
235
+ FROM t_user
236
+ WHERE user_id = %(user_id)s
237
+ ```
238
+
239
+ ### English mode (`en=True`)
240
+
241
+ ```python
242
+ rows = db.read_rows("read_user_alias", {"user_id": "gildong.hong"}, en=True)
243
+ print(rows[0])
244
+ # {'Id': 'gildong.hong', 'Name': '홍길동', 'Rank': 1}
245
+ ```
246
+
247
+ ### Korean mode (`en=False`)
248
+
249
+ ```python
250
+ rows = db.read_rows("read_user_alias", {"user_id": "gildong.hong"}, en=False)
251
+ print(rows[0])
252
+ # {'아이디': 'gildong.hong', '이름': '홍길동', '순위': 1}
253
+ ```
254
+
255
+ ## Conditional SQL (`#if`, `#elif`, `#endif`)
256
+
257
+ Enabled when `use_conditional=True`:
258
+
259
+ ```yaml
260
+ - name: read_user_search
261
+ value: |
262
+ SELECT user_id, user_name, user_rank, insert_time, update_time
263
+ FROM t_user
264
+ WHERE 1 = 1
265
+ #if user_id
266
+ AND user_id = %(user_id)s
267
+ #elif user_name
268
+ AND user_name LIKE %(user_name)s
269
+ #elif user_rank
270
+ AND user_rank <= %(user_rank)s
271
+ #endif
272
+ ```
273
+
274
+ ## Safety & Security
275
+
276
+ The `#if` preprocessor only allows parameter names, string literals, numbers, and basic boolean operators. Any attempt to inject raw SQL will raise a parsing error before execution.
277
+
278
+ ## Features Summary
279
+
280
+ | Feature | Notes |
281
+ | ----------------------------- | ------------------------------------------------------------------------------- |
282
+ | Connection pooling | Thread-safe pool via `minconn` / `maxconn` |
283
+ | Named queries | Stored in YAML / dictionary |
284
+ | Single-row / multi-row fetch | `read_row()` / `read_rows()` |
285
+ | Single / batch CUD operations | `update()` / `updates()` |
286
+ | Output parameters | Via `params_out` dict |
287
+ | Transactions via `with` | Auto rollback on exception |
288
+ | Partially return CSV | `read_csv_partial` / `read_csv_partial_async` |
289
+ | Bilingual column aliases | `"Name\|이름"` syntax |
290
+ | Conditional SQL | `#if` / `#elif` / `#endif` |
291
+ | Logging support | Before and after execute hooks via `before...` and `after...` callables |
292
+ | SQL injection protection | Strict parsing in conditionals |
293
+
294
+ ## License
295
+
296
+ MIT
@@ -0,0 +1,245 @@
1
+ # MysqlclientClient — Modern MySQL Helper for Python
2
+
3
+ A lightweight, opinionated wrapper around **mysqlclient** (`MySQLdb`) with built-in support for:
4
+
5
+ - Connection pooling (`minconn` / `maxconn`)
6
+ - Query dictionary management
7
+ - Conditional SQL (`#if` / `#elif` / `#endif`)
8
+ - Bilingual column aliases (`en|ko`)
9
+ - Simple transaction handling via context manager
10
+ - Safe parameter binding (`%(param)s` syntax)
11
+ - Streaming CSV export support
12
+
13
+ > Successor-friendly alternative to raw mysqlclient with better developer experience.
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ pip install mysqlclient-client
19
+ ```
20
+
21
+ > Note: `mysqlclient-client` is a custom helper class. See full source in repository.
22
+
23
+ ## Quick Start
24
+
25
+ ### 1. Define Queries
26
+
27
+ YAML format in `queries` folder (or dictionary):
28
+
29
+ ```yaml
30
+ - name: read_user_id_all
31
+ value: |
32
+ SELECT user_id
33
+ FROM t_user
34
+
35
+ - name: upsert_user
36
+ value: |
37
+ INSERT INTO t_user
38
+ (
39
+ user_id, user_name, user_rank
40
+ )
41
+ VALUES
42
+ (
43
+ %(user_id)s, %(user_name)s, %(user_rank)s
44
+ )
45
+ ON DUPLICATE KEY UPDATE
46
+ user_name = %(user_name)s,
47
+ user_rank = %(user_rank)s,
48
+ update_time = CURRENT_TIMESTAMP
49
+ ```
50
+
51
+ ### 2. Configure Database Connection
52
+
53
+ ```python
54
+ from mysqlclient_client.settings import Settings
55
+
56
+ db_settings = Settings(
57
+ host="127.0.0.1",
58
+ port=3306,
59
+ database="test",
60
+ user="root",
61
+ password="password",
62
+ minconn=3,
63
+ maxconn=10,
64
+ connect_timeout=5,
65
+ use_en_ko_column_alias=True,
66
+ use_conditional=True,
67
+ all_query=qry_dic,
68
+ before_read_execute=lambda qry_key, params, qry_str, qry_with_value: print(
69
+ f'READ_ROWS_START, QRY_KEY: "{qry_key}", QRY_WITH_VALUE: {qry_with_value}'
70
+ ),
71
+ after_read_execute=lambda qry_key, duration: print(
72
+ f'READ_ROWS_END, QRY_KEY: "{qry_key}", DURATION: {duration}'
73
+ ),
74
+ before_update_execute=lambda qry_key, params, params_out, qry_str, qry_with_value: (
75
+ print(f'UPDATES_START, QRY_KEY: "{qry_key}", QRY_WITH_VALUE: {qry_with_value}')
76
+ ),
77
+ after_update_execute=lambda qry_key, row_count, params_out, duration: print(
78
+ f'UPDATES_END, QRY_KEY: "{qry_key}", DURATION: {duration}'
79
+ ),
80
+ )
81
+ ```
82
+
83
+ ### 3. Basic Usage
84
+
85
+ ```python
86
+ from mysqlclient_client.client import Client
87
+
88
+ db = Client(db_settings=db_settings)
89
+
90
+ # Read single row
91
+ row = db.read_row("read_user_id_all", {})
92
+ print(row) # {'user_id': 'gildong.hong'}
93
+
94
+ # Read all rows
95
+ rows = db.read_rows("read_user_id_all", {})
96
+ print(rows[:2])
97
+ ```
98
+
99
+ ## Create / Update / Delete Operations
100
+
101
+ ### `update()` — Single CUD Statement
102
+
103
+ Returns affected row count:
104
+
105
+ ```python
106
+ affected = db.update(
107
+ "upsert_user", {"user_id": "gildong.hong", "user_name": "홍길동", "user_rank": 1}
108
+ )
109
+ print("Affected rows:", affected) # 1
110
+ ```
111
+
112
+ ### Capture Output Parameters
113
+
114
+ ```python
115
+ params_out = {"user_name": "", "user_rank": 0}
116
+ db.update(
117
+ "upsert_user",
118
+ {"user_id": "gildong.hong", "user_name": "홍길동", "user_rank": 1},
119
+ params_out=params_out,
120
+ )
121
+ print("Returned name:", params_out["user_name"], params_out["user_rank"])
122
+ ```
123
+
124
+ ### `updates()` — Batch Execution
125
+
126
+ ```python
127
+ batch = [
128
+ ("upsert_user", {"user_id": "sunja.kim", "user_name": "김순자", "user_rank": 2}),
129
+ ("upsert_user", {"user_id": "malja.kim", "user_name": "김말자", "user_rank": 3}),
130
+ ]
131
+
132
+ results = db.updates(batch)
133
+ print("Batch results:", results) # [1, 1]
134
+ ```
135
+
136
+ ## Transaction Support with `with`
137
+
138
+ Automatically commits on success, rolls back on exception:
139
+
140
+ ```python
141
+ with Client(db_settings=db_settings) as db:
142
+ new_id = "youngja.lee"
143
+ db.update("upsert_user", {"user_id": new_id, "user_name": "이영자", "user_rank": 4})
144
+ db.update("delete_user", {"user_id": new_id})
145
+ print("Committed successfully")
146
+ ```
147
+
148
+ ## Partially return CSV
149
+
150
+ Read rows partially and return immediately to client to show progress:
151
+
152
+ ```python
153
+ # Flask
154
+ @app.route("/read-csv-partial")
155
+ def read_csv_partial():
156
+ """read csv partial"""
157
+
158
+ db_client = Client(db_settings=db_settings)
159
+ filename = f"{datetime.now(UTC).strftime('%Y%m%d%H%M%S')}.csv"
160
+
161
+ return Response(
162
+ db_client.read_csv_partial("read_csv_partial", {}),
163
+ mimetype="text/csv",
164
+ headers={
165
+ "Access-Control-Expose-Headers": "Content-Disposition",
166
+ "Content-Disposition": f'attachment; filename="{filename}"',
167
+ "Cache-Control": "no-cache, no-store, must-revalidate",
168
+ "Pragma": "no-cache",
169
+ "Expires": "0",
170
+ "X-Accel-Buffering": "no",
171
+ "Transfer-Encoding": "chunked",
172
+ },
173
+ )
174
+ ```
175
+
176
+ ## Bilingual Column Aliases (English ↔ Korean)
177
+
178
+ Enabled when `use_en_ko_column_alias=True` and `en` not omitted:
179
+
180
+ ```yaml
181
+ - name: read_user_alias
182
+ value: |
183
+ SELECT user_id "Id|아이디", user_name "Name|이름", user_rank "Rank|순위"
184
+ FROM t_user
185
+ WHERE user_id = %(user_id)s
186
+ ```
187
+
188
+ ### English mode (`en=True`)
189
+
190
+ ```python
191
+ rows = db.read_rows("read_user_alias", {"user_id": "gildong.hong"}, en=True)
192
+ print(rows[0])
193
+ # {'Id': 'gildong.hong', 'Name': '홍길동', 'Rank': 1}
194
+ ```
195
+
196
+ ### Korean mode (`en=False`)
197
+
198
+ ```python
199
+ rows = db.read_rows("read_user_alias", {"user_id": "gildong.hong"}, en=False)
200
+ print(rows[0])
201
+ # {'아이디': 'gildong.hong', '이름': '홍길동', '순위': 1}
202
+ ```
203
+
204
+ ## Conditional SQL (`#if`, `#elif`, `#endif`)
205
+
206
+ Enabled when `use_conditional=True`:
207
+
208
+ ```yaml
209
+ - name: read_user_search
210
+ value: |
211
+ SELECT user_id, user_name, user_rank, insert_time, update_time
212
+ FROM t_user
213
+ WHERE 1 = 1
214
+ #if user_id
215
+ AND user_id = %(user_id)s
216
+ #elif user_name
217
+ AND user_name LIKE %(user_name)s
218
+ #elif user_rank
219
+ AND user_rank <= %(user_rank)s
220
+ #endif
221
+ ```
222
+
223
+ ## Safety & Security
224
+
225
+ The `#if` preprocessor only allows parameter names, string literals, numbers, and basic boolean operators. Any attempt to inject raw SQL will raise a parsing error before execution.
226
+
227
+ ## Features Summary
228
+
229
+ | Feature | Notes |
230
+ | ----------------------------- | ------------------------------------------------------------------------------- |
231
+ | Connection pooling | Thread-safe pool via `minconn` / `maxconn` |
232
+ | Named queries | Stored in YAML / dictionary |
233
+ | Single-row / multi-row fetch | `read_row()` / `read_rows()` |
234
+ | Single / batch CUD operations | `update()` / `updates()` |
235
+ | Output parameters | Via `params_out` dict |
236
+ | Transactions via `with` | Auto rollback on exception |
237
+ | Partially return CSV | `read_csv_partial` / `read_csv_partial_async` |
238
+ | Bilingual column aliases | `"Name\|이름"` syntax |
239
+ | Conditional SQL | `#if` / `#elif` / `#endif` |
240
+ | Logging support | Before and after execute hooks via `before...` and `after...` callables |
241
+ | SQL injection protection | Strict parsing in conditionals |
242
+
243
+ ## License
244
+
245
+ MIT