Skip to content

Instantly share code, notes, and snippets.

@spaghetti-
Last active September 7, 2017 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spaghetti-/797711b495f483bbcd4fa1d708be1d0f to your computer and use it in GitHub Desktop.
Save spaghetti-/797711b495f483bbcd4fa1d708be1d0f to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION update_table (target_table text, timestamp_col text,
from_timestamp timestamp with time zone, constraint_name text, t ANYELEMENT)
RETURNS SETOF ANYELEMENT
AS $$
DECLARE
querytext text;
DECLARE
tmp text;
BEGIN
SELECT
string_agg('"' || column_name || '"' || ' = EXCLUDED."' || column_name || '"', ',')
FROM
information_schema.columns
WHERE
table_name = target_table AND table_schema = 'public'
INTO
tmp;
querytext = format(
'INSERT INTO public.%s '
'SELECT * from production.%s WHERE %s > ''%s'' '
'ON CONFLICT ON CONSTRAINT %s DO UPDATE SET %s RETURNING *',
target_table, target_table, timestamp_col, from_timestamp, constraint_name, tmp);
raise log 'executing dynamic query %s', querytext;
RETURN QUERY EXECUTE querytext;
END
$$
LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment