Build with Daana

Chapter 9: One customer, two systems

In chapter 1, the bookstore combined three source tables because they shared a customer_id. Now the bookstore wants to add each reader's preferred genre to the customer record. Its CRM identifies a customer by customer number and also records an email address when it knows one. The external supplier sends one profile per email address. The bookstore cannot ask the supplier to include its customer number.

You will use the number and email on a CRM row to link the two sources. By the end of the chapter, you can check which customer received each genre and choose a join key that also works for a reader who has no CRM record.

Start state: The main project bookstore has completed daana execute. The terminal is in bookstore, and DuckDB is closed. To start at this chapter, follow Start at any chapter.

Create the project

With one identifier in the main project, the customer key is the CRM's customer_id. With several identifiers, Daana generates a key. Changing the identifier mode on a customer that already holds data passes daana check, but daana deploy refuses the change. Make the change in a new project before its first deploy.

This exercise uses the six-entity model from chapter 5 and runs on the Free tier. The finished ch9 checkpoint applies the same change to the full model from chapter 6.

Run in terminal

daana init ../bookstore-profiles --example bookstore --checkpoint ch5
cd ../bookstore-profiles

Read the two customer sources

Use the DuckDB 1.5.3 CLI to open the new project's database for writing so you can load the delivery:

Run in terminal

duckdb bookstore.duckdb

Load the three reader profiles. The supplier uses email as its primary key. The time on each row is when this delivery arrived.

Run in DuckDB

CREATE TABLE stage.reader_profiles (
    email VARCHAR PRIMARY KEY,
    preferred_genre VARCHAR NOT NULL,
    delivered_at TIMESTAMP NOT NULL
);

INSERT INTO stage.reader_profiles VALUES
    ('alex.kim@email.com', 'Poetry', TIMESTAMP '2024-11-26 09:00:00'),
    ('maria.garcia@email.com', 'History', TIMESTAMP '2024-11-26 09:00:00'),
    ('sarah.davis@email.com', 'Mystery', TIMESTAMP '2024-11-26 09:00:00');

Quit DuckDB with .quit, then run duckdb -readonly bookstore.duckdb in the terminal. Compare the delivery with the CRM. The CRM keeps a row for each edit, so select its distinct number and email pairs before joining.

Run in DuckDB

WITH crm AS (
    SELECT DISTINCT customer_number, email FROM stage.customers
)
SELECT p.email, p.preferred_genre, c.customer_number
FROM stage.reader_profiles p
LEFT JOIN crm c ON c.email = p.email
ORDER BY p.email;

Expected output

emailpreferred_genrecustomer_number
alex.kim@email.comPoetryNULL
maria.garcia@email.comHistoryCUST-000010
sarah.davis@email.comMysteryCUST-000004

Maria's number and email appear together on her CRM row. Each value identifies the same customer. Her profile can therefore find that customer by email alone. Alex's email has no match in the CRM.

Before you continue

The CRM has ten customers. Predict how many customer keys you will find after loading these three profiles. Which customers will have both a CRM number and a preferred genre?

Add the profile mapping

Exercise

Try the edits in dab/model.yaml and dab/mappings/customer-mapping.yaml before opening a correct answer.

  • Add a string attribute named customer_preferred_genre after customer_registration_date.
  • Enable allow_multiple_identifiers in the customer's default_mapping_group. In the CRM table's primary_keys, put customer_number first and add email. Keep customer_id as a third identifier because the existing address, loyalty and order mappings refer to it.
  • Append the delivery as a fourth customer source table. Use the duckdb connection and the FULL strategy. Identify each profile by email, date it by delivered_at, and map its preferred genre to the new attribute.

Hint: Each source table's first identifier must have a value on every row. The CRM supplies a customer number and the profile supplier supplies an email. The column that lets the two tables meet can occupy a different position in each list.

Show a correct answer

A correct answer

Add the attribute to the customer in dab/model.yaml:

        - id: customer_preferred_genre
          name: customer_preferred_genre
          definition: Reading genre selected in the external reader profile
          type: STRING

In the customer mapping, enable the group setting and update the CRM identifier list:

mapping_groups:
  - name: default_mapping_group
    allow_multiple_identifiers: true
    tables:
      # Source 1: CRM data. Every edit appends a row with the full record; each
      # run reads only the rows loaded into stage (popln_tmstp) since the last batch.
      - connection: duckdb
        table: stage.customers
        primary_keys:
          - customer_number
          - email
          - customer_id

Keep the address and loyalty tables as they are. Append the profile table to the same list:

      # External reader profiles arrive with one row per email address.
      - connection: duckdb
        table: stage.reader_profiles
        primary_keys:
          - email
        ingestion_strategy: FULL
        entity_effective_timestamp_expression: delivered_at
        attributes:
          - id: customer_preferred_genre
            transformation_expression: preferred_genre

Run the project

Quit DuckDB with .quit, then run the four commands:

Run in terminal

daana check && daana install && daana deploy && daana execute

Expected output, summary line of daana execute

Pipelines: 55 ran

The chapter 5 project had 50 pipelines. Daana added one identifier pipeline for each of the four customer source tables and one pipeline for the preferred genre.

Find the customer behind each profile

