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

drop function cg_UserTrackID(UserTrack.UserTrack%type);
drop table    UserTrack;

create table UserTrack(
	UserTrackID	serial NOT NULL primary key,
	utCreated	timestamp with time zone DEFAULT now(),
	UserTrack	text unique NOT NULL
);
--create unique index UserTrack_UserTrackID_uix on UserTrack(UserTrackID);
create unique index UserTrack_UserTrack_uix on UserTrack(UserTrack);

comment on table UserTrack is 'Map between UserTrack and UserTrackID.';
comment on column UserTrack.UserTrackID is 'Unique ID for UserTrack.';
comment on column UserTrack.UserTrack is 'The name of the web-server name as defined in Apache. A UserTrack could be ''example.com'' which is typically defined in ''vhost.conf''.
Use the function::cg_UserTrackID() to create and get UserTrack.
For ServerAlias and mod_rewrite see table::ReqHost.';

create function cg_UserTrackID(UserTrack.UserTrack%type) returns UserTrack.UserTrackID%type as '
declare
	id      UserTrack.UserTrackID%type;
	sname   UserTrack.UserTrack%type;
	p_name  alias for $1;
begin
	sname := lower(trim(p_name));
	--if p_name is null or length(sname)<1 then
	--	id := NULL;
	--else
		select UserTrackID into id from UserTrack where (UserTrack = sname);
		if not found then
			insert into UserTrack (UserTrack) values(sname);
			select last_value into id from UserTrack_UserTrackID_seq;
		end if;
	--end if;
	return id;
end;
' language 'PLpgSQL';

comment on function cg_UserTrackID(UserTrack.UserTrack%type) is 'Create UserTrackID and get UserTrack.';

select cg_UserTrackID('');

--EOF
