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

drop function cg_FileServedID(FileServed.FileServed%type);
drop table    FileServed;

create table FileServed(
	FileServedID	serial NOT NULL primary key,
	fsCreated	timestamp with time zone DEFAULT now(),
	FileServed	text unique NOT NULL
);
create unique index FileServed_FileServedID_uix on FileServed(FileServedID);
create unique index FileServed_FileServed_uix on FileServed(FileServed);

comment on table FileServed is 'Map between FileServed and FileServedID.';
comment on column FileServed.FileServedID is 'Unique ID for FileServed.';
comment on column FileServed.FileServed is '';

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

comment on function cg_FileServedID(FileServed.FileServed%type) is 'Create FileServedID and get FileServed.';

select cg_FileServedID('');

--EOF
