M.4. Объекты схемы #
- M.4.1. Список отношений
- M.4.2. Представление
bookings.aircrafts
- M.4.3. Таблица
bookings.aircrafts_data
- M.4.4. Представление
bookings.airports
- M.4.5. Таблица
bookings.airports_data
- M.4.6. Таблица
bookings.boarding_passes
- M.4.7. Таблица
bookings.bookings
- M.4.8. Таблица
bookings.flights
- M.4.9. Таблица
bookings.seats
- M.4.10. Таблица
bookings.ticket_flights
- M.4.11. Таблица
bookings.tickets
- M.4.12. Представление
bookings.flights_v
- M.4.13. Представление
bookings.routes
- M.4.14. Функция
bookings.now
- M.4.15. Функция
bookings.lang
M.4.1. Список отношений #
Имя | Тип | Small | Medium | Big | Описание -----------------+---------------+--------+--------+--------+------------------------- aircrafts | представление | | | | Самолеты aircrafts_data | таблица | 16 kB | 16 kB | 16 kB | Самолеты (переводы) airports | представление | | | | Аэропорты airports_data | таблица | 56 kB | 56 kB | 56 kB | Аэропорты (переводы) boarding_passes | таблица | 31 MB | 102 MB | 427 MB | Посадочные талоны bookings | таблица | 13 MB | 30 MB | 105 MB | Бронирования flights | таблица | 3 MB | 6 MB | 19 MB | Рейсы flights_v | представление | | | | Рейсы routes | представление | | | | Маршруты seats | таблица | 88 kB | 88 kB | 88 kB | Места ticket_flights | таблица | 64 MB | 145 MB | 516 MB | Перелеты tickets | таблица | 47 MB | 107 MB | 381 MB | Билеты
M.4.2. Представление bookings.aircrafts
#
Каждая модель воздушного судна идентифицируется своим трёхзначным кодом (aircraft_code
). Указывается также название модели (model
) и максимальная дальность полета в километрах (range
).
Значение поля model
определяется в зависимости от выбранного языка. За подробностями обратитесь к Подразделу M.4.15.
Столбец | Тип | Модификаторы | Описание ---------------+---------+--------------+----------------------------------- aircraft_code | char(3) | not null | Код самолета, IATA model | text | not null | Модель самолета range | integer | not null | Максимальная дальность полета, км Определение представления: SELECT ml.aircraft_code, ml.model ->> lang() AS model, ml.range FROM aircrafts_data ml;
M.4.3. Таблица bookings.aircrafts_data
#
Это базовая таблица для представления aircrafts
. Поле model
этой таблицы содержит переводы моделей самолётов на разные языки, в формате JSONB. В большинстве случаев к этой таблице не следует обращаться напрямую.
Столбец | Тип | Модификаторы | Описание ---------------+---------+--------------+----------------------------------- aircraft_code | char(3) | not null | Код самолета, IATA model | jsonb | not null | Модель самолета range | integer | not null | Максимальная дальность полета, км Индексы: PRIMARY KEY, btree (aircraft_code) Ограничения-проверки: CHECK (range > 0) Ссылки извне: TABLE "flights" FOREIGN KEY (aircraft_code) REFERENCES aircrafts_data(aircraft_code) TABLE "seats" FOREIGN KEY (aircraft_code) REFERENCES aircrafts_data(aircraft_code) ON DELETE CASCADE
M.4.4. Представление bookings.airports
#
Аэропорт идентифицируется трехбуквенным кодом (airport_code
) и имеет своё имя (airport_name
).
Для города не предусмотрено отдельной сущности, но введено поле с названием города (city
), позволяющее найти аэропорты одного города. Это представление также включает координаты аэропорта (coordinates
) и часовой пояс (timezone
).
Значения полей airport_name
и city
определяются в зависимости от выбранного языка. За подробностями обратитесь к Подразделу M.4.15.
Столбец | Тип | Модификаторы | Описание --------------+---------+--------------+-------------------------------------------- airport_code | char(3) | not null | Код аэропорта airport_name | text | not null | Название аэропорта city | text | not null | Город coordinates | point | not null | Координаты аэропорта (долгота и широта) timezone | text | not null | Часовой пояс аэропорта Определение представления: SELECT ml.airport_code, ml.airport_name ->> lang() AS airport_name, ml.city ->> lang() AS city, ml.coordinates, ml.timezone FROM airports_data ml;
M.4.5. Таблица bookings.airports_data
#
Это базовая таблица для представления airports
. Она содержит переводы значений airport_name
и city
на разные языки, в формате JSONB. В большинстве случаев к этой таблице не следует обращаться напрямую.
Столбец | Тип | Модификаторы | Описание --------------+---------+--------------+-------------------------------------------- airport_code | char(3) | not null | Код аэропорта airport_name | jsonb | not null | Название аэропорта city | jsonb | not null | Город coordinates | point | not null | Координаты аэропорта (долгота и широта) timezone | text | not null | Часовой пояс аэропорта Индексы: PRIMARY KEY, btree (airport_code) Ссылки извне: TABLE "flights" FOREIGN KEY (arrival_airport) REFERENCES airports_data(airport_code) TABLE "flights" FOREIGN KEY (departure_airport) REFERENCES airports_data(airport_code)
M.4.6. Таблица bookings.boarding_passes
#
При регистрации на рейс, которая возможна за сутки до плановой даты отправления, пассажиру выдаётся посадочный талон. Он идентифицируется также, как и перелёт — номером билета и номером рейса.
Посадочным талонам присваиваются последовательные номера (boarding_no
) в порядке регистрации пассажиров на рейс (этот номер будет уникальным только в пределах данного рейса). В посадочном талоне указывается номер места (seat_no
).
Столбец | Тип | Модификаторы | Описание -------------+------------+--------------+-------------------------- ticket_no | char(13) | not null | Номер билета flight_id | integer | not null | Идентификатор рейса boarding_no | integer | not null | Номер посадочного талона seat_no | varchar(4) | not null | Номер места Индексы: PRIMARY KEY, btree (ticket_no, flight_id) UNIQUE CONSTRAINT, btree (flight_id, boarding_no) UNIQUE CONSTRAINT, btree (flight_id, seat_no) Ограничения внешнего ключа: FOREIGN KEY (ticket_no, flight_id) REFERENCES ticket_flights(ticket_no, flight_id)
M.4.7. Таблица bookings.bookings
#
Пассажир заранее (book_date
, максимум за месяц до рейса) бронирует билет себе и, возможно, нескольким другим пассажирам. Бронирование идентифицируется номером (book_ref
, шестизначная комбинация букв и цифр).
Поле total_amount
хранит общую стоимость включённых в бронирование перелетов всех пассажиров.
Столбец | Тип | Модификаторы | Описание --------------+---------------+--------------+--------------------------- book_ref | char(6) | not null | Номер бронирования book_date | timestamptz | not null | Дата бронирования total_amount | numeric(10,2) | not null | Полная сумма бронирования Индексы: PRIMARY KEY, btree (book_ref) Ссылки извне: TABLE "tickets" FOREIGN KEY (book_ref) REFERENCES bookings(book_ref)
M.4.8. Таблица bookings.flights
#
Естественный ключ таблицы рейсов состоит из двух полей — номера рейса (flight_no
) и даты отправления (scheduled_departure
). Чтобы сделать внешние ключи на эту таблицу компактнее, в качестве первичного используется суррогатный ключ (flight_id
).
Рейс всегда соединяет две точки — аэропорты вылета (departure_airport
) и прибытия (arrival_airport
). Такое понятие, как «рейс с пересадками» отсутствует: если из одного аэропорта до другого нет прямого рейса, в билет просто включаются несколько необходимых рейсов.
У каждого рейса есть запланированные дата и время вылета (scheduled_departure
) и прибытия (scheduled_arrival
). Реальные время вылета (actual_departure
) и прибытия (actual_arrival
) могут отличаться: обычно не сильно, но иногда и на несколько часов, если рейс задержан.
Статус рейса (status
) может принимать одно из следующих значений:
-
Scheduled
Рейс доступен для бронирования. Это происходит за месяц до плановой даты вылета; до этого запись о рейсе не существует в базе данных.
-
On Time
Рейс доступен для регистрации (за сутки до плановой даты вылета) и не задержан.
-
Delayed
Рейс доступен для регистрации (за сутки до плановой даты вылета), но задержан.
-
Departed
Самолет уже вылетел и находится в воздухе.
-
Arrived
Самолет прибыл в пункт назначения.
-
Cancelled
Рейс отменён.
Столбец | Тип | Модификаторы | Описание ---------------------+-------------+--------------+----------------------------- flight_id | serial | not null | Идентификатор рейса flight_no | char(6) | not null | Номер рейса scheduled_departure | timestamptz | not null | Время вылета по расписанию scheduled_arrival | timestamptz | not null | Время прилёта по расписанию departure_airport | char(3) | not null | Аэропорт отправления arrival_airport | char(3) | not null | Аэропорт прибытия status | varchar(20) | not null | Статус рейса aircraft_code | char(3) | not null | Код самолета, IATA actual_departure | timestamptz | | Фактическое время вылета actual_arrival | timestamptz | | Фактическое время прилёта Индексы: PRIMARY KEY, btree (flight_id) UNIQUE CONSTRAINT, btree (flight_no, scheduled_departure) Ограничения-проверки: CHECK (scheduled_arrival > scheduled_departure) CHECK ((actual_arrival IS NULL) OR ((actual_departure IS NOT NULL AND actual_arrival IS NOT NULL) AND (actual_arrival > actual_departure))) CHECK (status IN ('On Time', 'Delayed', 'Departed', 'Arrived', 'Scheduled', 'Cancelled')) Ограничения внешнего ключа: FOREIGN KEY (aircraft_code) REFERENCES aircrafts(aircraft_code) FOREIGN KEY (arrival_airport) REFERENCES airports(airport_code) FOREIGN KEY (departure_airport) REFERENCES airports(airport_code) Ссылки извне: TABLE "ticket_flights" FOREIGN KEY (flight_id) REFERENCES flights(flight_id)
M.4.9. Таблица bookings.seats
#
Места определяют схему салона каждой модели. Каждое место определяется своим номером (seat_no
) и имеет закреплённый за ним класс обслуживания (fare_conditions
) — Economy
, Comfort
или Business
.
Столбец | Тип | Модификаторы | Описание -----------------+-------------+--------------+-------------------- aircraft_code | char(3) | not null | Код самолета, IATA seat_no | varchar(4) | not null | Номер места fare_conditions | varchar(10) | not null | Класс обслуживания Индексы: PRIMARY KEY, btree (aircraft_code, seat_no) Ограничения-проверки: CHECK (fare_conditions IN ('Economy', 'Comfort', 'Business')) Ограничения внешнего ключа: FOREIGN KEY (aircraft_code) REFERENCES aircrafts(aircraft_code) ON DELETE CASCADE
M.4.10. Таблица bookings.ticket_flights
#
Перелёт соединяет билет с рейсом и идентифицируется их номерами.
Для каждого перелета указываются его стоимость (amount
) и класс обслуживания (fare_conditions
).
Столбец | Тип | Модификаторы | Описание -----------------+---------------+--------------+--------------------- ticket_no | char(13) | not null | Номер билета flight_id | integer | not null | Идентификатор рейса fare_conditions | varchar(10) | not null | Класс обслуживания amount | numeric(10,2) | not null | Стоимость перелета Индексы: PRIMARY KEY, btree (ticket_no, flight_id) Ограничения-проверки: CHECK (amount >= 0) CHECK (fare_conditions IN ('Economy', 'Comfort', 'Business')) Ограничения внешнего ключа: FOREIGN KEY (flight_id) REFERENCES flights(flight_id) FOREIGN KEY (ticket_no) REFERENCES tickets(ticket_no) Ссылки извне: TABLE "boarding_passes" FOREIGN KEY (ticket_no, flight_id) REFERENCES ticket_flights(ticket_no, flight_id)
M.4.11. Таблица bookings.tickets
#
Билет имеет уникальный номер (ticket_no
), состоящий из 13 цифр.
Билет содержит идентификатор пассажира (passenger_id
) — номер документа, удостоверяющего личность, — его фамилию и имя (passenger_name
) и контактную информацию (contact_data
).
Ни идентификатор пассажира, ни имя не являются постоянными (можно поменять паспорт, можно сменить фамилию), поэтому однозначно найти все билеты одного и того же пассажира невозможно.
Столбец | Тип | Модификаторы | Описание ----------------+-------------+--------------+----------------------------- ticket_no | char(13) | not null | Номер билета book_ref | char(6) | not null | Номер бронирования passenger_id | varchar(20) | not null | Идентификатор пассажира passenger_name | text | not null | Имя пассажира contact_data | jsonb | | Контактные данные пассажира Индексы: PRIMARY KEY, btree (ticket_no) Ограничения внешнего ключа: FOREIGN KEY (book_ref) REFERENCES bookings(book_ref) Ссылки извне: TABLE "ticket_flights" FOREIGN KEY (ticket_no) REFERENCES tickets(ticket_no)
M.4.12. Представление bookings.flights_v
#
Над таблицей flights
создано представление flights_v
, содержащее дополнительную информацию:
расшифровку данных об аэропорте вылета —
departure_airport
,departure_airport_name
,departure_city
расшифровку данных об аэропорте прибытия —
arrival_airport
,arrival_airport_name
,arrival_city
местное время вылета —
scheduled_departure_local
,actual_departure_local
местное время прибытия —
scheduled_arrival_local
,actual_arrival_local
продолжительность полета —
scheduled_duration
,actual_duration
.
Столбец | Тип | Описание ---------------------------+-------------+-------------------------------------- flight_id | integer | Идентификатор рейса flight_no | char(6) | Номер рейса scheduled_departure | timestamptz | Время вылета по расписанию scheduled_departure_local | timestamp | Время вылета по расписанию, | | местное время в пункте отправления scheduled_arrival | timestamptz | Время прилёта по расписанию scheduled_arrival_local | timestamp | Время прилёта по расписанию, | | местное время в пункте прибытия scheduled_duration | interval | Планируемая продолжительность полета departure_airport | char(3) | Код аэропорта отправления departure_airport_name | text | Название аэропорта отправления departure_city | text | Город отправления arrival_airport | char(3) | Код аэропорта прибытия arrival_airport_name | text | Название аэропорта прибытия arrival_city | text | Город прибытия status | varchar(20) | Статус рейса aircraft_code | char(3) | Код самолета, IATA actual_departure | timestamptz | Фактическое время вылета actual_departure_local | timestamp | Фактическое время вылета, | | местное время в пункте отправления actual_arrival | timestamptz | Фактическое время прилёта actual_arrival_local | timestamp | Фактическое время прилёта, | | местное время в пункте прибытия actual_duration | interval | Фактическая продолжительность полета
M.4.13. Представление bookings.routes
#
Таблица рейсов (bookings.flights
) содержит избыточность: из неё можно было бы выделить информацию о маршруте (номер рейса, аэропорты отправления и назначения), которая не зависит от конкретных дат рейсов.
Именно такая информация составляет представление routes
.
Столбец | Тип | Описание ------------------------+-----------+------------------------------------- flight_no | char(6) | Номер рейса departure_airport | char(3) | Код аэропорта отправления departure_airport_name | text | Название аэропорта отправления departure_city | text | Город отправления arrival_airport | char(3) | Код аэропорта прибытия arrival_airport_name | text | Название аэропорта прибытия arrival_city | text | Город прибытия aircraft_code | char(3) | Код самолета, IATA duration | interval | Продолжительность полета days_of_week | integer[] | Дни недели, когда выполняются рейсы
M.4.14. Функция bookings.now
#
Демонстрационная база содержит временной «срез» данных — так, как будто в некоторый момент была сделана резервная копия реальной системы. Например, если некоторый рейс имеет статус Departed
, это означает, что в момент резервного копирования самолет вылетел и находился в воздухе.
Позиция «среза» сохранена в функции bookings.now()
function. Ей можно пользоваться в запросах там, где в обычной жизни использовалась бы функция now()
.
Кроме того, значение этой функции определяет версию демонстрационной базы данных. Актуальная версия на текущий момент — от 15 августа 2017 г.
M.4.15. Функция bookings.lang
#
Некоторые поля в демонстрационной базе содержат текст на английском и русском языках. Переводы на другие языки отсутствуют, но их несложно добавить. Функция bookings.lang
возвращает значение параметра bookings.lang
, то есть язык, на котором будут выдаваться значения этих полей.
Эта функция используется в представлениях aircrafts
и airports
и не предназначена для непосредственного использования в запросах.
M.4. Schema Objects #
- M.4.1. List of Relations
- M.4.2. View
bookings.aircrafts
- M.4.3. Table
bookings.aircrafts_data
- M.4.4. View
bookings.airports
- M.4.5. Table
bookings.airports_data
- M.4.6. Table
bookings.boarding_passes
- M.4.7. Table
bookings.bookings
- M.4.8. Table
bookings.flights
- M.4.9. Table
bookings.seats
- M.4.10. Table
bookings.ticket_flights
- M.4.11. Table
bookings.tickets
- M.4.12. View
bookings.flights_v
- M.4.13. View
bookings.routes
- M.4.14. Function
bookings.now
- M.4.15. Function
bookings.lang
M.4.1. List of Relations #
Name | Type | Small | Medium | Big | Description -----------------+---------------+--------+--------+--------+------------------------- aircrafts | view | | | | Aircraft aircrafts_data | table | 16 kB | 16 kB | 16 kB | Aircraft (translations) airports | view | | | | Airports airports_data | table | 56 kB | 56 kB | 56 kB | Airports (translations) boarding_passes | table | 31 MB | 102 MB | 427 MB | Boarding passes bookings | table | 13 MB | 30 MB | 105 MB | Bookings flights | table | 3 MB | 6 MB | 19 MB | Flights flights_v | view | | | | Flights routes | view | | | | Routes seats | table | 88 kB | 88 kB | 88 kB | Seats ticket_flights | table | 64 MB | 145 MB | 516 MB | Flight segments tickets | table | 47 MB | 107 MB | 381 MB | Tickets
M.4.2. View bookings.aircrafts
#
Each aircraft model is identified by its three-digit code (aircraft_code
). The view also includes the name of the aircraft model (model
) and the maximal flying distance, in kilometers (range
).
The value of the model
field is selected according to the chosen language. See Section M.4.15 for details.
Column | Type | Modifiers | Description ---------------+---------+--------------+----------------------------------- aircraft_code | char(3) | not null | Aircraft code, IATA model | text | not null | Aircraft model range | integer | not null | Maximal flying distance, km View definition: SELECT ml.aircraft_code, ml.model ->> lang() AS model, ml.range FROM aircrafts_data ml;
M.4.3. Table bookings.aircrafts_data
#
This is the base table for the aircrafts
view. The model
field of this table contains translations of aircraft models to different languages, in the JSONB format. In most cases, this table is not supposed to be used directly.
Column | Type | Modifiers | Description ---------------+---------+--------------+----------------------------------- aircraft_code | char(3) | not null | Aircraft code, IATA model | jsonb | not null | Aircraft model range | integer | not null | Maximal flying distance, km Indexes: PRIMARY KEY, btree (aircraft_code) Check constraints: CHECK (range > 0) Referenced by: TABLE "flights" FOREIGN KEY (aircraft_code) REFERENCES aircrafts_data(aircraft_code) TABLE "seats" FOREIGN KEY (aircraft_code) REFERENCES aircrafts_data(aircraft_code) ON DELETE CASCADE
M.4.4. View bookings.airports
#
An airport is identified by a three-letter code (airport_code
) and has a name (airport_name
).
There is no separate entity for the city, but there is a city name (city
) to identify the airports of the same city. The view also includes coordinates (coordinates
) and the time zone (timezone
).
The values of the airport_name
and city
fields are selected according to the chosen language. See Section M.4.15 for details.
Column | Type | Modifiers | Description --------------+---------+--------------+-------------------------------------------- airport_code | char(3) | not null | Airport code airport_name | text | not null | Airport name city | text | not null | City coordinates | point | not null | Airport coordinates (longitude and latitude) timezone | text | not null | Airport time zone View definition: SELECT ml.airport_code, ml.airport_name ->> lang() AS airport_name, ml.city ->> lang() AS city, ml.coordinates, ml.timezone FROM airports_data ml;
M.4.5. Table bookings.airports_data
#
This is the base table for the airports
view. This table contains translations of airport_name
and city
values to different languages, in the JSONB format. In most cases, this table is not supposed to be used directly.
Column | Type | Modifiers | Description --------------+---------+--------------+-------------------------------------------- airport_code | char(3) | not null | Airport code airport_name | jsonb | not null | Airport name city | jsonb | not null | City coordinates | point | not null | Airport coordinates (longitude and latitude) timezone | text | not null | Airport time zone Indexes: PRIMARY KEY, btree (airport_code) Referenced by: TABLE "flights" FOREIGN KEY (arrival_airport) REFERENCES airports_data(airport_code) TABLE "flights" FOREIGN KEY (departure_airport) REFERENCES airports_data(airport_code)
M.4.6. Table bookings.boarding_passes
#
At the time of check-in, which opens twenty-four hours before the scheduled departure, the passenger is issued a boarding pass. Like the flight segment, the boarding pass is identified by the ticket number and the flight number.
Boarding passes are assigned sequential numbers (boarding_no
), in the order of check-ins for the flight (this number is unique only within the context of a particular flight). The boarding pass specifies the seat number (seat_no
).
Column | Type | Modifiers | Description -------------+------------+--------------+-------------------------- ticket_no | char(13) | not null | Ticket number flight_id | integer | not null | Flight ID boarding_no | integer | not null | Boarding pass number seat_no | varchar(4) | not null | Seat number Indexes: PRIMARY KEY, btree (ticket_no, flight_id) UNIQUE CONSTRAINT, btree (flight_id, boarding_no) UNIQUE CONSTRAINT, btree (flight_id, seat_no) Foreign-key constraints: FOREIGN KEY (ticket_no, flight_id) REFERENCES ticket_flights(ticket_no, flight_id)
M.4.7. Table bookings.bookings
#
Passengers book tickets for themselves, and, possibly, for several other passengers, in advance (book_date
, not earlier than one month before the flight). The booking is identified by its number (book_ref
, a six-position combination of letters and digits).
The total_amount
field stores the total cost of all tickets included into the booking, for all passengers.
Column | Type | Modifiers | Description --------------+---------------+--------------+--------------------------- book_ref | char(6) | not null | Booking number book_date | timestamptz | not null | Booking date total_amount | numeric(10,2) | not null | Total booking cost Indexes: PRIMARY KEY, btree (book_ref) Referenced by: TABLE "tickets" FOREIGN KEY (book_ref) REFERENCES bookings(book_ref)
M.4.8. Table bookings.flights
#
The natural key of the bookings.flights
table consists of two fields — flight_no
and scheduled_departure
. To make foreign keys for this table more compact, a surrogate key is used as the primary key (flight_id
).
A flight always connects two points — the airport of departure (departure_airport
) and arrival (arrival_airport
). There is no such entity as a “connecting flight”: if there are no non-stop flights from one airport to another, the ticket simply includes several required flight segments.
Each flight has a scheduled date and time of departure (scheduled_departure
) and arrival (scheduled_arrival
). The actual departure time (actual_departure
) and arrival time (actual_arrival
) can differ: the difference is usually not very big, but sometimes can be up to several hours if the flight is delayed.
Flight status (status
) can take one of the following values:
-
Scheduled
The flight is available for booking. It happens one month before the planned departure date; before that time, there is no entry for this flight in the database.
-
On Time
The flight is open for check-in (in twenty-four hours before the scheduled departure) and is not delayed.
-
Delayed
The flight is open for check-in (in twenty-four hours before the scheduled departure) but is delayed.
-
Departed
The aircraft has already departed and is airborne.
-
Arrived
The aircraft has reached the point of destination.
-
Cancelled
The flight is canceled.
Column | Type | Modifiers | Description ---------------------+-------------+--------------+----------------------------- flight_id | serial | not null | Flight ID flight_no | char(6) | not null | Flight number scheduled_departure | timestamptz | not null | Scheduled departure time scheduled_arrival | timestamptz | not null | Scheduled arrival time departure_airport | char(3) | not null | Airport of departure arrival_airport | char(3) | not null | Airport of arrival status | varchar(20) | not null | Flight status aircraft_code | char(3) | not null | Aircraft code, IATA actual_departure | timestamptz | | Actual departure time actual_arrival | timestamptz | | Actual arrival time Indexes: PRIMARY KEY, btree (flight_id) UNIQUE CONSTRAINT, btree (flight_no, scheduled_departure) Check constraints: CHECK (scheduled_arrival > scheduled_departure) CHECK ((actual_arrival IS NULL) OR ((actual_departure IS NOT NULL AND actual_arrival IS NOT NULL) AND (actual_arrival > actual_departure))) CHECK (status IN ('On Time', 'Delayed', 'Departed', 'Arrived', 'Scheduled', 'Cancelled')) Foreign-key constraints: FOREIGN KEY (aircraft_code) REFERENCES aircrafts(aircraft_code) FOREIGN KEY (arrival_airport) REFERENCES airports(airport_code) FOREIGN KEY (departure_airport) REFERENCES airports(airport_code) Referenced by: TABLE "ticket_flights" FOREIGN KEY (flight_id) REFERENCES flights(flight_id)
M.4.9. Table bookings.seats
#
Seats define the cabin configuration of each aircraft model. Each seat is defined by its number (seat_no
) and has an assigned travel class (fare_conditions
): Economy
, Comfort
or Business
.
Column | Type | Modifiers | Description -----------------+-------------+--------------+-------------------- aircraft_code | char(3) | not null | Aircraft code, IATA seat_no | varchar(4) | not null | Seat number fare_conditions | varchar(10) | not null | Travel class Indexes: PRIMARY KEY, btree (aircraft_code, seat_no) Check constraints: CHECK (fare_conditions IN ('Economy', 'Comfort', 'Business')) Foreign-key constraints: FOREIGN KEY (aircraft_code) REFERENCES aircrafts(aircraft_code) ON DELETE CASCADE
M.4.10. Table bookings.ticket_flights
#
A flight segment connects a ticket with a flight and is identified by their numbers.
Each flight has its cost (amount
) and travel class (fare_conditions
).
Column | Type | Modifiers | Description -----------------+---------------+--------------+--------------------- ticket_no | char(13) | not null | Ticket number flight_id | integer | not null | Flight ID fare_conditions | varchar(10) | not null | Travel class amount | numeric(10,2) | not null | Travel cost Indexes: PRIMARY KEY, btree (ticket_no, flight_id) Check constraints: CHECK (amount >= 0) CHECK (fare_conditions IN ('Economy', 'Comfort', 'Business')) Foreign-key constraints: FOREIGN KEY (flight_id) REFERENCES flights(flight_id) FOREIGN KEY (ticket_no) REFERENCES tickets(ticket_no) Referenced by: TABLE "boarding_passes" FOREIGN KEY (ticket_no, flight_id) REFERENCES ticket_flights(ticket_no, flight_id)
M.4.11. Table bookings.tickets
#
A ticket has a unique number (ticket_no
) that consists of 13 digits.
The ticket includes a passenger ID (passenger_id
) — the identity document number, — their first and last names (passenger_name
), and contact information (contact_data
).
Neither the passenger ID, nor the name is permanent (for example, one can change the last name or passport), so it is impossible to uniquely identify all tickets of a particular passenger.
Column | Type | Modifiers | Description ----------------+-------------+--------------+----------------------------- ticket_no | char(13) | not null | Ticket number book_ref | char(6) | not null | Booking number passenger_id | varchar(20) | not null | Passenger ID passenger_name | text | not null | Passenger name contact_data | jsonb | | Passenger contact information Indexes: PRIMARY KEY, btree (ticket_no) Foreign-key constraints: FOREIGN KEY (book_ref) REFERENCES bookings(book_ref) Referenced by: TABLE "ticket_flights" FOREIGN KEY (ticket_no) REFERENCES tickets(ticket_no)
M.4.12. View bookings.flights_v
#
There is a flights_v
view over the flights
table that provides additional information:
Details about the airport of departure —
departure_airport
,departure_airport_name
,departure_city
Details about the airport of arrival —
arrival_airport
,arrival_airport_name
,arrival_city
Local departure time —
scheduled_departure_local
,actual_departure_local
Local arrival time —
scheduled_arrival_local
,actual_arrival_local
Flight duration —
scheduled_duration
,actual_duration
.
Column | Type | Description ---------------------------+-------------+-------------------------------------- flight_id | integer | Flight ID flight_no | char(6) | Flight number scheduled_departure | timestamptz | Scheduled departure time scheduled_departure_local | timestamp | Scheduled departure time, | | local time at the point of departure scheduled_arrival | timestamptz | Scheduled arrival time scheduled_arrival_local | timestamp | Scheduled arrival time, | | local time at the point of destination scheduled_duration | interval | Scheduled flight duration departure_airport | char(3) | Departure airport code departure_airport_name | text | Departure airport name departure_city | text | City of departure arrival_airport | char(3) | Arrival airport code arrival_airport_name | text | Arrival airport name arrival_city | text | City of arrival status | varchar(20) | Flight status aircraft_code | char(3) | Aircraft code, IATA actual_departure | timestamptz | Actual departure time actual_departure_local | timestamp | Actual departure time, | | local time at the point of departure actual_arrival | timestamptz | Actual arrival time actual_arrival_local | timestamp | Actual arrival time, | | local time at the point of destination actual_duration | interval | Actual flight duration
M.4.13. View bookings.routes
#
The bookings.flights
table contains some redundancies, which you can use to single out route information (flight number, airports of departure and destination) that does not depend on the exact flight dates.
Such information is shown in the routes
view.
Column | Type | Description ------------------------+-----------+------------------------------------- flight_no | char(6) | Flight number departure_airport | char(3) | Departure airport code departure_airport_name | text | Departure airport name departure_city | text | City of departure arrival_airport | char(3) | Arrival airport code arrival_airport_name | text | Arrival airport name arrival_city | text | City of arrival aircraft_code | char(3) | Aircraft code, IATA duration | interval | Flight duration days_of_week | integer[] | Days of the week on which flights are performed
M.4.14. Function bookings.now
#
The demo database contains “snapshots” of data — similar to a backup copy of a real system captured at some point in time. For example, if a flight has the Departed
status, it means that the aircraft had already departed and was airborne at the time of the backup copy.
The “snapshot” time is saved in the bookings.now()
function. You can use this function in demo queries for cases where you would use the now()
function in a real database.
In addition, the return value of this function determines the version of the demo database. The latest version available is of August 15, 2017.
M.4.15. Function bookings.lang
#
Some fields in the demo database are available in English and Russian. Translations to other languages are not provided, but are easy to add. The bookings.lang
returns the value of the bookings.lang
parameter, that is, the language in which these fields will be displayed.
This function is used in the aircrafts
and airports
views and is not intended to be used directly in queries.