AdvancedTopics: FlightAtTime.sql

File FlightAtTime.sql, 1.8 KB (added by 231044, 6 days ago)
Line 
1create or replace function FlightAtTime (
2 FlightID_P int,
3 Time_P timestamp
4) returns table (
5 CurrentLocation geography,
6 Route geography
7 )
8as
9$$
10 declare
11 DepartureTime timestamp;
12 ArrivalTime timestamp;
13 DepartureLocation geography;
14 ArrivalLocation geography;
15 Fraction numeric;
16 CurrentPosition_V geography;
17 Route_V geography;
18 begin
19 select flight.departure, flight.arrival, ad.location, aa.location
20 into DepartureTime, ArrivalTime, DepartureLocation, ArrivalLocation
21 from flight
22 join gate as ga on flight.actualgatearrivalid = ga.id
23 join gate as gd on flight.actualgatedepartureid = gd.id
24 join terminal as ta on ta.id = ga.terminalid
25 join terminal as td on td.id = gd.terminalid
26 join airport as aa on aa.id = ta.airportid
27 join airport as ad on ad.id = td.airportid
28 where flight.id = FlightID_P;
29
30 if Time_P <= DepartureTime then
31 CurrentPosition_V := DepartureLocation;
32 elsif Time_P >= ArrivalTime then
33 CurrentPosition_V := ArrivalLocation;
34 else
35 Fraction := EXTRACT(epoch FROM (Time_P - DepartureTime))
36 / EXTRACT(epoch FROM (ArrivalTime - DepartureTime));
37
38 CurrentPosition_V := ST_LineInterpolatePoint(
39 ST_MakeLine(DepartureLocation::geometry, ArrivalLocation::geometry),
40 fraction
41 )::geography;
42 end if;
43
44 Route_V := ST_MakeLine(
45 DepartureLocation::geometry,
46 ArrivalLocation::geometry
47 )::geography;
48
49 return query select CurrentPosition_V, Route_V;
50
51 end;
52$$ language plpgsql;
53
54select * from flight;
55
56select * from FlightAtTime(847585, '2025-12-07 10:00:00.000000'::timestamp)