sqlServerConnector 0.1.0__tar.gz → 0.1.2__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.
- sqlserverconnector-0.1.2/PKG-INFO +130 -0
- sqlserverconnector-0.1.2/README.md +111 -0
- {sqlserverconnector-0.1.0 → sqlserverconnector-0.1.2}/pyproject.toml +1 -1
- {sqlserverconnector-0.1.0 → sqlserverconnector-0.1.2}/src/connector.py +48 -47
- sqlserverconnector-0.1.2/src/sqlServerConnector.egg-info/PKG-INFO +130 -0
- sqlserverconnector-0.1.0/PKG-INFO +0 -57
- sqlserverconnector-0.1.0/README.md +0 -38
- sqlserverconnector-0.1.0/src/sqlServerConnector.egg-info/PKG-INFO +0 -57
- {sqlserverconnector-0.1.0 → sqlserverconnector-0.1.2}/setup.cfg +0 -0
- {sqlserverconnector-0.1.0 → sqlserverconnector-0.1.2}/src/__init__.py +0 -0
- {sqlserverconnector-0.1.0 → sqlserverconnector-0.1.2}/src/sqlServerConnector.egg-info/SOURCES.txt +0 -0
- {sqlserverconnector-0.1.0 → sqlserverconnector-0.1.2}/src/sqlServerConnector.egg-info/dependency_links.txt +0 -0
- {sqlserverconnector-0.1.0 → sqlserverconnector-0.1.2}/src/sqlServerConnector.egg-info/requires.txt +0 -0
- {sqlserverconnector-0.1.0 → sqlserverconnector-0.1.2}/src/sqlServerConnector.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sqlServerConnector
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: A custom SQL Server Connector for ETL processes with Pandas
|
|
5
|
+
Author-email: Nguyen Minh Son <nguyen.minhson1511@gmail.com>
|
|
6
|
+
Project-URL: Homepage, https://github.com/johnnyb1509/sqlServerConnector
|
|
7
|
+
Keywords: sql,etl,pandas,sqlalchemy
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.8
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
Requires-Dist: pandas>=1.5.0
|
|
13
|
+
Requires-Dist: numpy
|
|
14
|
+
Requires-Dist: sqlalchemy>=2.0.0
|
|
15
|
+
Requires-Dist: pyodbc
|
|
16
|
+
Requires-Dist: pyyaml
|
|
17
|
+
Requires-Dist: loguru
|
|
18
|
+
Requires-Dist: jupyterlab
|
|
19
|
+
|
|
20
|
+
# SQL Server Connector
|
|
21
|
+
|
|
22
|
+
Thư viện kết nối SQL Server chuyên dụng cho các tác vụ ETL, được tối ưu hóa cho **Pandas**, hỗ trợ **Tiếng Việt (Unicode)** và **Upsert (Merge)** hiệu năng cao.
|
|
23
|
+
|
|
24
|
+
## 🚀 Tính năng nổi bật
|
|
25
|
+
|
|
26
|
+
* **High Performance:** Sử dụng `fast_executemany` giúp insert dữ liệu nhanh gấp 10-50 lần so với thông thường.
|
|
27
|
+
* **Smart Upsert:** Tự động chèn mới (Insert) hoặc cập nhật (Update) dựa trên Khóa chính (Primary Key).
|
|
28
|
+
* **Schema Evolution:** Tự động tạo bảng nếu chưa có, tự động thêm cột mới (Add Column) nếu DataFrame có thay đổi.
|
|
29
|
+
* **Unicode Support:** Xử lý triệt để lỗi font chữ Tiếng Việt khi làm việc với SQL Server & Pandas.
|
|
30
|
+
* **SQLAlchemy 2.0:** Tuân thủ chuẩn kết nối hiện đại, an toàn.
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## 📦 Cài đặt
|
|
35
|
+
|
|
36
|
+
### Cách 1: Cài đặt trực tiếp từ Git (Khuyên dùng nội bộ)
|
|
37
|
+
Dành cho đồng nghiệp trong team, cài đặt không cần file whl.
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
# Cài phiên bản mới nhất từ nhánh main
|
|
41
|
+
|
|
42
|
+
pip install git+https://github.com/johnnyb1509/sqlServerConnector.git
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Cách 2: Cài đặt từ file .whl
|
|
46
|
+
Dành cho người dùng cuối, cài đặt từ file whl đã build sẵn.
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install sqlServerConnector
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
## Cấu hình kết nối Database
|
|
54
|
+
File cấu hình `db_config.yaml`
|
|
55
|
+
|
|
56
|
+
```yaml
|
|
57
|
+
# Thông tin kết nối Database
|
|
58
|
+
# Lưu ý: Đảm bảo máy tính đã cài đặt ODBC Driver 17 for SQL Server
|
|
59
|
+
db_info:
|
|
60
|
+
server: "localhost" # Ví dụ: localhost hoặc
|
|
61
|
+
database: "YOUR_DATABASE_NAME" # Ví dụ: TestDB
|
|
62
|
+
username: "YOUR_USERNAME" # Ví dụ: sa
|
|
63
|
+
password: "YOUR_PASSWORD" # Mật khẩu
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## 📝 Hướng dẫn sử dụng nhanh
|
|
67
|
+
|
|
68
|
+
1. Khởi tạo kết nối
|
|
69
|
+
```python
|
|
70
|
+
import yaml
|
|
71
|
+
from connector import SQLServerConnector
|
|
72
|
+
# Load config
|
|
73
|
+
with open('config/db_config.yaml', 'r') as f:
|
|
74
|
+
conf = yaml.safe_load(f)['db_info']
|
|
75
|
+
|
|
76
|
+
# Khởi tạo
|
|
77
|
+
db = SQLServerConnector(
|
|
78
|
+
server=conf['server'],
|
|
79
|
+
database=conf['database'],
|
|
80
|
+
username=conf['username'],
|
|
81
|
+
password=conf['password']
|
|
82
|
+
)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
2. Lấy dữ liệu (Read)
|
|
86
|
+
```python
|
|
87
|
+
# Cách 1: Lấy toàn bộ bảng
|
|
88
|
+
df = db.get_data("DM_KhachHang")
|
|
89
|
+
|
|
90
|
+
# Cách 2: Dùng câu lệnh SQL tùy ý
|
|
91
|
+
query = """
|
|
92
|
+
SELECT TOP 100 * FROM Sales_Transaction
|
|
93
|
+
WHERE created_date >= '2023-01-01'
|
|
94
|
+
"""
|
|
95
|
+
df_sales = db.get_data(query)
|
|
96
|
+
print(df_sales.head())
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
3. Ghi dữ liệu (Upsert)
|
|
100
|
+
```python
|
|
101
|
+
import pandas as pd
|
|
102
|
+
|
|
103
|
+
# Giả lập dữ liệu
|
|
104
|
+
data = {
|
|
105
|
+
'TransactionID': [101, 102],
|
|
106
|
+
'Product': ['Laptop Dell', 'Chuột Logitech'], # Hỗ trợ tiếng Việt
|
|
107
|
+
'Amount': [15000000, 250000]
|
|
108
|
+
}
|
|
109
|
+
df_new = pd.DataFrame(data)
|
|
110
|
+
|
|
111
|
+
# Đẩy vào DB
|
|
112
|
+
db.upsert_data(
|
|
113
|
+
df=df_new,
|
|
114
|
+
target_table="Fact_Sales",
|
|
115
|
+
primary_key="TransactionID", # Cột dùng để định danh (tránh trùng lặp)
|
|
116
|
+
auto_evolve_schema=True # Tự động thêm cột nếu thiếu
|
|
117
|
+
)
|
|
118
|
+
print("Dữ liệu đã được upsert thành công!")
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
4. Đóng kết nối
|
|
122
|
+
```python
|
|
123
|
+
# Luôn đóng kết nối khi hoàn tất để giải phóng tài nguyên
|
|
124
|
+
db.dispose()
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## ⚠️ Lưu ý quan trọng
|
|
128
|
+
1. **Primary Key:** Khi dùng upsert_data, bắt buộc phải cung cấp primary_key. Nếu bảng chưa có Primary Key, thư viện sẽ tự set cột đó làm khóa chính khi tạo bảng mới.
|
|
129
|
+
|
|
130
|
+
2. **Date Time:** Các cột ngày tháng nên được convert sang datetime64[ns] trong Pandas trước khi đẩy vào để đảm bảo tính chính xác.
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# SQL Server Connector
|
|
2
|
+
|
|
3
|
+
Thư viện kết nối SQL Server chuyên dụng cho các tác vụ ETL, được tối ưu hóa cho **Pandas**, hỗ trợ **Tiếng Việt (Unicode)** và **Upsert (Merge)** hiệu năng cao.
|
|
4
|
+
|
|
5
|
+
## 🚀 Tính năng nổi bật
|
|
6
|
+
|
|
7
|
+
* **High Performance:** Sử dụng `fast_executemany` giúp insert dữ liệu nhanh gấp 10-50 lần so với thông thường.
|
|
8
|
+
* **Smart Upsert:** Tự động chèn mới (Insert) hoặc cập nhật (Update) dựa trên Khóa chính (Primary Key).
|
|
9
|
+
* **Schema Evolution:** Tự động tạo bảng nếu chưa có, tự động thêm cột mới (Add Column) nếu DataFrame có thay đổi.
|
|
10
|
+
* **Unicode Support:** Xử lý triệt để lỗi font chữ Tiếng Việt khi làm việc với SQL Server & Pandas.
|
|
11
|
+
* **SQLAlchemy 2.0:** Tuân thủ chuẩn kết nối hiện đại, an toàn.
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## 📦 Cài đặt
|
|
16
|
+
|
|
17
|
+
### Cách 1: Cài đặt trực tiếp từ Git (Khuyên dùng nội bộ)
|
|
18
|
+
Dành cho đồng nghiệp trong team, cài đặt không cần file whl.
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
# Cài phiên bản mới nhất từ nhánh main
|
|
22
|
+
|
|
23
|
+
pip install git+https://github.com/johnnyb1509/sqlServerConnector.git
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
### Cách 2: Cài đặt từ file .whl
|
|
27
|
+
Dành cho người dùng cuối, cài đặt từ file whl đã build sẵn.
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install sqlServerConnector
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
## Cấu hình kết nối Database
|
|
35
|
+
File cấu hình `db_config.yaml`
|
|
36
|
+
|
|
37
|
+
```yaml
|
|
38
|
+
# Thông tin kết nối Database
|
|
39
|
+
# Lưu ý: Đảm bảo máy tính đã cài đặt ODBC Driver 17 for SQL Server
|
|
40
|
+
db_info:
|
|
41
|
+
server: "localhost" # Ví dụ: localhost hoặc
|
|
42
|
+
database: "YOUR_DATABASE_NAME" # Ví dụ: TestDB
|
|
43
|
+
username: "YOUR_USERNAME" # Ví dụ: sa
|
|
44
|
+
password: "YOUR_PASSWORD" # Mật khẩu
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## 📝 Hướng dẫn sử dụng nhanh
|
|
48
|
+
|
|
49
|
+
1. Khởi tạo kết nối
|
|
50
|
+
```python
|
|
51
|
+
import yaml
|
|
52
|
+
from connector import SQLServerConnector
|
|
53
|
+
# Load config
|
|
54
|
+
with open('config/db_config.yaml', 'r') as f:
|
|
55
|
+
conf = yaml.safe_load(f)['db_info']
|
|
56
|
+
|
|
57
|
+
# Khởi tạo
|
|
58
|
+
db = SQLServerConnector(
|
|
59
|
+
server=conf['server'],
|
|
60
|
+
database=conf['database'],
|
|
61
|
+
username=conf['username'],
|
|
62
|
+
password=conf['password']
|
|
63
|
+
)
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
2. Lấy dữ liệu (Read)
|
|
67
|
+
```python
|
|
68
|
+
# Cách 1: Lấy toàn bộ bảng
|
|
69
|
+
df = db.get_data("DM_KhachHang")
|
|
70
|
+
|
|
71
|
+
# Cách 2: Dùng câu lệnh SQL tùy ý
|
|
72
|
+
query = """
|
|
73
|
+
SELECT TOP 100 * FROM Sales_Transaction
|
|
74
|
+
WHERE created_date >= '2023-01-01'
|
|
75
|
+
"""
|
|
76
|
+
df_sales = db.get_data(query)
|
|
77
|
+
print(df_sales.head())
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
3. Ghi dữ liệu (Upsert)
|
|
81
|
+
```python
|
|
82
|
+
import pandas as pd
|
|
83
|
+
|
|
84
|
+
# Giả lập dữ liệu
|
|
85
|
+
data = {
|
|
86
|
+
'TransactionID': [101, 102],
|
|
87
|
+
'Product': ['Laptop Dell', 'Chuột Logitech'], # Hỗ trợ tiếng Việt
|
|
88
|
+
'Amount': [15000000, 250000]
|
|
89
|
+
}
|
|
90
|
+
df_new = pd.DataFrame(data)
|
|
91
|
+
|
|
92
|
+
# Đẩy vào DB
|
|
93
|
+
db.upsert_data(
|
|
94
|
+
df=df_new,
|
|
95
|
+
target_table="Fact_Sales",
|
|
96
|
+
primary_key="TransactionID", # Cột dùng để định danh (tránh trùng lặp)
|
|
97
|
+
auto_evolve_schema=True # Tự động thêm cột nếu thiếu
|
|
98
|
+
)
|
|
99
|
+
print("Dữ liệu đã được upsert thành công!")
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
4. Đóng kết nối
|
|
103
|
+
```python
|
|
104
|
+
# Luôn đóng kết nối khi hoàn tất để giải phóng tài nguyên
|
|
105
|
+
db.dispose()
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## ⚠️ Lưu ý quan trọng
|
|
109
|
+
1. **Primary Key:** Khi dùng upsert_data, bắt buộc phải cung cấp primary_key. Nếu bảng chưa có Primary Key, thư viện sẽ tự set cột đó làm khóa chính khi tạo bảng mới.
|
|
110
|
+
|
|
111
|
+
2. **Date Time:** Các cột ngày tháng nên được convert sang datetime64[ns] trong Pandas trước khi đẩy vào để đảm bảo tính chính xác.
|
|
@@ -23,6 +23,8 @@ class SQLServerConnector:
|
|
|
23
23
|
- Full Unicode/Vietnamese Support (NVARCHAR + UTF8).
|
|
24
24
|
- Automatic Schema Evolution (adds missing columns).
|
|
25
25
|
- Automatic Primary Key detection and creation.
|
|
26
|
+
- [NEW] Automatic Deduplication of source data before Upsert.
|
|
27
|
+
- [NEW] Prevents numeric conversion on Key columns.
|
|
26
28
|
"""
|
|
27
29
|
|
|
28
30
|
def __init__(self, server: str, database: str, username: str, password: str, driver: str = 'ODBC Driver 17 for SQL Server'):
|
|
@@ -146,7 +148,7 @@ class SQLServerConnector:
|
|
|
146
148
|
match_columns: Optional[List[str]] = None,
|
|
147
149
|
auto_evolve_schema: bool = True):
|
|
148
150
|
"""
|
|
149
|
-
Main ETL Function with Unicode Support.
|
|
151
|
+
Main ETL Function with Unicode Support and Auto-Deduplication.
|
|
150
152
|
|
|
151
153
|
Args:
|
|
152
154
|
df: The new data to push.
|
|
@@ -159,8 +161,19 @@ class SQLServerConnector:
|
|
|
159
161
|
logger.warning(f"Dataframe for {target_table} is empty. Skipping.")
|
|
160
162
|
return
|
|
161
163
|
|
|
162
|
-
#
|
|
163
|
-
|
|
164
|
+
# 0. DETERMINE JOIN KEYS FIRST
|
|
165
|
+
# We need this early to protect these keys from being converted to floats during sanitization
|
|
166
|
+
if match_columns:
|
|
167
|
+
join_keys = match_columns
|
|
168
|
+
elif primary_key in df.columns:
|
|
169
|
+
join_keys = [primary_key]
|
|
170
|
+
else:
|
|
171
|
+
# Fallback if table doesn't exist yet or columns missing, handled later but setup empty here
|
|
172
|
+
join_keys = []
|
|
173
|
+
|
|
174
|
+
# 1. PRE-PROCESS DATA (With Key Protection)
|
|
175
|
+
# Pass join_keys to exclude them from numeric conversion (prevents "123" -> 123.0)
|
|
176
|
+
df_clean = self._sanitize_dataframe(df, exclude_cols=join_keys)
|
|
164
177
|
|
|
165
178
|
# 2. CHECK TARGET TABLE
|
|
166
179
|
if not self.check_table_exists(target_table):
|
|
@@ -172,17 +185,26 @@ class SQLServerConnector:
|
|
|
172
185
|
if auto_evolve_schema:
|
|
173
186
|
self._sync_columns(df_clean, target_table)
|
|
174
187
|
|
|
175
|
-
# 4.
|
|
176
|
-
if
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
188
|
+
# 4. RE-VALIDATE JOIN KEYS
|
|
189
|
+
if not join_keys:
|
|
190
|
+
# Try to infer if not provided
|
|
191
|
+
if primary_key in df_clean.columns:
|
|
192
|
+
join_keys = [primary_key]
|
|
193
|
+
else:
|
|
194
|
+
logger.error(f"CRITICAL: Primary Key '{primary_key}' is missing from DataFrame.")
|
|
195
|
+
logger.error("You MUST provide 'match_columns' to identify which rows to update.")
|
|
196
|
+
raise ValueError("Missing match keys for Identity Column Upsert.")
|
|
197
|
+
|
|
198
|
+
# 5. AUTO DEDUPLICATE SOURCE (CRITICAL FIX)
|
|
199
|
+
# SQL MERGE fails if source has duplicates. We enforce uniqueness on join keys here.
|
|
200
|
+
initial_count = len(df_clean)
|
|
201
|
+
df_clean = df_clean.drop_duplicates(subset=join_keys, keep='last')
|
|
202
|
+
final_count = len(df_clean)
|
|
203
|
+
|
|
204
|
+
if initial_count != final_count:
|
|
205
|
+
logger.warning(f"Upsert Safety: Automatically dropped {initial_count - final_count} duplicate rows in source based on keys {join_keys}.")
|
|
184
206
|
|
|
185
|
-
#
|
|
207
|
+
# 6. EXECUTE UPSERT VIA STAGING
|
|
186
208
|
self._execute_merge_upsert(df_clean, target_table, join_keys)
|
|
187
209
|
|
|
188
210
|
def _execute_merge_upsert(self, df: pd.DataFrame, target_table: str, join_keys: List[str]):
|
|
@@ -322,22 +344,25 @@ class SQLServerConnector:
|
|
|
322
344
|
# HELPER: DATA CLEANING
|
|
323
345
|
# ========================================================
|
|
324
346
|
|
|
325
|
-
def _sanitize_dataframe(self, df: pd.DataFrame) -> pd.DataFrame:
|
|
326
|
-
"""
|
|
347
|
+
def _sanitize_dataframe(self, df: pd.DataFrame, exclude_cols: List[str] = []) -> pd.DataFrame:
|
|
348
|
+
"""
|
|
349
|
+
Cleans numeric strings, NaT, and NaN values.
|
|
350
|
+
Args:
|
|
351
|
+
df: Input dataframe.
|
|
352
|
+
exclude_cols: Columns to skip numeric conversion (e.g. IDs).
|
|
353
|
+
"""
|
|
327
354
|
df = df.copy()
|
|
328
355
|
|
|
329
|
-
# 1. Clean Numeric Strings
|
|
356
|
+
# 1. Clean Numeric Strings (Skip excluded columns)
|
|
330
357
|
for col in df.select_dtypes(include=['object']).columns:
|
|
331
|
-
|
|
332
|
-
|
|
358
|
+
if col in exclude_cols:
|
|
359
|
+
continue # PROTECT ID COLUMNS FROM BEING CONVERTED TO FLOATS
|
|
360
|
+
|
|
361
|
+
# Only try to convert to float if it looks like a number
|
|
333
362
|
sample = df[col].dropna().head(10).astype(str).tolist()
|
|
334
363
|
if any(any(char.isdigit() for char in str(x)) for x in sample):
|
|
335
364
|
try:
|
|
336
|
-
# Attempt conversion, but strictly ignore errors so we don't break text columns
|
|
337
|
-
# We use a temp series to check if conversion is successful for majority
|
|
338
365
|
temp = df[col].apply(self._clean_numeric_string)
|
|
339
|
-
# If the column was actually text (e.g., "Hà Nội"), _clean_numeric_string returns the original string.
|
|
340
|
-
# We trust _clean_numeric_string to be safe.
|
|
341
366
|
df[col] = temp
|
|
342
367
|
except:
|
|
343
368
|
pass
|
|
@@ -362,7 +387,6 @@ class SQLServerConnector:
|
|
|
362
387
|
if not s: return None
|
|
363
388
|
|
|
364
389
|
# Heuristic: If it contains many letters (excluding K,M,B,T for billions), it's probably text
|
|
365
|
-
# Count letters
|
|
366
390
|
alpha_count = sum(c.isalpha() for c in s)
|
|
367
391
|
if alpha_count > 1 and s[-1] not in ['K', 'M', 'B', 'T']:
|
|
368
392
|
return value # It's likely text (e.g. "Cổ phiếu")
|
|
@@ -380,27 +404,4 @@ class SQLServerConnector:
|
|
|
380
404
|
try:
|
|
381
405
|
return float(s_clean)
|
|
382
406
|
except ValueError:
|
|
383
|
-
return value
|
|
384
|
-
|
|
385
|
-
# ========================================================
|
|
386
|
-
# ENTRY POINT
|
|
387
|
-
# ========================================================
|
|
388
|
-
|
|
389
|
-
# def get_db_connector(yaml_path: Optional[str] = None, env_prefix: str = "DB") -> SQLServerConnector:
|
|
390
|
-
# """Factory function to initialize connector."""
|
|
391
|
-
# if yaml_path and os.path.exists(yaml_path):
|
|
392
|
-
# with open(yaml_path, 'r') as f:
|
|
393
|
-
# config = yaml.safe_load(f).get('db_info', {})
|
|
394
|
-
# return SQLServerConnector(
|
|
395
|
-
# config.get('server'),
|
|
396
|
-
# config.get('database'),
|
|
397
|
-
# config.get('username'),
|
|
398
|
-
# config.get('password')
|
|
399
|
-
# )
|
|
400
|
-
# else:
|
|
401
|
-
# return SQLServerConnector(
|
|
402
|
-
# os.environ.get(f'{env_prefix}_SERVER'),
|
|
403
|
-
# os.environ.get(f'{env_prefix}_NAME'),
|
|
404
|
-
# os.environ.get(f'{env_prefix}_USER'),
|
|
405
|
-
# os.environ.get(f'{env_prefix}_PASS')
|
|
406
|
-
# )
|
|
407
|
+
return value
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sqlServerConnector
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: A custom SQL Server Connector for ETL processes with Pandas
|
|
5
|
+
Author-email: Nguyen Minh Son <nguyen.minhson1511@gmail.com>
|
|
6
|
+
Project-URL: Homepage, https://github.com/johnnyb1509/sqlServerConnector
|
|
7
|
+
Keywords: sql,etl,pandas,sqlalchemy
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.8
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
Requires-Dist: pandas>=1.5.0
|
|
13
|
+
Requires-Dist: numpy
|
|
14
|
+
Requires-Dist: sqlalchemy>=2.0.0
|
|
15
|
+
Requires-Dist: pyodbc
|
|
16
|
+
Requires-Dist: pyyaml
|
|
17
|
+
Requires-Dist: loguru
|
|
18
|
+
Requires-Dist: jupyterlab
|
|
19
|
+
|
|
20
|
+
# SQL Server Connector
|
|
21
|
+
|
|
22
|
+
Thư viện kết nối SQL Server chuyên dụng cho các tác vụ ETL, được tối ưu hóa cho **Pandas**, hỗ trợ **Tiếng Việt (Unicode)** và **Upsert (Merge)** hiệu năng cao.
|
|
23
|
+
|
|
24
|
+
## 🚀 Tính năng nổi bật
|
|
25
|
+
|
|
26
|
+
* **High Performance:** Sử dụng `fast_executemany` giúp insert dữ liệu nhanh gấp 10-50 lần so với thông thường.
|
|
27
|
+
* **Smart Upsert:** Tự động chèn mới (Insert) hoặc cập nhật (Update) dựa trên Khóa chính (Primary Key).
|
|
28
|
+
* **Schema Evolution:** Tự động tạo bảng nếu chưa có, tự động thêm cột mới (Add Column) nếu DataFrame có thay đổi.
|
|
29
|
+
* **Unicode Support:** Xử lý triệt để lỗi font chữ Tiếng Việt khi làm việc với SQL Server & Pandas.
|
|
30
|
+
* **SQLAlchemy 2.0:** Tuân thủ chuẩn kết nối hiện đại, an toàn.
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## 📦 Cài đặt
|
|
35
|
+
|
|
36
|
+
### Cách 1: Cài đặt trực tiếp từ Git (Khuyên dùng nội bộ)
|
|
37
|
+
Dành cho đồng nghiệp trong team, cài đặt không cần file whl.
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
# Cài phiên bản mới nhất từ nhánh main
|
|
41
|
+
|
|
42
|
+
pip install git+https://github.com/johnnyb1509/sqlServerConnector.git
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Cách 2: Cài đặt từ file .whl
|
|
46
|
+
Dành cho người dùng cuối, cài đặt từ file whl đã build sẵn.
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install sqlServerConnector
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
## Cấu hình kết nối Database
|
|
54
|
+
File cấu hình `db_config.yaml`
|
|
55
|
+
|
|
56
|
+
```yaml
|
|
57
|
+
# Thông tin kết nối Database
|
|
58
|
+
# Lưu ý: Đảm bảo máy tính đã cài đặt ODBC Driver 17 for SQL Server
|
|
59
|
+
db_info:
|
|
60
|
+
server: "localhost" # Ví dụ: localhost hoặc
|
|
61
|
+
database: "YOUR_DATABASE_NAME" # Ví dụ: TestDB
|
|
62
|
+
username: "YOUR_USERNAME" # Ví dụ: sa
|
|
63
|
+
password: "YOUR_PASSWORD" # Mật khẩu
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## 📝 Hướng dẫn sử dụng nhanh
|
|
67
|
+
|
|
68
|
+
1. Khởi tạo kết nối
|
|
69
|
+
```python
|
|
70
|
+
import yaml
|
|
71
|
+
from connector import SQLServerConnector
|
|
72
|
+
# Load config
|
|
73
|
+
with open('config/db_config.yaml', 'r') as f:
|
|
74
|
+
conf = yaml.safe_load(f)['db_info']
|
|
75
|
+
|
|
76
|
+
# Khởi tạo
|
|
77
|
+
db = SQLServerConnector(
|
|
78
|
+
server=conf['server'],
|
|
79
|
+
database=conf['database'],
|
|
80
|
+
username=conf['username'],
|
|
81
|
+
password=conf['password']
|
|
82
|
+
)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
2. Lấy dữ liệu (Read)
|
|
86
|
+
```python
|
|
87
|
+
# Cách 1: Lấy toàn bộ bảng
|
|
88
|
+
df = db.get_data("DM_KhachHang")
|
|
89
|
+
|
|
90
|
+
# Cách 2: Dùng câu lệnh SQL tùy ý
|
|
91
|
+
query = """
|
|
92
|
+
SELECT TOP 100 * FROM Sales_Transaction
|
|
93
|
+
WHERE created_date >= '2023-01-01'
|
|
94
|
+
"""
|
|
95
|
+
df_sales = db.get_data(query)
|
|
96
|
+
print(df_sales.head())
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
3. Ghi dữ liệu (Upsert)
|
|
100
|
+
```python
|
|
101
|
+
import pandas as pd
|
|
102
|
+
|
|
103
|
+
# Giả lập dữ liệu
|
|
104
|
+
data = {
|
|
105
|
+
'TransactionID': [101, 102],
|
|
106
|
+
'Product': ['Laptop Dell', 'Chuột Logitech'], # Hỗ trợ tiếng Việt
|
|
107
|
+
'Amount': [15000000, 250000]
|
|
108
|
+
}
|
|
109
|
+
df_new = pd.DataFrame(data)
|
|
110
|
+
|
|
111
|
+
# Đẩy vào DB
|
|
112
|
+
db.upsert_data(
|
|
113
|
+
df=df_new,
|
|
114
|
+
target_table="Fact_Sales",
|
|
115
|
+
primary_key="TransactionID", # Cột dùng để định danh (tránh trùng lặp)
|
|
116
|
+
auto_evolve_schema=True # Tự động thêm cột nếu thiếu
|
|
117
|
+
)
|
|
118
|
+
print("Dữ liệu đã được upsert thành công!")
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
4. Đóng kết nối
|
|
122
|
+
```python
|
|
123
|
+
# Luôn đóng kết nối khi hoàn tất để giải phóng tài nguyên
|
|
124
|
+
db.dispose()
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## ⚠️ Lưu ý quan trọng
|
|
128
|
+
1. **Primary Key:** Khi dùng upsert_data, bắt buộc phải cung cấp primary_key. Nếu bảng chưa có Primary Key, thư viện sẽ tự set cột đó làm khóa chính khi tạo bảng mới.
|
|
129
|
+
|
|
130
|
+
2. **Date Time:** Các cột ngày tháng nên được convert sang datetime64[ns] trong Pandas trước khi đẩy vào để đảm bảo tính chính xác.
|
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: sqlServerConnector
|
|
3
|
-
Version: 0.1.0
|
|
4
|
-
Summary: A custom SQL Server Connector for ETL processes with Pandas
|
|
5
|
-
Author-email: Nguyen Minh Son <nguyen.minhson1511@gmail.com>
|
|
6
|
-
Project-URL: Homepage, https://github.com/johnnyb1509/sqlServerConnector
|
|
7
|
-
Keywords: sql,etl,pandas,sqlalchemy
|
|
8
|
-
Classifier: Programming Language :: Python :: 3
|
|
9
|
-
Classifier: Operating System :: OS Independent
|
|
10
|
-
Requires-Python: >=3.8
|
|
11
|
-
Description-Content-Type: text/markdown
|
|
12
|
-
Requires-Dist: pandas>=1.5.0
|
|
13
|
-
Requires-Dist: numpy
|
|
14
|
-
Requires-Dist: sqlalchemy>=2.0.0
|
|
15
|
-
Requires-Dist: pyodbc
|
|
16
|
-
Requires-Dist: pyyaml
|
|
17
|
-
Requires-Dist: loguru
|
|
18
|
-
Requires-Dist: jupyterlab
|
|
19
|
-
|
|
20
|
-
# SQL Data Connector Project
|
|
21
|
-
|
|
22
|
-
Project này cung cấp module Python mạnh mẽ (`dbConnector`) để tương tác với Microsoft SQL Server, tối ưu hóa cho các tác vụ Data Engineering như: ETL, Insert dữ liệu lớn, và Đồng bộ hóa (Upsert) dữ liệu từ Pandas DataFrame.
|
|
23
|
-
|
|
24
|
-
## Tính năng nổi bật
|
|
25
|
-
|
|
26
|
-
* **Tự động hóa cao**: Tự động tạo bảng, phát hiện kiểu dữ liệu, và thêm cột mới nếu DataFrame thay đổi.
|
|
27
|
-
* **Hiệu năng cao**: Sử dụng `fast_executemany=True` của SQLAlchemy/pyodbc để tăng tốc độ Insert.
|
|
28
|
-
* **An toàn dữ liệu**: Hỗ trợ Transaction (Commit/Rollback) để đảm bảo tính toàn vẹn dữ liệu.
|
|
29
|
-
* **Sync thông minh**: Hàm `check_and_update_table` giúp so sánh và chỉ update những dòng thay đổi, insert những dòng mới.
|
|
30
|
-
* **Tiện ích**: Hỗ trợ làm sạch dữ liệu số (ví dụ: convert "1.5M" thành 1,500,000).
|
|
31
|
-
|
|
32
|
-
## Yêu cầu cài đặt
|
|
33
|
-
|
|
34
|
-
1. **Hệ điều hành**: Windows, Linux, hoặc MacOS.
|
|
35
|
-
2. **Driver**: Cần cài đặt **ODBC Driver 17 for SQL Server**.
|
|
36
|
-
* [Tải về tại đây (Microsoft)](https://learn.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server)
|
|
37
|
-
3. **Python Libraries**:
|
|
38
|
-
```bash
|
|
39
|
-
pip install -r requirements.txt
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
## Cấu trúc Project
|
|
43
|
-
|
|
44
|
-
* `src/dbConnector.py`: Module chính chứa class `dbJob`.
|
|
45
|
-
* `config/db_config.yaml`: File cấu hình database (cần tự tạo dựa trên mẫu).
|
|
46
|
-
* `notebooks/demo_usage.ipynb`: Ví dụ cách sử dụng.
|
|
47
|
-
|
|
48
|
-
## Hướng dẫn sử dụng nhanh
|
|
49
|
-
|
|
50
|
-
### 1. Cấu hình kết nối
|
|
51
|
-
Tạo file `config/db_config.yaml`:
|
|
52
|
-
```yaml
|
|
53
|
-
db_info:
|
|
54
|
-
server: "localhost"
|
|
55
|
-
database: "MyDatabase"
|
|
56
|
-
username: "sa"
|
|
57
|
-
password: "mypassword"
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
# SQL Data Connector Project
|
|
2
|
-
|
|
3
|
-
Project này cung cấp module Python mạnh mẽ (`dbConnector`) để tương tác với Microsoft SQL Server, tối ưu hóa cho các tác vụ Data Engineering như: ETL, Insert dữ liệu lớn, và Đồng bộ hóa (Upsert) dữ liệu từ Pandas DataFrame.
|
|
4
|
-
|
|
5
|
-
## Tính năng nổi bật
|
|
6
|
-
|
|
7
|
-
* **Tự động hóa cao**: Tự động tạo bảng, phát hiện kiểu dữ liệu, và thêm cột mới nếu DataFrame thay đổi.
|
|
8
|
-
* **Hiệu năng cao**: Sử dụng `fast_executemany=True` của SQLAlchemy/pyodbc để tăng tốc độ Insert.
|
|
9
|
-
* **An toàn dữ liệu**: Hỗ trợ Transaction (Commit/Rollback) để đảm bảo tính toàn vẹn dữ liệu.
|
|
10
|
-
* **Sync thông minh**: Hàm `check_and_update_table` giúp so sánh và chỉ update những dòng thay đổi, insert những dòng mới.
|
|
11
|
-
* **Tiện ích**: Hỗ trợ làm sạch dữ liệu số (ví dụ: convert "1.5M" thành 1,500,000).
|
|
12
|
-
|
|
13
|
-
## Yêu cầu cài đặt
|
|
14
|
-
|
|
15
|
-
1. **Hệ điều hành**: Windows, Linux, hoặc MacOS.
|
|
16
|
-
2. **Driver**: Cần cài đặt **ODBC Driver 17 for SQL Server**.
|
|
17
|
-
* [Tải về tại đây (Microsoft)](https://learn.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server)
|
|
18
|
-
3. **Python Libraries**:
|
|
19
|
-
```bash
|
|
20
|
-
pip install -r requirements.txt
|
|
21
|
-
```
|
|
22
|
-
|
|
23
|
-
## Cấu trúc Project
|
|
24
|
-
|
|
25
|
-
* `src/dbConnector.py`: Module chính chứa class `dbJob`.
|
|
26
|
-
* `config/db_config.yaml`: File cấu hình database (cần tự tạo dựa trên mẫu).
|
|
27
|
-
* `notebooks/demo_usage.ipynb`: Ví dụ cách sử dụng.
|
|
28
|
-
|
|
29
|
-
## Hướng dẫn sử dụng nhanh
|
|
30
|
-
|
|
31
|
-
### 1. Cấu hình kết nối
|
|
32
|
-
Tạo file `config/db_config.yaml`:
|
|
33
|
-
```yaml
|
|
34
|
-
db_info:
|
|
35
|
-
server: "localhost"
|
|
36
|
-
database: "MyDatabase"
|
|
37
|
-
username: "sa"
|
|
38
|
-
password: "mypassword"
|
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: sqlServerConnector
|
|
3
|
-
Version: 0.1.0
|
|
4
|
-
Summary: A custom SQL Server Connector for ETL processes with Pandas
|
|
5
|
-
Author-email: Nguyen Minh Son <nguyen.minhson1511@gmail.com>
|
|
6
|
-
Project-URL: Homepage, https://github.com/johnnyb1509/sqlServerConnector
|
|
7
|
-
Keywords: sql,etl,pandas,sqlalchemy
|
|
8
|
-
Classifier: Programming Language :: Python :: 3
|
|
9
|
-
Classifier: Operating System :: OS Independent
|
|
10
|
-
Requires-Python: >=3.8
|
|
11
|
-
Description-Content-Type: text/markdown
|
|
12
|
-
Requires-Dist: pandas>=1.5.0
|
|
13
|
-
Requires-Dist: numpy
|
|
14
|
-
Requires-Dist: sqlalchemy>=2.0.0
|
|
15
|
-
Requires-Dist: pyodbc
|
|
16
|
-
Requires-Dist: pyyaml
|
|
17
|
-
Requires-Dist: loguru
|
|
18
|
-
Requires-Dist: jupyterlab
|
|
19
|
-
|
|
20
|
-
# SQL Data Connector Project
|
|
21
|
-
|
|
22
|
-
Project này cung cấp module Python mạnh mẽ (`dbConnector`) để tương tác với Microsoft SQL Server, tối ưu hóa cho các tác vụ Data Engineering như: ETL, Insert dữ liệu lớn, và Đồng bộ hóa (Upsert) dữ liệu từ Pandas DataFrame.
|
|
23
|
-
|
|
24
|
-
## Tính năng nổi bật
|
|
25
|
-
|
|
26
|
-
* **Tự động hóa cao**: Tự động tạo bảng, phát hiện kiểu dữ liệu, và thêm cột mới nếu DataFrame thay đổi.
|
|
27
|
-
* **Hiệu năng cao**: Sử dụng `fast_executemany=True` của SQLAlchemy/pyodbc để tăng tốc độ Insert.
|
|
28
|
-
* **An toàn dữ liệu**: Hỗ trợ Transaction (Commit/Rollback) để đảm bảo tính toàn vẹn dữ liệu.
|
|
29
|
-
* **Sync thông minh**: Hàm `check_and_update_table` giúp so sánh và chỉ update những dòng thay đổi, insert những dòng mới.
|
|
30
|
-
* **Tiện ích**: Hỗ trợ làm sạch dữ liệu số (ví dụ: convert "1.5M" thành 1,500,000).
|
|
31
|
-
|
|
32
|
-
## Yêu cầu cài đặt
|
|
33
|
-
|
|
34
|
-
1. **Hệ điều hành**: Windows, Linux, hoặc MacOS.
|
|
35
|
-
2. **Driver**: Cần cài đặt **ODBC Driver 17 for SQL Server**.
|
|
36
|
-
* [Tải về tại đây (Microsoft)](https://learn.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server)
|
|
37
|
-
3. **Python Libraries**:
|
|
38
|
-
```bash
|
|
39
|
-
pip install -r requirements.txt
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
## Cấu trúc Project
|
|
43
|
-
|
|
44
|
-
* `src/dbConnector.py`: Module chính chứa class `dbJob`.
|
|
45
|
-
* `config/db_config.yaml`: File cấu hình database (cần tự tạo dựa trên mẫu).
|
|
46
|
-
* `notebooks/demo_usage.ipynb`: Ví dụ cách sử dụng.
|
|
47
|
-
|
|
48
|
-
## Hướng dẫn sử dụng nhanh
|
|
49
|
-
|
|
50
|
-
### 1. Cấu hình kết nối
|
|
51
|
-
Tạo file `config/db_config.yaml`:
|
|
52
|
-
```yaml
|
|
53
|
-
db_info:
|
|
54
|
-
server: "localhost"
|
|
55
|
-
database: "MyDatabase"
|
|
56
|
-
username: "sa"
|
|
57
|
-
password: "mypassword"
|
|
File without changes
|
|
File without changes
|
{sqlserverconnector-0.1.0 → sqlserverconnector-0.1.2}/src/sqlServerConnector.egg-info/SOURCES.txt
RENAMED
|
File without changes
|
|
File without changes
|
{sqlserverconnector-0.1.0 → sqlserverconnector-0.1.2}/src/sqlServerConnector.egg-info/requires.txt
RENAMED
|
File without changes
|
{sqlserverconnector-0.1.0 → sqlserverconnector-0.1.2}/src/sqlServerConnector.egg-info/top_level.txt
RENAMED
|
File without changes
|