-- ToughLog
\set HOSTNAME `echo "'$HOSTNAME'"`
select syslog('I', :HOSTNAME, 'setcookie.sql', 'ID',
'$Id$'
);
select syslog('I', :HOSTNAME, 'setcookie.sql', 'INSTALL',
'Install table SetCookie and function cg_SetCookieID().'
);

drop function cg_SetCookieID(SetCookie.SetCookie%type);
drop table    SetCookie;

create table SetCookie(
	SetCookieID	serial NOT NULL primary key,
	scCreated	timestamp with time zone DEFAULT now(),
	SetCookie	text unique NOT NULL
);
create unique index SetCookie_SetCookieID_uix on SetCookie(SetCookieID);
create unique index SetCookie_SetCookie_uix on SetCookie(SetCookie);

comment on table SetCookie is 'Map between SetCookie and SetCookieID.';
comment on column SetCookie.SetCookieID is 'Unique ID for SetCookie.';
comment on column SetCookie.SetCookie is '';

create function cg_SetCookieID(SetCookie.SetCookie%type) returns SetCookie.SetCookieID%type as '
declare
	id      SetCookie.SetCookieID%type;
	sname   SetCookie.SetCookie%type;
	p_name  alias for $1;
begin
	sname := trim(p_name);
	select SetCookieID into id from SetCookie where (SetCookie = sname);
	if not found then
		insert into SetCookie (SetCookie) values(sname);
		select last_value into id from SetCookie_SetCookieID_seq;
	end if;
	return id;
end;
' language 'PLpgSQL';

comment on function cg_SetCookieID(SetCookie.SetCookie%type) is 'Create SetCookieID and get SetCookie.';

select cg_SetCookieID('');

--EOF
