I wanted to make an update function for a schema in PG SQL database. A test function is below. It doesn't work because it should never raise a notice, but will do that when running test_schema_update('second')
.
CREATE OR REPLACE FUNCTION test_schema_update(my_schema_name VARCHAR(200))
RETURNS void AS
$__marker__$
DECLARE
actualValue varchar(1000);
testValue varchar(1000);
BEGIN
EXECUTE 'SET search_path TO ' || quote_ident(my_schema_name);
testValue := (SELECT max(value) FROM setting WHERE settingkey = 'libraryname');
EXECUTE ('SELECT max(value) FROM setting WHERE settingkey = ''libraryname''')
INTO actualValue;
IF (actualValue != testValue)
THEN
RAISE NOTICE '% != %', actualValue, testValue;
RAISE INFO 'Schema was: %', current_schema();
END IF;
RESET search_path;
END;
$__marker__$ LANGUAGE plpgsql;
test_schema_update('first');
test_schema_update('second');
The problem is that PG SQL seem to analyze SELECT
statements only once per session and then tables are fixed to specific schema. What is interesting is that you will get Schema was: second
.
So is there a way reset SELECT
statement analysis or some other way to work around this?
Side note: All schema creation function (ALTER TABLE
, CREATE TABLE
...) work fine. Only data manipulation functions seem to be affected (SELECT
, INSERT
, UPDATE
).
Workaround
Before:
IF (
SELECT max(id) FROM dimtime
)
THEN
INSERT INTO dimtime SELECT * FROM public.src_dimtime;
END IF;
After:
EXECUTE ('
SELECT max(id) FROM dimtime
')
INTO testInt;
IF (testInt IS NULL)
THEN
EXECUTE 'INSERT INTO dimtime SELECT * FROM public.src_dimtime';
END IF;
Edit: The problem occurs in PostgreSQL 9.2, but seem not to occur in 9.3. Maybe it was fixed?