PostgreSQL:麻烦将数据从一个模式复制到另一个模式

PostgreSQL: Trubles with copy data from one schema to another

你能帮帮我吗?

我正在尝试使用 psycopg2 命令将数据从一种模式复制到另一种模式:

columns = ('name', 'description', 'manufacturer')
source_schema = "public"
target_schema = "target"
table = "supplies"

query = sql.SQL('INSERT INTO {target_schema}.{table} select ({columns}) from {source_schema}.{table}').format(
    source_schema=sql.Identifier(source_schema),
    target_schema=sql.Identifier(target_schema),
    table=sql.Identifier(table),
    columns=sql.SQL(',').join(map(sql.Identifier, columns)),

)

但是我得到一个错误:

column "id" is of type integer but expression is of type record
LINE 1: INSERT INTO "target"."supplies" select ("name","description"...

早期我创建了方案 'target' 作为:

CREATE TABLE IF NOT EXISTS target.supplies (
id SERIAL PRIMARY KEY,
name VARCHAR,
description VARCHAR,
manufacturer VARCHAR
);

问题是您正在将 SELECT 列表转换为记录,也没有为目标指定列列表 table:

CREATE TABLE IF NOT EXISTS public.supplies (
id SERIAL PRIMARY KEY,
name VARCHAR,
description VARCHAR,
manufacturer VARCHAR
);

CREATE TABLE IF NOT EXISTS test.supplies (
id SERIAL PRIMARY KEY,
name VARCHAR,
description VARCHAR,
manufacturer VARCHAR
);

insert into public.supplies (name, description, manufacturer) values ('test', 'test_desc', 'big company'), ('test2', 'test2_desc', 'small company');

--What you did:
select (name, description, manufacturer) from public.supplies;
                row                 
------------------------------------
 (test,test_desc,"big company")
 (test2,test2_desc,"small company")

insert into test.supplies select (name, description, manufacturer) from public.supplies;
ERROR:  column "id" is of type integer but expression is of type record
LINE 1: insert into test.supplies select (name, description, manufac...
                                         ^
HINT:  You will need to rewrite or cast the expression.


--What it should be:
select name, description, manufacturer from public.supplies;
 name  | description | manufacturer  
-------+-------------+---------------
 test  | test_desc   | big company
 test2 | test2_desc  | small company

insert into test.supplies(name, description, manufacturer) select name, description, manufacturer from public.supplies;
INSERT 0 2

所以你需要:

'INSERT INTO {target_schema}.{table}({columns}) select {columns} from {source_schema}.{table}'