SET search_path=public;

ALTER TABLE public.tokens ADD CONSTRAINT tokens_pkey PRIMARY KEY(id);


DROP FUNCTION IF EXISTS public.get_token();

CREATE OR REPLACE FUNCTION public.get_token()
    RETURNS text AS
$BODY$
DECLARE
    tok bigint;
    ts bigint := floor(EXTRACT(EPOCH FROM NOW()));
BEGIN
    INSERT INTO public.tokens DEFAULT VALUES RETURNING id INTO tok;
    IF mod(tok, 10000) = 0 THEN -- 10k period
        DELETE FROM public.tokens WHERE id < (tok - 100000); -- 100k for history
    END IF;
    RETURN ts||':'||tok;
END;
$BODY$
LANGUAGE plpgsql;


