Build with Daana
Chapter 6: Time travel
In chapter 5, you completed and tested the order-line mapping in a side project. Questions about past events need the related values from that time, because a join on current values can put today's address on an earlier order.
You will join an order to its customer, then read the full model's payments, shipment, and support ticket at four instants. Afterward, you will be able to join entities and relationships at one instant and say where the history of a value starts.
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.
Two tools for the past
A team answering historical questions from current tables could schedule daily copies and keep a table for each snapshot. Queries would then join the snapshots for the date in question. Those copies answer only for the days the job ran, at the job's granularity.
Daana's history already holds changes to attributes and relationships, so these questions need no additional snapshot tables.
Chapter 1 introduced history views view_<entity>_hist, and chapter 2 introduced point-in-time functions f_<entity>(ts).
The relationship function f_<source>_<target>_x(ts) returns the relationship pairs effective at ts. Both kinds of function accept a timestamp column as the argument, so one query can read several instants.
Part 1: Query the main project
Every reader can do this part on the main project. Open its database:
Run in terminal
duckdb -readonly bookstore.duckdb
Order 12 and its customer
The joined view has the order's purchase time and the customer's values in one row. Read order 12 with its customer's current address:
Run in DuckDB
SELECT order_id, order_purchase_ts, customer_name, customer_city, customer_state
FROM daana_dw.view_order_with_rel
WHERE order_id = '12';
Expected output
| order_id | order_purchase_ts | customer_name | customer_city | customer_state |
|---|---|---|---|---|
| 12 | 2024-11-20 11:00:00 | Emily Johnson | Philadelphia | PA |
The order was placed on 20 November, but Philadelphia is Emily's current city. The view has the customer's current values, not the values at order_purchase_ts.
Exercise
Find Emily's city and state when she placed order 12. Join the order, its customer relationship, and the customer through their point-in-time functions at 2024-11-20 11:00:00. Write the join before opening a correct answer.
Hint: Join f_order to f_order_customer_x on order_key, then to f_customer on customer_key. Pass the same timestamp to every function and filter on order_id.
Show a correct answer
A correct answer
Read the order and its customer at the order's time:
Run in DuckDB
SELECT o.order_id, o.order_purchase_ts, c.customer_name, c.customer_city, c.customer_state
FROM daana_dw.f_order(TIMESTAMP '2024-11-20 11:00:00') o
JOIN daana_dw.f_order_customer_x(TIMESTAMP '2024-11-20 11:00:00') oc ON oc.order_key = o.order_key
JOIN daana_dw.f_customer(TIMESTAMP '2024-11-20 11:00:00') c ON c.customer_key = oc.customer_key
WHERE o.order_id = '12';
Expected output
| order_id | order_purchase_ts | customer_name | customer_city | customer_state |
|---|---|---|---|---|
| 12 | 2024-11-20 11:00:00 | Emily Johnson | Boston | MA |
Emily lived in Boston, MA, when she placed the order.
If one of the three timestamps differs, the query still runs, but it reads the order and the customer at different instants. Inspect the history rows of Emily, customer 2:
Run in DuckDB
SELECT eff_tmstp, customer_name, customer_city, customer_status, customer_loyalty_tier
FROM daana_dw.view_customer_hist
WHERE customer_key = '2'
ORDER BY eff_tmstp;
Expected output
| eff_tmstp | customer_name | customer_city | customer_status | customer_loyalty_tier |
|---|---|---|---|---|
| 2023-02-14 11:05:40 | Emily Johnson | NULL | Active | NULL |
| 2024-11-01 00:00:00 | Emily Johnson | NULL | Active | Silver |
| 2024-11-05 00:00:00 | Emily Johnson | Boston | Active | Silver |
| 2024-11-29 00:00:00 | Emily Johnson | Philadelphia | Active | Silver |
The Boston row began on 5 November and ended when the Philadelphia row began on 29 November, so it covers the order's time. The earlier NULL city values mean there was no address yet in the loaded history. They do not give an earlier city.
What Daana did
- Daana generated the entity and relationship functions used in the join.
- Daana selected Emily's historical address, so the same order has Boston in the result at the order's time and Philadelphia in the current view.
- Daana skipped repeated addresses: Emily's 25 nightly address snapshots (chapter 1) became two city values in the warehouse history shown above.
John Smith's orders
Exercise
John Smith's account is inactive now. Was it active when he placed order 11 on 15 November? Did his history have an address when he placed order 1 on 1 November? Write the queries before opening a correct answer.
Hint: Find each order's purchase timestamp and customer key in view_order_with_rel. Use the generated point-in-time function f_customer with the full timestamp, then inspect the history to explain the answers.
Show a correct answer
A correct answer
Find John's orders with their purchase timestamps and the customer's current values:
Run in DuckDB
SELECT order_id, order_purchase_ts, customer_key, customer_name,
customer_status AS status_now, customer_city AS city_now
FROM daana_dw.view_order_with_rel
WHERE customer_name = 'John Smith'
ORDER BY order_purchase_ts;
Expected output
| order_id | order_purchase_ts | customer_key | customer_name | status_now | city_now |
|---|---|---|---|---|---|
| 1 | 2024-11-01 10:30:00 | 1 | John Smith | Inactive | New York |
| 11 | 2024-11-15 13:30:00 | 1 | John Smith | Inactive | New York |
The customer columns show Inactive and New York on both orders because they hold current values. Pass the full timestamp, because a date alone means midnight. Use order 11's timestamp to read John's status and address when he placed it:
Run in DuckDB
SELECT customer_name, customer_status, customer_city, customer_state
FROM daana_dw.f_customer(TIMESTAMP '2024-11-15 13:30:00')
WHERE customer_key = '1';
Expected output
| customer_name | customer_status | customer_city | customer_state |
|---|---|---|---|
| John Smith | Active | New York | NY |
John's account was active when he placed order 11. Using the current status would incorrectly give Inactive. Read John's values at order 1's purchase timestamp:
Run in DuckDB
SELECT customer_name, customer_status, customer_city, customer_state
FROM daana_dw.f_customer(TIMESTAMP '2024-11-01 10:30:00')
WHERE customer_key = '1';
Expected output
| customer_name | customer_status | customer_city | customer_state |
|---|---|---|---|
| John Smith | Active | NULL | NULL |
The warehouse's history has no address for John at that instant. NULL means that no address value was available, not that the query failed. Optionally, pass each order's timestamp through a lateral subquery to compare both historical answers with his current status:
Run in DuckDB
SELECT o.order_id, o.order_purchase_ts, c.customer_name,
c.customer_status AS status_at_order_time,
c.customer_city AS city_at_order_time,
o.customer_status AS status_now
FROM daana_dw.view_order_with_rel o,
LATERAL (SELECT * FROM daana_dw.f_customer(o.order_purchase_ts) fc
WHERE fc.customer_key = o.customer_key) c
WHERE o.order_id IN ('1', '11')
ORDER BY o.order_purchase_ts;
Expected output
| order_id | order_purchase_ts | customer_name | status_at_order_time | city_at_order_time | status_now |
|---|---|---|---|---|---|
| 1 | 2024-11-01 10:30:00 | John Smith | Active | NULL | Inactive |
| 11 | 2024-11-15 13:30:00 | John Smith | Active | New York | Inactive |
The combined result agrees with both individual queries. John's account was active at both order times, but his address was available only at the later instant. Inspect John's history to find when his address first appeared and when his status changed:
Run in DuckDB
SELECT eff_tmstp, customer_status, customer_city, customer_state, customer_loyalty_tier
FROM daana_dw.view_customer_hist
WHERE customer_key = '1'
ORDER BY eff_tmstp;
Expected output
| eff_tmstp | customer_status | customer_city | customer_state | customer_loyalty_tier |
|---|---|---|---|---|
| 2023-01-10 14:22:05 | Active | NULL | NULL | NULL |
| 2024-10-01 00:00:00 | Active | NULL | NULL | Gold |
| 2024-11-10 00:00:00 | Active | New York | NY | Gold |
| 2024-11-25 14:30:22 | Inactive | New York | NY | Gold |
John's address first appears on 10 November. His status changed on 25 November.
Address history starts when the source system starts sending snapshots. Daana cannot reconstruct an earlier address from a later snapshot.
The queries of this exercise take the customer key from the current relationship in view_order_with_rel. This is safe here because an order keeps its customer. Where a relationship can change, take the key from its point-in-time function at the same instant, as the join for order 12 does.
Optional: Changes to author credits
The book-author relationship also has history. Test a change in a side project, because later chapters use the main project's data. Quit DuckDB, then copy the main project into a side project and enter it:
Run in terminal
cp -R ../bookstore ../bookstore-credits
cd ../bookstore-credits
Load the data file author-credits, which holds a later change to The Talisman's author credits:
Run in terminal
daana init . --example bookstore --load-data author-credits
Expected output
Loaded data/author-credits.sql into bookstore.duckdb
The data file is now in the source tables. Execute the pipelines to load the warehouse:
Run in terminal
daana execute
Expected output, summary line of daana execute
Pipelines: 39 ran, 11 skipped: nothing new above the watermark to read (batch_history row_st S)
11 pipelines were skipped because their source tables have no new rows above the watermark. The summary does not show which author pairs changed, so query the loaded relationship next. From bookstore-credits, reopen DuckDB.
Exercise
Find The Talisman's authors before and after the change, using 1 December and 4 December 2024 at midnight. Show author identifiers as well as names, and decide whether the author set changed. Try the comparison before opening a correct answer.
Hint: The Talisman's book_key is '17'. Query f_book_author_x at each instant and join on author_key to read author_name and author_id.
Show a correct answer
A correct answer
Compare the author sets:
Run in DuckDB
SELECT 'at 2024-12-01 00:00' AS as_of,
string_agg(a.author_name || ' (' || a.author_id || ')', ', ' ORDER BY CAST(a.author_id AS INT)) AS authors
FROM daana_dw.f_book_author_x(TIMESTAMP '2024-12-01 00:00:00') x
JOIN daana_dw.view_author a ON a.author_key = x.author_key
WHERE x.book_key = '17'
UNION ALL
SELECT 'at 2024-12-04 00:00',
string_agg(a.author_name || ' (' || a.author_id || ')', ', ' ORDER BY CAST(a.author_id AS INT))
FROM daana_dw.f_book_author_x(TIMESTAMP '2024-12-04 00:00:00') x
JOIN daana_dw.view_author a ON a.author_key = x.author_key
WHERE x.book_key = '17'
ORDER BY as_of;
Expected output
| as_of | authors |
|---|---|
| at 2024-12-01 00:00 | Stephen King (8), Peter Straub (12) |
| at 2024-12-04 00:00 | Stephen King (8), Peter Straub (13) |
The author set changed: the book's second author is author 12 at the first instant and author 13 at the second. Both records have the name Peter Straub, so the names do not show the change.
The data file added author 13, a second Peter Straub record, and the book's whole author set again, dated 3 December at 10:00. The query reads the pairs at each instant and takes the names from view_author, which has the current values.
Quit DuckDB, then return to the main project:
Run in terminal
cd ../bookstore
The full model needs a license
Part 1 joined an order to its customer at one instant and showed where a customer's history starts. Part 2 answers the question about order 3 that the index asks. The main project cannot answer it because its six entities do not include payments, shipments or support tickets.
The full model is a DAB (Data according to Business) of 43 entities over 49 of the 54 source tables.
To continue without either the trial or a license, skip the part 2 commands and read the recorded results.
On this route, create no project and stay in bookstore, where chapter 7 also runs. Under One order at four instants, run the first query in bookstore and read the result of the second as recorded.
The full model has 335 executable DAB pipelines. The free allowance is 90, enough for chapters 1 to 5 (chapter 5 has 50). Deploying the full model needs a license. Without one, daana deploy stops with DAB deployment requires 335 executable pipelines; allowed 90; over by 245 before it writes anything, and daana check still passes.
The message suggests reducing pipelines (the Free tier route above stays within the allowance) or using your account's license, which can be a Developer trial. Run daana license activate, open the address it shows on any device, confirm the code, and then run daana deploy again in the same project. With a private edition, run daana license activate <license-file> instead. When the trial ends, deploying above the free limit needs a license; tell us what you need through the production enquiry. See daana license. The licensing guide shows activation and the license status before, during, and after the trial.
Part 2: Query the full model
The supplied model and mappings add entities and relationships. The queries use the same functions as part 1.
Quit DuckDB if it is open, then create the full-model project beside the main project and enter it:
Run in terminal
daana init ../bookstore-ch6 --example bookstore --checkpoint ch6
cd ../bookstore-ch6
Before building, inspect two relationships in dab/model.yaml, or use the excerpt below on the Free tier. A support ticket concerns an order, and a payment pays an order. Their entries have the same keys as is_written_by in chapter 1. The query below reads each through a function named after its two entities, f_support_ticket_order_x and f_payment_order_x, not after the relationship:
- name: concerns
definition: Ticket concerns an order
description: "Cardinality: many-to-one. Ticket concerns an order."
source_entity_id: support_ticket
target_entity_id: order
# ...
- name: pays
definition: Payment pays an order
description: "Cardinality: many-to-one. Payment pays an order."
source_entity_id: payment
target_entity_id: order
Run the four commands:
Run in terminal
daana check && daana install && daana deploy && daana execute
If daana deploy stops because the model is over the free allowance, run daana license activate for the Developer trial, as described above, then run daana deploy again and daana execute.
After a successful deployment and execution, the queries below can read the full model. From bookstore-ch6, reopen DuckDB.
One order at four instants
At noon on 13 November 2024, had order 3 been paid, where was its shipment, and was its customer suspended?
Order 3's customer, payments, and shipment changed at different times. Reading all of them at one instant gives the order's state at that instant.
Before you continue
Michael Brown placed order 3 at 09:20 on 3 November. From chapter 5, recall whether order 3 had lines at 09:22 on 3 November. From chapters 1 and 2, recall whether Michael Brown's account was active or suspended at noon on 13 November.
Predict whether a payment for an order means that its shipment has arrived. Write down both recalled answers and the prediction before reading the result.
The main project holds the order's customer, the customer's tier, and the order's lines. In the query, m.as_of gives every function the same timestamp.
Without a license, reopen DuckDB in bookstore if it is closed. With the full model, the complete query below returns the same values in these columns. Read the three values at the four instants:
Run in DuckDB
WITH moments(as_of) AS (
VALUES (TIMESTAMP '2024-11-03 09:22:00'), (TIMESTAMP '2024-11-05 12:00:00'),
(TIMESTAMP '2024-11-13 12:00:00'), (TIMESTAMP '2024-11-28 12:00:00')
)
SELECT m.as_of,
(SELECT c.customer_name || ' (' || c.customer_status || ')'
FROM daana_dw.f_order_customer_x(m.as_of) oc
JOIN daana_dw.f_customer(m.as_of) c ON c.customer_key = oc.customer_key
WHERE oc.order_key = '3') AS customer,
(SELECT c.customer_loyalty_tier
FROM daana_dw.f_order_customer_x(m.as_of) oc
JOIN daana_dw.f_customer(m.as_of) c ON c.customer_key = oc.customer_key
WHERE oc.order_key = '3') AS tier,
(SELECT count(*) FROM daana_dw.f_order_line_order_x(m.as_of) x WHERE x.order_key = '3') AS lines
FROM moments m
ORDER BY m.as_of;
Expected output
| as_of | customer | tier | lines |
|---|---|---|---|
| 2024-11-03 09:22:00 | Michael Brown (Active) | Bronze | 0 |
| 2024-11-05 12:00:00 | Michael Brown (Active) | Bronze | 3 |
| 2024-11-13 12:00:00 | Michael Brown (Active) | Bronze | 3 |
| 2024-11-28 12:00:00 | Michael Brown (Suspended) | Bronze | 3 |
Order 3 has no lines at 09:22. Its three lines arrived in the source table at 09:40. The mapping dates a line by its load time, not by the order's purchase time.
Michael's account was Active at noon on 13 November. The suspension shown in the fourth row began on 27 November, after the instant in the question.
The other five columns need the full model. Each set of related rows has its own subquery, so several payments or tickets for one order do not multiply the other counts. With the full model, run the complete query. Without a license, read its result:
Run in DuckDB
WITH moments(as_of) AS (
VALUES (TIMESTAMP '2024-11-03 09:22:00'), (TIMESTAMP '2024-11-05 12:00:00'),
(TIMESTAMP '2024-11-13 12:00:00'), (TIMESTAMP '2024-11-28 12:00:00')
)
SELECT m.as_of,
(SELECT c.customer_name || ' (' || c.customer_status || ')'
FROM daana_dw.f_order_customer_x(m.as_of) oc
JOIN daana_dw.f_customer(m.as_of) c ON c.customer_key = oc.customer_key
WHERE oc.order_key = '3') AS customer,
(SELECT c.customer_loyalty_tier
FROM daana_dw.f_order_customer_x(m.as_of) oc
JOIN daana_dw.f_customer(m.as_of) c ON c.customer_key = oc.customer_key
WHERE oc.order_key = '3') AS tier,
(SELECT count(*) FROM daana_dw.f_order_line_order_x(m.as_of) x WHERE x.order_key = '3') AS lines,
(SELECT sum(p.payment_amount_amount)
FROM daana_dw.f_payment_order_x(m.as_of) x
JOIN daana_dw.f_payment(m.as_of) p ON p.payment_key = x.payment_key
WHERE x.order_key = '3') AS paid,
(SELECT coalesce(string_agg(s.shipment_status || ' @ ' || s.shipment_location, '; '), 'no shipment yet')
FROM daana_dw.f_shipment_order_x(m.as_of) x
JOIN daana_dw.f_shipment(m.as_of) s ON s.shipment_key = x.shipment_key
WHERE x.order_key = '3') AS shipment,
(SELECT count(*) FROM daana_dw.f_support_ticket_order_x(m.as_of) x WHERE x.order_key = '3') AS tickets,
(SELECT count(*) FROM daana_dw.f_product_return_order_x(m.as_of) x WHERE x.order_key = '3') AS returns,
(SELECT count(*) FROM daana_dw.f_review_order_x(m.as_of) x WHERE x.order_key = '3') AS reviews
FROM moments m
ORDER BY m.as_of;
Expected output
| as_of | customer | tier | lines | paid | shipment | tickets | returns | reviews |
|---|---|---|---|---|---|---|---|---|
| 2024-11-03 09:22:00 | Michael Brown (Active) | Bronze | 0 | NULL | no shipment yet | 0 | 0 | 0 |
| 2024-11-05 12:00:00 | Michael Brown (Active) | Bronze | 3 | 71.39 | In Transit @ Philadelphia, PA | 0 | 0 | 0 |
| 2024-11-13 12:00:00 | Michael Brown (Active) | Bronze | 3 | 71.39 | In Transit @ Philadelphia, PA | 1 | 1 | 0 |
| 2024-11-28 12:00:00 | Michael Brown (Suspended) | Bronze | 3 | 71.39 | In Transit @ Philadelphia, PA | 1 | 1 | 1 |
At noon on 13 November, order 3 was paid 71.39, its shipment was In Transit in Philadelphia, and Michael's account was Active. Reading the entities and relationships at the same instant gives this answer. The single payment for order 3 in stage.payments is also 71.39, the sum of the order's three lines, so the order was paid in full. In the first row, NULL in paid means there was no payment to sum.
The latest carrier scan at each later instant is In Transit in Philadelphia, so the payment does not establish that the shipment had arrived.
The tickets column counts the ticket from 6 November 2024 at 18:00:25, its updated_at, and the ticket's source row already has the status Resolved. Because the source has no column for the time a ticket was opened, the warehouse cannot say when this ticket was opened.
The functions return the effective values at an instant, using all data loaded so far. For each attribute, they select the value with the latest effective timestamp at or before the instant.
The functions ignore when Daana stored a row. They therefore do not reconstruct the rows that the warehouse held at that instant. A row that arrives late can change the answer for an earlier instant.
Optional agent request
The supplied queries need neither an agent nor a plugin to run. With the full model loaded in bookstore-ch6, you could ask your agent:
Using the loaded bookstore project, show how order 3 developed over time.
Return one row at each of these UTC instants:
- 2024-11-03 09:22:00
- 2024-11-05 12:00:00
- 2024-11-13 12:00:00
- 2024-11-28 12:00:00
For each instant, show the customer's name, account status and loyalty
tier; the number of order lines; the amount paid; shipment status and
location; and the numbers of support tickets, returns and reviews.
Use the entity and relationship state effective at each instant, based
on the data loaded so far. Do not attach today's customer or shipment
values to every historical row.
Inspect the project's model and mappings, then the available generated
database interfaces. You may run read-only queries with DuckDB 1.5.x.
Do not edit files or run install, deploy, execute or dar apply.
Show the SQL and its output. Explain how the query keeps the related
entities at the same instant and avoids multiplying amounts or counts
when an order has several related records. Distinguish missing payments
from a payment amount of zero. State anything you could not verify.
Compare the result with the four rows above, row by row. Check that every entity and relationship uses the same instant, with a separate subquery for each set of related rows. Run any untested query before comparing its result.
What you can do now
You can join an order to its customer, through their relationship, at one instant. Daana kept the history and generated the functions used here. Read every entity and every relationship at the same instant when the question asks for their historical values.
The functions return the effective values at an instant. They do not reconstruct the rows that the warehouse held at that instant. Address history starts with the source's snapshots.
These queries are written by hand for each question. Chapter 7 uses DAR (Data according to Requirements) to declare a reusable reporting output in bookstore.
Quit DuckDB if it is open. A reader on the Free tier is already in bookstore. From bookstore-ch6, return to the main project:
Run in terminal
cd ../bookstore