来自远程服务器

时间:2018-06-18 15:29:20

标签: postgresql sequence postgres-fdw

我使用postgres_fdw扩展名来连接远程数据库(PostgresSQL)   IMPORT FOREIGN SCHEMA public。
问题远程表需要为INSERT指示id。没有id引发异常。

我做得很糟糕: - 在第一台服务器上创建一个包含表格及其序列的视图 - 在此视图上的第二台服务器上创建FOREIGN TABLE

我的步骤:
1.我从第二台服务器调用INSERT以将数据插入第一台服务器;
2插入传递:id,name
但是第一台服务器上的id序列没有改变。

查看图像。
问题:如何更改第一台服务器的ID 整个脚本:

第一台服务器

CREATE TABLE table_seq (
  last_value bigint
);

CREATE OR REPLACE FUNCTION func_table_seq(name text)
  RETURNS setof table_seq as
$delimeter$
BEGIN
  RETURN QUERY EXECUTE 'SELECT last_value FROM ' || name ||';';
END;
$delimeter$
LANGUAGE plpgsql
STRICT;

-- check
select last_value from func_table_seq('auth_group_id_seq');

-- view
    CREATE or replace VIEW sequence_tables AS
select
  c.table_name,
  (select last_value
   from func_table_seq(regexp_replace(regexp_replace(c.column_default, 'nextval\(''', ''), '''::regclass\)', ''))) as t
FROM information_schema.tables t
  left join information_schema.columns c on c.table_name = t.table_name
WHERE t.table_type = 'BASE TABLE'
      AND t.table_schema = 'public' and c.column_name = 'id'
ORDER BY t.table_type, t.table_name;

-- check
select table_name, t from sequence_tables;
第二个服务器上的

-- create foreign table
CREATE FOREIGN TABLE foreign_seq_table (table_name text, t bigint)
SERVER postgres OPTIONS ( table_name 'sequence_tables');

CREATE FUNCTION insert_ids()
  RETURNS trigger AS $$
declare f_seq_t bigint;
BEGIN
  IF NEW.id is NULL
  THEN
    select t
    into f_seq_t
    from foreign_seq_table
    where table_name = TG_TABLE_NAME;
    NEW.id = f_seq_t + 1;
  ELSE
    NEW.id = NEW.id;
  END IF;
  RETURN NEW;
END;
$$
LANGUAGE 'plpgsql';

-- create trigger, (now for one table, on prod for all tables)
CREATE TRIGGER trg_insert_ids
  BEFORE INSERT
  on auth_group
  FOR EACH ROW
EXECUTE PROCEDURE insert_ids();

查看所有流程的图像 enter image description here

enter image description here enter image description here

0 个答案:

没有答案