如何从 psql -f my_script.sql 调用的脚本中引发错误
How to raise an error from a script called from psql -f my_script.sql
我在 sql 脚本中执行以下操作,我通过 psql -f my_script.sql
:
调用该脚本
select not exists(select 1 from pg_class where relname='my_table') as my_table_not_exists
\gset
\if :my_table_not_exists
-- raise error
\endif
我怎样才能 return 一个非 0 的状态代码并将 table 'table_name' doesn't exist
写入那里的标准错误?
您可以设置ON_ERROR_STOP
,然后使用table,然后您将收到所需的错误消息,处理将终止:
\set ON_ERROR_STOP on
SELECT * FROM my_table WHERE FALSE;
您可以将任意消息输出到标准输出:
\! echo 'Hello!' 1>&2
但是没有办法使用非零 return 代码退出 psql
,除非导致数据库错误。
也许您应该使用带有 psql
协同进程的 bash 脚本来进行更花哨的处理。
您可以在 ON_ERROR_STOP
上设置
\set ON_ERROR_STOP on
select * from Table Name;
\unset ON_ERROR_STOP
请参考this
我在 sql 脚本中执行以下操作,我通过 psql -f my_script.sql
:
select not exists(select 1 from pg_class where relname='my_table') as my_table_not_exists
\gset
\if :my_table_not_exists
-- raise error
\endif
我怎样才能 return 一个非 0 的状态代码并将 table 'table_name' doesn't exist
写入那里的标准错误?
您可以设置ON_ERROR_STOP
,然后使用table,然后您将收到所需的错误消息,处理将终止:
\set ON_ERROR_STOP on
SELECT * FROM my_table WHERE FALSE;
您可以将任意消息输出到标准输出:
\! echo 'Hello!' 1>&2
但是没有办法使用非零 return 代码退出 psql
,除非导致数据库错误。
也许您应该使用带有 psql
协同进程的 bash 脚本来进行更花哨的处理。
您可以在 ON_ERROR_STOP
上设置\set ON_ERROR_STOP on
select * from Table Name;
\unset ON_ERROR_STOP
请参考this