Skip to content

Instantly share code, notes, and snippets.

@coryetzkorn
Created October 6, 2025 23:19
Show Gist options
  • Select an option

  • Save coryetzkorn/632bfa7a81dc3c7a7a75c7e0af13dba1 to your computer and use it in GitHub Desktop.

Select an option

Save coryetzkorn/632bfa7a81dc3c7a7a75c7e0af13dba1 to your computer and use it in GitHub Desktop.
Format and escape SQL for insertion into a Postgres text[] column
#!/usr/bin/env python3
import sys
def format_migration_as_text_array(filename):
"""Format a migration file as PostgreSQL text[] array literal"""
try:
with open(filename, 'r') as f:
lines = f.read().splitlines()
# Escape double quotes in each line
escaped = [line.replace('"', '\\"') for line in lines]
# Format as PostgreSQL array literal
result = '{"' + '","'.join(escaped) + '"}'
print(result)
except FileNotFoundError:
print(f"Error: File '{filename}' not found", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python3 format_migration.py <migration_file>", file=sys.stderr)
sys.exit(1)
format_migration_as_text_array(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment