Postgresql - 为可重新运行的插入脚本动态生成不存在的条件

Postgresql - Generating where not Exists condition dynamically for re-runnable insert script

我需要在 postgres 中为数据库中的所有表生成插入脚本,以便它可以再次 运行 而不会抛出任何错误。 问题是,只有少数表具有主键,而其余表在不同列上具有唯一索引。

这就是为什么我无法列出已创建唯一索引的列的原因。 这背后的原因是模式是通过 Magnolia 自动创建的。

任何人都可以帮我编写生成插入语句的查询,包括基于主 Key/Unique 列的 'Where not Exists (Select 1 from table where column = value)' 条件吗?

您可以使用 on conflict:

insert into t ( . . . )
    values ( . . . )
    on conflict do nothing;

此函数returns 插入数据脚本并且适用于主约束不可用的表。 我修改了我在另一个线程上找到的代码,添加了条件。

CREATE OR REPLACE FUNCTION public.generate_inserts(varSchema text, varTable text) RETURNS TABLE(resultado text) AS $$

DECLARE CODE TEXT;

BEGIN
CODE :=
(
SELECT
'SELECT ''INSERT INTO '
|| table_schema || '.'
|| table_name ||' ('
|| replace(replace(array_agg(column_name::text)::text,'{',''),'}','') || ') SELECT ''||'
|| replace(replace(replace(array_agg( 'quote_nullable(' || column_name::text || ')')::text,'{',''),'}',''),',',' || '','' || ')
|| ' || '' Where Not Exists (Select 1 From ' || table_name ||' Where 1 = 1 ' 
|| ''''
|| replace(replace(replace(replace(array_agg(' || '' and (' || column_name::text || ' = '' || quote_nullable(' || column_name::text || '),' || ' || '' or ' || column_name::text || ' is null)''')::text,'{',''),'}',''),'"',''),',','')
|| '|| '');'''
|| ' FROM ' || table_schema || '.' || table_name || ';'
FROM information_schema.columns c 
WHERE table_schema = varSchema
AND table_name = varTable
GROUP BY table_schema, table_name);



RETURN QUERY
EXECUTE CODE;
END;
$$ LANGUAGE plpgsql;