
CREATE SCHEMA env;

CREATE FUNCTION env.initialise() RETURNS void
AS $$
	Begin
		If Not Exists ( 
			Select * From information_schema.tables
			Where table_name = '_env_variable_store'
			And table_type = 'LOCAL TEMPORARY'
		)
		Then
			Create Temporary Table _env_variable_store
			(
				variable text Not Null Primary Key,
				value text Null
			);
		End If;
	
		Return;
	End;
$$ LANGUAGE plpgsql VOLATILE;


CREATE FUNCTION env.get(in_variable text) RETURNS text
AS $$
	Declare
		ret_value text;
	Begin
		Perform	env.initialise();
	
		Select Into ret_value
			value
		From
			_env_variable_store
		Where
			variable = in_variable;
		
		Return ret_value;
	End;
$$ LANGUAGE plpgsql STABLE;


CREATE FUNCTION env.set(in_variable text, in_value text) RETURNS void
AS $$
	Begin
		Perform env.initialise();
	
		If Exists (
			Select * From _env_variable_store
			Where variable = in_variable
		)
		Then
			Update _env_variable_store
			Set value = in_value
			Where variable = in_variable;
		Else
			Insert Into _env_variable_store
			( variable, value )
			Values
			( in_variable, in_value );
		End If;
	
		Return;
	End;
$$ LANGUAGE plpgsql VOLATILE;

