import os
import psycopg2
from psycopg2.extras import RealDictCursor

# Read credentials from environment variables
POSTGRES_HOST = os.getenv("POSTGRES_HOST", "postgres")
POSTGRES_USER = os.getenv("POSTGRES_USER")
POSTGRES_PASSWORD = os.getenv("POSTGRES_PASSWORD")
POSTGRES_DB = os.getenv("POSTGRES_DB")

def get_db_connection():
    conn = psycopg2.connect(
        host=POSTGRES_HOST,
        user=POSTGRES_USER,
        password=POSTGRES_PASSWORD,
        dbname=POSTGRES_DB
    )
    return conn

# Example usage
if __name__ == "__main__":
    conn = get_db_connection()
    cur = conn.cursor(cursor_factory=RealDictCursor)
    
    # Get all table names in the public schema
    cur.execute("""
        SELECT table_name 
        FROM information_schema.tables 
        WHERE table_schema = 'public' 
        AND table_type = 'BASE TABLE';
    """)
    tables = cur.fetchall()
    
    for table in tables:
        table_name = table['table_name']
        print(f"Contents of table: {table_name}")
        
        # Fetch all rows in the table
        cur.execute(f"SELECT * FROM {table_name};")
        rows = cur.fetchall()
        
        for row in rows:
            print(row)
        print("\n")
    
    cur.close()
    conn.close()

