问题
Is there a way to save, temporarily change, and then restore the value of the
psqlON_ERROR_STOPvariable?
Basically, I'd like to have the "moral equivalent" of the following in a psql script:
save_on_error_stop=ON_ERROR_STOP
\unset ON_ERROR_STOP
ALTER TABLE foo DROP COLUMN bar; -- (for example)
\set ON_ERROR_STOP save_on_error_stop
ALTER TABLE foo ADD COLUMN bar;
The point being that the '\set' command at the end won't actually set ON_ERROR_STOP unless it was set before.
回答1:
I don't think it is possible to do this in a single psql session. According to the manual, one can use \set command on it's own to list all psql variables.
One can memorize the setting in shell, but this makes the whole thing useless, as it is much more simple just to execute the desired set of queries enforcing the desired ON_ERROR_STOP value.
Another alternative is to write an anonymous code block and DO some extra logic to detect, whether column needs to be dropped before adding it.
BTW, What is the purpose of dropping and adding column straight after?
If it is only to make sure no such column exists, how bout this DO block:
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema='public' AND table_name='foo'
AND column_name='bar')
THEN
EXECUTE format('ALTER TABLE %I.%I ADD %I text',
'public','foo','bar');
END IF;
END; $$;
You can also create a function if you tend to do such check quite often.
来源:https://stackoverflow.com/questions/14730762/how-to-save-and-restore-value-of-on-error-stop