Upload ml/db.py with huggingface_hub
Browse files
ml/db.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Database connection helper for the ML pipeline."""
|
| 2 |
+
|
| 3 |
+
import psycopg2
|
| 4 |
+
import psycopg2.extras
|
| 5 |
+
from config import DB
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def get_conn():
|
| 9 |
+
"""Return a new psycopg2 connection."""
|
| 10 |
+
return psycopg2.connect(
|
| 11 |
+
host=DB["host"],
|
| 12 |
+
port=DB["port"],
|
| 13 |
+
dbname=DB["dbname"],
|
| 14 |
+
user=DB["user"],
|
| 15 |
+
password=DB["password"],
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def fetch_all(sql, params=None):
|
| 20 |
+
with get_conn() as conn:
|
| 21 |
+
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
|
| 22 |
+
cur.execute(sql, params or ())
|
| 23 |
+
return cur.fetchall()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def fetch_one(sql, params=None):
|
| 27 |
+
with get_conn() as conn:
|
| 28 |
+
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
|
| 29 |
+
cur.execute(sql, params or ())
|
| 30 |
+
return cur.fetchone()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def execute(sql, params=None):
|
| 34 |
+
with get_conn() as conn:
|
| 35 |
+
with conn.cursor() as cur:
|
| 36 |
+
cur.execute(sql, params or ())
|
| 37 |
+
conn.commit()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def execute_batch(sql, params_list, page_size=500):
|
| 41 |
+
with get_conn() as conn:
|
| 42 |
+
with conn.cursor() as cur:
|
| 43 |
+
psycopg2.extras.execute_batch(cur, sql, params_list, page_size=page_size)
|
| 44 |
+
conn.commit()
|