|
| 1 | +# This script connects to a PostgreSQL database using credentials from a .env file, |
| 2 | +# executes a SQL query from create_list.sql, and writes the results to a CSV file. |
| 3 | +# It is intended to generate a validator acceptance list for GTFS feeds. |
| 4 | + |
| 5 | +import os |
| 6 | +import csv |
| 7 | +import psycopg2 |
| 8 | +import argparse |
| 9 | +from dotenv import load_dotenv |
| 10 | + |
| 11 | +# Parse command-line arguments for the --env-file parameter |
| 12 | +# This allows the user to specify which .env file to use for DB credentials |
| 13 | +def parse_args(): |
| 14 | + parser = argparse.ArgumentParser(description="Create validator acceptance list CSV from DB query.") |
| 15 | + parser.add_argument('--env-file', default='config/.env.local', help='Path to .env file (default: config/.env.local)') |
| 16 | + return parser.parse_args() |
| 17 | + |
| 18 | +# Define the paths for the SQL query file and the output CSV file |
| 19 | +SQL_FILE = os.path.join(os.path.dirname(__file__), 'create_list.sql') |
| 20 | +CSV_FILE = os.path.join(os.path.dirname(__file__), 'acceptance_test_feed_list.csv') |
| 21 | + |
| 22 | +def main(): |
| 23 | + args = parse_args() |
| 24 | + # Load environment variables from the specified env file |
| 25 | + load_dotenv(args.env_file) |
| 26 | + |
| 27 | + # Read PostgreSQL connection parameters from environment variables |
| 28 | + DB_HOST = os.getenv('POSTGRES_HOST') |
| 29 | + DB_PORT = os.getenv('POSTGRES_PORT') |
| 30 | + DB_NAME = os.getenv('POSTGRES_DB') |
| 31 | + DB_USER = os.getenv('POSTGRES_USER') |
| 32 | + DB_PASS = os.getenv('POSTGRES_PASSWORD') |
| 33 | + |
| 34 | + # Print DB connection variables (except password) for debugging |
| 35 | + print(f"Connecting to PostgreSQL with:") |
| 36 | + print(f" HOST: {DB_HOST}") |
| 37 | + print(f" PORT: {DB_PORT}") |
| 38 | + print(f" DB: {DB_NAME}") |
| 39 | + print(f" USER: {DB_USER}") |
| 40 | + |
| 41 | + # Read SQL query from file |
| 42 | + with open(SQL_FILE, 'r') as f: |
| 43 | + query = f.read() |
| 44 | + |
| 45 | + # Connect to PostgreSQL and execute the query |
| 46 | + conn = psycopg2.connect( |
| 47 | + host=DB_HOST, |
| 48 | + port=DB_PORT, |
| 49 | + dbname=DB_NAME, |
| 50 | + user=DB_USER, |
| 51 | + password=DB_PASS |
| 52 | + ) |
| 53 | + cur = conn.cursor() |
| 54 | + # Enforce read-only session for extra safety |
| 55 | + cur.execute("SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY;") |
| 56 | + cur.execute(query) |
| 57 | + rows = cur.fetchall() |
| 58 | + headers = [desc[0] for desc in cur.description] |
| 59 | + |
| 60 | + # Write results to CSV file |
| 61 | + with open(CSV_FILE, 'w', newline='') as csvfile: |
| 62 | + writer = csv.writer(csvfile) |
| 63 | + writer.writerow(headers) |
| 64 | + writer.writerows(rows) |
| 65 | + |
| 66 | + # Clean up DB connection |
| 67 | + cur.close() |
| 68 | + conn.close() |
| 69 | + |
| 70 | +if __name__ == '__main__': |
| 71 | + main() |
0 commit comments