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

drop function cg_ProtocolID(Protocol.Protocol%type);
drop table    Protocol;

create table Protocol(
	ProtocolID	serial NOT NULL primary key,
	prCreated	timestamp with time zone DEFAULT now(),
	Protocol	text unique NOT NULL
);
--create unique index Protocol_ProtocolID_uix on Protocol(ProtocolID);
--create unique index Protocol_Protocol_uix on Protocol(Protocol);

comment on table Protocol is 'Map between Protocol and ProtocolID.';
comment on column Protocol.ProtocolID is 'Unique ID for Protocol.';
comment on column Protocol.Protocol is '';

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

comment on function cg_ProtocolID(Protocol.Protocol%type) is 'Create ProtocolID and get Protocol.';

select cg_ProtocolID('');

--EOF
