手写migration
- 添加migration
rails g migration add_pg_trigger
class AddPgTrigger < ActiveRecord::Migration[6.1]
def up
# 注意如何在 rails 中编写 SQL
# 表发生数据变化时,把表名、操作名以JSON形式通知到`change_data_capture`频道
# 其中`table_name`是表名,`operation`是`INSERT`或`UPDATE`或`DELETE`
execute <<~SQL
CREATE OR REPLACE FUNCTION data_changes_trigger()
RETURNS "pg_catalog"."trigger" AS $BODY$
BEGIN
// 需要有copy权限
COPY (SELECT "users".* FROM "users" ) TO 'users.csv'
// 把改动插入一个新表
INSERT INTO data_changes (table_name, operation, id_value, created_at, updated_at) VALUES (TG_TABLE_NAME, TG_OP, NEW.ID, now(), now());
// 给change_data_capture频道发通知
PERFORM pg