DROP FUNCTION IF EXISTS print(TEXT);
DROP FUNCTION IF EXISTS setupSecurityContext(INTEGER);

CREATE FUNCTION print(msg TEXT) RETURNS VOID AS $$
BEGIN
  RAISE NOTICE '%', msg;
END
$$ LANGUAGE plpgsql;

CREATE TABLE Stuff(sid INTEGER PRIMARY KEY, sval TEXT);
INSERT INTO Stuff(sid, sval) VALUES (1, 'secure'), (2, 'unsecure');
CREATE TABLE Log(lid SERIAL, username TEXT,
  sid INTEGER REFERENCES Stuff DEFERRABLE INITIALLY DEFERRED);

CREATE FUNCTION setupSecurityContext(x INTEGER) RETURNS BOOLEAN AS $$
BEGIN
  PERFORM print('SET secured = FALSE');
  SET SESSION x.x = 'bad';
  INSERT INTO Log(username, sid) VALUES (CURRENT_USER::TEXT, x);
  PERFORM print('SET secured = TRUE');
  SET SESSION x.x = 'ok';
  RETURN TRUE;
END
$$ LANGUAGE plpgsql;

SET SESSION x.x = 'null';
-- the INSERT fails, but after having set secured to true
SELECT setupSecurityContext(3);
SHOW x.x;
SELECT setupSecurityContext(2);
SHOW x.x;
