Бронзовый слой

Слой Bronze содержит две отдельные схемы данных, каждая из которых обслуживает различные аспекты платформы телематики и бизнес-аналитики:

  • raw_business_data - содержит таблицы, атрибуты и значения, связанные с бизнес-информацией, такими как транспортные средства, сотрудники, геозоны, добавленные пользователями, и т.д.

  • raw_telematics_data - содержит таблицы, атрибуты и значения, связанные с телематическими данными, передаваемыми от контролируемых устройств, такими как местоположения, входы, выходы и события.

Каждая схема оптимизирована для своей предметной области данных и шаблонов доступа, обеспечивая всестороннее покрытие оперативных, телематических и задач управления активами.

raw_business_data structure

Эта схема содержит более 40 тщательно подобранных таблиц для охвата различных бизнес-аспектов и сценариев использования. Эти таблицы представляют ваши основные бизнес-сущности, организационную структуру и операционные данные.

Интерактивная диаграмма схемы raw_business_data доступна на dbdiagram.io: https://dbdiagram.io/d/V3-bronze-layer-68ecfd1c2e68d21b4131089a

Подробности схемы raw_business_data приведены ниже.

схема raw_business_data

Таблица "vehicle_service_tasks" {

  "record_added_at" timestamp [not null]

  "start_mileage" numeric

  "comment" "character varying(255)"

  "status" "character varying(10)" [not null]

  "completion_date" timestamp

  "start_engine_hours" numeric

  "service_task_id" integer [not null]

  "is_notification_push_enabled" boolean [not null]

  "date_notification_interval" interval

  "predicted_datetime" timestamp

  "cost" numeric [not null]

  "mileage_limit" numeric

  "notification_emails" text

  "is_unplanned" boolean [not null]

  "is_repeat" boolean [not null]

  "completion_engine_hours" integer

  "engine_hours_limit" numeric

  "mileage_repeat_interval" integer

  "vehicle_id" integer [not null]

  "engine_hours_notification_interval" integer

  "start_date" timestamp

  "mileage_notification_interval" integer

  "date_repeat_interval" interval

  "description" "character varying(255)"

  "notification_sms_phone_numbers" text

  "end_date" timestamp

  "engine_hours_repeat_interval" integer

  "completion_mileage" integer

}

  

Таблица "garages" {

  "record_added_at" timestamp [not null]

  "garage_id" integer [not null]

  "longitude" numeric

  "mechanic_name" "character varying(255)"

  "radius" integer [not null]

  "latitude" numeric

  "organization_label" "character varying(255)"

  "user_id" integer [not null]

  "dispatcher_name" "character varying(255)"

  "address" "character varying(255)"

}

  

Таблица "driver_history" {

  "server_datetime" timestamp [not null]

  "address" "character varying(255)"

  "updated_by" integer [not null]

  "object_id" integer

  "longitude" numeric

  "latitude" numeric

  "driver_history_id" integer [not null]

  "hardware_key" "character varying(64)"

  "new_employee_id" integer

  "changed_datetime" timestamp

  "record_added_at" timestamp [not null]

  "old_employee_id" integer

}

  

Таблица "departments" {

  "record_added_at" timestamp [not null]

  "department_label" "character varying(255)" [not null]

  "latitude" numeric

  "department_id" integer [not null]

  "address" "character varying(255)"

  "radius" integer [not null]

  "longitude" numeric

  "user_id" integer [not null]

}

  

Таблица "checkins" {

  "radius" integer [not null]

  "latitude" numeric [not null]

  "employee_id" integer [not null]

  "longitude" numeric [not null]

  "record_added_at" timestamp [not null]

  "actual_datetime" timestamp [not null]

  "user_id" integer [not null]

  "form_id" integer [not null]

  "address" "character varying(255)"

  "planned_datetime" timestamp [not null]

  "object_id" integer [not null]

  "checkin_id" integer [not null]

  "comment" text

}

  

Таблица "statuses" {

  "order_sort" integer [not null]

  "listing_id" integer [not null]

  "color" "character varying(6)" [not null]

  "status_id" integer [not null]

  "status_label" "character varying(200)" [not null]

  "record_added_at" timestamp [not null]

  "is_deleted" boolean [not null]

}

  

Таблица "places_linked_entity_fields" {

  "value" bigint [not null]

  "record_added_at" timestamp [not null]

  "place_id" integer [not null]

  "field_id" integer [not null]

}

  

Таблица "places_text_fields" {

  "place_id" integer [not null]

  "record_added_at" timestamp [not null]

  "value" text [not null]

  "field_id" integer [not null]

}

  

Таблица "users2zones" {

  "zone_id" integer [not null]

  "record_added_at" timestamp [not null]

  "user_id" integer [not null]

}

  

Таблица "objects" {

  "record_added_at" timestamp [not null]

  "create_datetime" timestamp [not null]

  "client_id" integer [not null]

  "group_id" integer

  "object_label" "character varying(100)"

  "model" "character varying(64)"

  "is_clone" boolean [not null]

  "is_deleted" boolean [not null]

  "device_id" integer [not null]

  "object_id" integer [not null]

}

  

Таблица "device_output_name" {

  "device_id" integer [not null]

  "record_added_at" timestamp [not null]

  "label" "character varying(100)" [not null]

  "number" integer [not null]

}

  

Таблица "geofence_points" {

  "longitude" numeric [not null]

  "number" integer [not null]

  "zone_id" integer [not null]

  "record_added_at" timestamp [not null]

  "latitude" numeric [not null]

}

  

Таблица "custom_fields" {

  "record_added_at" timestamp [not null]

  "entity_id" integer [not null]

  "is_required" boolean [not null]

  "custom_field_label" text [not null]

  "parameters" jsonb

  "custom_field_type" integer [not null]

  "description" text

  "custom_field_id" integer [not null]

}

  

Таблица "places_decimal_fields" {

  "field_id" integer [not null]

  "record_added_at" timestamp [not null]

  "place_id" integer [not null]

  "value" numeric [not null]

}

  

Таблица "task_history" {

  "task_id" integer [not null]

  "activity" integer [not null]

  "task_history_id" integer [not null]

  "record_added_at" timestamp [not null]

  "user_id" integer [not null]

  "event_datetime" timestamp [not null]

  "payload" text

}

  

Таблица "tags" {

  "tag_label" "character varying(64)" [not null]

  "color" "character varying(6)"

  "user_id" integer [not null]

  "record_added_at" timestamp [not null]

  "tag_id" integer [not null]

}

  

Таблица "places" {

  "description" text

  "custom_fields" jsonb

  "place_id" integer [not null]

  "external_id" "character varying(32)"

  "record_added_at" timestamp [not null]

  "user_id" integer

  "latitude" numeric

  "radius" integer

  "place_label" "character varying(256)"

  "assigned_datetime" timestamp

  "address" "character varying(256)"

  "longitude" numeric

}

  

Таблица "status_listings" {

  "user_id" integer [not null]

  "is_supervisor_controlled" boolean [not null]

  "is_deleted" boolean [not null]

  "status_listing_id" integer [not null]

  "is_employee_controlled" boolean [not null]

  "record_added_at" timestamp [not null]

  "status_listing_label" "character varying(200)" [not null]

}

  

