最近我在portgres上使用了分区表。我对INSERT RETURNING id有一些问题。这是我的触发器函数和触发器:

CREATE OR REPLACE FUNCTION f_port_vessels_insert_trigger_auto()
  RETURNS TRIGGER AS $$
DECLARE
  insert_sql TEXT;
  week_num INTEGER;
  year_num INTEGER;
  partition_table VARCHAR;
  prefix_partition_table VARCHAR :='port_vessels_p_';
BEGIN
  SELECT CAST (EXTRACT(WEEK FROM NEW.created_at) AS INTEGER) INTO week_num;
  SELECT CAST (EXTRACT(YEAR FROM NEW.created_at) AS INTEGER) INTO year_num;
  partition_table :=  prefix_partition_table || year_num || '_' || week_num;
  insert_sql := 'INSERT INTO ' || partition_table || ' VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)';
  EXECUTE insert_sql
  USING NEW.id, NEW.port_id, NEW.vessel_id,
    NEW.last_position_updated_at, NEW.nav_status_code,
    NEW.created_at, NEW.updated_at, NEW.berth_id,
    NEW.berth_shift_id;
  RETURN NULL;
END;
$$
LANGUAGE plpgsql;

CREATE TRIGGER f_port_vessels_insert_trigger
BEFORE INSERT ON port_vessels
FOR EACH ROW EXECUTE PROCEDURE f_port_vessels_insert_trigger_auto();

我用google搜索了所有这些,并看到一个解决方案创建了一个视图,创建了triggerinsert instead on the view而不是table。我认为如果我们只在数据库上工作是可以的,但是我在Rails中使用Active Record,我不想再改变我的模型了,所以有人经历过这种情况吗?或者有别的办法解决这个问题。

最佳答案

你应该(在PostgreSQL v10或更高版本上)使用declarative partitioning,而不是重新发明轮子。

关于ruby-on-rails - 插入返回和分区POSTGRESQL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47469504/

10-16 13:32