PostgreSQL 中文参考文档
🌐 英文原版 官方 ↗

44.9. 实用工具函数 #

plpy 模块还提供了这些函数

plpy.debug(msg, **kwargs)
plpy.log(msg, **kwargs)
plpy.info(msg, **kwargs)
plpy.notice(msg, **kwargs)
plpy.warning(msg, **kwargs)
plpy.error(msg, **kwargs)
plpy.fatal(msg, **kwargs)

plpy.error 和 plpy.fatal 实际上会抛出一个 Python 异常,如果未被捕获,它会传播到调用查询, 导致当前事务或子事务被中止。 raise plpy.Error(msg) 和 raise plpy.Fatal(msg) 分别等价于调用 plpy.error(msg) 和 plpy.fatal(msg),但 raise 形式不允许传递关键字参数。 其他函数只会生成不同优先级的消息。 特定优先级的消息是否被报告给客户端、写入服务器日志或两者兼有,由 log_min_messages 和 client_min_messages 配置 变量控制。更多信息见 Chapter 19。

msg 参数以位置参数的形式给出。 出于向后兼容的原因,可以给出多于一个位置参数。这种情况下,位置 参数元组的字符串表示会成为报告给客户端的消息。

接受以下仅限关键字的参数:

detail
hint
sqlstate
schema_name
table_name
column_name
datatype_name
constraint_name

以仅限关键字参数传入的对象的字符串表示被用于丰富报告给客户端的 消息。例如:

CREATE FUNCTION raise_custom_exception() RETURNS void AS $$
plpy.error("custom exception message",
           detail="some info about exception",
           hint="hint for users")
$$ LANGUAGE plpython3u;

=# SELECT raise_custom_exception();
ERROR:  plpy.Error: custom exception message
DETAIL:  some info about exception
HINT:  hint for users
CONTEXT:  Traceback (most recent call last):
  PL/Python function "raise_custom_exception", line 4, in <module>
    hint="hint for users")
PL/Python function "raise_custom_exception"

另一组实用工具函数是 plpy.quote_literal(string)、 plpy.quote_nullable(string) 和 plpy.quote_ident(string)。 它们等价于 Section 9.4 中描述的内建引号处理函数。它们在构造 临时查询时很有用。 Example 41.1 中动态 SQL 的 PL/Python 等价写法是:

plpy.execute("UPDATE tbl SET %s = %s WHERE key = %s" % (
    plpy.quote_ident(colname),
    plpy.quote_nullable(newvalue),
    plpy.quote_literal(keyvalue)))