set SEARCH_PATH to public,postgis;

create table point (
  id serial primary key,
  nom text not null,
  altitude double precision,
  geom postgis.geometry(point, 4326) not null
);

create index idx_point_geom
  on point using gist (geom);

create table route (
  id serial primary key,
  depart int,
  arrivee int,
  geom postgis.geometry(linestring, 4326) not null,
  longueur double precision
);

create index idx_route_geom
  on route using gist (geom);

create or replace function maj_longueur()
returns trigger as $$
begin
  new.longueur := postgis.st_length(new.geom) * 1000;
  return new;
end;
$$ language plpgsql;

create trigger trigger_longueur
  before insert or update on route
  for each row
  execute function maj_longueur();

-- ************************************************************

create table route_cout (
  route_id int references route(id),
  tag text,
  cout float,
  cout_inverse float,
  primary key (route_id, tag)
);

create table zone (
  id int primary key,
  nom text,
  categorie text,
  geom postgis.geometry(multipolygon, 4326) -- on choisit srid 4326 (wgs84)
);

-- ************************************************************

\COPY point FROM '/tmp/point.csv' (FORMAT CSV, header, ENCODING 'UTF8');
\COPY route(id, depart, arrivee, geom) FROM '/tmp/route.csv' (FORMAT CSV, header, ENCODING 'UTF8');
\COPY route_cout FROM '/tmp/route_cout.csv' (FORMAT CSV, header, ENCODING 'UTF8');
\COPY zone FROM '/tmp/zone.csv' (FORMAT CSV, header, ENCODING 'UTF8');
