@@ -161,7 +161,7 @@ $$ LANGUAGE SQL IMMUTABLE;
161
161
CREATE OR REPLACE VIEW "${ opt . schema } ".arrivals_departures AS
162
162
WITH stop_times_based AS NOT MATERIALIZED (
163
163
SELECT
164
- routes .agency_id,
164
+ agency .agency_id,
165
165
trips.route_id,
166
166
route_short_name,
167
167
route_long_name,
@@ -212,7 +212,14 @@ WITH stop_times_based AS NOT MATERIALIZED (
212
212
LEFT JOIN "${ opt . schema } ".stops stations ON stops.parent_station = stations.stop_id
213
213
JOIN "${ opt . schema } ".trips ON s.trip_id = trips.trip_id
214
214
JOIN "${ opt . schema } ".routes ON trips.route_id = routes.route_id
215
- LEFT JOIN "${ opt . schema } ".agency ON routes.agency_id = agency.agency_id
215
+ LEFT JOIN "${ opt . schema } ".agency ON (
216
+ -- The GTFS spec allows routes.agency_id to be NULL if there is exactly one agency in the feed.
217
+ -- Note: We implicitly rely on other parts of the code base to validate that agency has just one row!
218
+ -- It seems that GTFS has allowed this at least since 2016:
219
+ -- https://github.com/google/transit/blame/217e9bf/gtfs/spec/en/reference.md#L544-L554
220
+ routes.agency_id IS NULL -- match first (and only) agency
221
+ OR routes.agency_id = agency.agency_id -- match by ID
222
+ )
216
223
JOIN "${ opt . schema } ".service_days ON trips.service_id = service_days.service_id
217
224
)
218
225
-- todo: this slows down slightly
@@ -422,7 +429,14 @@ WITH stop_times_based AS NOT MATERIALIZED (
422
429
to_stations.stop_timezone as to_station_tz
423
430
FROM "${ opt . schema } ".trips
424
431
LEFT JOIN "${ opt . schema } ".routes ON trips.route_id = routes.route_id
425
- LEFT JOIN "${ opt . schema } ".agency ON routes.agency_id = agency.agency_id
432
+ LEFT JOIN "${ opt . schema } ".agency ON (
433
+ -- The GTFS spec allows routes.agency_id to be NULL if there is exactly one agency in the feed.
434
+ -- Note: We implicitly rely on other parts of the code base to validate that agency has just one row!
435
+ -- It seems that GTFS has allowed this at least since 2016:
436
+ -- https://github.com/google/transit/blame/217e9bf/gtfs/spec/en/reference.md#L544-L554
437
+ routes.agency_id IS NULL -- match first (and only) agency
438
+ OR routes.agency_id = agency.agency_id -- match by ID
439
+ )
426
440
LEFT JOIN "${ opt . schema } ".stop_times ON trips.trip_id = stop_times.trip_id
427
441
LEFT JOIN "${ opt . schema } ".stops from_stops ON stop_times.stop_id = from_stops.stop_id
428
442
LEFT JOIN "${ opt . schema } ".stops from_stations ON from_stops.parent_station = from_stations.stop_id
0 commit comments