Таблица "models" {

  "record_added_at" timestamp [not null]

  "model_id" integer [not null]

  "has_battery_level" boolean [not null]

  "alternative_label" "character varying(50)" [not null]

  "vendor" "character varying(30)" [not null]

  "is_clone" boolean

  "has_altitude" boolean [not null]

  "has_phone" boolean [not null]

  "type_output_control" "character varying(30)" [not null]

  "has_gsm_roaming" boolean [not null]

  "has_gsm_level" boolean [not null]

  "model" "character varying(255)" [not null]

  "type_special_control" "character varying(255)" [not null]

  "digital_amount" integer [not null]

  "has_detach_button" boolean [not null]

  "has_gsm_name" boolean [not null]

  "analog_amount" integer [not null]

  "outputs_amount" integer [not null]

}

  

Таблица "vehicle_trackers_history" {

  "vehicle_id" integer [not null]

  "record_added_at" timestamp [not null]

  "object_id" integer [not null]

  "changed_datetime" timestamp [not null]

  "vehicle_tracker_history_id" integer [not null]

}

  

Таблица "groups" {

  "group_id" integer [not null]

  "group_color" "character varying(6)" [not null]

  "group_label" "character varying(255)" [not null]

  "client_id" integer [not null]

  "record_added_at" timestamp [not null]

}

  

Таблица "sensor_description" {

  "record_added_at" timestamp [not null]

  "parameters" jsonb

  "input_id" integer [not null]

  "accuracy" numeric [not null]

  "sensor_units" "character varying(10)"

  "multiplier" doubleprecision [not null]

  "input_label" "character varying(64)"

  "sensor_label" "character varying(100)"

  "units_type" integer [not null]

  "divider" doubleprecision [not null]

  "group_id" integer [not null]

  "sensor_id" integer [not null]

  "device_id" integer [not null]

  "sensor_type" "character varying(45)" [not null]

  "group_type" integer [not null]

}

  

Таблица "entities" {

  "entity_label" jsonb

  "record_added_at" timestamp [not null]

  "entity_id" integer [not null]

  "builtin_type" integer [not null]

  "user_id" integer [not null]

}

  

Таблица "zones" {

  "address" "character varying(255)"

  "radius" integer [not null]

  "zone_id" integer [not null]

  "circle_center_latitude" numeric [not null]

  "client_id" integer [not null]

  "zone_label" "character varying(100)"

  "color" "character varying(6)" [not null]

  "zone_type" "character varying(20)" [not null]

  "circle_center_longitude" numeric [not null]

  "latitude" numeric [not null]

  "record_added_at" timestamp [not null]

  "longitude" numeric [not null]

}

  

Таблица "vehicles" {

  "vehicle_id" integer [not null]

  "payload_length" numeric

  "vin" "character varying(20)"

  "free_insurance_policy_number" "character varying(50)"

  "vehicle_label" "character varying(100)"

  "payload_width" numeric

  "color" "character varying(6)"

  "trailer" "character varying(255)"

  "object_id" integer

  "vehicle_status_id" integer

  "liability_insurance_valid_till" timestamp

  "manufacture_year" integer

  "fuel_grade" "character varying(16)"

  "fuel_cost" numeric

  "fuel_tank_volume" numeric

  "model" "character varying(100)"

  "garage_id" integer

  "payload_height" numeric

  "max_speed" numeric

  "registration_number" "character varying(32)"

  "tyre_size" "character varying(50)"

  "passenger_capacity" integer

  "record_added_at" timestamp [not null]

  "trailer_reg_number" "character varying(32)"

  "free_insurance_valid_till_date" timestamp

  "gross_weight" numeric

  "standard_fuel_consumption" numeric

  "fuel_type" integer

  "payload_weight" numeric

  "additional_info" text

  "vehicle_subtype" "character varying(32)"

  "liability_insurance_policy_number" "character varying(50)"

  "frame_number" "character varying(32)"

  "user_id" integer [not null]

  "vehicle_type" integer [not null]

  "chassis_number" "character varying(32)"

  "tyres_number" integer

  "wheel_arrangement" "character varying(16)"

}

  

Таблица "tag_links" {

  "entity_id" integer [not null]

  "record_added_at" timestamp [not null]

  "entity_type" integer [not null]

  "ordinal" integer [not null]

  "tag_id" integer [not null]

}

  

Таблица "rules" {

  "rule_id" integer [not null]

  "object_id" integer [not null]

  "parameters" jsonb

  "alert_phone" "character varying(210)" [not null]

  "event_type" "character varying(100)" [not null]

  "client_id" integer [not null]

  "is_push_enabled" boolean [not null]

  "event_comment1" "character varying(255)" [not null]

  "event_label" "character varying(255)" [not null]

  "description" "character varying(255)" [not null]

  "record_added_at" timestamp [not null]

  "alert_sms" text [not null]

  "event_group" integer [not null]

  "created_at" timestamp [not null]

  "maximum" integer [not null]

  "is_deleted" boolean [not null]

  "alert_email" text [not null]

  "event_comment2" "character varying(255)" [not null]

}

  

Таблица "status_history" {

  "longitude" numeric

  "new_status_id" integer

  "status_history_id" integer [not null]

  "device_id" integer [not null]

  "updated_by" integer [not null]

  "address" "character varying(255)"

  "latitude" numeric

  "record_added_at" timestamp [not null]

  "server_datetime" timestamp [not null]

  "changed_datetime" timestamp

  "old_status_id" integer

}

  

Таблица "rules2zones" {

  "zone_id" integer [not null]

  "record_added_at" timestamp [not null]

  "rule_id" integer [not null]

}

  

Таблица "forms" {

  "object_id" integer [not null]

  "description" text

  "form_label" "character varying(255)" [not null]

  "fields" text

  "created_at" timestamp [not null]

  "submission_address" "character varying(255)"

  "submission_latitude" numeric

  "form_id" integer [not null]

  "submission_longitude" numeric

  "is_submission_in_zone" boolean [not null]

  "values" text

  "record_added_at" timestamp [not null]

  "task_id" integer

  "submitted_at" timestamp

}

  

Таблица "sensor_calibration_data" {

  "value" numeric [not null]

  "sensor_id" integer [not null]

  "record_added_at" timestamp [not null]

  "volume" numeric [not null]

  "device_id" integer [not null]

  "sensor_calibration_id" bigint [not null]

}

  

Таблица "rules2objects" {

  "object_params" jsonb

  "param_group_number" integer [not null]

  "object_id" integer [not null]

  "record_added_at" timestamp [not null]

  "rule_id" integer [not null]

}

  

Таблица "tasks" {

  "time_from" timestamp

  "stay_duration_minutes" interval

  "external_id" "character varying(100)"

  "object_id" integer

  "task_type" integer

  "arrival_duration_minutes" interval

  "status" integer

  "arrival_datetime" timestamp

  "record_added_at" timestamp [not null]

  "task_id" integer [not null]

  "user_id" integer

  "status_change_datetime" timestamp

  "order_sort" integer

  "time_to" timestamp

  "max_delay_minuts" integer

  "is_stay_control_enabled" boolean

  "address" "character varying(255)"

  "task_label" "character varying(200)" [not null]

  "longitude" numeric

  "created_by" integer

  "description" text [not null]

  "radius" integer

  "latitude" numeric

  "stay_duration" integer

  "created_at" timestamp [not null]

  "custom_fields" jsonb

  "parent_task_id" integer

}

  

Таблица "places_bigint_fields" {

  "field_id" integer [not null]

  "value" bigint [not null]

  "place_id" integer [not null]

  "record_added_at" timestamp [not null]

}

  

Таблица "devices" {

  "is_sim_blocked" boolean [not null]

  "device_id" integer [not null]

  "device_imei" "character varying(64)" [not null]

  "network_label" "character varying(50)" [not null]

  "status_listing_id" integer [not null]

  "signal_level" numeric [not null]

  "phone" "character varying(32)" [not null]

  "has_roaming" boolean [not null]

  "created_at" timestamp [not null]

  "owner_id" integer [not null]

  "record_added_at" timestamp [not null]

}

  

