
create or replace function get_value(tname text, vtext text) returns bigint as $$
begin
  case tname
    when 'node' then
      return get_node(vtext);
    when 'int' then
      return to_number(vtext, '99999999');
    else
      return 0;
  end case;
end;
$$ language plpgsql;


create or replace function get_node(vtext text) returns bigint as $$
declare
  pfx text;
  vname text;
  value bigint;
begin
  pfx := split_part(vtext, ':', 1);
  vname := split_part(vtext, ':', 2);
  select nodes.id into value from nodes, namespaces ns
    where ns.prefix = pfx
      and nodes.namespace = ns.id
      and nodes.name = vname;
  if not found then 
      insert into nodes (namespace, name)
        (select ns.id, vname from namespaces ns where ns.prefix = pfx)
        returning nodes.id into value;
  end if;
  return value;
end;
$$ language plpgsql;


create or replace function load_triple(
    stname text, stext text, ptext text,
    otname text, otext text, event bigint) returns bigint as $$
declare
  st smallint;
  sv bigint;
  pred bigint;
  ot smallint;
  ov bigint;
  trid bigint;
begin
  select dt.id into st from datatypes dt where dtname = stname;
  select dt.id into ot from datatypes dt where dtname = otname;
  sv := get_value(stname, stext);
  pred := get_value('node', ptext);
  ov := get_value(otname, otext);
  select tr.id into trid from triples tr
    where stype = st and svalue = sv and predicate = pred 
      and otype = ot and ovalue = ov;
  if not found then
    insert into triples (stype, svalue, predicate, otype, ovalue, creation)
      values (st, sv, pred, ot, ov, event)
      returning triples.id into trid;
  end if;
  return trid;
end;
$$ language plpgsql;


create or replace function get_event() returns bigint as $$
  insert into events default values returning id;
$$ language sql;
