source_db: art_relations
dim_table: dim_label
export_sql: >-
  SELECT
    v.vendor_id AS labelId,
    IF(v.company IS NULL OR TRIM(v.company)='',
      TRIM(v.NAME),
      TRIM(v.company)) AS labelName,
    v.priority AS priority,
    v.country AS countryId,
    v.owner AS OWNER,
    v.is_distributor AS isDistributor,
    o.owner_id AS ownerId
  FROM
    vendor v
  LEFT JOIN
    owner o ON o.owner_abbrivation = v.owner
update_sql:
  - >-
    UPDATE
      {db}.{schema}.{dim_table}
    SET
      labelName = st.labelName,
      priority = st.priority,
      countryId = st.countryId,
      owner = st.owner,
      last_updated = '{current_timestamp}',
      isDistributor = st.isDistributor,
      ownerId = st.ownerId
    FROM
      {db}.{schema}.{staging_table} st
    WHERE
      {db}.{schema}.{dim_table}.labelId = st.labelId AND
      (
        NOT (
          nvl({db}.{schema}.{dim_table}.labelName = st.labelName, false) OR
          ({db}.{schema}.{dim_table}.labelName is null and st.labelName is null)
        ) OR
        NOT (
          nvl({db}.{schema}.{dim_table}.priority = st.priority, false) OR
          ({db}.{schema}.{dim_table}.priority is null and st.priority is null)
        ) OR
        NOT (
          nvl({dim_table}.countryId = st.countryId, false) OR
          ({dim_table}.countryId is null and st.countryId is null)
        ) OR
        NOT (
          nvl({db}.{schema}.{dim_table}.owner = st.owner, false) OR
          ({db}.{schema}.{dim_table}.owner is null and st.owner is null)
        ) OR
        NOT (
          nvl({db}.{schema}.{dim_table}.isDistributor = st.isDistributor, false) OR
          ({db}.{schema}.{dim_table}.isDistributor is null and st.isDistributor is null)
        ) OR
        NOT (
          nvl({db}.{schema}.{dim_table}.ownerId = st.ownerId, false) OR
          ({db}.{schema}.{dim_table}.ownerId is null and st.ownerId is null)
        )
      )
insert_sql:
  - >-
    INSERT INTO
      {db}.{schema}.{dim_table}
    (labelid, labelname, priority, countryid, owner, last_updated, date_created, isdistributor, ownerid)
    SELECT
      st.labelId,
      st.labelName,
      st.priority,
      st.countryId,
      st.owner,
      '{current_timestamp}',
      '{current_timestamp}',
      st.isDistributor,
      st.ownerId
    FROM
      {db}.{schema}.{staging_table} st
    LEFT JOIN
      {db}.{schema}.{dim_table} dl ON st.labelId = dl.labelId
    WHERE
      dl.labelId is null
