
-- create functions for loading cities data as triples

create or replace function load_cities() returns int as $$
declare 
  count int := 0;
  event bigint := new_event();
  city record;
  rkey text;
begin
  for city in
    select name, regiokey, ckey, inhabitants from cities
      where rectype = '60'
      --limit 1
  loop
    rkey := load_city(city.name, city.regiokey, city.ckey, city.inhabitants, event);
    count := count + 1;
  end loop;
  return count;
end;
$$ language plpgsql;


create or replace function load_city(
    name text, regiokey text, ckey text, inhabitants int, 
    event bigint) returns text as $$
declare
  key text := 'xcd:' || regiokey;
begin
  insert into vtriples (stname, stext, ptext, otname, otext, creation) values 
    ('node', key, 'rdf:type', 'node', 'xc:City', event),
    ('node', key, 'rdfs:label', 'text', name, event),
    ('node', key, 'xc:regiokey', 'text', regiokey, event),
    ('node', key, 'xc:ckey', 'text', ckey, event),
    ('node', key, 'xc:population', 'int', text(inhabitants), event);
  return regiokey;
end;
$$ language plpgsql;
