根據Documentation表示, Notify 可以在table 有insert/update/delete 的時候推出一個通知.
那麼來做個小測試吧~
首先, 我們用 pgadmin 的 query 視窗先建立一個測試用的table
CREATE TABLE test_table
然後, 建立一個 trigger 觸發後要執行的 function(id serial NOT NULL,test_col_1 character varying)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION notify_event() RETURNS TRIGGER AS $$ | |
BEGIN | |
// Execute pg_notify(channel, notification) | |
PERFORM pg_notify('table_changed', 'new row added'::text); | |
// Result is ignored since this is an AFTER trigger | |
RETURN NULL; | |
END; | |
$$ LANGUAGE plpgsql; | |
最後, 建立一個 trigger 來觸發事件
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Trigger: table_changed on test_table | |
CREATE TRIGGER table_changed | |
AFTER INSERT | |
ON test_table | |
FOR EACH ROW | |
EXECUTE PROCEDURE notify_event(); |
DB 的部分處理好了之後, 我們來寫一段小程式試試看
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include '../conn.php'; | |
set_time_limit(0); | |
ob_end_clean(); | |
//開始監聽之前要先向DB下一個 LISTEN table_changed 的 query | |
pg_query($conn, 'LISTEN table_changed;'); | |
while(true){ | |
$notify = pg_get_notify($conn); | |
if (!$notify) { | |
echo json_encode(array('result'=>false, 'data'=>'No messages')).PHP_EOL; | |
ob_flush(); | |
flush(); | |
sleep(1); | |
} else { | |
echo json_encode(array('result'=>true, 'process_id'=>$pid , 'pid' => pg_get_pid($conn), 'data' => $notify)).PHP_EOL; | |
} | |
} |
然後就在該目錄下cmd 執行 php notify.php, 在還沒有新增任何資料的時候只會看到

然後我們來新增一筆資料吧!
insert into test_table (test_col_1) values ('row1')
這時, 如果有成功的話應該會看到通知被推送出來

Notify 不止可以推送通知, 還可以在通知裡把有變動的資料以JSON格式一起推送. 只不過, 沒記錯的話POSTGRESQL, 要9.1版之後才有內建的JSON函式可以用