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

drop function cg_ViaID(Via.Via%type);
drop table    Via;

create table Via(
	ViaID	serial NOT NULL primary key,
	viCreated	timestamp with time zone DEFAULT now(),
	Via	text unique NOT NULL
);
create unique index Via_ViaID_uix on Via(ViaID);
create unique index Via_Via_uix on Via(Via);

comment on table Via is 'Map between Via and ViaID.';
comment on column Via.ViaID is 'Unique ID for Via.';
comment on column Via.Via is '';

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

comment on function cg_ViaID(Via.Via%type) is 'Create ViaID and get Via.';

select cg_ViaID('');

--EOF
