Spaces:
Sleeping
Sleeping
Download utils/db.py from bagustenan/backend: direct link, hf CLI and curl.
- Browser
- Download file 2.19 kB
-
https://huggingface.co/spaces/bagustenan/backend/resolve/main/utils/db.py
- Command line
-
hf download hf://spaces/bagustenan/backend/utils/db.py
-
curl -L -o db.py https://huggingface.co/spaces/bagustenan/backend/resolve/main/utils/db.py
2.19 kB
| import os | |
| import psycopg2 | |
| from psycopg2.extras import RealDictCursor | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| def get_db_connection(): | |
| """Create a connection to PostgreSQL database""" | |
| return psycopg2.connect( | |
| os.getenv("DIRECT_URL"), | |
| cursor_factory=RealDictCursor | |
| ) | |
| def save_file_metadata(name: str, file_type: str, bps_var_id: int = None, bps_year: int = None, bps_subject: str = None): | |
| """ | |
| Save file metadata to the Files table in Supabase. | |
| Args: | |
| name: File or dataset name | |
| file_type: 'upload' or 'bps' | |
| bps_var_id: BPS variable ID (optional) | |
| bps_year: BPS year code (optional) | |
| bps_subject: BPS subject name (optional) | |
| Returns: | |
| dict: Created file record | |
| """ | |
| conn = get_db_connection() | |
| cursor = conn.cursor() | |
| try: | |
| query = """ | |
| INSERT INTO "Files" (id, name, type, "bpsVarId", "bpsYear", "bpsSubject", created_at, updated_at) | |
| VALUES (gen_random_uuid()::text, %s, %s, %s, %s, %s, NOW(), NOW()) | |
| RETURNING * | |
| """ | |
| cursor.execute(query, (name, file_type, bps_var_id, bps_year, bps_subject)) | |
| result = cursor.fetchone() | |
| conn.commit() | |
| return dict(result) if result else None | |
| except Exception as e: | |
| conn.rollback() | |
| print(f"Error saving file metadata: {e}") | |
| return None | |
| finally: | |
| cursor.close() | |
| conn.close() | |
| def check_duplicate_bps_data(var_id: int, year: int): | |
| """ | |
| Check if BPS data for a specific var_id and year already exists. | |
| Returns: | |
| bool: True if exists, False otherwise | |
| """ | |
| conn = get_db_connection() | |
| cursor = conn.cursor() | |
| try: | |
| query = """ | |
| SELECT COUNT(*) as count FROM "Files" | |
| WHERE type = 'bps' AND "bpsVarId" = %s AND "bpsYear" = %s | |
| """ | |
| cursor.execute(query, (var_id, year)) | |
| result = cursor.fetchone() | |
| return result['count'] > 0 if result else False | |
| except Exception as e: | |
| print(f"Error checking duplicate: {e}") | |
| return False | |
| finally: | |
| cursor.close() | |
| conn.close() | |