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

drop function cg_HostNameID(HostName.HostName%type);
drop function cg_HostNameID(HostName.HostName%type, HostName.LocalName%type);
drop table    HostName;

create table HostName(
	HostNameID	serial NOT NULL primary key,
	hnCreated	timestamp with time zone DEFAULT now(),
	LocalName	bool default false,
	HostName	text unique NOT NULL
);
--create unique index HostName_HostNameID_uix on HostName(HostNameID);
--create unique index HostName_HostName_uix on HostName(HostName);

comment on table HostName is 'Map between HostName and HostNameID.';
comment on column HostName.HostNameID is 'Unique ID for HostName.';
comment on column HostName.LocalName is 'A hostname which is used by this server.';
comment on column HostName.HostName is 'The name of the web-server name as defined in Apache. A HostName could be ''example.com'' which is typically defined in ''vhost.conf''.
Shortname: hn.
Use the function::cg_HostNameID() to create and get HostName.
For ServerAlias and mod_rewrite see table::ReqHost.';

create function cg_HostNameID(HostName.HostName%type, HostName.LocalName%type) returns HostName.HostNameID%type as '
declare
	id      HostName.HostNameID%type;
	sname   HostName.HostName%type;
	p_name  alias for $1;
	p_local	alias for $2;
begin
	sname := lower(trim(p_name));
	select HostNameID into id from HostName where (HostName = sname);
	if not found then
		insert into HostName(HostName,LocalName) values(sname,p_local);
		select last_value into id from HostName_HostNameID_seq;
	end if;
	return id;
end;
' language 'PLpgSQL';

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

comment on function cg_HostNameID(HostName.HostName%type) is 'Create HostNameID and get HostName.
SELECT cg_HostNameID(''example.com'')
or
INSERT INTO HttpLog(HostNameID) VALUES(cg_HostNameID(''example.com''))';

select cg_HostNameID('LocalHost');

--EOF
