简体   繁体   English

如何获取function中某行的主键值?

[英]How to get the primary key value of a row in a function?

I have a function in postgres that sends events on CRUD operations in my tables.我在 postgres 中有一个 function,它在我的表中发送有关 CRUD 操作的事件。 However the problem is that it only works for tables that have an id column which is the primary key.然而,问题是它只适用于具有主键id列的表。 How can I change this so that I can use whatever column is the primary key?我该如何更改它以便我可以使用任何列作为主键?

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
SET search_path = PUBLIC,
pg_catalog;
CREATE OR REPLACE FUNCTION psycopg2_pgevents_create_event() RETURNS TRIGGER AS $function$
  BEGIN
    IF (TG_OP = 'DELETE') THEN
        PERFORM pg_notify('psycopg2_pgevents_channel',
        json_build_object(
            'event_id', uuid_generate_v4(),
            'event_type', TG_OP,
            'schema_name', TG_TABLE_SCHEMA,
            'table_name', TG_TABLE_NAME,
            'row_id', OLD.id            -------- this is not always "id"
        )::text
     );
         RETURN NULL;
    ELSE
        raise notice 'Value: %', NEW;
        PERFORM pg_notify('psycopg2_pgevents_channel',
            json_build_object(
                'event_id', uuid_generate_v4(),
                'event_type', TG_OP,
                'schema_name', TG_TABLE_SCHEMA,
                'table_name', TG_TABLE_NAME,
                'row_id', NEW.id,         -------- this is not always "id"
                'data', NEW
        )::text
    );
    RETURN NULL;
    END IF;
  END;
$function$ LANGUAGE PLPGSQL;
SET search_path = "$user",
    PUBLIC;

If you only have a single primary key column, and you just want its value, you can extract it using:如果你只有一个主键列,而你只想要它的值,你可以使用以下方法提取它:

to_jsonb(NEW)->>(
  SELECT attname
  FROM pg_attribute
  JOIN pg_index ON indexrelid = attrelid
  WHERE indrelid = TG_RELID
    AND indisprimary
)

If you've got multiple primary key columns, and/or you want to retrieve the PK in {"key":"value"} format, you could use:如果你有多个主键列,和/或你想以{"key":"value"}格式检索 PK,你可以使用:

SELECT jsonb_object_agg(attname, to_jsonb(NEW)->attname)
FROM pg_attribute
JOIN pg_index ON indexrelid = attrelid
WHERE indrelid = TG_RELID
  AND indisprimary

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM