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

drop function cg_QueryID(Query.Query%type);
drop table    Query;

create table Query(
	QueryID	serial NOT NULL primary key,
	quCreated	timestamp with time zone DEFAULT now(),
	Query	text unique NOT NULL
);
--create unique index Query_QueryID_uix on Query(QueryID);
--create unique index Query_Query_uix on Query(Query);

comment on table Query is 'Map between Query and QueryID.';
comment on column Query.QueryID is 'Unique ID for Query.';
comment on column Query.Query is '';

create function cg_QueryID(Query.Query%type) returns Query.QueryID%type as '
declare
	id      Query.QueryID%type;
	sname   Query.Query%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 QueryID into id from Query where (Query = sname);
		if not found then
			insert into Query (Query) values(sname);
			select last_value into id from Query_QueryID_seq;
		end if;
	--end if;
	return id;
end;
' language 'PLpgSQL';

comment on function cg_QueryID(Query.Query%type) is 'Create QueryID and get Query.
SELECT cg_QueryID(''example.com'')
or
INSERT INTO HttpLog(QueryID) VALUES(cg_QueryID(''example.com''))';

select cg_QueryID('');

--EOF