Таблица "description_parametrs" {

  "description" "character varying(150)"

  "record_added_at" timestamp [not null]

  "type" "character varying(100)" [not null]

  "key" integer [not null]

}

  

Таблица "users" {

  "company_label" "character varying(255)" [not null]

  "registration_datetime" timestamp

  "first_name" "character varying(100)" [not null]

  "master_id" integer

  "last_name" "character varying(100)" [not null]

  "birth_date" timestamp

  "timezone_label" "character varying(30)"

  "middle_name" "character varying(100)" [not null]

  "user_id" integer [not null]

  "locale" "character varying(10)" [not null]

  "record_added_at" timestamp [not null]

}

  

Таблица "counters" {

  "sensor_id" integer

  "multiplier" numeric [not null]

  "counter_id" integer [not null]

  "device_id" integer [not null]

  "counter_type" integer [not null]

  "record_added_at" timestamp [not null]

}

  

Таблица "employees" {

  "driver_license_valid_till" timestamp

  "record_added_at" timestamp [not null]

  "last_name" "character varying(100)"

  "department_id" integer

  "citizen_id_number" "character varying(32)"

  "first_name" "character varying(100)"

  "driver_license_categories" "character varying(32)"

  "user_id" integer [not null]

  "phone_number" "character varying(32)"

  "object_id" integer

  "is_deleted" boolean [not null]

  "driver_license_issue_date" boolean

  "hardware_key" "character varying(64)"

  "middle_name" "character varying(100)"

  "address" "character varying(255)"

  "latitude" numeric

  "employee_id" integer [not null]

  "personnel_number" "character varying(15)"

  "fuel_cost" doubleprecision

  "driver_license_number" "character varying(32)"

  "email" "character varying(100)"

  "fuel_consumption" doubleprecision

  "radius" integer [not null]

  "longitude" numeric

}

  

Таблица "places_longtext_fields" {

  "field_id" integer [not null]

  "value" text [not null]

  "record_added_at" timestamp [not null]

  "place_id" integer [not null]

}

  

Таблица "raw_device_data" {

  "device_id" integer

  "device_time" timestamp

  "created_at" timestamp

  "gps_fix_type" integer

  "longitude" integer

  "latitude" integer

  "altitude" integer

  "speed" integer

  "satellites" integer

  "hdop" integer

  "event_id" integer

  "inputs" jsonb

  "states" jsonb

}

  

Таблица "groups_objects" {

  "groups_client_id" integer

  "objects_client_id" integer

  

  Индексы {

    (groups_client_id, objects_client_id) [pk]

  }

}

  

Ссылка:"employees"."employee_id" < "checkins"."employee_id"

  

Ссылка:"objects"."object_id" < "checkins"."object_id"

  

Ссылка:"forms"."form_id" < "checkins"."form_id"

  

Ссылка:"sensor_description"."sensor_id" < "counters"."sensor_id"

  

Ссылка:"devices"."device_id" < "counters"."device_id"

  

Ссылка:"entities"."entity_id" < "custom_fields"."entity_id"

  

Ссылка:"departments"."department_id" < "employees"."department_id"

  

Ссылка:"users"."user_id" < "departments"."user_id"

  

Ссылка:"description_parametrs"."key" < "counters"."counter_type"

  

Ссылка:"description_parametrs"."key" < "custom_fields"."custom_field_type"

  

Ссылка:"description_parametrs"."key" < "driver_history"."updated_by"

  

Ссылка:"description_parametrs"."key" < "entities"."builtin_type"

  

Ссылка:"description_parametrs"."key" < "sensor_description"."units_type"

  

Ссылка:"description_parametrs"."key" < "status_history"."updated_by"

  

Ссылка:"description_parametrs"."key" < "tasks"."status"

  

Ссылка:"description_parametrs"."key" < "tasks"."created_at"

  

Ссылка:"description_parametrs"."key" < "tasks"."task_type"

  

Ссылка:"description_parametrs"."key" < "vehicles"."fuel_type"

  

Ссылка:"description_parametrs"."key" < "task_history"."activity"

  

Ссылка:"description_parametrs"."key" < "sensor_description"."group_type"

  

Ссылка:"devices"."device_id" < "device_output_name"."device_id"

  

Ссылка:"status_listings"."status_listing_id" < "devices"."status_listing_id"

  

Ссылка:"employees"."employee_id" < "driver_history"."new_employee_id"

  

Ссылка:"employees"."employee_id" < "driver_history"."old_employee_id"

  

Ссылка:"objects"."object_id" < "driver_history"."object_id"

  

Ссылка:"objects"."object_id" < "employees"."object_id"

  

Ссылка:"users"."user_id" < "employees"."user_id"

  

Ссылка:"users"."user_id" < "entities"."user_id"

  

Ссылка:"tasks"."task_id" < "forms"."task_id"

  

Ссылка:"objects"."object_id" < "forms"."object_id"

  

Ссылка:"objects"."object_id" < "tasks"."object_id"

  

Ссылка:"users"."user_id" < "garages"."user_id"

  

Ссылка:"groups"."client_id" < "groups_objects"."groups_client_id"

  

Ссылка:"objects"."client_id" < "groups_objects"."objects_client_id"

  

Ссылка:"models"."model" < "objects"."model"

  

Ссылка:"devices"."device_id" < "objects"."device_id"

  

Ссылка:"users"."user_id" < "places"."user_id"

  

Ссылка:"custom_fields"."custom_field_id" < "places_bigint_fields"."field_id"

  

Ссылка:"places"."place_id" < "places_bigint_fields"."place_id"

  

Ссылка:"custom_fields"."custom_field_id" < "places_decimal_fields"."field_id"

  

Ссылка:"places"."place_id" < "places_decimal_fields"."place_id"

  

Ссылка:"custom_fields"."custom_field_id" < "places_linked_entity_fields"."field_id"

  

Ссылка:"places"."place_id" < "places_linked_entity_fields"."place_id"

  

Ссылка:"custom_fields"."custom_field_id" < "places_longtext_fields"."field_id"

  

Ссылка:"places"."place_id" < "places_longtext_fields"."place_id"

  

Ссылка:"custom_fields"."custom_field_id" < "places_text_fields"."field_id"

  

Ссылка:"places"."place_id" < "places_text_fields"."place_id"

  

Ссылка:"rules"."rule_id" < "rules2zones"."rule_id"

  

Ссылка:"objects"."object_id" < "rules2objects"."object_id"

  

Ссылка:"rules"."rule_id" < "rules2objects"."object_id"

  

Ссылка:"zones"."zone_id" < "rules2zones"."zone_id"

  

Ссылка:"sensor_description"."sensor_id" < "sensor_calibration_data"."device_id"

  

Ссылка:"sensor_description"."device_id" < "sensor_calibration_data"."sensor_id"

  

Ссылка:"devices"."device_id" < "sensor_description"."device_id"

  

Ссылка:"statuses"."status_id" < "status_history"."new_status_id"

  

Ссылка:"statuses"."status_id" < "status_history"."old_status_id"

  

Ссылка:"devices"."device_id" < "status_history"."device_id"

  

Ссылка:"users"."user_id" < "status_listings"."user_id"

  

Ссылка:"status_listings"."status_listing_id" < "statuses"."listing_id"

  

Ссылка:"tags"."tag_id" < "tag_links"."tag_id"

  

Ссылка:"users"."user_id" < "tags"."user_id"

  

Ссылка:"tasks"."task_id" < "task_history"."task_id"

  

