
create table vehicle_position_current
(
 vehicle_id	integer	not null
,position	integer	not null
);
create unique index vpc_idx on vehicle_position_current (vehicle_id);

create table vehicle_position_history
(
 vehicle_id	integer	not null
,log_datetime	timestamp not null default current_timestamp
,position	integer	not null
);
create index vph_idx on vehicle_position_history (vehicle_id);

create or replace function set_vehicle_position(p_veh_id integer, p_position integer) 
returns integer 
as $$
declare
    p integer;
begin
    select into p position 
        from vehicle_position_current    
        where vehicle_id = p_veh_id;
    if not found then
        insert into vehicle_position_current (vehicle_id, position)
        values (p_veh_id, 1);
        insert into vehicle_position_history (vehicle_id, position)
        values (p_veh_id, 1);
    else
        insert into vehicle_position_history (vehicle_id, position)
        values (p_veh_id, p);
        update vehicle_position_current
        set position = position + 1
        where vehicle_id = p_veh_id;
    end if;
    return 0;
end;
$$
language plpgsql;

create or replace function simulate_vehicle_route(p_veh_id integer, npoints integer) 
returns integer 
as $$
declare
    i integer;
begin
    for i in 1..npoints loop
        perform set_vehicle_position(p_veh_id, i);
    end loop;
    return 0;
end;
$$
language plpgsql;

insert into vehicle_position_history
select generate_series(1,10000000),current_timestamp,1;
insert into vehicle_position_current
select generate_series(1,10000000),1;
