CREATE OR REPLACE FUNCTION public.fn_clone_row(in_table_name character varying, in_row_pk integer)
RETURNS integer
LANGUAGE plpgsql
AS $function$
DECLARE
my_table_pk_col_name varchar;
my_row record;
my_pk_default text;
BEGIN
-- This is a function we've written and tested already
my_table_pk_col_name := fn_get_table_pk_col(in_table_name);
-- Get the next value of the pk column for the table
EXECUTE 'SELECT pa.adsrc '
' FROM pg_attrdef pa '
' JOIN pg_attribute pat '
' ON pat.attnum = pa.adnum '
' AND pat.attrelid = pa.adrelid '
' JOIN pg_class pc '
' ON pc.oid = pat.attrelid '
' JOIN pg_namespace pn '
' ON pn.oid = pc.relnamespace '
' WHERE pat.attname = ' || quote_nullable( my_table_pk_col_name ) ||
' AND pc.relname = ' || quote_nullable( in_table_name ) ||
' AND pn.nspname = ''public'''
INTO my_pk_default;
-- Copy over only the given row to the temp table.
EXECUTE ' SELECT * '
' FROM ' || quote_ident( in_table_name ) ||
' WHERE ' || quote_ident( my_table_pk_col_name ) || ' = '
|| quote_nullable( in_row_pk )
INTO my_row;
EXECUTE 'my_row.' || my_key || ' := ' || my_pk_default;
-- Copy the created row back into the original table.
EXECUTE ' INSERT INTO ' || quote_ident( in_table_name ) ||
' SELECT my_row.* ';
RETURN my_pk_default;
END
$function$