Ссылка:"users"."user_id" < "task_history"."user_id"

  

Ссылка:"tasks"."parent_task_id" < "tasks"."task_id"

  

Ссылка:"users"."user_id" < "tasks"."user_id"

  

Ссылка:"users"."master_id" < "users"."user_id"

  

Ссылка:"users"."user_id" < "users2zones"."user_id"

  

Ссылка:"zones"."zone_id" < "users2zones"."zone_id"

  

Ref:"vehicles"."vehicle_id" < "vehicle_service_tasks"."vehicle_id"

  

Ref:"objects"."object_id" < "vehicle_trackers_history"."object_id"

  

Ref:"vehicles"."vehicle_id" < "vehicle_trackers_history"."vehicle_id"

  

Ref:"garages"."garage_id" < "vehicles"."garage_id"

  

Ref:"objects"."object_id" < "vehicles"."object_id"

  

Ref:"users"."user_id" < "vehicles"."user_id"

  

Ref:"zones"."zone_id" < "geofence_points"."zone_id"

  

Ref:"sensor_calibration_data"."value" < "sensor_calibration_data"."device_id"

  

Ref:"devices"."device_id" < "raw_device_data"."device_id"

  

Ref:"users"."user_id" < "devices"."owner_id"

  

Ref:"users"."user_id" < "objects"."client_id"

Частота обновления

Данные в этой схеме синхронизируются с основной БД. Обновления происходят инкрементально по мере изменения данных в исходной базе MySQL, обычно менее чем через 5 минут после изменения в источнике.

description_parameters

Система включает справочные данные для стандартизации значений по всей базе данных:

Тип справочника
Описание
Примеры значений

Определения типов

Стандартные типы сущностей

vehicle_type: car, truck, bus

Коды статусов

Значения статусов задач и системы

tasks_status: unassigned, assigned, done

Определения единиц измерения

Единицы измерения для датчиков

units_type: liter, gallon, celsius

Классификации сущностей

Категории бизнес-сущностей

entities_type: place, task, customer

Ключевые таблицы по категориям

Таблицы в raw_business_data схеме организованы по функциональным категориям для удобства навигации. В таблице ниже приведено краткое описание ключевых таблиц по их бизнес-назначению:

Обзор схемы базы данных

Категория
Имя таблицы
Описание

Организационная структура

  1. users

  2. departments

  3. employees

  4. groups

  1. Учетные записи пользователей с информацией профиля

  2. Отделы с геолокационными данными

  3. Сведения о сотрудниках и водителях

  4. Группы организации трекеров

Объекты и устройства

  1. devices

  2. models

  3. objects

  4. vehicles

  5. sensor_description

  1. Физические трекинговые устройства

  2. Спецификации моделей устройств

  3. Мониторируемые объекты

  4. Данные и спецификации транспортных средств

  5. Детали конфигурации датчиков

Места и зоны

  1. places

  2. zones

  3. garages

  4. tags

  1. Точки интереса с геолокацией

  2. Области мониторинга с геозаборами

  3. Места обслуживания транспортных средств

  4. Организационные метки

Операционные данные

  1. tasks

  2. forms

  3. checkins

  4. events

  5. statuses

  6. vehicle_service_tasks

  1. Назначения и отслеживание задач

  2. Формы для сбора данных

  3. Записи посещений по местоположению

  4. События системы и уведомления

  5. Определения статусов

  6. Записи обслуживания транспортных средств

raw_telematics_data structure

Схема raw_telematics_data содержит три основных типа таблиц, которые работают совместно, обеспечивая полный набор данных об устройствах.

Bronze layer raw telematics data ERD
ERD слоя Bronze: необработанные телематические данные

Интерактивная диаграмма схемы raw_telematics_data доступна на dbdiagram.io: https://dbdiagram.io/d/v1-schema-telematics-bd-67a0acef263d6cf9a0d8e750

Ниже приведены детали схемы необработанных телематических данных.

схема raw_telematics_data
Таблица tracking_data_core {

  device_id integer [primary key]

  device_time timestampz [primary key]

  platform_time timestampz

  record_added_at timestampz [default: `now()`]

  latitude integer

  longitude integer

  speed integer

  altitude integer

  satellites integer

  event_id integer

  gps_fix_type integer

  hdop integer

  

  indexes {(device_id, device_time)}

}

  

Таблица inputs {

  event_id integer [primary key]

  device_id integer [primary key]

  record_added_at timestampz [default: `now()`]

  device_time timestampz [primary key]

  sensor_name text [primary key]

  value text

  indexes {(device_id, device_time)}

}

  

Таблица states {

  event_id integer [primary key]

  device_id serial [primary key]

  record_added_at timestampz [default: `now()`]

  device_time timestampz [primary key]

  state_name text [primary key]

  value text

  indexes {(device_id, device_time)}

}

  

Ref: inputs.(device_id, device_time) > tracking_data_core.(device_id, device_time)

Ref: states.(device_id, device_time) > tracking_data_core.(device_id, device_time)

Ключевые таблицы по категориям

Каждая таблица выполняет конкретную функцию для захвата разных аспектов информации об устройстве:

tracking_data_core

Назначение: Основные данные о местоположении и движении

Атрибут
Детали

Ключевые поля

device_id, device_time, platform_time, latitude, longitude, speed, altitude, satellites, hdop, event_id

Индексация

Оптимизировано с индексом на (device_id, device_time)

Особые замечания

Данные местоположения (широта и долгота) используют целочисленный формат с точностью 10⁷ для оптимальной производительности в TimescaleDB Скорость также хранится в целочисленном формате, поэтому её необходимо делить на 100

inputs

Назначение: Показания датчиков с устройств

Атрибут
Детали

Ключевые поля

input_id, device_id, device_time, sensor_name, value

Содержание

Аналоговые показания (уровень топлива, температура, напряжение), вычисляемые значения (обороты двигателя)

Связи

FROM raw_telematics_data.inputs AS i
JOIN raw_business_data.sensor_description AS sd
    ON i.device_id = sd.device_id AND i.sensor_name = sd.input_label
JOIN raw_telematics_data.tacking_data_core AS tdc
    ON i.device_id = tdc.device_id AND i.device_time = tdc.device_time

states

Назначение: Индикаторы состояния устройства и рабочие режимы

Атрибут
Детали

Ключевые поля

state_id, device_id, device_time, state_name, value

Содержание

Индикаторы режимов работы (работа, простои, выкл.), состояния компонентов (зажигание, двери)

Формат значения

Булевы значения (1/0) или специфические коды статусов

Данные в этой схеме поступают напрямую от устройств с минимальной задержкой (обычно секунды). Схема оптимизирована для временных рядов с использованием TimescaleDB для эффективного хранения и выборки.

Дополнительная информация

Валидация данных

База данных обеспечивает целостность данных посредством нескольких механизмов:

  • Ограничения CHECK проверяют, что значения находятся в допустимых границах

  • Внешние ключи обеспечивают согласованность связей между таблицами

  • Ограничения NOT NULL гарантируют, что обязательные поля всегда содержат значения

  • Значения по умолчанию DEFAULT обеспечивают запасной вариант, когда данные явно не предоставлены

Оптимизация запросов

Таблицы организованы со специфическими стратегиями индексации:

  • Во всех таблицах включены временные индексы на record_added_at

  • Колонки внешних ключей имеют выделенные индексы для повышения производительности джойнов

  • Часто используемые комбинации колонок имеют составные индексы

  • TimescaleDB предоставляет специализированные индексы для запросов по временным рядам

repo структура данных

