GeXiangDong

精通Java、SQL、Spring的拼写,擅长Linux、Windows的开关机

0%

PostgreSQL foreign table with generated column

Remote Server:

1
2
3
4
5
create table a0(
id int primary key,
name text not null,
name_hash char(32) GENERATED ALWAYS AS (md5(name)) STORED
);

Name_hash 是计算列

Local Server

略过创建server, user mapping等,只管创建 foreign table

方法1

不映射计算列,这种方法创建的外部表,向它插入数据是没问题的。

1
2
3
4
5
6

create foreign table a0_0001 (
id int not null,
name text not null
)
SERVER remote_server OPTIONS (schema_name 'public', table_name 'a0');
1
insert into a0_0001 (id, name) values (1, 'Jack');

OK

方法2

映射计算列为普通列,这种方法创建的外部表,向它插入数据是有问题的。即使insert sql中不包含此列也不行。

1
2
3
4
5
6
7

create foreign table a0_0002 (
id int not null,
name text not null,
name_hash char(32)
)
SERVER remote_server OPTIONS (schema_name 'public', table_name 'a0');
1
2
3
4
5
insert into a0_0002 (id, name) values (2, 'Jack');
ERROR: cannot insert a non-DEFAULT value into column "name_hash"
DETAIL: Column "name_hash" is a generated column.
CONTEXT: remote SQL command: INSERT INTO public.a0(id, name, name_hash) VALUES ($1, $2, $3)

方法3

映射计算列为计算列,这种方法创建的外部表,向它插入数据(insert 的column list中无此列)是没问题的。

1
2
3
4
5
6
7

create foreign table a0_0002 (
id int not null,
name text not null,
name_hash char(32) GENERATED ALWAYS AS (md5(name)) STORED
)
SERVER remote_server OPTIONS (schema_name 'public', table_name 'a0');
1
2
insert into a0_0003 (id, name) values (3, 'Jack');

OK