如何检查触发器函数中是否存在列?

How can I check if a column exists in a trigger function?

我想创建一个触发器函数。但是我想检查指定的列是否存在。

CREATE FUNCTION MyFunction()
RETURNS trigger AS '
BEGIN
  IF NEW.A >= 5 AND NEW.B <= 5 THEN
    // Do something ...
  END IF;
  RETURN NEW;
END' LANGUAGE 'plpgsql'

但我想检查 NEW.A 列是否存在。我该怎么做?

尝试并处理异常:

BEGIN
   IF NEW.a >= 5 ...
EXCEPTION
   WHEN undefined_column THEN
      [column "a" does not exist]
END;

您可以使用 json functions, 例如:

if 'col' = any(select jsonb_object_keys(to_jsonb(new))) then
    raise notice 'column col exists';
...

将行转换为 jsonb(在本例中不是 json)后,使用 ? 运算符检查是否存在给定的钥匙。但是检查是否存在,你运行其他检查之前运行否则会触发异常。

CREATE OR REPLACE FUNCTION myfunction()
  RETURNS trigger
  LANGUAGE plpgsql AS
$func$
BEGIN
   IF to_jsonb(NEW) ? 'a' THEN  -- lower-case!
      IF NEW.a >= 5 AND NEW.b <= 5 THEN
         -- do something
      END IF;
   ELSE
      -- RAISE EXCEPTION ?
   END IF;
   RETURN NEW;
END
$func$;

The manual about the ? operator:

Does the text string exist as a top-level key or array element within the JSON value?

旁白:

  • 不要引用语言名称,它是一个标识符。
  • 注意大写拼写。您的列名 A 最终是 a,没有双引号 ("A")。最好只使用合法的小写标识符以避免混淆。参见:
  • Are PostgreSQL column names case-sensitive?