File size: 2,192 Bytes
495399f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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()