Restore data from sql file in a consistent way with a procedure

Viewed 26

My aim is to restore data from .sql file that has COPY statements inside of it. This I can easily do with

psql -U username -d dbname -1 -f filename.sql

Before that I truncate all the tables. For that I've written this function:

CREATE OR REPLACE FUNCTION clinical_trial.truncate_tables(dbusername text, dbschema text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
    _tbl text;
    _sch text;
BEGIN
FOR _sch, _tbl IN
SELECT schemaname, tablename
FROM pg_tables
WHERE tableowner = dbUserName
  AND schemaname = dbSchema
  AND tablename NOT like 'flyway%' LOOP
      EXECUTE format('TRUNCATE TABLE %I.%I CASCADE', _sch, _tbl);
END LOOP;
END;
$function$
;

Now I want these both steps to happen in a procedure to make it consistent in case smth goes wrong at any of these steps, but not sure if that is really a good idea in general. I am struggling to put my first restore step into a procedure so far and not sure if that can be done at all.

0 Answers
Related