Files
syncrow-data/scripts/deploy_views.py

89 lines
2.8 KiB
Python

import os
import psycopg2
import argparse
from pathlib import Path
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv(dotenv_path='.env.azure-development')
#load_dotenv(dotenv_path='.env.localhost')
# Database connection parameters
db_params = {
'host': os.getenv('POSTGRES_HOST'),
'port': os.getenv('POSTGRES_PORT'),
'database': os.getenv('POSTGRES_DB'),
'user': os.getenv('POSTGRES_USER'),
'password': os.getenv('POSTGRES_PASSWORD')
}
def create_or_replace_view(cursor, view_name, sql_content):
# First drop the view if it exists
drop_sql = f"DROP VIEW IF EXISTS {view_name} CASCADE"
cursor.execute(drop_sql)
# Create view
view_sql = f"CREATE VIEW {view_name} AS {sql_content}"
cursor.execute(view_sql)
def main():
# Set up argument parser
parser = argparse.ArgumentParser(description='Deploy SQL views to database')
parser.add_argument('--list', action='store_true', help='Only print the SQL files that would be processed without making changes')
parser.add_argument('--target', help='Deploy only a specific SQL file (provide the file name with or without .sql extension)')
args = parser.parse_args()
# Find all .sql files
sql_files = list(Path('.').rglob('*.sql'))
# Filter for specific file if --target is provided
if args.target:
target = args.target if args.target.endswith('.sql') else f"{args.target}.sql"
sql_files = [f for f in sql_files if f.name == target]
if not sql_files:
print(f"Error: Target file '{target}' not found")
exit(1)
# If list mode, just print the files and exit
if args.list:
print("SQL files detected:")
for sql_file in sql_files:
print(f" - {sql_file}")
return
# Connect to the database
conn = psycopg2.connect(**db_params)
cursor = conn.cursor()
try:
for sql_file in sql_files:
# Get view name from file path (remove .sql extension)
view_name = sql_file.stem
# Read SQL content
with open(sql_file, 'r') as f:
sql_content = f.read().strip()
# Skip empty files
if not sql_content:
print(f"Skipping empty file: {sql_file}")
continue
print(f"Creating/replacing view: {view_name}")
create_or_replace_view(cursor, view_name, sql_content)
# Commit all changes
conn.commit()
print("All views deployed successfully!")
except Exception as e:
print(f"Error: {str(e)}")
conn.rollback()
exit(1)
finally:
cursor.close()
conn.close()
if __name__ == "__main__":
main()