Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop a Postgres script when it encounters an error?

Is there a way to specify that when executing a sql script it stops when encountering the first error on the script, it usually continues, regardless of previous errors.

like image 743
Ray Avatar asked Dec 18 '10 21:12

Ray


People also ask

How do I stop a Postgres session?

The meta-command for exiting psql is \q .

What is error in PostgreSQL?

All messages emitted by the PostgreSQL server are assigned five-character error codes that follow the SQL standard's conventions for "SQLSTATE" codes. Applications that need to know which error condition has occurred should usually test the error code, rather than looking at the textual error message.

Does PostgreSQL requires maintenance as its unstable?

Advantage and disadvantage of PostgreSQLIt requires low maintenance management for enterprise as well as embedded usage. PostgreSQL manages data in a relational database as it is very powerful and robust.


2 Answers

I think the solution to add following to .psqlrc is far from perfection

\set ON_ERROR_STOP on 

there exists much more simple and convenient way - use psql with parameter:

psql -v ON_ERROR_STOP=1 

better to use also -X parameter turning off .psqlrc file usage. Works perfectly for me

p.s. the solution found in great post from Peter Eisentraut. Thank you, Peter! http://petereisentraut.blogspot.com/2010/03/running-sql-scripts-with-psql.html

like image 89
Alfishe Avatar answered Oct 09 '22 08:10

Alfishe


I assume you are using psql, this might be handy to add to your ~/.psqlrc file.

\set ON_ERROR_STOP on 

This will make it abort on the first error. If you don't have it, even with a transaction it will keep executing your script but fail on everything until the end of your script.

And you probably want to use a transaction as Paul said. Which also can be done with psql --single-transaction ... if you don't want to alter the script.

So a complete example, with ON_ERROR_STOP in your .psqlrc:

psql --single-transaction --file /your/script.sql 
like image 20
plundra Avatar answered Oct 09 '22 09:10

plundra