PostgreSQL 11 版本新增加 ERROR、SQLSTATE、ROW_COUNT、LAST_ERROR_MESSAGE、LAST_ERROR_SQLSTATE 五个变量用来记录SQL语句的执行结果状态和错误信息。
这些变量的值随着SQL执行后进行刷新,主要用来编写脚本时捕获SQL的执行结果。
Release 说明
Add psql variables to report query activity and errors (Fabien Coelho)
Specifically, the new variables are ERROR, SQLSTATE, ROW_COUNT, LAST_ERROR_MESSAGE, and LAST_ERROR_SQLSTATE.
变量解释
关于这几个变量的说明如下:
**ERROR**
true if the last SQL query failed, false if it succeeded. See also SQLSTATE.
**SQLSTATE**
The error code (see Appendix A) associated with the last SQL query is failure, or 00000 if it succeeded.
**ROW_COUNT**
The number of rows returned or affected by the last SQL query, or 0 if the query failed or did not report a row count.
**LAST_ERROR_MESSAGE**
**LAST_ERROR_SQLSTATE**
The primary error message and associated SQLSTATE code for the most recent failed query in the current psql session, or an empty string and 00000 if no error has occurred in the current session.
这几个变更的解释很容易理解,下面演示下。
演示:SQL执行成功
正常执行一条SQL,执行后查看 ERROR、SQLSTATE、ROW_COUNT 变量,如下:
[pg11@pghost2 ~]$ psql francs francs
psql (11beta3)
Type "help" for help.
francs=> SELECT * FROM generate_series(1,3);
generate_series
-----------------
1
2
3
(3 rows)
francs=> \echo :ERROR
false
francs=> \echo :SQLSTATE
00000
francs=> \echo :ROW_COUNT
3
演示:SQL执行失败
SQL执行失败,执行后查看 ERROR、SQLSTATE、ROW_COUNT 变更,如下:
francs=> SELECT *,afcd FROM generate_series(1,3);
ERROR: column "afcd" does not exist
LINE 1: SELECT *,afcd FROM generate_series(1,3);
^
francs=> \echo :ERROR
true
francs=> \echo :SQLSTATE
42703
francs=> \echo :ROW_COUNT
0
francs=> \echo :LAST_ERROR_MESSAGE
column "afcd" does not exist
francs=> \echo :LAST_ERROR_SQLSTATE
42703
SQLSTATE 变量返回SQL报错代码,SQL报错代码可参考手册 PostgreSQL Error Codes 。
参考
- psql
- PostgreSQL Error Codes
- Waiting for PostgreSQL 11 – Add psql variables to track success/failure of SQL queries.
新书推荐
最后推荐和张文升共同编写的《PostgreSQL实战》,本书基于PostgreSQL 10 编写,共18章,重点介绍SQL高级特性、并行查询、分区表、物理复制、逻辑复制、备份恢复、高可用、性能优化、PostGIS等,涵盖大量实战用例!