在 PostgreSQL 中设置变量 Funtion/Trigger

Set variables in a PostgreSQL Funtion/Trigger

我正在尝试根据时间在 PostgreSQL 数据库中创建分区。虽然下面的 function/trigger 是我遇到服务器的大部分目的,但我仍然需要找出一种方法来设置 table 名称和模式名称参数。正如我们计划在 运行 上一样,针对不同 table 和模式的相同触发器会更改参数值。非常感谢任何帮助,因为我几乎没有使用 functions/triggers 的经验。

CREATE OR REPLACE FUNCTION
myschema.server_partition_function()
RETURNS TRIGGER AS 
$BODY$
DECLARE
_new_time int;
_tablename text;
_startdate text;
_enddate text;
_result record;
BEGIN
--Takes the current inbound "time" value and determines when midnight is for the given date
_new_time := ((NEW."time"/86400)::int)*86400;
_startdate := to_char(to_timestamp(_new_time), 'YYYY-MM-DD');
_tablename := 'server_'||_startdate;

-- Check if the partition needed for the current record exists
PERFORM 1
FROM   pg_catalog.pg_class c
JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE  c.relkind = 'r'
AND    c.relname = _tablename
AND    n.nspname = 'myschema';

-- If the partition needed does not yet exist, then we create it:
-- Note that || is string concatenation (joining two strings to make one)
IF NOT FOUND THEN
_enddate:=_startdate::timestamp + INTERVAL '1 day';
EXECUTE 'CREATE TABLE myschema.' || quote_ident(_tablename) || ' (
CHECK ( "time" >= EXTRACT(EPOCH FROM DATE ' || quote_literal(_startdate) || ')
AND "time" < EXTRACT(EPOCH FROM DATE ' || quote_literal(_enddate) || ')
)
) INHERITS (myschema.server_master)';

-- Table permissions are not inherited from the parent.
-- If permissions change on the master be sure to change them on the child also.
EXECUTE 'ALTER TABLE myschema.' || quote_ident(_tablename) || ' OWNER TO postgres';
EXECUTE 'GRANT ALL ON TABLE myschema.' || quote_ident(_tablename) || ' TO my_role';

-- Indexes are defined per child, so we assign a default index that uses the partition columns
EXECUTE 'CREATE INDEX ' || quote_ident(_tablename||'_indx1') || ' ON myschema.' || quote_ident(_tablename) || ' (time, id)';
END IF;

-- Insert the current record into the correct partition, which we are sure will now exist.
EXECUTE 'INSERT INTO myschema.' || quote_ident(_tablename) || ' VALUES (.*)' USING NEW;
RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql;

您可能需要使用一些动态触发特殊变量。调用触发器时,PostgreSQL 使用特殊变量自动提供一些值:http://www.postgresql.org/docs/current/static/plpgsql-trigger.html

_tablename  := TG_TABLE_NAME || '_' || _startdate;
_schemaname := TG_TABLE_SCHEMA || '_partitions';