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

drop function cg_CookieID(Cookie.Cookie%type);
drop table    Cookie;

create table Cookie(
	CookieID	serial NOT NULL primary key,
	ckCreated	timestamp with time zone DEFAULT now(),
	Cookie	text unique NOT NULL
);
create unique index Cookie_CookieID_uix on Cookie(CookieID);
create unique index Cookie_Cookie_uix on Cookie(Cookie);

comment on table Cookie is 'Map between Cookie and CookieID.';
comment on column Cookie.CookieID is 'Unique ID for Cookie.';
comment on column Cookie.Cookie is '';

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

comment on function cg_CookieID(Cookie.Cookie%type) is 'Create CookieID and get Cookie.';

select cg_CookieID('');

--EOF
