sqlite3-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) 2026 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,422 @@
1
+ Metadata-Version: 2.4
2
+ Name: sqlite3-client
3
+ Version: 1.0.0
4
+ Summary: Sqlite3 helper function to run SQLite query with #if support
5
+ Author-email: Gu Park <doctorgu@kakao.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 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/sqlite3-client
29
+ Project-URL: repository, https://github.com/doctorgu/sqlite3-client
30
+ Project-URL: documentation, https://github.com/doctorgu/sqlite3-client
31
+ Keywords: sqlite3 client,sqlite3 helper
32
+ Requires-Python: >=3.11
33
+ Description-Content-Type: text/markdown
34
+ License-File: LICENSE
35
+ Requires-Dist: pyhumps
36
+ Requires-Dist: typing-extensions
37
+ Requires-Dist: python-dotenv
38
+ Requires-Dist: pydantic-settings
39
+ Requires-Dist: Flask
40
+ Requires-Dist: ruff
41
+ Provides-Extra: test
42
+ Requires-Dist: pytest; extra == "test"
43
+ Requires-Dist: pytest-cov; extra == "test"
44
+ Requires-Dist: pytest-env; extra == "test"
45
+ Requires-Dist: pytest-mock; extra == "test"
46
+ Requires-Dist: pytest-asyncio; extra == "test"
47
+ Requires-Dist: build; extra == "test"
48
+ Dynamic: license-file
49
+
50
+ # Sqlite3Client — Modern SQLite Helper for Python
51
+
52
+ A lightweight, opinionated wrapper around **sqlite3** with built-in support for:
53
+
54
+ - Connection pooling (`minconn` / `maxconn`)
55
+ - Query dictionary management
56
+ - Conditional SQL (`#if` / `#elif` / `#endif`)
57
+ - Bilingual column aliases (`en|ko`)
58
+ - Simple transaction handling via context manager
59
+ - Safe parameter binding (`:param` syntax)
60
+ - Streaming CSV export support
61
+
62
+ > Successor-friendly alternative to raw sqlite3 with better developer experience.
63
+
64
+ ## Installation
65
+
66
+ ```bash
67
+ pip install sqlite3-client
68
+ ```
69
+
70
+ > Note: `sqlite3-client` is a custom helper class. See full source in repository.
71
+
72
+ ## Quick Start
73
+
74
+ ### 1. Define Queries
75
+
76
+ ```python
77
+ qry_dic: dict[str, str] = {}
78
+
79
+ qry_dic.update(
80
+ {
81
+ "read_user_id_all": """
82
+ SELECT user_id
83
+ FROM t_user
84
+ """
85
+ }
86
+ )
87
+
88
+ qry_dic.update(
89
+ {
90
+ "upsert_user": """
91
+ INSERT INTO t_user
92
+ (
93
+ user_id, user_name, user_rank
94
+ )
95
+ VALUES
96
+ (
97
+ :user_id, :user_name, :user_rank
98
+ )
99
+ ON CONFLICT (user_id)
100
+ DO UPDATE
101
+ SET user_name = :user_name,
102
+ user_rank = :user_rank,
103
+ update_time = CURRENT_TIMESTAMP
104
+ RETURNING user_name, user_rank;
105
+ """
106
+ }
107
+ )
108
+ ```
109
+
110
+ ### 2. Configure Database Connection
111
+
112
+ ```python
113
+ from sqlite3_client.settings import Settings
114
+
115
+ db_settings = Settings(
116
+ database="test.db",
117
+ minconn=3,
118
+ maxconn=10,
119
+ connect_timeout=5,
120
+ use_en_ko_column_alias=True,
121
+ use_conditional=True,
122
+ all_query=qry_dic,
123
+ before_read_execute=lambda qry_key, params, qry_str, qry_with_value: print(
124
+ f'READ_ROWS_START, QRY_KEY: "{qry_key}", QRY_WITH_VALUE: {qry_with_value}'
125
+ ),
126
+ after_read_execute=lambda qry_key, duration: print(
127
+ f'READ_ROWS_END, QRY_KEY: "{qry_key}", DURATION: {duration}'
128
+ ),
129
+ before_update_execute=lambda qry_key, params, params_out, qry_str, qry_with_value: (
130
+ print(f'UPDATES_START, QRY_KEY: "{qry_key}", QRY_WITH_VALUE: {qry_with_value}')
131
+ ),
132
+ after_update_execute=lambda qry_key, row_count, params_out, duration: print(
133
+ f'UPDATES_END, QRY_KEY: "{qry_key}", DURATION: {duration}'
134
+ ),
135
+ )
136
+ ```
137
+
138
+ ### 3. Basic Usage
139
+
140
+ ```python
141
+ from sqlite3_client.client import Client
142
+
143
+ db = Client(db_settings=db_settings)
144
+
145
+ # Read single row
146
+ row = db.read_row("read_user_id_all", {})
147
+ print(row) # {'user_id': 'gildong.hong'}
148
+
149
+ # Read all rows
150
+ rows = db.read_rows("read_user_id_all", {})
151
+ print(rows[:2])
152
+ ```
153
+
154
+ ## Create / Update / Delete Operations
155
+
156
+ ### `update()` — Single CUD Statement
157
+
158
+ Returns affected row count:
159
+
160
+ ```python
161
+ affected = db.update(
162
+ "upsert_user", {"user_id": "gildong.hong", "user_name": "홍길동", "user_rank": 1}
163
+ )
164
+ print("Affected rows:", affected) # 1
165
+ ```
166
+
167
+ ### Capture Output Parameters
168
+
169
+ ```python
170
+ params_out = {"user_name": "", "user_rank": 0}
171
+ db.update(
172
+ "upsert_user",
173
+ {"user_id": "gildong.hong", "user_name": "홍길동", "user_rank": 1},
174
+ params_out=params_out,
175
+ )
176
+ print("Returned name:", params_out["user_name"], params_out["user_rank"]) # 홍길동 1
177
+ ```
178
+
179
+ ### `updates()` — Batch Execution
180
+
181
+ ```python
182
+ batch = [
183
+ ("upsert_user", {"user_id": "sunja.kim", "user_name": "김순자", "user_rank": 2}),
184
+ ("upsert_user", {"user_id": "malja.kim", "user_name": "김말자", "user_rank": 3}),
185
+ ]
186
+
187
+ results = db.updates(batch)
188
+ print("Batch results:", results) # [1, 1]
189
+ ```
190
+
191
+ ## Transaction Support with `with`
192
+
193
+ Automatically commits on success, rolls back on exception:
194
+
195
+ ```python
196
+ with Client(db_settings=db_settings) as db:
197
+ new_id = "youngja.lee"
198
+ db.update("upsert_user", {"user_id": new_id, "user_name": "이영자", "user_rank": 4})
199
+ db.update("delete_user", {"user_id": new_id}) # Oops! Will rollback entire block
200
+ print("This won't print if error occurs")
201
+ ```
202
+
203
+ ## Partially return CSV
204
+
205
+ Read rows partially and return immediately to client to show progress in client:
206
+
207
+ ```python
208
+ # Flask
209
+ @app.route("/read-csv-partial")
210
+ def read_csv_partial():
211
+ """read csv partial"""
212
+
213
+ db_client = Client(db_settings=db_settings)
214
+ filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}.csv"
215
+
216
+ return Response(
217
+ db_client.read_csv_partial("read_csv_partial", {}),
218
+ mimetype="text/csv",
219
+ headers={
220
+ # if FE and BE are on different origins,
221
+ # server must expose the Content-Disposition header
222
+ "Access-Control-Expose-Headers": "Content-Disposition",
223
+ "Content-Disposition": f'attachment; filename="{filename}"',
224
+ # Very important for progressive saving in many browsers
225
+ "Cache-Control": "no-cache, no-store, must-revalidate",
226
+ "Pragma": "no-cache",
227
+ "Expires": "0",
228
+ "X-Accel-Buffering": "no", # Important if using nginx
229
+ "Transfer-Encoding": "chunked",
230
+ },
231
+ )
232
+
233
+
234
+ # Fast API
235
+ @router.get("/read-csv-partial-async")
236
+ async def read_csv_partial_async():
237
+ """read csv partial async"""
238
+
239
+ db_client = Client(db_settings=db_settings)
240
+ filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}.csv"
241
+
242
+ return StreamingResponse(
243
+ content=db_client.read_csv_partial_async("read_csv_partial", {}),
244
+ media_type="text/csv",
245
+ headers={
246
+ # if FE and BE are on different origins,
247
+ # server must expose the Content-Disposition header
248
+ "Access-Control-Expose-Headers": "Content-Disposition",
249
+ "Content-Disposition": f'attachment; filename="{filename}"',
250
+ # Very important for progressive saving in many browsers
251
+ "Cache-Control": "no-cache, no-store, must-revalidate",
252
+ "Pragma": "no-cache",
253
+ "Expires": "0",
254
+ "X-Accel-Buffering": "no", # Important if using nginx
255
+ "Transfer-Encoding": "chunked",
256
+ },
257
+ )
258
+ ```
259
+
260
+ ## Bilingual Column Aliases (English ↔ Korean)
261
+
262
+ Enabled when `use_en_ko_column_alias=True` and `en` not omitted:
263
+
264
+ ```python
265
+ qry_dic.update(
266
+ {
267
+ "read_user_alias": """
268
+ SELECT user_id "Id|아이디", user_name "Name|이름", user_rank "Rank|순위"
269
+ FROM t_user
270
+ WHERE user_id = :user_id
271
+ """
272
+ }
273
+ )
274
+ ```
275
+
276
+ ### English mode (`en=True`)
277
+
278
+ ```python
279
+ rows = db.read_rows("read_user_alias", {"user_id": "gildong.hong"}, en=True)
280
+ print(rows[0])
281
+ # {'Id': 'gildong.hong', 'Name': '홍길동'}
282
+ ```
283
+
284
+ ### Korean mode (`en=False`)
285
+
286
+ ```python
287
+ rows = db.read_rows("read_user_alias", {"user_id": "gildong.hong"}, en=False)
288
+ print(rows[0])
289
+ # {'아이디': 'gildong.hong', '이름': '홍길동'}
290
+ ```
291
+
292
+ ## Conditional SQL (`#if`, `#elif`, `#endif`)
293
+
294
+ Enabled when `use_conditional=True`:
295
+
296
+ ```python
297
+ qry_dic.update(
298
+ {
299
+ "read_user_search": """
300
+ SELECT user_id, user_name, user_rank, insert_time, update_time
301
+ FROM t_user
302
+ WHERE 1 = 1
303
+ #if user_id
304
+ AND user_id = :user_id
305
+ #elif user_name
306
+ AND user_name LIKE :user_name
307
+ #elif user_rank
308
+ AND user_rank <= :user_rank
309
+ #endif
310
+ """
311
+ }
312
+ )
313
+ ```
314
+
315
+ ### Example: Search by `user_id`
316
+
317
+ ```python
318
+ rows = db.read_rows(
319
+ "read_user_search", {"user_id": "gildong.hong", "user_name": "", "user_rank": 0}
320
+ )
321
+ print([r["user_name"] for r in rows])
322
+ # ['홍길동']
323
+ ```
324
+
325
+ ### Example: Search by `user_name` (partial match)
326
+
327
+ ```python
328
+ rows = db.read_rows(
329
+ "read_user_search", {"user_id": "", "user_name": "%김%", "user_rank": 0}
330
+ )
331
+ print([r["user_name"] for r in rows])
332
+ # ['김순자', '김말자']
333
+ ```
334
+
335
+ ### Example: Search by `user_rank` (partial match)
336
+
337
+ ```python
338
+ rows = db.read_rows(
339
+ "read_user_search", {"user_id": "", "user_name": "", "user_rank": 3}
340
+ )
341
+ print([r["user_name"] for r in rows])
342
+ # ['홍길동', '김순자', '김말자']
343
+ ```
344
+
345
+ ## Logging support
346
+
347
+ - `before_read_execute` called before execute query for read
348
+ - `after_read_execute` called after execute query for read
349
+ - `before_update_execute` called before execute query for CUD
350
+ - `after_update_execute` called after execute query for CUD
351
+
352
+ Can be replaced `print` with `logger`:
353
+
354
+ ### Example: Use logger to write debug info
355
+
356
+ ```python
357
+ import logging
358
+
359
+
360
+ def get_sql_logger(name="sql"):
361
+ logger = logging.getLogger(name)
362
+ if not logger.handlers:
363
+ logging.basicConfig(
364
+ filename="sql.log",
365
+ level=logging.DEBUG,
366
+ format="%(asctime)s [%(levelname)7s] %(message)s",
367
+ encoding="utf-8",
368
+ )
369
+ return logger
370
+
371
+
372
+ logger = get_sql_logger()
373
+ db_settings.before_read_execute = lambda qry_key, params, qry_str, qry_with_value: (
374
+ logger.debug(
375
+ f'READ_ROWS_START, QRY_KEY: "{qry_key}", QRY_WITH_VALUE: {qry_with_value}'
376
+ )
377
+ )
378
+ ```
379
+
380
+ ## Safety & Security
381
+
382
+ ### Q: Is conditional SQL safe from injection?
383
+
384
+ **A: Yes — completely safe.**
385
+
386
+ The `#if` preprocessor **only allows**:
387
+
388
+ - Parameter names (e.g. `user_id` or `:user_id`)
389
+ - String literals (`'active'`, `"pending"`)
390
+ - Numbers and basic operators
391
+ - Whitespace and comments
392
+
393
+ Any attempt to inject raw SQL will raise a parsing error **before** execution.
394
+
395
+ ```python
396
+ # This will RAISE an exception "ValueError: 'user_id;' not in ..." (not execute!)
397
+ "#if user_id; DROP TABLE t_user; --"
398
+ ```
399
+
400
+ ## Features Summary
401
+
402
+ | Feature | Notes |
403
+ | ----------------------------- | ------------------------------------------------------------------------------- |
404
+ | Connection pooling | Via `minconn` / `maxconn` |
405
+ | Named queries | Stored in dictionary |
406
+ | Single-row / multi-row fetch | `read_row()` / `read_rows()` |
407
+ | Single / batch CUD operations | `update()` / `updates()` |
408
+ | Output parameters | Via `params_out` dict |
409
+ | Transactions via `with` | Auto rollback on exception |
410
+ | Partially return CSV | `read_csv_partial` / `read_csv_partial_async` |
411
+ | Bilingual column aliases | `"Name\|이름"` syntax |
412
+ | Conditional SQL | `#if` / `#elif` / `#endif` |
413
+ | Logging support | Before and after execute to DB via `before...` and `after...` callable function |
414
+ | SQL injection protection | Strict parsing in conditionals |
415
+
416
+ ## License
417
+
418
+ MIT (or as defined in your project)
419
+
420
+ ---
421
+
422
+ Made with ❤️ for cleaner, safer SQLite code in Python.