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

drop function cg_UserAgentID(UserAgent.UserAgent%type);
drop table    UserAgent;

create table UserAgent(
	UserAgentID	serial NOT NULL primary key,
	uaCreated	timestamp with time zone DEFAULT now(),
	UserAgent	text unique NOT NULL
);
--create unique index UserAgent_UserAgentID_uix on UserAgent(UserAgentID);
--create unique index UserAgent_UserAgent_uix on UserAgent(UserAgent);

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

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

comment on function cg_UserAgentID(UserAgent.UserAgent%type) is 'Create UserAgentID and get UserAgent.';

select cg_UserAgentID('');
--EOF
