SQLPyHelper 0.1.0__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
ADDED
|
File without changes
|
sqlpyhelper/db_helper.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import sqlite3
|
|
2
|
+
import psycopg2
|
|
3
|
+
import mysql.connector
|
|
4
|
+
import pyodbc
|
|
5
|
+
import cx_Oracle
|
|
6
|
+
import csv
|
|
7
|
+
from psycopg2 import pool
|
|
8
|
+
from dotenv import load_dotenv
|
|
9
|
+
import os
|
|
10
|
+
|
|
11
|
+
load_dotenv() # Load environment variables from .env file
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SQLPyHelper:
|
|
15
|
+
def __init__(self):
|
|
16
|
+
self.db_type = os.getenv("DB_TYPE").lower()
|
|
17
|
+
self.host = os.getenv("DB_HOST")
|
|
18
|
+
self.user = os.getenv("DB_USER")
|
|
19
|
+
self.password = os.getenv("DB_PASSWORD")
|
|
20
|
+
self.database = os.getenv("DB_NAME")
|
|
21
|
+
self.driver = os.getenv("DB_DRIVER")
|
|
22
|
+
self.oracle_sid = os.getenv("ORACLE_SID")
|
|
23
|
+
|
|
24
|
+
if self.db_type == "sqlite":
|
|
25
|
+
self.connection = sqlite3.connect(self.database)
|
|
26
|
+
elif self.db_type == "postgres":
|
|
27
|
+
self.connection = psycopg2.connect(host=self.host, user=self.user,
|
|
28
|
+
password=self.password, dbname=self.database)
|
|
29
|
+
elif self.db_type == "mysql":
|
|
30
|
+
self.connection = mysql.connector.connect(host=self.host, user=self.user,
|
|
31
|
+
password=self.password, database=self.database)
|
|
32
|
+
elif self.db_type == "sqlserver":
|
|
33
|
+
self.connection = pyodbc.connect(f"DRIVER={self.driver};SERVER={self.host};DATABASE={self.database};"
|
|
34
|
+
f"UID={self.user};PWD={self.password}")
|
|
35
|
+
elif self.db_type == "oracle":
|
|
36
|
+
oracle_port = os.getenv("ORACLE_DB_PORT", "1521") # Default to 1521 if not set
|
|
37
|
+
dsn = cx_Oracle.makedsn(self.host, oracle_port, self.oracle_sid)
|
|
38
|
+
self.connection = cx_Oracle.connect(self.user, self.password, dsn)
|
|
39
|
+
else:
|
|
40
|
+
raise ValueError("Unsupported database type")
|
|
41
|
+
|
|
42
|
+
self.cursor = self.connection.cursor()
|
|
43
|
+
|
|
44
|
+
def execute_query(self, query, params=None):
|
|
45
|
+
"""Executes a query with optional parameters"""
|
|
46
|
+
try:
|
|
47
|
+
if params:
|
|
48
|
+
self.cursor.execute(query, params)
|
|
49
|
+
else:
|
|
50
|
+
self.cursor.execute(query)
|
|
51
|
+
self.connection.commit()
|
|
52
|
+
except Exception as e:
|
|
53
|
+
print(f"Error executing query: {e}")
|
|
54
|
+
|
|
55
|
+
def fetch_all(self):
|
|
56
|
+
"""Fetches all rows from the last executed query"""
|
|
57
|
+
return self.cursor.fetchall()
|
|
58
|
+
|
|
59
|
+
def close(self):
|
|
60
|
+
"""Closes the connection"""
|
|
61
|
+
self.cursor.close()
|
|
62
|
+
self.connection.close()
|
|
63
|
+
|
|
64
|
+
def create_table(self, table_name, columns):
|
|
65
|
+
"""
|
|
66
|
+
Creates a table dynamically using a dictionary format.
|
|
67
|
+
Example:
|
|
68
|
+
columns = {'id': 'INTEGER PRIMARY KEY', 'name': 'TEXT', 'age': 'INTEGER'}
|
|
69
|
+
"""
|
|
70
|
+
column_defs = ", ".join(f"{col} {dtype}" for col, dtype in columns.items())
|
|
71
|
+
query = f"CREATE TABLE {table_name} ({column_defs})"
|
|
72
|
+
self.execute_query(query)
|
|
73
|
+
|
|
74
|
+
def insert_bulk(self, table_name, data):
|
|
75
|
+
"""
|
|
76
|
+
Inserts multiple rows at once.
|
|
77
|
+
Example:
|
|
78
|
+
data = [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}]
|
|
79
|
+
"""
|
|
80
|
+
columns = ", ".join(data[0].keys()) # Extract column names
|
|
81
|
+
placeholders = ", ".join(["%s" for _ in data[0].keys()]) # Generate placeholders
|
|
82
|
+
query = f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})"
|
|
83
|
+
values = [tuple(row.values()) for row in data] # Convert dictionaries to tuples
|
|
84
|
+
self.cursor.executemany(query, values)
|
|
85
|
+
self.connection.commit()
|
|
86
|
+
|
|
87
|
+
def log_query(self, query):
|
|
88
|
+
"""Logs queries for debugging purposes."""
|
|
89
|
+
with open("query_log.txt", "a") as f:
|
|
90
|
+
f.write(query + "\n")
|
|
91
|
+
|
|
92
|
+
def backup_table(self, table_name, backup_file):
|
|
93
|
+
"""
|
|
94
|
+
Exports table data into a CSV file.
|
|
95
|
+
Example:
|
|
96
|
+
backup_table('users', 'users_backup.csv')
|
|
97
|
+
"""
|
|
98
|
+
query = f"SELECT * FROM {table_name}"
|
|
99
|
+
self.execute_query(query)
|
|
100
|
+
rows = self.fetch_all()
|
|
101
|
+
|
|
102
|
+
with open(backup_file, mode="w", newline="") as file:
|
|
103
|
+
writer = csv.writer(file)
|
|
104
|
+
writer.writerow([desc[0] for desc in self.cursor.description]) # Column headers
|
|
105
|
+
writer.writerows(rows)
|
|
106
|
+
|
|
107
|
+
def setup_postgres_pool(self, min_conn=1, max_conn=5):
|
|
108
|
+
"""
|
|
109
|
+
Creates a connection pool for PostgreSQL.
|
|
110
|
+
Example:
|
|
111
|
+
setup_postgres_pool(min_conn=2, max_conn=10)
|
|
112
|
+
"""
|
|
113
|
+
self.pool = pool.SimpleConnectionPool(min_conn, max_conn,
|
|
114
|
+
host=self.host,
|
|
115
|
+
user=self.user,
|
|
116
|
+
password=self.password,
|
|
117
|
+
dbname=self.database)
|
|
118
|
+
|
|
119
|
+
def get_connection_from_pool(self):
|
|
120
|
+
"""Fetches a connection from the pool."""
|
|
121
|
+
return self.pool.getconn()
|
|
122
|
+
|
|
123
|
+
def return_connection_to_pool(self, conn):
|
|
124
|
+
"""Returns a connection back to the pool."""
|
|
125
|
+
self.pool.putconn(conn)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: SQLPyHelper
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A simple SQL database helper package for Python.
|
|
5
|
+
Author: Adebayo Olaonipekun
|
|
6
|
+
Author-email: pekunmi@live.com
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.8
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: psycopg2
|
|
14
|
+
Requires-Dist: mysql-connector-python
|
|
15
|
+
Requires-Dist: pyodbc
|
|
16
|
+
Requires-Dist: cx_Oracle
|
|
17
|
+
Requires-Dist: python-dotenv
|
|
18
|
+
Dynamic: author
|
|
19
|
+
Dynamic: author-email
|
|
20
|
+
Dynamic: classifier
|
|
21
|
+
Dynamic: description
|
|
22
|
+
Dynamic: description-content-type
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
Dynamic: requires-dist
|
|
25
|
+
Dynamic: requires-python
|
|
26
|
+
Dynamic: summary
|
|
27
|
+
|
|
28
|
+
# 📌 SQLPyHelper
|
|
29
|
+
|
|
30
|
+
A Python library for simplified database interactions across **SQLite, PostgreSQL, MySQL, SQL Server, and Oracle**. This open-source package provides an intuitive API for handling database operations efficiently.
|
|
31
|
+
|
|
32
|
+
## 📖 Table of Contents
|
|
33
|
+
- [🚀 Features](#-features)
|
|
34
|
+
- [📦 Installation](#-installation)
|
|
35
|
+
- [⚙️ Setup Using `.env`](#️-setup-using-env)
|
|
36
|
+
- [🛠 Usage Examples](#-usage-examples)
|
|
37
|
+
- [SQLite Example](#sqlite-example)
|
|
38
|
+
- [PostgreSQL Example](#postgresql-example)
|
|
39
|
+
- [MySQL Example](#mysql-example)
|
|
40
|
+
- [SQL Server Example](#sql-server-example)
|
|
41
|
+
- [Oracle Example](#oracle-example)
|
|
42
|
+
- [📂 Project Structure](#-project-structure)
|
|
43
|
+
- [🌍 Contributing](#-contributing)
|
|
44
|
+
- [☕ Support the Project](#-support-the-project)
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## 🚀 Features
|
|
49
|
+
- **Unified Interface** for multiple databases
|
|
50
|
+
- **Connection pooling support** for PostgreSQL
|
|
51
|
+
- **Bulk insertion & dynamic table creation**
|
|
52
|
+
- **Automated logging & query execution**
|
|
53
|
+
- **CSV export & backup functionality**
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
## 📦 Installation
|
|
57
|
+
```sh
|
|
58
|
+
pip install sqlpyhelper
|
|
59
|
+
```
|
|
60
|
+
Or, if working from source:
|
|
61
|
+
```sh
|
|
62
|
+
git clone https://github.com/adebayopeter/sqlpyhelper.git
|
|
63
|
+
cd sqlpyhelper
|
|
64
|
+
pip install -r requirements.txt
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## ⚙️ Setup Using `.env`
|
|
70
|
+
Create a `.env` file in your project root to manage database configurations securely by renaming `.env_example`.
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
# .env_example (Rename to .env)
|
|
74
|
+
DB_TYPE=postgres
|
|
75
|
+
DB_HOST=localhost
|
|
76
|
+
DB_USER=your_user
|
|
77
|
+
DB_PASSWORD=your_secure_password
|
|
78
|
+
DB_NAME=test_db
|
|
79
|
+
DB_PORT=5432
|
|
80
|
+
DB_DRIVER={ODBC Driver 17 for SQL Server}
|
|
81
|
+
ORACLE_SID=XE
|
|
82
|
+
ORACLE_PORT=1521
|
|
83
|
+
```
|
|
84
|
+
### Loading `.env` in Code
|
|
85
|
+
```pycon
|
|
86
|
+
from dotenv import load_dotenv
|
|
87
|
+
import os
|
|
88
|
+
|
|
89
|
+
load_dotenv()
|
|
90
|
+
db_type = os.getenv("DB_TYPE")
|
|
91
|
+
host = os.getenv("DB_HOST")
|
|
92
|
+
user = os.getenv("DB_USER")
|
|
93
|
+
password = os.getenv("DB_PASSWORD")
|
|
94
|
+
database = os.getenv("DB_NAME")
|
|
95
|
+
```
|
|
96
|
+
---
|
|
97
|
+
## 🛠 Usage Examples
|
|
98
|
+
### SQLite Example
|
|
99
|
+
```pycon
|
|
100
|
+
from sqlpyhelper.db_helper import SQLPyHelper
|
|
101
|
+
|
|
102
|
+
db = SQLPyHelper()
|
|
103
|
+
db.execute_query("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
|
|
104
|
+
db.execute_query("INSERT INTO users (name) VALUES (?)", ("Alice",))
|
|
105
|
+
db.execute_query("SELECT * FROM users")
|
|
106
|
+
print(db.fetch_all())
|
|
107
|
+
db.close()
|
|
108
|
+
```
|
|
109
|
+
### PostgreSQL Example
|
|
110
|
+
```pycon
|
|
111
|
+
db = SQLPyHelper()
|
|
112
|
+
db.execute_query("CREATE TABLE IF NOT EXISTS employees (id SERIAL PRIMARY KEY, name VARCHAR(100))")
|
|
113
|
+
db.execute_query("INSERT INTO employees (name) VALUES (%s)", ("Charlie",))
|
|
114
|
+
db.execute_query("SELECT * FROM employees")
|
|
115
|
+
print(db.fetch_all())
|
|
116
|
+
db.close()
|
|
117
|
+
```
|
|
118
|
+
### MySQL Example
|
|
119
|
+
```pycon
|
|
120
|
+
db = SQLPyHelper()
|
|
121
|
+
db.execute_query("CREATE TABLE IF NOT EXISTS customers (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100))")
|
|
122
|
+
db.execute_query("INSERT INTO customers (name) VALUES (%s)", ("David",))
|
|
123
|
+
db.execute_query("SELECT * FROM customers")
|
|
124
|
+
print(db.fetch_all())
|
|
125
|
+
db.close()
|
|
126
|
+
```
|
|
127
|
+
### SQL Server Example
|
|
128
|
+
```pycon
|
|
129
|
+
db = SQLPyHelper()
|
|
130
|
+
db.execute_query("CREATE TABLE IF NOT EXISTS orders (id INT PRIMARY KEY, product VARCHAR(100))")
|
|
131
|
+
db.execute_query("INSERT INTO orders (id, product) VALUES (?, ?)", (1, "Laptop"))
|
|
132
|
+
db.execute_query("SELECT * FROM orders")
|
|
133
|
+
print(db.fetch_all())
|
|
134
|
+
db.close()
|
|
135
|
+
```
|
|
136
|
+
### Oracle Example
|
|
137
|
+
```pycon
|
|
138
|
+
db = SQLPyHelper()
|
|
139
|
+
db.execute_query("CREATE TABLE employees (id NUMBER PRIMARY KEY, name VARCHAR2(100))")
|
|
140
|
+
db.execute_query("INSERT INTO employees (id, name) VALUES (:1, :2)", (1, "Emily"))
|
|
141
|
+
db.execute_query("SELECT * FROM employees")
|
|
142
|
+
print(db.fetch_all())
|
|
143
|
+
db.close()
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## 📂 Project Structure
|
|
147
|
+
```
|
|
148
|
+
📦 SQLPyHelper/
|
|
149
|
+
├─ sqlpyhelper/
|
|
150
|
+
│ ├─ __init__.py
|
|
151
|
+
│ └─ db_helper.py
|
|
152
|
+
├─ tests/
|
|
153
|
+
│ └─ test_sqlpyhelper.py
|
|
154
|
+
├─ .env_example
|
|
155
|
+
├─ .gitignore
|
|
156
|
+
├─ setup.py
|
|
157
|
+
├─ README.md
|
|
158
|
+
└─ requirements.txt
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
---
|
|
162
|
+
## 🌍 Contributing
|
|
163
|
+
We welcome contributions from the **open-source community**! Follow these steps to contribute:
|
|
164
|
+
|
|
165
|
+
1. Fork the repo: [SQLPyHelper GitHub Repository](https://github.com/adebayopeter/sqlpyhelper)
|
|
166
|
+
2. Clone your fork:
|
|
167
|
+
```sh
|
|
168
|
+
git clone https://github.com/adebayopeter/sqlpyhelper.git
|
|
169
|
+
```
|
|
170
|
+
3. Create a new branch:
|
|
171
|
+
```sh
|
|
172
|
+
git checkout -b feature-new-functionality
|
|
173
|
+
```
|
|
174
|
+
4. Make changes, commit, and push:
|
|
175
|
+
```sh
|
|
176
|
+
git commit -m "Added new feature"
|
|
177
|
+
git push origin feature-new-functionality
|
|
178
|
+
```
|
|
179
|
+
5. Submit a Pull Request!
|
|
180
|
+
|
|
181
|
+
---
|
|
182
|
+
## ☕ Support the Project
|
|
183
|
+
|
|
184
|
+
If you find SQLPyHelper useful, consider buying me a coffee to support continued development!
|
|
185
|
+
Donate Here: [PayPal](https://paypal.me/adebayopeter?country.x=GB&locale.x=en_GB)
|
|
186
|
+
---
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
sqlpyhelper/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
sqlpyhelper/db_helper.py,sha256=9z2WjA7tQaNZ1fd1TYZZAooJS2N8szescOtTMNDTCgE,4896
|
|
3
|
+
sqlpyhelper-0.1.0.dist-info/licenses/LICENSE,sha256=9XzXxZ_8mWFM9-2TlqyE3L69zvRf4VPY_xIzSj5iU-g,1076
|
|
4
|
+
sqlpyhelper-0.1.0.dist-info/METADATA,sha256=YTa0XzA-AliUNOIlRKZBolekfrTcXaVIpS6NRDea8dI,5211
|
|
5
|
+
sqlpyhelper-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
6
|
+
sqlpyhelper-0.1.0.dist-info/top_level.txt,sha256=FrLqTmqTGDa8jHnnf2ZVkYO-gFvLXX9QonpUCE6wKGs,12
|
|
7
|
+
sqlpyhelper-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Adebayo Olaonipekun
|
|
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 @@
|
|
|
1
|
+
sqlpyhelper
|