create table point (
    id serial primary key,
    nom text not null,
  altitude double precision,
    geom 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 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 := st_length(new.geom);
  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 serial primary key,
  nom text,
    geom geometry(polygon, 4326) -- on choisit srid 4326 (wgs84)
);

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

INSERT INTO route (source, target, cost, reverse_cost, geom)
SELECT
    a.id AS source,
    b.id AS target,
    1 AS cost,
    1 AS reverse_cost,
    ST_MakeLine(a.geom, b.geom) AS geom
FROM point a
JOIN point b ON a.id = 6 and b.id = 7;


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