Схема repo схема предоставляет комплексную основу для управления организационными структурами, активами, устройствами и их связями в многопользовательских средах. Построенная на PostgreSQL 14+ с расширением ltree, схема поддерживает иерархические организации, произвольные определения полей для любых типов сущностей, ролевой доступ с ограничениями на уровне объектов и полные журналы аудита с отслеживанием изменений на уровне полей. Все сущности могут быть расширены без модификации схемы, локализованы для международных внедрений и связаны через гибкие полиморфные отношения.

Схема решает сложные сценарии управления данными, включая иерархии активов автопарка на разных уровнях организаций, многопользовательские SaaS-платформы, требующие изоляции данных, операции, требующие соответствия с подробными требованиями аудита, и системы, нуждающиеся в динамичных моделях данных, адаптируемых через пользовательские поля вместо миграций базы данных.

Интерактивная диаграммаrepo схемы данных доступна на dbdiagram.io: https://dbdiagram.io/d/Navixy-Repo-data-schema-68ad788c1e7a611967a0930e

Ниже найдите repo детали схемы.

repo схема данных
// ============================================
// New DataHub Schema - Customer Journey
// PostgreSQL 14+ with ltree extension
// Version: 2.0 (Concept)
// ============================================

// ============================================
// BASE REFERENCE TABLES (ci_base hierarchy)
// ============================================

Таблица ci_base {
  id uuid [primary key]
  code text [not null]
  title_en text [not null]
  order int
  is_system boolean [not null, default: false]
  discriminator text [not null]
  catalog_id uuid
  organization_id uuid
  parent_id uuid
  path ltree
  is_hierarchical boolean [default: false]
  extra jsonb
  created_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  updated_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  deleted_at timestamptz
  
  индексы {
    (parent_id) [name: 'idx_ci_parent']
    (path) [type: gist, name: 'idx_ci_path_gist']
    (catalog_id) [name: 'idx_ci_catalog']
    (organization_id) [name: 'idx_ci_org']
    (discriminator) [name: 'idx_ci_discriminator']
    (code) [unique, name: 'uq_ci_code_per_type']
    (organization_id, code) [unique, name: 'uq_ci_org_code']
  }
}

Таблица ci_module {
  id uuid [primary key]
}

Таблица ci_catalog_category {
  id uuid [primary key]
}

Таблица ci_country {
  id uuid [primary key]
}

Таблица ci_role {
  id uuid [primary key]
}

Таблица ci_entity_type {
  id uuid [primary key]
}

Таблица ci_device_status {
  id uuid [primary key]
}

Таблица ci_permission_scope {
  id uuid [primary key]
  module_id uuid
  entity_type_id uuid
  category text
}

Таблица ci_device_type {
  id uuid [primary key]
}

Таблица ci_asset_type {
  id uuid [primary key]
  category_id uuid
}

Таблица ci_asset_type_category {
  id uuid [primary key]
}

Таблица ci_inventory_type {
  id uuid [primary key]
}

Таблица ci_organization_type {
  id uuid [primary key]
}

Таблица ci_user_type {
  id uuid [primary key]
}

Таблица ci_asset_group_type {
  id uuid [primary key]
  max_items int
  color text
  icon text
  allowed_asset_type_id uuid
}

Таблица ci_device_relation_type {
  id uuid [primary key]
}

Таблица ci_tag {
  id uuid [primary key]
  entity_type_id uuid
  color text
}

// ============================================
// БАЗОВАЯ СУЩНОСТЬ С ПОДДЕРЖКОЙ ПОЛЕЙ НАСТРОЙКИ
// ============================================

Таблица customizable_entity {
  id uuid [primary key]
  entity_type_id uuid [not null]
  cf_data jsonb
  created_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  
  индексы {
    (entity_type_id) [name: 'idx_customizable_entity_type']
  }
}

// ============================================
// КЛЮЧЕВЫЕ БИЗНЕС-СУЩНОСТИ
// ============================================

Таблица organization {
  id uuid [primary key]
  parent_id uuid
  path ltree
  organization_type_id uuid [not null]
  title_en text [not null]
  is_active boolean [not null, default: true]
  created_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  updated_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  deleted_at timestamptz
  deleted_by uuid
  
  индексы {
    (parent_id) [name: 'idx_org_parent']
    (path) [type: gist, name: 'idx_org_path_gist']
    (organization_type_id) [name: 'idx_org_type']
  }
}

Таблица catalog {
  id uuid [primary key]
  organization_id uuid [not null]
  module_id uuid
  category_id uuid
  title_en text [not null]
  is_system boolean [not null, default: false]
  created_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  updated_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  
  индексы {
    (organization_id) [name: 'idx_catalog_org']
    (module_id) [name: 'idx_catalog_module']
  }
}

Таблица user {
  id uuid [primary key]
  organization_id uuid [not null]
  user_type_id uuid [not null]
  identity_provider text [not null]
  identity_provider_id uuid [not null]
  full_name text [not null]
  is_active boolean [not null, default: true]
  created_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  updated_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  deleted_at timestamptz
  deleted_by uuid
  
  индексы {
    (organization_id) [name: 'idx_user_org']
    (user_type_id) [name: 'idx_user_type']
    (organization_id, identity_provider, identity_provider_id) [unique, name: 'uq_user_org_idp']
  }
}

// ============================================
// УПРАВЛЕНИЕ ДОСТУПОМ (ACL)
// ============================================

Таблица user_role {
  id uuid [primary key]
  user_id uuid [not null]
  role_id uuid [not null]
  assigned_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  assigned_by uuid
  
  индексы {
    (user_id) [name: 'idx_user_role_user']
    (role_id) [name: 'idx_user_role_role']
    (user_id, role_id) [unique, name: 'uq_user_role']
  }
}

Таблица acl_role_permission {
  id uuid [primary key]
  role_id uuid [not null]
  permission_scope_id uuid [not null]
  target_entity_id uuid
  actions int [not null]
  granted_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  granted_by uuid
  
  индексы {
    (role_id) [name: 'idx_acl_role_perm_role']
    (permission_scope_id) [name: 'idx_acl_role_perm_scope']
    (role_id, permission_scope_id, target_entity_id) [unique, name: 'uq_acl_role_permission']
  }
}

Таблица acl_user_scope {
  id uuid [primary key]
  user_id uuid [not null]
  permission_scope_id uuid [not null]
  target_entity_id uuid [not null]
  actions int [not null]
  
  индексы {
    (user_id, permission_scope_id) [name: 'idx_acl_user_scope_user']
    (user_id, permission_scope_id, target_entity_id) [unique, name: 'uq_acl_user_scope']
  }
}

// ============================================
// БИЗНЕС-СУЩНОСТИ
// ============================================

Таблица asset {
  id uuid [primary key]
  organization_id uuid [not null]
  asset_type_id uuid [not null]
  label text [not null]
  description text
  created_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  updated_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  deleted_at timestamptz
  deleted_by uuid
  
  индексы {
    (organization_id) [name: 'idx_asset_org']
    (asset_type_id) [name: 'idx_asset_type']
  }
}

Таблица inventory {
  id uuid [primary key]
  organization_id uuid [not null]
  inventory_type_id uuid [not null]
  code text [not null]
  created_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  updated_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  deleted_at timestamptz
  deleted_by uuid
  
  индексы {
    (organization_id) [name: 'idx_inventory_org']
    (inventory_type_id) [name: 'idx_inventory_type']
    (organization_id, code) [unique, name: 'uq_inventory_org_code']
  }
}