Open the warehouse again:

Run in terminal

duckdb -readonly bookstore.duckdb

The table daana_dw.customer_idfr records each identifier value with its generated customer key. Count the values and the distinct keys to check your prediction:

Run in DuckDB

SELECT count(*) AS identifier_values, count(DISTINCT customer_key) AS customers
FROM daana_dw.customer_idfr;

Expected output

identifier_valuescustomers
3111

The CRM supplied three identifiers for each of its ten customers. Two profile emails were already among those values. Alex's email added one identifier and one customer.

Look up each profile's email in customer_idfr. Then look up the CRM customer number independently and compare the two keys:

Run in DuckDB

WITH crm AS (
    SELECT DISTINCT customer_number, email FROM stage.customers
)
SELECT p.email, crm.customer_number,
       by_email.customer_key = by_number.customer_key AS same_key,
       c.customer_name, c.customer_preferred_genre
FROM stage.reader_profiles p
JOIN daana_dw.customer_idfr by_email ON by_email.customer_idfr = p.email
LEFT JOIN crm ON crm.email = p.email
LEFT JOIN daana_dw.customer_idfr by_number
       ON by_number.customer_idfr = crm.customer_number
JOIN daana_dw.view_customer c ON c.customer_key = by_email.customer_key
ORDER BY p.email;

Expected output

emailcustomer_numbersame_keycustomer_namecustomer_preferred_genre
alex.kim@email.comNULLNULLNULLPoetry
maria.garcia@email.comCUST-000010trueMaria GarciaHistory
sarah.davis@email.comCUST-000004trueSarah DavisMystery

Maria's number and email both find the customer who received History. Sarah's find the customer who received Mystery. Alex also has a customer key and a genre, but the CRM has supplied neither a number nor a name for this reader.

Daana takes the pairing from the structure of the source row. It cannot correct a number paired with the wrong person's email, or follow an email address that moves from one person to another. The source owner must resolve those cases before loading the data.

There is also a limit within one load. In a separate DuckDB run, two CRM customers had different numbers and the same previously unknown email. The identifier pipeline generated a key for each distinct combination and tried to write the email under both keys. DuckDB rejected the insert, so no identifier from that load reached customer_idfr, and daana execute stopped with exit status 1. Repeated CRM history rows with identical identifier values are read only once by the identifier pipeline.

Keys in multiple-identifier mode

The generated key is text. Chapter 1's numeric sort on customer_key no longer applies. List two CRM customers and the profile-only reader with the length of their keys:

Run in DuckDB

SELECT customer_id, customer_name, length(customer_key) AS key_length
FROM daana_dw.view_customer
WHERE customer_id IN ('1', '2') OR customer_id IS NULL
ORDER BY customer_id NULLS LAST;

Expected output

customer_idcustomer_namekey_length
1John Smith36
2Emily Johnson36
NULLNULL36

Daana generated all three keys, and none is the CRM's customer_id.

Exercise

Every customer has a history row. Join daana_dw.view_customer to daana_dw.view_customer_hist and count distinct customers. Before running the query, write down both counts, once joined on customer_id and once on customer_key, and name any customer that a join loses. Run the query before opening a correct answer.

Hint: Alex has NULL in customer_id. Decide whether a NULL matches another NULL in a join.

Show a correct answer

A correct answer

Count the customers that each join returns:

Run in DuckDB

SELECT 'customer_key' AS joined_on, count(DISTINCT c.customer_key) AS customers
FROM daana_dw.view_customer c
JOIN daana_dw.view_customer_hist h ON h.customer_key = c.customer_key
UNION ALL
SELECT 'customer_id', count(DISTINCT c.customer_key)
FROM daana_dw.view_customer c
JOIN daana_dw.view_customer_hist h ON h.customer_id = c.customer_id
ORDER BY customers DESC;

Expected output

joined_oncustomers
customer_key11
customer_id10

The join on customer_key returns all 11 customers. The join on customer_id returns 10 because Alex's NULL matches no row. In the main project, every customer has a customer_id, so both joins return the same 10 customers there.

Join entities and relationships on customer_key without a cast.

Check that existing orders still resolve to customers:

Run in DuckDB

SELECT count(*) AS orders, count(customer_key) AS with_customer
FROM daana_dw.view_order_with_rel;

Expected output

orderswith_customer
1616

All 16 orders have a customer. Their mapping still uses customer_id, which is one of the CRM's identifiers.

Quit DuckDB, then return to the main project:

Run in terminal

cd ../bookstore

What Daana did

Daana recorded the CRM number, email and internal ID under one key for each CRM customer. It used that key to load Maria's and Sarah's profile attributes and kept Alex's email-only profile available to joins on customer_key.

What you can do now

You can connect a delivery that uses its own identifier when a source row supplies the link to a known customer. Establish which values identify the same customer before declaring them as identifiers. If the entity already uses several identifiers, ordinary loads can add new identifier values. If you change allow_multiple_identifiers on an entity that already holds rows, follow the rebuild procedure in Adding identifiers later.

Chapter 10: Going to production starts from the main project bookstore. It deploys to a second target in the same DuckDB file.

The terminal is in bookstore, and DuckDB is closed.