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

drop function cg_AuthUserID(AuthUser.AuthUser%type);
drop table    AuthUser;

create table AuthUser(
	AuthUserID	serial NOT NULL primary key,
	auCreated	timestamp with time zone DEFAULT now(),
	AuthUser	text unique NOT NULL
);
--create unique index AuthUser_AuthUserID_uix on AuthUser(AuthUserID);
--create unique index AuthUser_AuthUser_uix on AuthUser(AuthUser);

comment on table AuthUser is 'Map between AuthUser and AuthUserID.';
comment on column AuthUser.AuthUserID is 'Unique ID for AuthUser.';
comment on column AuthUser.AuthUser is '';

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

comment on function cg_AuthUserID(AuthUser.AuthUser%type) is 'Create AuthUserID and get AuthUser.';

select cg_AuthUserID('');

--EOF
