make sql dump with stdin like syntax to update table with condition

时间:2016-07-11 20:08:56

标签: postgresql

when making dump file with pg_dump command this performace is very fine but in dump is only create alter and inserts with syntax

COPY table1 (id, name) FROM stdin; 1 developer's portal ... .

I want to make with this syntax sql dump where table will updated for example update table1 set name ='hello' where id=1

with pg_dump syntax

1 个答案:

答案 0 :(得分:0)

这个脚本虽然为了简单起见,却假定表的主键是第一个字段:

table=table1
psql -Atc "with a as (select attrelid::regclass::text rel, attnum i, quote_ident(attname) col from pg_attribute where attrelid='$table'::regclass)
select 'select format(\$\$update '||rel||' set '||string_agg(col||'=%s', ', ' order by i)||'\$\$, '||string_agg('quote_nullable('||col||')', ',' order by i)||')||\$\$ where '||
       (select col||'=\$\$||quote_nullable('||col||')||\$\$;\$\$ from '||rel from a where i = 1) from a where i > 1 group by rel" |\
psql -At

如果你正在使用PostgreSQL 9.5+,那么你可以使用INSERT ... ON CONFLICT UPDATE ...代替:

table=table1
psql -Atc "with a as (select attrelid::regclass::text rel, attnum i, quote_ident(attname) col from pg_attribute where attrelid='$table'::regclass)
select 'select format(\$\$insert into '||rel||'('||string_agg(col, ',' order by i)||
       ') values ('||string_agg('%s', ',')||
       ') on conflict ('||(select col from a where i=1)||') do update set '||
       string_agg(case when i > 1 then col||'=excluded.'||col end, ', ' order by i)||';\$\$, '||
       string_agg('quote_nullable('||col||')', ',' order by i)||') from '||rel from a where i > 0 group by rel" |\
psql -At