Quote your substitutions
Don't have to commit; that's implicit
Save output to a log file that gets removed if we complete successfully
Run in single transaction mode
Use psql built-in option to store query results to log file