插入分区表返回违反检查约束但不应该

时间:2014-06-08 18:11:31

标签: sql postgresql triggers data-partitioning check-constraint

我在postgresql中有一个表,我希望它被分区。结构如下

TABLE "DTD1"."logAdminActivity" ( 
    "username" CHARACTER VARYING( 200 ) NOT NULL, 
    "action" CHARACTER VARYING( 100 ) NOT NULL, 
    "pk" CHARACTER VARYING( 5 )  NOT NULL, 
    "tabel" CHARACTER VARYING( 200 )NOT NULL, 
    "timestamp" TIMESTAMP WITHOUT TIME ZONE
);

然后我创建了一个继承Tabel“DTD1”的分区表。上面的“logAdminActivity”如下所示:

CREATE TABLE "DTD1".logAdminActivity_kategori ( 
    CHECK ('tabel'='kategori')
) INHERITS ("DTD1"."logAdminActivity");

CREATE TABLE "DTD1".logAdminActivity_subyek (
    CHECK ('tabel'='subyek')
 ) INHERITS ("DTD1"."logAdminActivity");

...

CREATE TABLE "DTD1".logAdminActivity_satuan (
    CHECK ('tabel'='satuan')
 ) INHERITS ("DTD1"."logAdminActivity");

CREATE TABLE "DTD1".logAdminActivity_memberfilter (
    CHECK ('tabel'='memberFilter')
 ) INHERITS ("DTD1"."logAdminActivity");

之后,我在username coloumn中为每个分区表创建索引。然后我创建了这个触发器函数并在下面触发该调用触发器函数。因此,当我插入数据时,相应的tabel coloumn将被重定向到正确的分区表。

CREATE OR REPLACE FUNCTION "DTD1".logAdminActivity_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN
    IF ( New."tabel" = 'kategori' ) THEN
        INSERT INTO "DTD1".logAdminActivity_kategori VALUES (NEW.*);
    ELSIF ( New."tabel" = 'subyek' ) THEN
        INSERT INTO "DTD1".logAdminActivity_subyek VALUES (NEW.*);
    ..    
    ELSE
        RAISE EXCEPTION 'Tabel out of range.  Fix the logAdminActivity_insert_trigger() function!' ;
    END IF;
    RETURN NULL;
END;
$$
LANGUAGE plpgsql;

CREATE TRIGGER insert_logAdminActivity_trigger
    BEFORE INSERT ON "DTD1"."logAdminActivity"
    FOR EACH ROW EXECUTE PROCEDURE "DTD1".logAdminActivity_insert_trigger();

然后我通过插入程序测试它,如

INSERT INTO "DTD1"."logadminactivity_subyek" ( "action", "pk", "tabel", "timestamp", "username") 
VALUES ( 'bla', '12312', 'subyek', '2014-01-01 02:02:03', 'asdf' );

但为什么它返回错误看起来像这样

  

错误:关系“logadminactivity_subyek”的新行违反了检查   约束“logadminactivity_subyek_check”DETAIL:失败的行   包含(asdf,bla,subyek,12312,2014-01-01 02:02:03)。

如何发生这种情况,因为我试图按照此处的文档进行操作?

  

http://www.postgresql.org/docs/9.3/static/ddl-partitioning.html

我认为上面查询中的'tabel'值('subyek')与触发函数不匹配,但是当我检查check约束时它会通过。 有没有我想念它的部分,还是有任何解决方案来解决这个问题?

此致

1 个答案:

答案 0 :(得分:2)

CHECK ('tabel'='subyek')

该检查约束不正确,因为'tabel'是常量。

相当于CHECK (false)

你想要

CHECK ("tabel"='subyek')