-- IPnames
-- view of IP-addresses
-- If resolved: Use the name
-- else use the IP-address

drop function find_ip_name(integer);
create function find_ip_name(integer) returns text as '
  declare
    p_IPID		alias for $1; -- ID of IP-address

    this_rec		record;
    v_return		text;
  begin
    select * into this_rec from IP where IPID=p_IPID;
    if this_rec.IPcountry = null then
        -- This has not been resolved
	v_return = this_rec.IPText;
    else if this_rec.IPname = '''' then
	    -- No hostname: Just a domainname (billund-lufthavn.dk)
	    v_return = this_rec.IPdomain || ''.'' || this_rec.IPcountry;
        else 
            -- Normal: host.domain.country
	    v_return = this_rec.IPname || ''.'' 
		       || this_rec.IPdomain || ''.'' 
		       || this_rec.IPcountry;
        end if;
    end if;

    return v_return;      
  end;
' language 'PLpgSQL';

drop view IPnames;
create view IPnames as
select IPID, find_ip_name(IPID) as IPText from IP;

