Skip to content

Instantly share code, notes, and snippets.

@walerian777
Created November 7, 2016 15:51
Show Gist options
  • Save walerian777/8aedef0baabd20f25b68ee10334c54a4 to your computer and use it in GitHub Desktop.
Save walerian777/8aedef0baabd20f25b68ee10334c54a4 to your computer and use it in GitHub Desktop.
PostgreSQL: Transfering scoped tables
-- This function transfers all rows from tables which contains `_scope_column_name` AND `_update_column_name`,
-- whose value in a column called `_scope_column_name` is equal to `_scope_column_value`,
-- by updating the value of `_update_column_name` with `_update_column_value`.
-- Finally, it updates `_update_column_name` with `_update_column_value` in the record from `_scope_table_name` table,
-- where primary key is equal to `_scope_column_value`.
CREATE OR REPLACE FUNCTION transfer_tables(_scope_table_name regclass, _scope_column_name text, _scope_column_value uuid, _update_column_name text, _update_column_value uuid)
RETURNS void AS
$func$
DECLARE
_table regclass;
BEGIN
FOR _table IN EXECUTE format('SELECT table_name FROM information_schema.columns WHERE is_updatable = ''YES'' AND column_name = ''%1$s''
AND table_name IN (SELECT table_name FROM information_schema.columns WHERE column_name = ''%2$s'')', _update_column_name, _scope_column_name)
LOOP
EXECUTE format('UPDATE %1$s SET %2$s = ''%3$s'' WHERE %4$s = ''%5$s''', _table, _update_column_name, _update_column_value, _scope_column_name, _scope_column_value);
END LOOP;
EXECUTE format('UPDATE %1$s SET %2$s = ''%3$s'' WHERE id = ''%4$s''', _scope_table_name, _update_column_name, _update_column_value, _scope_column_value);
END
$func$
LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment