select
    'DRIVER_FLEET' as relation_type,
    'DRIVER' as from_entity_type,
    cast(d.id as varchar(128)) as from_source_entity_id,
    'FLEET' as to_entity_type,
    cast(d.fleet_id as varchar(128)) as to_source_entity_id,
    null::timestamptz as valid_from,
    null::timestamptz as valid_to,
    null::timestamptz as source_updated_at,
    'data.driver' as source_table,
    cast(d.id as varchar(128)) as source_row_id
from data.driver d
where d.fleet_id is not null

union all

select
    'DRIVER_CARD_DRIVER' as relation_type,
    'DRIVER_CARD' as from_entity_type,
    cast(d.id as varchar(128)) as from_source_entity_id,
    'DRIVER' as to_entity_type,
    cast(d.id as varchar(128)) as to_source_entity_id,
    null::timestamptz as valid_from,
    null::timestamptz as valid_to,
    null::timestamptz as source_updated_at,
    'data.driver' as source_table,
    cast(d.id as varchar(128)) as source_row_id
from data.driver d
where nullif(trim(d.drivers_card), '') is not null

union all

select
    'VEHICLE_FLEET' as relation_type,
    'VEHICLE' as from_entity_type,
    cast(v.id as varchar(128)) as from_source_entity_id,
    'FLEET' as to_entity_type,
    cast(v.fleet_id as varchar(128)) as to_source_entity_id,
    null::timestamptz as valid_from,
    null::timestamptz as valid_to,
    null::timestamptz as source_updated_at,
    'data.vehicle' as source_table,
    cast(v.id as varchar(128)) as source_row_id
from data.vehicle v
where v.fleet_id is not null
  and nullif(trim(v.vin), '') is not null

union all

select
    'VEHICLE_REGISTRATION_VEHICLE' as relation_type,
    'VEHICLE_REGISTRATION' as from_entity_type,
    cast(v.id as varchar(128)) as from_source_entity_id,
    'VEHICLE' as to_entity_type,
    cast(v.id as varchar(128)) as to_source_entity_id,
    null::timestamptz as valid_from,
    null::timestamptz as valid_to,
    null::timestamptz as source_updated_at,
    'data.vehicle' as source_table,
    cast(v.id as varchar(128)) as source_row_id
from data.vehicle v
where nullif(trim(v.vrn), '') is not null
  and nullif(trim(v.vin), '') is not null

union all

select
    'VEHICLE_TELEMATIC_PROVIDER' as relation_type,
    'VEHICLE' as from_entity_type,
    cast(v.id as varchar(128)) as from_source_entity_id,
    'TELEMATIC_PROVIDER' as to_entity_type,
    cast(v.telematic_provider_id as varchar(128)) as to_source_entity_id,
    null::timestamptz as valid_from,
    null::timestamptz as valid_to,
    null::timestamptz as source_updated_at,
    'data.vehicle' as source_table,
    cast(v.id as varchar(128)) as source_row_id
from data.vehicle v
where v.telematic_provider_id is not null
  and nullif(trim(v.vin), '') is not null;
