簡體   English   中英

在Postgresql中插入的條件規則

[英]Conditional rule on Insert in Postgresql

我的問題與我遇到的postgresql問題有關。 我想修改一個包含類似新聞組論壇的數據庫。 它的消息描述了一棵樹,並存儲在下表中:

\d messages
                                         Table « public.messages »
  Column   |            Type             |                          Modifiers
-----------+-----------------------------+------------------------------------------------------------------
 idmessage | integer                     | not NULL By default, nextval('messages_idmessage_seq'::regclass)
 title     | character varying(50)       | not NULL
 datemsg   | timestamp without time zone | By default, ('now'::text)::timestamp without time zone
 author    | character varying(10)       | By default, "current_user"()
 text      | text                        | not NULL
 idgroup   | integer                     | not NULL
 msgfather | integer                     |

(我翻譯了法語的輸出,希望不要添加誤解)

標題是消息標題,datemsg其時間戳,作者和文本都非常明確,idgroup是找到消息的討論組標識符,msgfather是該消息提示的另一條消息。 我要在插入時實施的規則是關於防止用戶為消息添加答案的組與父親不同的答案(如果有答案的話,因為新的討論會從沒有父項的情況下發布新消息開始)。

現在我有這個看法:

\d newmessage
           View « public.newmessage »
  Column   |         Type          | Modifiers
-----------+-----------------------+---------------
 idmessage | integer               |
 title     | character varying(50) |
 text      | text                  |
 idgroup   | integer               |
 msgfather | integer               |
View definition :
 SELECT messages.idmessage, messages.title, messages.text, messages.idgroup, messages.msgfather
   FROM messages;
Rules :
 ins_message AS
    ON INSERT TO newmessage DO INSTEAD  INSERT INTO messages (title, text, idgroup, msgfather)
  VALUES (new.title, new.text, new.idgroup, new.msgfather)

由於人們已經在使用數據庫,因此無法更改視圖或表,因此我認為我必須使用規則或觸發器。

我試圖將以下規則添加到視圖中,但沒有達到預期的效果:

CREATE OR REPLACE RULE ins_message_answer AS ON INSERT TO newmessage WHERE NEW.msgfather IS NOT NULL DO INSTEAD INSERT INTO messages( title, text, idgroup, msgfather) VALUES ( NEW.title, NEW.text, (SELECT idgroup FROM messages WHERE idmessage=new.msgfather), NEW.msgfather);

即使有了這個新規則,人們仍然可以回答一條消息,並將此答案設置在另一個組中。

我也嘗試通過添加WHERE NEW.msgfather IS NULL來更改ins_message規則,但是當我嘗試添加一條消息時,卻遇到了在newmessage視圖中插入時找不到規則的錯誤。

那么如何實現我想做的呢? 有觸發器嗎? (我不知道如何用postgresql做一個)。

首先為(idmessage, idgroup)創建一個唯一索引:

alter table messages add constraint messages_idmessage_idgroup_key
  unique (idmessage, idgroup);

下面的msgfather_idgroup_fkey需要此約束,因為外鍵約束要求匹配唯一索引,否則,將出現ERROR: there is no unique constraint matching given keys for referenced table "messages"

然后添加自引用外鍵:

alter table messages add constraint msgfather_idgroup_fkey
  foreign key (msgfather,idgroup) references messages(idmessage,idgroup);

順便:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM