我正在开发一个框架,可以在 PostgreSQL 9.1 上为内容存储动态创建表。API 函数之一允许调用者通过指定给定对象(例如,Web 表单)中的所有字段来保存新的内容条目。为了接收一组字段,框架创建了一个复合类型。
考虑以下代码:
CREATE SEQUENCE seq_contents MINVALUE 10000;
CREATE TABLE contents (
content_id int8 not null,
is_edited boolean not null default false,
is_published boolean not null default false,
"Input1" varchar(60),
"CheckBox1" int2,
"TheBox" varchar(60),
"Slider1" varchar(60)
);
CREATE TYPE "contentsType" AS (
"Input1" varchar(60),
"CheckBox1" int2,
"TheBox" varchar(60),
"Slider1" varchar(60)
);
CREATE OR REPLACE FUNCTION push(in_all anyelement) RETURNS int8 AS $push$
DECLARE
_c_id int8;
BEGIN
SELECT nextval('seq_contents') INTO _c_id;
EXECUTE $$INSERT INTO contents
SELECT a.*, b.*
FROM (SELECT $1, true, false) AS a,
(SELECT $2.*) AS b$$ USING _c_id, in_all;
RETURN _c_id;
END;
$push$ LANGUAGE plpgsql;
现在,为了调用这个函数,我必须添加显式转换,如下所示:
SELECT push(('input1',1,'thebox','slider1')::"contentsType");
有没有办法避免显式转换?因为我希望外部调用者不要处理强制转换,即隐藏 PostgreSQL 函数背后的逻辑。目前我有这样的错误:
SELECT push(('input1',1,'thebox','slider1'));
ERROR: PL/pgSQL functions cannot accept type record
CONTEXT: compilation of PL/pgSQL function "push" near line 1