When I create a new schema in Postgres through executing a script in psql I want to put it in a tablespace. If this tablespace does not exist then I want to create it first. Since the default SQL does not have this option I created a function:
CREATE OR REPLACE FUNCTION make_tablespace(tablespace CHARACTER,
directory CHARACTER,
owner CHARACTER)
RETURNS void
AS
$$
BEGIN
IF tablespace = '' THEN
RAISE EXCEPTION 'No tablespace.';
END IF;
PERFORM SPCNAME FROM PG_TABLESPACE WHERE SPCNAME=tablespace;
IF NOT FOUND THEN
IF directory = '' THEN
RAISE EXCEPTION 'No directory.';
END IF;
IF owner = '' THEN
RAISE EXCEPTION 'No owner.';
END IF;
EXECUTE 'CREATE TABLESPACE '||tablespace||' OWNER '||owner||' LOCATION '''||directory||''';';
RAISE NOTICE 'Tablespace % created.', tablespace;
ELSE
RAISE NOTICE 'Tablespace % already exists.', tablespace;
END IF;
END $$ LANGUAGE plpgsql;
Unfortunately when I execute it (select make_tablespace('marco', '/opt/marco', 'marco');) this gives an error:
ERROR: CREATE TABLESPACE cannot be executed from a function or multi-command string
I searched the internet and there seems to be a workaround (some years ago) by using the dblink package. I do not want to install this. Is there today another way? I can return the SQL statement as a string but how to execute it then?
CREATE TABLESPACEthrows an exception if it already exists and causes the script to stop. With this function I want to work around this problem.