Improve robustness of insert generator

This commit is contained in:
Derry Hamilton 2019-06-26 16:31:24 +01:00
parent 9d82c9f279
commit 97baf0d11a

View file

@ -14,7 +14,7 @@ declare
pks text; pks text;
begin begin
SELECT SELECT
array_to_string(array_agg(pg_attribute.attname::text ),', ') into pks array_to_string(array_agg(quote_ident(pg_attribute.attname::text) ),', ') into pks
FROM FROM
pg_index, pg_index,
pg_class, pg_class,
@ -29,39 +29,42 @@ begin
pg_attribute.attnum = any(pg_index.indkey) pg_attribute.attnum = any(pg_index.indkey)
AND indisprimary ; AND indisprimary ;
header := 'INSERT INTO '||sch||'.'||tabname||E' as t (\n '; header := 'INSERT INTO '||quote_ident(sch)||'.'||quote_ident(tabname)||E' as t (\n ';
for colinfo in for colinfo in
select select
* *
from from
information_schema.columns information_schema.columns
where where
table_schema = 'bi_processing' table_schema = sch
and table_name = 'player' and table_name = tabname
order by ordinal_position order by ordinal_position
loop loop
raise info 'Working on %.% (%)',sch,tabname,colinfo::text;
if not is_first then if not is_first then
col_list := col_list || E',\n '; col_list := col_list || E',\n ';
vals := vals || E',\n '; vals := vals || E',\n ';
sets := sets || E',\n '; sets := sets || E',\n ';
changes := changes || E'\n OR '; changes := changes || E'\n OR ';
end if; end if;
col_list := col_list || colinfo.column_name; col_list := col_list || quote_ident(colinfo.column_name);
vals := vals || '?::' || colinfo.data_type; vals := vals || '?::' || quote_ident(colinfo.data_type);
sets := sets || colinfo.column_name || E' = EXCLUDED.' || colinfo.column_name; sets := sets || quote_ident(colinfo.column_name) ||
changes := changes || E't.' || colinfo.column_name || E' IS DISTINCT FROM EXCLUDED.' || colinfo.column_name; E' = EXCLUDED.' || quote_ident(colinfo.column_name);
changes := changes || E't.' || quote_ident(colinfo.column_name) ||
E' IS DISTINCT FROM EXCLUDED.' || quote_ident(colinfo.column_name);
is_first = false; is_first = false;
end loop; end loop;
s := header || s := coalesce(header,'header failed') ||
col_list || coalesce(col_list,'col_list failed') ||
E'\n)VALUES(\n ' || E'\n)VALUES(\n ' ||
vals || coalesce(vals,'vals failed') ||
E')\nON CONFLICT(' || pks || E') DO UPDATE\nSET\n ' || E')\nON CONFLICT(' || coalesce(pks,'No primary keys found') || E') DO UPDATE\nSET\n ' ||
sets || coalesce(sets,'sets failed') ||
E'\nWHERE\n '|| E'\nWHERE\n '||
changes; coalesce(changes,'changes failed');
return s; return s;
end; end;
$function$ $function$