PostgreSQL继承表始终返回具有空值的行

时间:2010-01-27 11:20:40

标签: postgresql triggers

我指的是http://www.if-not-true-then-false.com/2009/11/howto-create-postgresql-table-partitioning-part-1/

要重现此问题,请执行以下一些简单步骤:

(1)创建名为“tutorial”的数据库

(2)执行以下SQL查询:

CREATE TABLE impressions_by_day (
    advertiser_id SERIAL NOT NULL,
    day DATE NOT NULL DEFAULT CURRENT_DATE,
    impressions INTEGER NOT NULL,
        PRIMARY KEY (advertiser_id, day)
);

CREATE OR REPLACE FUNCTION insert_table()
  RETURNS void AS
$BODY$DECLARE
    _impressions_by_day impressions_by_day;
BEGIN
    INSERT INTO impressions_by_day(impressions ) VALUES(888) RETURNING  * INTO _impressions_by_day;

    RAISE NOTICE 'After insert, the returned advertiser_id is %', _impressions_by_day.advertiser_id;
END;$BODY$
  LANGUAGE 'plpgsql' VOLATILE;
ALTER FUNCTION insert_table() OWNER TO postgres;

(3)创建名为“tutorial_partition”的数据库

(4)执行以下SQL查询:

CREATE TABLE impressions_by_day (
    advertiser_id SERIAL NOT NULL,
    day DATE NOT NULL DEFAULT CURRENT_DATE,
    impressions INTEGER NOT NULL,
        PRIMARY KEY (advertiser_id, day)
);

CREATE OR REPLACE FUNCTION insert_table()
  RETURNS void AS
$BODY$DECLARE
    _impressions_by_day impressions_by_day;
BEGIN
    INSERT INTO impressions_by_day(impressions ) VALUES(888) RETURNING  * INTO _impressions_by_day;

    RAISE NOTICE 'After insert, the returned advertiser_id is %', _impressions_by_day.advertiser_id;
END;$BODY$
  LANGUAGE 'plpgsql' VOLATILE;
ALTER FUNCTION insert_table() OWNER TO postgres;

CREATE TABLE impressions_by_day_y2010m1ms2 (
    PRIMARY KEY (advertiser_id, day), 
    CHECK ( day >= DATE '2010-01-01' AND day < DATE '2010-03-01' )
) INHERITS (impressions_by_day);


CREATE INDEX impressions_by_day_y2010m1ms2_index ON impressions_by_day_y2010m1ms2 (day);


CREATE OR REPLACE FUNCTION impressions_by_day_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN
    IF ( NEW.day >= DATE '2010-01-01' AND NEW.day < DATE '2010-03-01' ) THEN 
        INSERT INTO impressions_by_day_y2010m1ms2 VALUES (NEW.*); 
    ELSE
        RAISE EXCEPTION 'Date out of range.  Something wrong with the impressions_by_day_insert_trigger() function!';
    END IF;
    RETURN NULL;
END;
$$
LANGUAGE plpgsql;

CREATE TRIGGER insert_impressions_by_day_trigger 
    BEFORE INSERT ON impressions_by_day 
    FOR EACH ROW EXECUTE PROCEDURE impressions_by_day_insert_trigger();

(5)执行

SELECT * FROM insert_table() on tutorial

我们得到了

注意:插入后,返回的advertiser_id为1

(6)执行

SELECT * FROM insert_table() on tutorial_partition

我们得到了

注意:插入后,返回的advertiser_id为

如何将advertiser_id设为1,也可以在tutorial_partition中找到?

1 个答案:

答案 0 :(得分:0)

触发器返回NULL,这表示INSERT不执行任何操作。由于未执行任何操作,因此RETURNING *子句不返回任何内容。您无法在同一操作中拦截(并覆盖)INSERT 使用RETURNING并获得有意义的任何内容。