-- CREATE FUNCTION tlf_survey_hstore_check() RETURNS void AS $$
--   DECLARE hstore_exists integer;
-- BEGIN
-- select 1 into hstore_exists from pg_proc where proname = 'hstore_in';
-- IF NOT FOUND THEN
--   RAISE EXCEPTION 'hstore not found. This package requires hstore';
-- END IF;
-- END;
-- $$ LANGUAGE 'plpgsql';

-- SELECT * FROM tlf_survey_hstore_check();
-- DROP FUNCTION tlf_survey_hstore_check;

CREATE TABLE tlf_survey(
    survey_id integer references cr_items(item_id) on delete cascade,
    user_id integer references users(user_id) on delete cascade,
    completion_time timestamp without time zone,
    survey_completed_p boolean default false,
    context_id integer references acs_objects(object_id) on delete cascade
);

CREATE unique INDEX tlf_survey_idx1 on tlf_survey(survey_id,user_id,context_id);
CREATE INDEX tlf_survey_contextx on tlf_survey(context_id);
CREATE INDEX tlf_survey_user_id_idx ON public.tlf_survey USING btree (user_id);
ALTER TABLE tlf_survey ADD CONSTRAINT tlf_survey_pk PRIMARY KEY (survey_id, user_id);

create or replace function close_survey (integer,integer)
returns integer as '
declare
    p_survey_id      alias for $1;
    p_user_id        alias for $2;
begin
    update tlf_survey
     set completion_time   = now(),
     survey_completed_p = true
     where survey_id = p_survey_id
     and user_id = p_user_id;
return 1;
end;' language 'plpgsql';
