How to save and restore value of ON_ERROR_STOP?

房东的猫 提交于 2019-12-11 09:55:59

问题


Is there a way to save, temporarily change, and then restore the value of the psql ON_ERROR_STOP variable?

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!