插入INSERT RULE而不是UPDATE

时间:2019-02-26 21:57:37

标签: python database postgresql freebsd

我有一个简单的表,该表由三列组成;一个bigint,一个布尔值和一个文本。像这样的东西:

CREATE SEQUENCE foo_seq;
CREATE TABLE foo (
    i_foo     BIGINT DEFAULT nextval('foo_seq'),
    isok      BOOLEAN DEFAULT TRUE,
    who       CHARACTER VARYING(32) NOT NULL
);
ALTER TABLE foo ADD CONSTRAINT foo_pkey PRIMARY KEY (i_foo);
CREATE RULE foo_insert AS ON INSERT TO foo DO (
    DELETE FROM foo
        WHERE ((foo.i_foo < NEW.i_foo) AND (NEW.who = foo.who))
);

更新非常接近。我希望在插入之后,该表始终具有一行并且仅增加i_foo。

当我手动插入新项目时,它可以正常工作,它将删除最后一个项目并插入新项目。换句话说,只是i_foo增加一。

但是,相同的命令在python脚本中无法正常工作。所有实体(包括新实体)将被删除。并且表格在插入后将为空。

INSERT INTO foo (isok, who) VALUES (True, 'someone');

class adoerclass(threading.Thread):

    def __init__(self, db):
        self.db = db
        threading.Thread.__init__(self)
        self.setDaemon(True)
        self.start()

    def run(self):
        while True:
            isGood = True
            try:
                lock.acquire()
                self.db.execute("INSERT INTO foo (isok, who) "
                "VALUES (%s, %s)", [isGood, 'someone'])
                self.db.commit()
                lock.release()
            except:
                lock.release()
                print("exception!")
                time.sleep(RETRY_TIME)
                lock.release()

我很困惑。

1 个答案:

答案 0 :(得分:2)

最后,我为此写了一个触发器。效果很好

CREATE SEQUENCE foo_seq;
CREATE TABLE foo (
    i_foo     BIGINT DEFAULT nextval('foo_seq'),
    isok      BOOLEAN DEFAULT TRUE,
    who       CHARACTER VARYING(32) NOT NULL
);
ALTER TABLE foo ADD CONSTRAINT foo_pkey PRIMARY KEY (i_foo);
CREATE FUNCTION foo_insert_before() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
BEGIN
    DELETE FROM foo WHERE (( NEW.i_foo > foo.i_foo ) AND (NEW.who = foo.who));
    RETURN NEW;
END;
$$;

CREATE TRIGGER foo_insert BEFORE INSERT ON foo FOR EACH ROW EXECUTE PROCEDURE foo_insert_before();