Таблица device {
  id uuid [primary key]
  organization_id uuid [not null]
  device_type_id uuid [not null]
  status_id uuid [not null]
  hw_id text
  label text [not null]
  created_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  updated_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  deleted_at timestamptz
  deleted_by uuid
  
  индексы {
    (organization_id) [name: 'idx_device_org']
    (device_type_id) [name: 'idx_device_type']
    (status_id) [name: 'idx_device_status']
    (hw_id) [name: 'idx_device_hw_id']
  }
}

Таблица device_asset_link {
  id uuid [primary key]
  device_id uuid [unique, not null]
  asset_id uuid [not null]
  linked_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  linked_by uuid
  
  индексы {
    (device_id) [unique, name: 'idx_device_asset_link_device']
    (asset_id) [name: 'idx_device_asset_link_asset']
  }
}

Таблица device_inventory_link {
  id uuid [primary key]
  device_id uuid [unique, not null]
  inventory_id uuid [not null]
  linked_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  linked_by uuid
  
  индексы {
    (device_id) [unique, name: 'idx_device_inventory_link_device']
    (inventory_id) [name: 'idx_device_inventory_link_inventory']
  }
}

Таблица device_relation {
  id uuid [primary key]
  master_id uuid [not null]
  slave_id uuid [not null]
  relation_type_id uuid [not null]
  
  индексы {
    (master_id) [name: 'idx_device_relation_master']
    (slave_id) [name: 'idx_device_relation_slave']
    (master_id, slave_id, relation_type_id) [unique, name: 'uq_device_relation']
  }
}

Таблица asset_group {
  id uuid [primary key]
  organization_id uuid [not null]
  group_type_id uuid [not null]
  title_en text [not null]
  description text
  created_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  updated_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  deleted_at timestamptz
  deleted_by uuid
  
  индексы {
    (organization_id) [name: 'idx_asset_group_org']
    (group_type_id) [name: 'idx_asset_group_type']
  }
}

Таблица asset_group_item {
  id uuid [primary key]
  group_id uuid [not null]
  asset_id uuid [not null]
  attached_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  detached_at timestamptz
  
  индексы {
    (group_id) [name: 'idx_asset_group_item_group']
    (asset_id) [name: 'idx_asset_group_item_asset']
    (group_id, asset_id, detached_at) [unique, name: 'uq_asset_group_item']
  }
}

Таблица entity_tag {
  id uuid [primary key]
  tag_id uuid [not null]
  entity_id uuid [not null]
  tagged_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  
  индексы {
    (tag_id) [name: 'idx_entity_tag_tag']
    (entity_id) [name: 'idx_entity_tag_entity']
    (tag_id, entity_id) [unique, name: 'uq_entity_tag']
  }
}

// ============================================
// ЛОКАЛИЗАЦИЯ
// ============================================

Таблица i18n_text {
  entity_id uuid [pk]
  field_code text [pk]
  locale text [pk]
  text_value text [not null]
  
  индексы {
    (entity_id) [name: 'idx_i18n_entity']
    (locale) [name: 'idx_i18n_locale']
  }
}

// ============================================
// ОПРЕДЕЛЕНИЯ ПОЛЕЙ НАСТРОЙКИ
// ============================================

Таблица custom_field_def {
  id uuid [primary key]
  organization_id uuid [not null]
  owner_entity_type_id uuid [not null]
  code text [not null]
  title_en text [not null]
  field_type text [not null]
  is_multi boolean [not null, default: false]
  is_required boolean [not null, default: false]
  order int
  ref_entity_type_id uuid
  ref_catalog_id uuid
  created_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  updated_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  
  индексы {
    (organization_id) [name: 'idx_cfd_org']
    (owner_entity_type_id) [name: 'idx_cfd_owner_type']
    (organization_id, owner_entity_type_id, code) [unique, name: 'uq_cfd_org_type_code']
  }
}

// ============================================
// ЗНАЧЕНИЯ ПОЛЕЙ НАСТРОЙКИ (по типу)
// ============================================

Таблица custom_field_value_text {
  customizable_entity_id uuid [pk]
  field_def_id uuid [pk]
  value_index smallint [pk]
  value text [not null]
  
  индексы {
    (field_def_id, value) [name: 'idx_cfv_text_value']
  }
}

Таблица custom_field_value_number {
  customizable_entity_id uuid [pk]
  field_def_id uuid [pk]
  value_index smallint [pk]
  value numeric [not null]
  
  индексы {
    (field_def_id, value) [name: 'idx_cfv_number_value']
  }
}

Таблица custom_field_value_boolean {
  customizable_entity_id uuid [pk]
  field_def_id uuid [pk]
  value_index smallint [pk]
  value boolean [not null]
  
  индексы {
    (field_def_id, value) [name: 'idx_cfv_boolean_value']
  }
}

Таблица custom_field_value_date {
  customizable_entity_id uuid [pk]
  field_def_id uuid [pk]
  value_index smallint [pk]
  value date [not null]
  
  индексы {
    (field_def_id, value) [name: 'idx_cfv_date_value']
  }
}

Таблица custom_field_value_datetime {
  customizable_entity_id uuid [pk]
  field_def_id uuid [pk]
  value_index smallint [pk]
  value timestamptz [not null]
  
  индексы {
    (field_def_id, value) [name: 'idx_cfv_datetime_value']
  }
}

Таблица custom_field_value_entity {
  customizable_entity_id uuid [pk]
  field_def_id uuid [pk]
  value_index smallint [pk]
  ref_entity_id uuid [not null]
  
  индексы {
    (field_def_id, ref_entity_id) [name: 'idx_cfv_entity_value']
  }
}

Таблица custom_field_value_catalog {
  customizable_entity_id uuid [pk]
  field_def_id uuid [pk]
  value_index smallint [pk]
  ref_item_id uuid [not null]
  
  индексы {
    (field_def_id, ref_item_id) [name: 'idx_cfv_catalog_value']
  }
}

// ============================================
// АУДИТ
// ============================================

Таблица audit_event {
  id uuid [primary key]
  event_category text [not null]
  user_id uuid
  identity_provider_id uuid
  ip_address inet
  user_agent text
  aggregate_type text
  aggregate_id uuid
  event_type text [not null]
  event_data jsonb
  occurred_at timestamptz [not null, default: `CURRENT_TIMESTAMP`]
  
  индексы {
    (user_id, occurred_at) [name: 'idx_audit_event_user']
    (aggregate_type, aggregate_id, occurred_at) [name: 'idx_audit_event_aggregate']
    (event_category, occurred_at) [name: 'idx_audit_event_category']
    (event_type, occurred_at) [name: 'idx_audit_event_type']
  }
}

// ============================================
// ОТНОШЕНИЯ
// ============================================

Ссылка: ci_base.catalog_id > catalog.id
Ссылка: ci_base.organization_id > organization.id
Ссылка: ci_base.parent_id > ci_base.id

Ссылка: ci_module.id - ci_base.id
Ссылка: ci_catalog_category.id - ci_base.id
Ссылка: ci_country.id - ci_base.id
Ссылка: ci_role.id - ci_base.id
Ссылка: ci_entity_type.id - ci_base.id
Ссылка: ci_device_status.id - ci_base.id
Ссылка: ci_permission_scope.id - ci_base.id
Ссылка: ci_device_type.id - ci_entity_type.id
Ссылка: ci_asset_type.id - ci_entity_type.id
Ссылка: ci_asset_type_category.id - ci_base.id
Ссылка: ci_inventory_type.id - ci_entity_type.id
Ссылка: ci_organization_type.id - ci_entity_type.id
Ссылка: ci_user_type.id - ci_entity_type.id
Ссылка: ci_asset_group_type.id - ci_entity_type.id
Ссылка: ci_device_relation_type.id - ci_base.id
Ссылка: ci_tag.id - ci_base.id

