SQLPyHelper 0.1.7__py3-none-any.whl → 0.1.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.
sqlpyhelper/__init__.py CHANGED
@@ -1,6 +1,11 @@
1
1
  # Match the version in setup.py
2
- __version__ = "0.1.7"
2
+ __version__ = "0.1.9"
3
3
 
4
+ from sqlpyhelper.async_helper import ( # noqa: F401
5
+ AsyncConnectionError,
6
+ AsyncQueryError,
7
+ AsyncSQLPyHelper,
8
+ )
4
9
  from sqlpyhelper.db_helper import ( # noqa: F401
5
10
  BackupError,
6
11
  ConnectionError,
@@ -0,0 +1,598 @@
1
+ """
2
+ sqlpyhelper.async_helper
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~
4
+ Async-native database helper supporting SQLite, PostgreSQL, MySQL,
5
+ SQL Server, and Oracle.
6
+
7
+ Uses async-native drivers:
8
+ - SQLite: aiosqlite
9
+ - PostgreSQL: asyncpg
10
+ - MySQL: aiomysql
11
+ - SQL Server: aioodbc
12
+ - Oracle: python-oracledb (async mode)
13
+
14
+ Example usage::
15
+
16
+ import asyncio
17
+ from sqlpyhelper.async_helper import AsyncSQLPyHelper
18
+
19
+ async def main():
20
+ async with AsyncSQLPyHelper(db_type="sqlite", database="my.db") as db:
21
+ await db.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER, name TEXT)")
22
+ await db.execute("INSERT INTO users VALUES ($1, $2)", 1, "Alice")
23
+ rows = await db.fetch_all("SELECT * FROM users")
24
+ print(rows)
25
+
26
+ asyncio.run(main())
27
+ """
28
+
29
+ import logging
30
+ import os
31
+ from typing import Any, Optional
32
+
33
+ from dotenv import load_dotenv
34
+
35
+ load_dotenv()
36
+
37
+ logger = logging.getLogger("sqlpyhelper.async")
38
+
39
+
40
+ class AsyncConnectionError(Exception):
41
+ """Raised when an async database connection fails."""
42
+
43
+
44
+ class AsyncQueryError(Exception):
45
+ """Raised when an async query fails."""
46
+
47
+
48
+ class AsyncSQLPyHelper:
49
+ """
50
+ Async-native database helper with a unified API across
51
+ SQLite, PostgreSQL, MySQL, SQL Server, and Oracle.
52
+
53
+ Use as an async context manager::
54
+
55
+ async with AsyncSQLPyHelper(db_type="postgres", ...) as db:
56
+ rows = await db.fetch_all("SELECT * FROM users")
57
+
58
+ Or manage the connection lifecycle manually::
59
+
60
+ db = AsyncSQLPyHelper(db_type="sqlite", database="my.db")
61
+ await db.connect()
62
+ try:
63
+ rows = await db.fetch_all("SELECT * FROM users")
64
+ finally:
65
+ await db.close()
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ db_type: Optional[str] = None,
71
+ host: Optional[str] = None,
72
+ user: Optional[str] = None,
73
+ password: Optional[str] = None,
74
+ database: Optional[str] = None,
75
+ driver: Optional[str] = None,
76
+ port: Optional[str] = None,
77
+ oracle_sid: Optional[str] = None,
78
+ ) -> None:
79
+ self.db_type: str = (db_type or os.getenv("DB_TYPE") or "").lower()
80
+ self.host: Optional[str] = host or os.getenv("DB_HOST")
81
+ self.user: Optional[str] = user or os.getenv("DB_USER")
82
+ self.password: Optional[str] = password or os.getenv("DB_PASSWORD")
83
+ self.database: Optional[str] = database or os.getenv("DB_NAME")
84
+ self.driver: Optional[str] = driver or os.getenv("DB_DRIVER")
85
+ self.port: Optional[str] = port or os.getenv("DB_PORT")
86
+ self.oracle_sid: Optional[str] = oracle_sid or os.getenv("ORACLE_SID")
87
+
88
+ self._connection: Any = None
89
+ self._pool: Any = None
90
+
91
+ if not self.db_type or not self.database:
92
+ raise ValueError("Missing required database configuration.")
93
+
94
+ if self.db_type not in ("sqlite", "postgres", "mysql", "sqlserver", "oracle"):
95
+ raise ValueError(f"Unsupported database type: {self.db_type!r}")
96
+
97
+ # -----------------------------------------------------------------------
98
+ # Connection lifecycle
99
+ # -----------------------------------------------------------------------
100
+
101
+ async def connect(self) -> None:
102
+ """Open the database connection."""
103
+ try:
104
+ if self.db_type == "sqlite":
105
+ import aiosqlite
106
+
107
+ self._connection = await aiosqlite.connect(self.database or "") # type: ignore[arg-type]
108
+ logger.info("Connected to SQLite database: %s", self.database)
109
+
110
+ elif self.db_type == "postgres":
111
+ import asyncpg
112
+
113
+ self._connection = await asyncpg.connect(
114
+ host=self.host,
115
+ port=int(self.port or 5432),
116
+ user=self.user,
117
+ password=self.password,
118
+ database=self.database,
119
+ )
120
+ logger.info("Connected to PostgreSQL database: %s", self.database)
121
+
122
+ elif self.db_type == "mysql":
123
+ import aiomysql
124
+
125
+ self._connection = await aiomysql.connect(
126
+ host=self.host or "localhost",
127
+ port=int(self.port or 3306),
128
+ user=self.user,
129
+ password=self.password or "",
130
+ db=self.database,
131
+ autocommit=False,
132
+ )
133
+ logger.info("Connected to MySQL database: %s", self.database)
134
+
135
+ elif self.db_type == "sqlserver":
136
+ import aioodbc
137
+
138
+ dsn = (
139
+ f"DRIVER={self.driver};"
140
+ f"SERVER={self.host};"
141
+ f"DATABASE={self.database};"
142
+ f"UID={self.user};"
143
+ f"PWD={self.password}"
144
+ )
145
+ self._connection = await aioodbc.connect(dsn=dsn)
146
+ logger.info("Connected to SQL Server database: %s", self.database)
147
+
148
+ elif self.db_type == "oracle":
149
+ import oracledb
150
+
151
+ oracle_port = int(os.getenv("ORACLE_DB_PORT", "1521"))
152
+ dsn = oracledb.makedsn(
153
+ self.host, oracle_port, sid=self.oracle_sid # type: ignore[arg-type]
154
+ )
155
+ self._connection = await oracledb.connect_async(
156
+ user=self.user, password=self.password, dsn=dsn
157
+ )
158
+ logger.info("Connected to Oracle database: %s", self.oracle_sid)
159
+
160
+ except Exception as e:
161
+ raise AsyncConnectionError(
162
+ f"Failed to connect to {self.db_type}: {e}"
163
+ ) from e
164
+
165
+ async def close(self) -> None:
166
+ """Close the database connection."""
167
+ try:
168
+ if self._connection is not None:
169
+ await self._connection.close()
170
+ self._connection = None
171
+ logger.info("Closed %s connection", self.db_type)
172
+ except Exception as e:
173
+ raise AsyncConnectionError(f"Failed to close connection: {e}") from e
174
+
175
+ async def __aenter__(self) -> "AsyncSQLPyHelper":
176
+ await self.connect()
177
+ return self
178
+
179
+ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:
180
+ await self.close()
181
+ return False
182
+
183
+ # -----------------------------------------------------------------------
184
+ # Internal helpers
185
+ # -----------------------------------------------------------------------
186
+
187
+ def _check_connection(self) -> None:
188
+ if self._connection is None:
189
+ raise AsyncConnectionError(
190
+ "No active connection. Call connect() or use async with."
191
+ )
192
+
193
+ def _adapt_query(self, query: str, args: tuple) -> tuple[str, tuple]:
194
+ """
195
+ Adapt a query and its arguments for the active database driver.
196
+
197
+ asyncpg uses $1, $2, ... positional placeholders.
198
+ aiosqlite and aiomysql use ? and %s respectively.
199
+ Callers should write queries using $1, $2, ... style and this
200
+ method will translate as needed.
201
+ """
202
+ if not args:
203
+ return query, args
204
+
205
+ if self.db_type == "postgres":
206
+ # asyncpg natively uses $1, $2 — pass through unchanged
207
+ return query, args
208
+
209
+ elif self.db_type == "sqlite":
210
+ # Replace $1, $2 with ?
211
+ import re
212
+
213
+ adapted = re.sub(r"\$\d+", "?", query)
214
+ return adapted, args
215
+
216
+ elif self.db_type in ("mysql", "sqlserver"):
217
+ # Replace $1, $2 with %s
218
+ import re
219
+
220
+ adapted = re.sub(r"\$\d+", "%s", query)
221
+ return adapted, args
222
+
223
+ elif self.db_type == "oracle":
224
+ # Replace $1, $2 with :1, :2
225
+ import re
226
+
227
+ def replace_placeholder(m: Any) -> str:
228
+ return f":{m.group(0)[1:]}"
229
+
230
+ adapted = re.sub(r"\$(\d+)", replace_placeholder, query)
231
+ return adapted, args
232
+
233
+ return query, args
234
+
235
+ # -----------------------------------------------------------------------
236
+ # Query execution
237
+ # -----------------------------------------------------------------------
238
+
239
+ async def execute(self, query: str, *args: Any) -> None:
240
+ """
241
+ Execute a SQL statement (INSERT, UPDATE, DELETE, DDL).
242
+
243
+ Use $1, $2, ... for parameterised values::
244
+
245
+ await db.execute(
246
+ "INSERT INTO users (id, name) VALUES ($1, $2)",
247
+ 1, "Alice"
248
+ )
249
+
250
+ Args:
251
+ query: SQL query string using $1, $2 placeholders.
252
+ *args: Query parameters.
253
+
254
+ Raises:
255
+ AsyncQueryError: If the query fails.
256
+ """
257
+ self._check_connection()
258
+ adapted_query, adapted_args = self._adapt_query(query, args)
259
+ try:
260
+ if self.db_type == "postgres":
261
+ await self._connection.execute(adapted_query, *adapted_args)
262
+
263
+ elif self.db_type == "sqlite":
264
+ await self._connection.execute(adapted_query, adapted_args)
265
+ await self._connection.commit()
266
+
267
+ elif self.db_type in ("mysql", "sqlserver"):
268
+ async with self._connection.cursor() as cursor:
269
+ await cursor.execute(adapted_query, adapted_args)
270
+ await self._connection.commit()
271
+
272
+ elif self.db_type == "oracle":
273
+ cursor = self._connection.cursor()
274
+ await cursor.execute(adapted_query, adapted_args)
275
+ await self._connection.commit()
276
+
277
+ logger.debug("Executed: %s", query)
278
+
279
+ except Exception as e:
280
+ raise AsyncQueryError(f"Query failed: {e}") from e
281
+
282
+ async def fetch_one(self, query: str, *args: Any) -> Optional[Any]:
283
+ """
284
+ Execute a SELECT query and return a single row, or None.
285
+
286
+ Args:
287
+ query: SQL query string using $1, $2 placeholders.
288
+ *args: Query parameters.
289
+
290
+ Returns:
291
+ A single row, or None if no rows matched.
292
+
293
+ Raises:
294
+ AsyncQueryError: If the query fails.
295
+ """
296
+ self._check_connection()
297
+ adapted_query, adapted_args = self._adapt_query(query, args)
298
+ try:
299
+ if self.db_type == "postgres":
300
+ return await self._connection.fetchrow(adapted_query, *adapted_args)
301
+
302
+ elif self.db_type == "sqlite":
303
+ async with self._connection.execute(
304
+ adapted_query, adapted_args
305
+ ) as cursor:
306
+ return await cursor.fetchone()
307
+
308
+ elif self.db_type in ("mysql", "sqlserver"):
309
+ async with self._connection.cursor() as cursor:
310
+ await cursor.execute(adapted_query, adapted_args)
311
+ return await cursor.fetchone()
312
+
313
+ elif self.db_type == "oracle":
314
+ cursor = self._connection.cursor()
315
+ await cursor.execute(adapted_query, adapted_args)
316
+ return await cursor.fetchone()
317
+
318
+ return None
319
+
320
+ except Exception as e:
321
+ raise AsyncQueryError(f"fetch_one failed: {e}") from e
322
+
323
+ async def fetch_all(self, query: str, *args: Any) -> list[Any]:
324
+ """
325
+ Execute a SELECT query and return all rows.
326
+
327
+ Args:
328
+ query: SQL query string using $1, $2 placeholders.
329
+ *args: Query parameters.
330
+
331
+ Returns:
332
+ A list of rows (empty list if no rows matched).
333
+
334
+ Raises:
335
+ AsyncQueryError: If the query fails.
336
+ """
337
+ self._check_connection()
338
+ adapted_query, adapted_args = self._adapt_query(query, args)
339
+ try:
340
+ if self.db_type == "postgres":
341
+ return await self._connection.fetch(adapted_query, *adapted_args)
342
+
343
+ elif self.db_type == "sqlite":
344
+ async with self._connection.execute(
345
+ adapted_query, adapted_args
346
+ ) as cursor:
347
+ return await cursor.fetchall()
348
+
349
+ elif self.db_type in ("mysql", "sqlserver"):
350
+ async with self._connection.cursor() as cursor:
351
+ await cursor.execute(adapted_query, adapted_args)
352
+ return await cursor.fetchall()
353
+
354
+ elif self.db_type == "oracle":
355
+ cursor = self._connection.cursor()
356
+ await cursor.execute(adapted_query, adapted_args)
357
+ return await cursor.fetchall()
358
+
359
+ return []
360
+
361
+ except Exception as e:
362
+ raise AsyncQueryError(f"fetch_all failed: {e}") from e
363
+
364
+ async def fetch_val(self, query: str, *args: Any) -> Optional[Any]:
365
+ """
366
+ Execute a SELECT query and return a single scalar value.
367
+
368
+ Useful for COUNT, SUM, or any query returning one value::
369
+
370
+ count = await db.fetch_val("SELECT COUNT(*) FROM users")
371
+
372
+ Args:
373
+ query: SQL query string using $1, $2 placeholders.
374
+ *args: Query parameters.
375
+
376
+ Returns:
377
+ A single scalar value, or None.
378
+
379
+ Raises:
380
+ AsyncQueryError: If the query fails.
381
+ """
382
+ self._check_connection()
383
+ adapted_query, adapted_args = self._adapt_query(query, args)
384
+ try:
385
+ if self.db_type == "postgres":
386
+ return await self._connection.fetchval(adapted_query, *adapted_args)
387
+
388
+ elif self.db_type == "sqlite":
389
+ async with self._connection.execute(
390
+ adapted_query, adapted_args
391
+ ) as cursor:
392
+ row = await cursor.fetchone()
393
+ return row[0] if row else None
394
+
395
+ elif self.db_type in ("mysql", "sqlserver"):
396
+ async with self._connection.cursor() as cursor:
397
+ await cursor.execute(adapted_query, adapted_args)
398
+ row = await cursor.fetchone()
399
+ return row[0] if row else None
400
+
401
+ elif self.db_type == "oracle":
402
+ cursor = self._connection.cursor()
403
+ await cursor.execute(adapted_query, adapted_args)
404
+ row = await cursor.fetchone()
405
+ return row[0] if row else None
406
+
407
+ return None
408
+
409
+ except Exception as e:
410
+ raise AsyncQueryError(f"fetch_val failed: {e}") from e
411
+
412
+ async def execute_many(self, query: str, args_list: list[tuple]) -> None:
413
+ """
414
+ Execute a SQL statement multiple times with different parameters.
415
+ Efficient for bulk inserts::
416
+
417
+ await db.execute_many(
418
+ "INSERT INTO users (id, name) VALUES ($1, $2)",
419
+ [(1, "Alice"), (2, "Bob"), (3, "Charlie")]
420
+ )
421
+
422
+ Args:
423
+ query: SQL query string using $1, $2 placeholders.
424
+ args_list: List of parameter tuples.
425
+
426
+ Raises:
427
+ AsyncQueryError: If the operation fails.
428
+ """
429
+ self._check_connection()
430
+ if not args_list:
431
+ return
432
+ try:
433
+ if self.db_type == "postgres":
434
+ await self._connection.executemany(query, args_list)
435
+
436
+ elif self.db_type == "sqlite":
437
+ import re
438
+
439
+ adapted = re.sub(r"\$\d+", "?", query)
440
+ await self._connection.executemany(adapted, args_list)
441
+ await self._connection.commit()
442
+
443
+ elif self.db_type in ("mysql", "sqlserver"):
444
+ import re
445
+
446
+ adapted = re.sub(r"\$\d+", "%s", query)
447
+ async with self._connection.cursor() as cursor:
448
+ await cursor.executemany(adapted, args_list)
449
+ await self._connection.commit()
450
+
451
+ elif self.db_type == "oracle":
452
+ import re
453
+
454
+ def replace_placeholder(m: Any) -> str:
455
+ return f":{m.group(1)}"
456
+
457
+ adapted = re.sub(r"\$(\d+)", replace_placeholder, query)
458
+ cursor = self._connection.cursor()
459
+ await cursor.executemany(adapted, args_list)
460
+ await self._connection.commit()
461
+
462
+ logger.debug("execute_many: %d rows", len(args_list))
463
+
464
+ except Exception as e:
465
+ raise AsyncQueryError(f"execute_many failed: {e}") from e
466
+
467
+ # -----------------------------------------------------------------------
468
+ # Transaction management
469
+ # -----------------------------------------------------------------------
470
+
471
+ async def begin_transaction(self) -> None:
472
+ """
473
+ Begin an explicit transaction.
474
+
475
+ For PostgreSQL, use the transaction() context manager instead,
476
+ which is the idiomatic asyncpg approach.
477
+
478
+ Raises:
479
+ AsyncQueryError: If the transaction cannot be started.
480
+ """
481
+ self._check_connection()
482
+ try:
483
+ if self.db_type == "sqlite":
484
+ await self._connection.execute("BEGIN")
485
+ elif self.db_type == "mysql":
486
+ await self._connection.begin()
487
+ elif self.db_type == "sqlserver":
488
+ async with self._connection.cursor() as cursor:
489
+ await cursor.execute("BEGIN TRANSACTION")
490
+ elif self.db_type == "oracle":
491
+ pass # Oracle starts transactions implicitly
492
+ elif self.db_type == "postgres":
493
+ # asyncpg transactions are managed via connection.transaction()
494
+ # Calling begin() manually is supported but the context manager
495
+ # is preferred — see transaction() below
496
+ self._pg_transaction = self._connection.transaction()
497
+ await self._pg_transaction.start()
498
+ logger.info("Transaction started on %s", self.db_type)
499
+ except Exception as e:
500
+ raise AsyncQueryError(f"Failed to begin transaction: {e}") from e
501
+
502
+ async def commit_transaction(self) -> None:
503
+ """Commit the current transaction."""
504
+ self._check_connection()
505
+ try:
506
+ if self.db_type == "postgres":
507
+ await self._pg_transaction.commit()
508
+ else:
509
+ await self._connection.commit()
510
+ logger.info("Transaction committed on %s", self.db_type)
511
+ except Exception as e:
512
+ raise AsyncQueryError(f"Failed to commit transaction: {e}") from e
513
+
514
+ async def rollback_transaction(self) -> None:
515
+ """Roll back the current transaction."""
516
+ self._check_connection()
517
+ try:
518
+ if self.db_type == "postgres":
519
+ await self._pg_transaction.rollback()
520
+ else:
521
+ await self._connection.rollback()
522
+ logger.info("Transaction rolled back on %s", self.db_type)
523
+ except Exception as e:
524
+ raise AsyncQueryError(f"Failed to rollback transaction: {e}") from e
525
+
526
+ # -----------------------------------------------------------------------
527
+ # Connection pooling
528
+ # -----------------------------------------------------------------------
529
+
530
+ async def setup_pool(self, min_size: int = 1, max_size: int = 10) -> None:
531
+ """
532
+ Set up an async connection pool.
533
+
534
+ Supported for PostgreSQL and MySQL only.
535
+ After calling this, use get_connection_from_pool() to acquire
536
+ connections.
537
+
538
+ Args:
539
+ min_size: Minimum number of connections in the pool.
540
+ max_size: Maximum number of connections in the pool.
541
+
542
+ Raises:
543
+ AsyncConnectionError: If pool setup fails or db_type
544
+ does not support pooling.
545
+ """
546
+ try:
547
+ if self.db_type == "postgres":
548
+ import asyncpg
549
+
550
+ self._pool = await asyncpg.create_pool(
551
+ host=self.host,
552
+ port=int(self.port or 5432),
553
+ user=self.user,
554
+ password=self.password,
555
+ database=self.database,
556
+ min_size=min_size,
557
+ max_size=max_size,
558
+ )
559
+ logger.info(
560
+ "PostgreSQL async pool created (min=%d, max=%d)", min_size, max_size
561
+ )
562
+
563
+ elif self.db_type == "mysql":
564
+ import aiomysql
565
+
566
+ self._pool = await aiomysql.create_pool(
567
+ host=self.host or "localhost",
568
+ port=int(self.port or 3306),
569
+ user=self.user,
570
+ password=self.password or "",
571
+ db=self.database,
572
+ minsize=min_size,
573
+ maxsize=max_size,
574
+ )
575
+ logger.info(
576
+ "MySQL async pool created (min=%d, max=%d)", min_size, max_size
577
+ )
578
+
579
+ else:
580
+ raise AsyncConnectionError(
581
+ f"Async connection pooling not supported for {self.db_type!r}. "
582
+ "Supported: postgres, mysql."
583
+ )
584
+ except AsyncConnectionError:
585
+ raise
586
+ except Exception as e:
587
+ raise AsyncConnectionError(f"Failed to create async pool: {e}") from e
588
+
589
+ async def close_pool(self) -> None:
590
+ """Close the async connection pool."""
591
+ if self._pool is not None:
592
+ if self.db_type == "mysql":
593
+ self._pool.close()
594
+ await self._pool.wait_closed()
595
+ else:
596
+ await self._pool.close()
597
+ self._pool = None
598
+ logger.info("Async pool closed for %s", self.db_type)
sqlpyhelper/db_helper.py CHANGED
@@ -96,6 +96,7 @@ class SQLPyHelper:
96
96
  user=self.user,
97
97
  password=self.password,
98
98
  dbname=self.database,
99
+ port=self.port,
99
100
  )
100
101
  elif self.db_type == "mysql":
101
102
  import mysql.connector
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: SQLPyHelper
3
- Version: 0.1.7
3
+ Version: 0.1.9
4
4
  Summary: A simple SQL database helper package for Python.
5
5
  Home-page: https://github.com/adebayopeter/sqlpyhelper
6
6
  Author: Adebayo Olaonipekun
@@ -34,11 +34,28 @@ Provides-Extra: sqlserver
34
34
  Requires-Dist: pyodbc; extra == "sqlserver"
35
35
  Provides-Extra: oracle
36
36
  Requires-Dist: oracledb; extra == "oracle"
37
+ Provides-Extra: async-postgres
38
+ Requires-Dist: asyncpg; extra == "async-postgres"
39
+ Provides-Extra: async-mysql
40
+ Requires-Dist: aiomysql; extra == "async-mysql"
41
+ Provides-Extra: async-sqlite
42
+ Requires-Dist: aiosqlite; extra == "async-sqlite"
43
+ Provides-Extra: async-sqlserver
44
+ Requires-Dist: aioodbc; extra == "async-sqlserver"
45
+ Provides-Extra: async-all
46
+ Requires-Dist: asyncpg; extra == "async-all"
47
+ Requires-Dist: aiomysql; extra == "async-all"
48
+ Requires-Dist: aiosqlite; extra == "async-all"
49
+ Requires-Dist: aioodbc; extra == "async-all"
37
50
  Provides-Extra: all
38
51
  Requires-Dist: psycopg2; extra == "all"
39
52
  Requires-Dist: mysql-connector-python; extra == "all"
40
53
  Requires-Dist: pyodbc; extra == "all"
41
54
  Requires-Dist: oracledb; extra == "all"
55
+ Requires-Dist: asyncpg; extra == "all"
56
+ Requires-Dist: aiomysql; extra == "all"
57
+ Requires-Dist: aiosqlite; extra == "all"
58
+ Requires-Dist: aioodbc; extra == "all"
42
59
  Dynamic: author
43
60
  Dynamic: author-email
44
61
  Dynamic: classifier
@@ -84,6 +101,7 @@ with SQLPyHelper(db_type="postgres", host="localhost", user="user",
84
101
  - [MySQL Example](#mysql-example)
85
102
  - [SQL Server Example](#sql-server-example)
86
103
  - [Oracle Example](#oracle-example)
104
+ - [Async Example (FastAPI / asyncio)](#async-example-fastapi--asyncio)
87
105
  - [📂 Project Structure](#-project-structure)
88
106
  - [📌 Available Methods in SQLPyHelper](#-available-methods-in-sqlpyhelper)
89
107
  - [🌍 Contributing](#-contributing)
@@ -91,14 +109,16 @@ with SQLPyHelper(db_type="postgres", host="localhost", user="user",
91
109
 
92
110
  ---
93
111
 
94
- ## 🚀 Features in v0.1.4
95
- - Unified connection pooling for multiple databases.
96
- - Automatic reconnection for lost connections.
97
- - Transaction support (BEGIN, ROLLBACK, COMMIT).
98
- - Secure parameterized queries to prevent SQL injection.
99
- - Bulk insertion & dynamic table creation.
100
- - Logging & error handling for better debugging.
112
+ ## 🚀 Features in v0.1.8
113
+ - Unified connection pooling for multiple databases.
114
+ - Automatic reconnection for lost connections.
115
+ - Transaction support (BEGIN, ROLLBACK, COMMIT).
116
+ - Secure parameterized queries to prevent SQL injection.
117
+ - Bulk insertion & dynamic table creation.
118
+ - Logging & error handling for better debugging.
101
119
  - CSV export & database backups.
120
+ - **Cross-database migration** — copy tables between any two supported databases.
121
+ - **Async support** — `AsyncSQLPyHelper` for FastAPI and asyncio applications.
102
122
 
103
123
  ---
104
124
  ## 📦 Installation
@@ -197,20 +217,50 @@ db.setup_connection_pool(min_conn=2, max_conn=10) # Enable pooling for better p
197
217
  conn = db.get_connection_from_pool()
198
218
  db.return_connection_to_pool(conn)
199
219
  ```
220
+ ### Async Example (FastAPI / asyncio)
221
+ ```python
222
+ import asyncio
223
+ from sqlpyhelper.async_helper import AsyncSQLPyHelper
224
+
225
+ async def main():
226
+ async with AsyncSQLPyHelper(db_type="sqlite", database="my.db") as db:
227
+ await db.execute(
228
+ "CREATE TABLE IF NOT EXISTS users (id INTEGER, name TEXT)"
229
+ )
230
+ await db.execute(
231
+ "INSERT INTO users VALUES ($1, $2)", 1, "Alice"
232
+ )
233
+ rows = await db.fetch_all("SELECT * FROM users")
234
+ print(rows)
235
+
236
+ asyncio.run(main())
237
+ ```
200
238
 
201
239
  ## 📂 Project Structure
202
240
  ```
203
241
  📦 SQLPyHelper/
204
- ├─ sqlpyhelper/
205
-   ├─ __init__.py
206
-   └─ db_helper.py
207
- ├─ tests/
208
-   └─ test_sqlpyhelper.py
209
- ├─ .env_example
210
- ├─ .gitignore
211
- ├─ setup.py
212
- ├─ README.md
213
- └─ requirements.txt
242
+ ├─ sqlpyhelper/
243
+ ├─ __init__.py
244
+ ├─ db_helper.py
245
+ ├─ async_helper.py
246
+ ├─ automation_utils.py
247
+ ├─ cli.py
248
+ │ └─ migration.py
249
+ ├─ test/
250
+ ├─ test_sqlpyhelper.py
251
+ │ ├─ test_async_helper.py
252
+ │ └─ test_migration.py
253
+ ├─ docs/
254
+ ├─ .env_example
255
+ ├─ .gitignore
256
+ ├─ setup.py
257
+ ├─ setup.cfg
258
+ ├─ pyproject.toml
259
+ ├─ CHANGELOG.md
260
+ ├─ CONTRIBUTING.md
261
+ ├─ pre-commit.sh
262
+ ├─ README.md
263
+ └─ requirements.txt
214
264
  ```
215
265
  ---
216
266
  ## 📌 Available Methods in SQLPyHelper
@@ -232,6 +282,7 @@ db.return_connection_to_pool(conn)
232
282
  | `commit_transaction()` | Commits the current transaction. |
233
283
  | `close()` | Closes the database connection safely. |
234
284
  | `__enter__` / `__exit__()` | Use as a context manager — connection closes automatically. |
285
+ | `AsyncSQLPyHelper` | Async-native class for FastAPI/asyncio — see [Async docs](https://sqlpyhelper.readthedocs.io/en/latest/async.html). |
235
286
 
236
287
  ---
237
288
  ## 🌍 Contributing
@@ -0,0 +1,13 @@
1
+ sqlpyhelper/__init__.py,sha256=8oatB3lhbYVLzbkCIDrlE1mTJVljs2GeNuUG34_vYd0,370
2
+ sqlpyhelper/async_helper.py,sha256=beq0wKxDl7Qv-CW_qA1-h_DPhDpC1CQHdstnKO-4FSI,21473
3
+ sqlpyhelper/automation_utils.py,sha256=pC6pH6bJ-k8iPVeHJ4gUiwEe822dasmKg53ya9bMxyE,5381
4
+ sqlpyhelper/cli.py,sha256=yj0kWJu3oh_JLnmi0L7a5ing2_0x4CQGOKSOhZLAtoY,5646
5
+ sqlpyhelper/db_helper.py,sha256=SrXro_-ki5AT_Yj6u1k5-aUZYq-d2QXeQPXURXqUMLk,14223
6
+ sqlpyhelper/migration.py,sha256=byAn7ToVgIB8tl1N39DB0MbHigjH2l-qX7QSskgzzTg,11673
7
+ sqlpyhelper/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ sqlpyhelper-0.1.9.dist-info/licenses/LICENSE,sha256=9XzXxZ_8mWFM9-2TlqyE3L69zvRf4VPY_xIzSj5iU-g,1076
9
+ sqlpyhelper-0.1.9.dist-info/METADATA,sha256=TTa0zKb4o_Zuf9x1j63Xg15vE9rUBbgDUnSjJHi0Hq0,11607
10
+ sqlpyhelper-0.1.9.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
11
+ sqlpyhelper-0.1.9.dist-info/entry_points.txt,sha256=uAzSqwkAbbJqQUKHlPNwOebTJVA0FqkOvn2CRP6xSz8,52
12
+ sqlpyhelper-0.1.9.dist-info/top_level.txt,sha256=FrLqTmqTGDa8jHnnf2ZVkYO-gFvLXX9QonpUCE6wKGs,12
13
+ sqlpyhelper-0.1.9.dist-info/RECORD,,
@@ -1,12 +0,0 @@
1
- sqlpyhelper/__init__.py,sha256=wiwMpojvoi0j_qunbTQgMfyxzzIsHMkmDr1ADLyhvfY,246
2
- sqlpyhelper/automation_utils.py,sha256=pC6pH6bJ-k8iPVeHJ4gUiwEe822dasmKg53ya9bMxyE,5381
3
- sqlpyhelper/cli.py,sha256=yj0kWJu3oh_JLnmi0L7a5ing2_0x4CQGOKSOhZLAtoY,5646
4
- sqlpyhelper/db_helper.py,sha256=4DbdBVo86zz1d0hNHtSc4b3Tks7bJGTMTyabsydQyOE,14191
5
- sqlpyhelper/migration.py,sha256=byAn7ToVgIB8tl1N39DB0MbHigjH2l-qX7QSskgzzTg,11673
6
- sqlpyhelper/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
- sqlpyhelper-0.1.7.dist-info/licenses/LICENSE,sha256=9XzXxZ_8mWFM9-2TlqyE3L69zvRf4VPY_xIzSj5iU-g,1076
8
- sqlpyhelper-0.1.7.dist-info/METADATA,sha256=C2jJX7sEHHqLnQxL5iZxiG8on4xCDHpEu8_8zuaZWlk,9763
9
- sqlpyhelper-0.1.7.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
10
- sqlpyhelper-0.1.7.dist-info/entry_points.txt,sha256=uAzSqwkAbbJqQUKHlPNwOebTJVA0FqkOvn2CRP6xSz8,52
11
- sqlpyhelper-0.1.7.dist-info/top_level.txt,sha256=FrLqTmqTGDa8jHnnf2ZVkYO-gFvLXX9QonpUCE6wKGs,12
12
- sqlpyhelper-0.1.7.dist-info/RECORD,,