Ссылка: ci_permission_scope.module_id > ci_module.id
Ссылка: ci_permission_scope.entity_type_id > ci_entity_type.id
Ссылка: ci_asset_type.category_id > ci_asset_type_category.id
Ссылка: ci_asset_group_type.allowed_asset_type_id > ci_asset_type.id
Ссылка: ci_tag.entity_type_id > ci_entity_type.id

Ссылка: customizable_entity.entity_type_id > ci_entity_type.id

Ссылка: organization.id - customizable_entity.id
Ссылка: organization.parent_id > organization.id
Ссылка: organization.organization_type_id > ci_organization_type.id
Ссылка: organization.deleted_by > user.id

Ссылка: catalog.organization_id > organization.id
Ссылка: catalog.module_id > ci_module.id
Ссылка: catalog.category_id > ci_catalog_category.id

Ссылка: user.id - customizable_entity.id
Ссылка: user.organization_id > organization.id
Ссылка: user.user_type_id > ci_user_type.id
Ссылка: user.deleted_by > user.id

Ссылка: user_role.user_id > user.id
Ссылка: user_role.role_id > ci_role.id
Ссылка: user_role.assigned_by > user.id

Ссылка: acl_role_permission.role_id > ci_role.id
Ссылка: acl_role_permission.permission_scope_id > ci_permission_scope.id
Ссылка: acl_role_permission.granted_by > user.id

Ссылка: acl_user_scope.user_id > user.id
Ссылка: acl_user_scope.permission_scope_id > ci_permission_scope.id

Ссылка: asset.id - customizable_entity.id
Ссылка: asset.organization_id > organization.id
Ссылка: asset.asset_type_id > ci_asset_type.id
Ссылка: asset.deleted_by > user.id

Ссылка: inventory.id - customizable_entity.id
Ссылка: inventory.organization_id > organization.id
Ссылка: inventory.inventory_type_id > ci_inventory_type.id
Ссылка: inventory.deleted_by > user.id

Ссылка: device.id - customizable_entity.id
Ссылка: device.organization_id > organization.id
Ссылка: device.device_type_id > ci_device_type.id
Ссылка: device.status_id > ci_device_status.id
Ссылка: device.deleted_by > user.id

Ссылка: device_asset_link.device_id - device.id
Ссылка: device_asset_link.asset_id > asset.id
Ссылка: device_asset_link.linked_by > user.id

Ссылка: device_inventory_link.device_id - device.id
Ссылка: device_inventory_link.inventory_id > inventory.id
Ссылка: device_inventory_link.linked_by > user.id

Ссылка: device_relation.master_id > device.id
Ссылка: device_relation.slave_id > device.id
Ссылка: device_relation.relation_type_id > ci_device_relation_type.id

Ссылка: asset_group.id - customizable_entity.id
Ссылка: asset_group.organization_id > organization.id
Ссылка: asset_group.group_type_id > ci_asset_group_type.id
Ссылка: asset_group.deleted_by > user.id

Ссылка: asset_group_item.group_id > asset_group.id
Ссылка: asset_group_item.asset_id > asset.id

Ссылка: entity_tag.tag_id > ci_tag.id

Ссылка: custom_field_def.organization_id > organization.id
Ссылка: custom_field_def.owner_entity_type_id > ci_entity_type.id
Ссылка: custom_field_def.ref_entity_type_id > ci_entity_type.id
Ссылка: custom_field_def.ref_catalog_id > catalog.id

Ссылка: custom_field_value_text.customizable_entity_id > customizable_entity.id
Ссылка: custom_field_value_text.field_def_id > custom_field_def.id

Ссылка: custom_field_value_number.customizable_entity_id > customizable_entity.id
Ссылка: custom_field_value_number.field_def_id > custom_field_def.id

Ссылка: custom_field_value_boolean.customizable_entity_id > customizable_entity.id
Ссылка: custom_field_value_boolean.field_def_id > custom_field_def.id

Ссылка: custom_field_value_date.customizable_entity_id > customizable_entity.id
Ссылка: custom_field_value_date.field_def_id > custom_field_def.id

Ссылка: custom_field_value_datetime.customizable_entity_id > customizable_entity.id
Ссылка: custom_field_value_datetime.field_def_id > custom_field_def.id

Ссылка: custom_field_value_entity.customizable_entity_id > customizable_entity.id
Ссылка: custom_field_value_entity.field_def_id > custom_field_def.id
Ссылка: custom_field_value_entity.ref_entity_id > customizable_entity.id

Ссылка: custom_field_value_catalog.customizable_entity_id > customizable_entity.id
Ссылка: custom_field_value_catalog.field_def_id > custom_field_def.id
Ссылка: custom_field_value_catalog.ref_item_id > ci_base.id

Ссылка: audit_event.user_id > user.id

Частота обновления

Данные в repo схема синхронизируется в режиме реального времени с исходными системами. Обновления происходят немедленно по мере внесения изменений, при этом журналы аудита фиксируют все модификации для соответствия требованиям и исторического анализа.

ci_base

Схема repo схема использует шаблон Single Table Inheritance для всех справочных данных через ci_base таблица:

Схема repo схема использует Single Table Inheritance шаблон для всех справочных данных через ci_base таблица. Эта конструкция объединяет системные словари, классификации и пользовательские справочные элементы в единую структуру, обеспечивая согласованность и гибкость по всей схеме.

Архитектура:

Схема ci_base таблица служит основой для всех справочных данных, используя дискриминатор поле для идентификации конкретного типа справочника. Каждый тип справочника имеет соответствующую таблицу (например, ci_device_type, ci_asset_type) которая разделяет тот же id как ci_base, создавая типобезопасное наследственное отношение.

Как бизнес-сущности подключаются к ci_base:

Все бизнес-сущности в repo схеме ссылаются на ci_base подтипы, чтобы определить свою классификацию и поведение:

  • organization → ссылается на ci_organization_type (который наследуется от ci_entity_typeci_base)

  • user → ссылается на ci_user_type (который наследуется от ci_entity_typeci_base)

  • device → ссылается на ci_device_type и ci_device_status (оба наследуются от ci_base)

  • asset → ссылается на ci_asset_type (который наследуется от ci_entity_typeci_base)

  • inventory → ссылается на ci_inventory_type (который наследуется от ci_entity_typeci_base)

  • asset_group → ссылается на ci_asset_group_type (который наследуется от ci_entity_typeci_base)

Категории типов справочников:

Категория
Таблицы
Назначение

Системная конфигурация

ci_module, ci_country, ci_role

Определяют модули системы, географические справочники и роли пользователей

Определения типов сущностей

ci_entity_type, ci_device_type, ci_asset_type, ci_inventory_type, ci_organization_type, ci_user_type, ci_asset_group_type

Классифицируют все бизнес-сущности по типу

Статус и классификация

ci_device_status, ci_asset_type_category

Отслеживают состояния сущностей и группируют типы в категории

Контроль доступа

ci_permission_scope

Определяет, какие разрешения могут быть предоставлены (связано с ci_module и ci_entity_type)

Связи

ci_device_relation_type

Определяет типы отношений между устройствами (master-slave, резервирование и т.д.)

Категоризация

ci_tag, ci_catalog_category

Обеспечивают гибкое тегирование и организацию каталога

Примеры шаблонов запросов
-- Получить все типы устройств для организации (системные + пользовательские)
SELECT cb.id, cb.code, cb.title_en, cb.is_system
FROM repo.ci_base cb
JOIN repo.ci_device_type dt ON dt.id = cb.id
WHERE cb.discriminator = 'device_type'
  AND (cb.is_system = true OR cb.organization_id = $org_id)
  AND cb.deleted_at IS NULL;

-- Получить тип актива с его категорией
SELECT 
  cb.code as asset_type_code,
  cb.title_en as asset_type_name,
  cat_cb.title_en as category_name
FROM repo.ci_base cb
JOIN repo.ci_asset_type at ON at.id = cb.id
LEFT JOIN repo.ci_asset_type_category cat ON cat.id = at.category_id
LEFT JOIN repo.ci_base cat_cb ON cat_cb.id = cat.id
WHERE cb.discriminator = 'asset_type'
  AND cb.deleted_at IS NULL;

-- Получить иерархическую структуру тегов
SELECT cb.id, cb.code, cb.title_en, cb.path, cb.parent_id
FROM repo.ci_base cb
JOIN repo.ci_tag t ON t.id = cb.id
WHERE cb.discriminator = 'tag'
  AND cb.deleted_at IS NULL
ORDER BY cb.path;

Ключевые таблицы по категориям

Таблицы в repo схема организована в функциональные категории. Описания ниже суммируют наиболее важные таблицы по их бизнес-назначению.

organization

Назначение: Иерархическое управление организациями

Атрибут
Детали

Ключевые поля

id, parent_id, path, organization_type_id, title_en, is_active, deleted_at

Индексация

GiST-индекс на path для иерархических запросов, индексы на parent_id и organization_type_id

Особые замечания

Использует ltree для многоуровневых иерархий, наследуется от customizable_entity для поддержки пользовательских полей

user

Назначение: Учетные записи пользователей и аутентификация

Атрибут
Детали

Ключевые поля

id, organization_id, user_type_id, identity_provider, identity_provider_id, full_name, is_active

Индексация

Уникальный индекс на (organization_id, identity_provider, identity_provider_id)

Особые замечания

Интеграция внешних поставщиков идентификации (Keycloak, Auth0, Okta), наследуется от customizable_entity

device

Назначение: Физические трекинговые устройства

Атрибут
Детали

Ключевые поля

id, organization_id, device_type_id, status_id, hw_id, label

Индексация

Индексы на organization_id, device_type_id, status_id, hw_id

Особые замечания

Аппаратный идентификатор для отслеживания устройства, наследуется от customizable_entity для пользовательских полей

asset

Назначение: Физические или виртуальные активы

Атрибут
Детали

Ключевые поля

id, organization_id, asset_type_id, label, description

Индексация

Индексы на organization_id и asset_type_id

Особые замечания

Наследуется от customizable_entity, связаны с устройствами через device_asset_link

inventory

Назначение: Инвентарные и складские записи

Атрибут
Детали

Ключевые поля

id, organization_id, inventory_type_id, code

Индексация

Уникальный индекс на (organization_id, code)

Особые замечания

Уникальные коды в рамках организации, связаны с устройствами через device_inventory_link

asset_group

Назначение: Группировка активов с историческим отслеживанием

Атрибут
Детали

Ключевые поля

id, organization_id, group_type_id, title_en, description

Связи

FROM repo.asset_group AS ag JOIN repo.asset_group_item AS agi ON agi.group_id = ag.id JOIN repo.asset AS a ON a.id = agi.asset_id WHERE agi.detached_at IS NULL

Особые замечания

Членство, основанное на времени, через asset_group_item, запросите текущих членов с помощью WHERE detached_at IS NULL

custom_field_def

Назначение: Определения и метаданные пользовательских полей

Атрибут
Детали

Ключевые поля

id, organization_id, owner_entity_type_id, code, field_type, is_multi, is_required

Содержание

Типы полей включают text, number, boolean, date, datetime, entity_ref, catalog_item_ref

Особые замечания

Обеспечивает гибкие пользовательские поля для любого типа сущности, значения хранятся в типоспецифичных custom_field_value_* таблицах

acl_role_permission

Назначение: Управление разрешениями на основе ролей

Атрибут
Детали

Ключевые поля

id, role_id, permission_scope_id, target_entity_id, actions

Содержание

Битовая маска действий (READ=1, UPDATE=2, DELETE=4, CREATE=8), разрешения могут быть специфичны для цели или для всего типа сущности

Связи

FROM repo.user_role AS ur JOIN repo.acl_role_permission AS rp ON rp.role_id = ur.role_id WHERE ur.user_id = $user_id

Особые замечания

Работает с user_role и acl_user_scope для определения окончательных прав пользователя

audit_event

Назначение: Единый журнал аудита для всех изменений в системе

Атрибут
Детали

Ключевые поля

id, event_category, user_id, aggregate_type, aggregate_id, event_type, event_data, occurred_at

Индексация

Индексы на (user_id, occurred_at), (aggregate_type, aggregate_id, occurred_at), (event_category, occurred_at)

Особые замечания

Разделение по occurred_at (ежемесячно), две категории: auth (аутентификация) и domain (бизнес-события), хранит дельты изменений на уровне полей в event_data JSONB

Связи данных

Схема repo схема реализует сложные шаблоны отношений для гибкого моделирования данных:

Иерархические структуры

  • Организации используют пути ltree для эффективных запросов по дереву

  • Справочные элементы (ci_base) поддерживают опциональные иерархии

  • Автоматическое поддержание путей через триггеры базы данных

Шаблоны наследования

  • Наследование таблиц: customizable_entity → бизнес-сущности (organization, user, device, asset, inventory, asset_group)

  • Наследование ID: ci_base → таблицы типов справочников

  • Различение типов через entity_type_id и дискриминатор поля

Полиморфные отношения

Некоторые таблицы используют полиморфные ссылки без ограничений внешних ключей для максимальной гибкости:

  • acl_role_permission.target_entity_id → любая customizable_entity

  • acl_user_scope.target_entity_id → любая customizable_entity

  • entity_tag.entity_id → любая customizable_entity

Эти отношения проверяются на уровне приложения.

Дополнительная информация

Валидация данных

Схема repo схема обеспечивает целостность данных с помощью нескольких механизмов:

Ограничения базы данных

  • ОГРАНИЧЕНИЯ UNIQUE с поддержкой мягкого удаления (частичные индексы WHERE deleted_at IS NULL)

  • ОГРАНИЧЕНИЯ CHECK (например, device_relation обеспечивает master_idslave_id)

  • ОГРАНИЧЕНИЯ NOT NULL для обязательных полей

  • ЗНАЧЕНИЯ DEFAULT для временных меток и булевых флагов

Проверки на уровне приложения

  • Проверка типа сущности для полиморфных ссылок

  • Проверка каталога для ссылок пользовательских полей

  • Проверка типа пользовательского поля

  • Управление массивами для полей с множественными значениями

Оптимизация запросов

Таблицы организованы со специфическими стратегиями индексации:

Стандартные индексы:

  • Все внешние ключи имеют выделенные индексы

  • Временные индексы по created_at, updated_at, deleted_at

  • Составные индексы для часто объединяемых столбцов

Специализированные индексы:

  • GiST-индексы на путях ltree для иерархических запросов

  • Частичные уникальные индексы, поддерживающие мягкое удаление

  • Индексы значений пользовательских полей для фильтрации и сортировки

  • Индексы событий аудита по времени + сущности для эффективных поисков

Соображения по производительности:

  • Рекомендуется пула соединений (PgBouncer)

  • Регулярное обслуживание VACUUM для больших таблиц

  • Возможное будущее разбиение для device таблица по organization_id

  • Материализованные представления для сложных вычислений контроля доступа

Последнее обновление

Это было полезно?