Guides

Apply DAR on a deployed DAB

This guide is for readers who have completed chapter 7 or already use DAR on a deployed DAB. It shows how to apply DAR documents, check what a failed apply leaves behind, restore the previous outputs, and preview SQL without a database. The examples start with a bookstore project created with --checkpoint ch5, after daana install, daana deploy and daana execute, on the Free tier.

daana dar apply creates the reporting views and tables that DAR documents declare, directly in the target database of a deployed Daana DAB. It runs the documents' output checks and records the result as the active DAR revision in the DAB's a0 ledger. The failure example below shows when the published outputs and the revision in the ledger differ.

For BigQuery projects that run DAR through Dataform, see Generate DAR for Dataform. daana dar apply and daana dar generate read the same DAR documents.

Prerequisites

This guide's DAR document declares outputs on the order_line entity, which the default bookstore project does not have, so the examples use the ch5 checkpoint. Before daana dar apply:

  • The project has daana.yaml, dab/model.yaml, dab/mappings/, dab/workflow.yaml and dar/.
  • daana install, daana deploy and daana execute have run against the DuckDB profile, so daana_dw.view_order_line holds the 31 bookstore order lines. daana install creates the a0 ledger in daana_metadata; DAR reads the DAB's entities, attributes and keys from that ledger. A Daana installation without an a0 ledger cannot be used.
  • The daana build has DuckDB support.

To create this start state, run daana init bookstore --example bookstore --checkpoint ch5 in a directory where bookstore does not exist, then change to the new project directory. The --example bookstore flag selects the example, and --checkpoint ch5 selects its chapter 5 model and mappings.

The dar_schema setting chooses the schema where DAR writes its outputs. The generated connections.yaml has no such line, and Daana then uses daana_dar. The profile below states that default; the examples run with or without the line:

connections:
  duckdb:
    type: duckdb
    database: bookstore.duckdb
    target_schema: daana_dw
    stage_schema: daana_stage
    metadata_schema: daana_metadata
    dar_schema: daana_dar

A different dar_schema, such as reporting, works only when it is set before daana install, which creates the schema. Changing it after installation makes the apply fail because the new schema does not exist, and daana install refuses to install again. Keep daana_dar for the examples below.

For the new project, run daana check, daana install, daana deploy and daana execute in that order. These commands validate the project, create the framework schemas, deploy the model, and load the data. If DuckDB is open, quit it with .quit before running commands that write to the file, because an open session locks it.

The declaration

dar/order_line.yaml declares an order-line dimension, a line fact and daily revenue by date and currency; chapter 7 explains these parts. Its axis dates each line by order_line_purchase_ts, the order's date, using chapter 8's correction. No checkpoint ships this exact file, so create dar/order_line.yaml with this declaration:

spec: dar/v1.0
anchor:
  entity: order_line
source:
  dab: order_line

outputs:
  dim:                                # dim__order_line (+ __latest)
    kind: dimension
    description: The order line, with its fulfillment status and amounts over time
    latest: view
    attributes: all

  line_fact:                          # fct__order_line
    kind: fact.state
    description: >
      One row per order line, at the time its order was placed.
    axis:
      expr: order_line_purchase_ts    # the order's order_date; eff_tmstp is when the line landed
      description: When the order the line is on was placed (event time, not load time)
    measures:
      - name: order_line_amount_amount
        additivity: additive
        description: Amount charged for the line, tax included
    columns: [order_line_amount_currency]

  daily_revenue:                      # fct__order_line_daily_revenue
    kind: fact.consolidated
    description: >
      Daily revenue: order lines' amounts summed by the day the order was
      placed. One row per day and currency.
    grain: [order_date, order_line_amount_currency]
    spine: {driving: lines}
    legs:
      lines:
        fact: order_line.line_fact
        date: "CAST(fact_ts AS DATE)"
        order_line_amount_currency: order_line_amount_currency
        aggregates:
          daily_revenue_amount:
            expr: order_line_amount_amount
            agg: sum
            description: >
              The amounts charged on the order lines of orders placed that
              day, tax included, in the lines' currency.

The DAR document reference explains keys from the bookstore documents, with examples and field tables.

Check, then apply

Check the documents before applying them. daana dar check runs offline and compares each document with the local model, refusing an unknown source.dab entity, a relationship the model does not have, a dimension's attributes list with a name the entity does not have, a name in measures or columns that is not a column of the view the output reads, or a wide pick that the joined dimension does not publish. It does not test an axis expression or an aggregate's expression. daana dar apply refuses a document that fails the check.

dar/ holds DAR documents only: the model stays in dab/model.yaml, and no copy of it belongs in dar/. The dar/ argument selects the documents, and --connection duckdb selects the profile in connections.yaml. From the project directory with DuckDB closed, check the documents and create their outputs:

Run in terminal

daana dar check dar/
daana dar apply dar/ --connection duckdb

daana dar check prints the spec dar/v1.0, the anchor entity:order_line, one document, three outputs and ✓ Validation passed. This result does not test the amounts in the data. dar apply reads the a0 ledger through the connection profile, compiles the documents against it, and writes the outputs:

Expected output of daana dar apply

Applied 4 objects (4 views) after 0 checks to daana_dar

The three declared outputs produce four views because the dimension also has a latest view. The result reports no output checks, because the declaration has none yet. Chapter 7's daily revenue query shows the amounts for this data.

Applying the same documents again prints the same line and adds nothing to the ledger. Here, a change to dar/order_line.yaml such as adding a measure gives only order_line a new revision, because its outputs read no other document's relationship. A document that reads a key through another anchor with via reads it as that anchor's document declares it, so apply refuses a change to that declaration unless the reading document is applied with it; see via in Generate DAR.

Output checks

An output check tests values in one output after Daana has created the outputs. Its SQL expression must return TRUE to pass; NULL, a missing value, fails. Keep the existing daily_revenue declaration and add these checks, which count daily rows with missing amounts or amounts above 80 USD:

  daily_revenue:
    kind: fact.consolidated
    # ... as above ...
    checks:
      every_day_has_revenue:
        # No bad rows: COALESCE so an empty output passes.
        expr: COALESCE(SUM(IF(daily_revenue_amount IS NULL, 1, 0)), 0) = 0
        over: output
        severity: error
        description: Every day in the output carries a revenue amount.
      no_day_above_80_usd:
        expr: COALESCE(SUM(IF(daily_revenue_amount > 80, 1, 0)), 0) = 0
        over: output
        severity: warn
        description: Flags a day whose revenue exceeds 80 USD for review.

every_day_has_revenue tests whether every row in the daily output has an amount. no_day_above_80_usd flags a daily amount above 80; every line in this example uses USD.

An aggregate over an empty output is NULL, and NULL fails, so both expressions use COALESCE to let an empty output pass. Neither check therefore tests that the output has rows. Write each check for the empty case you intend. The command reference gives patterns for checks that require data to exist and for ratios.

Output checks run on DuckDB. For any other target, daana dar apply refuses a document with an output check when it compiles the documents, for example over: output checks for nativesql dialect "postgres" are not implemented.

These checks do not find a line without an amount. Later in this guide, one line of 2024-11-06 loses its amount. SUM skips it, so the day falls from 82.59 to 60.85 and the total from 762.88 to 741.14. The day still has an amount and is below 80, so both checks pass without a warning.

Chapter 7 explains the missing discount and shows the check on the line fact that finds it.

On the unchanged data, 2024-11-06 has 82.59 USD, so no_day_above_80_usd warns. Run daana dar apply dar/ --connection duckdb with the checks above. The terminal prints the warning and the applied line shown here:

Expected output

Warning: DAR data-quality check "no_day_above_80_usd" warned for entity:order_line output "fct__order_line_daily_revenue"
Applied 4 objects (4 views) after 2 checks to daana_dar

The apply exits with status 0 and records the revision despite the warning. Save this version of dar/order_line.yaml, for example in version control, for the recovery step below.

Change only no_day_above_80_usd to severity: error, then run daana dar apply dar/ --connection duckdb again. Read the error:

Expected output

Error: dar apply: data-quality check "no_day_above_80_usd" failed for entity:order_line output "fct__order_line_daily_revenue": the new outputs are already published in daana_dar; the ledger was not updated and keeps the previously active DAR revision, if any — fix the data or the check and apply again

The apply exits with status 1 and leaves the previously active revision in the ledger. The message also says that the new outputs are already published. The next example changes a column name to show what that means for a query.

What a failed check leaves behind

A failed output check can leave a dashboard reading different outputs from the revision named in the ledger. Daana replaces the objects in daana_dar, runs the checks, and then records the revision if no error check fails. A renamed or removed column is already gone when the check reports its error.

Keep no_day_above_80_usd at severity: error. Rename daily_revenue_amount to daily_revenue_total in the aggregate and both checks' expressions, then run daana dar apply dar/ --connection duckdb. The apply exits with status 1 again, but the view has the renamed column.

Open bookstore.duckdb with duckdb -readonly -markdown bookstore.duckdb using the DuckDB 1.5 CLI. The flags open the file read-only and print results as Markdown tables. Query the renamed column for the day that fails the check:

Run in DuckDB

SELECT order_date, order_line_amount_currency, daily_revenue_total
FROM daana_dar.fct__order_line_daily_revenue
WHERE daily_revenue_total > 80;

The query returns one row: order_date is 2024-11-06, order_line_amount_currency is USD, and daily_revenue_total is 82.59000000. DuckDB prints the amount with eight decimals. This shows that the failed apply has already published the renamed column and the flagged day. A query that still names daily_revenue_amount fails because that column no longer exists.

A CI job or an orchestrator can stop on exit status 1, but by then the new objects are published.

An output declared with materialize: table is a table, not a view. The failed apply has already replaced it too, so it holds the new columns and the flagged rows. It keeps them until the next daana dar apply, because daana execute does not write DAR tables.

What a check does not do

An output check runs only during daana dar apply, so it does not check changes loaded by a later daana execute. The kind of output determines what a query sees after that load:

  • A view reads the DAB each time it is queried. A later load can therefore bring values into the view that would fail a check, without running that check. All outputs in the first example are views.
  • A table holds what the last apply wrote. A later load changes the DAB but leaves that table unchanged until the next apply.

An output already published as a view cannot become a table in place, and a table cannot become a view. Adding materialize: table and applying again is refused before anything is written:

Error: dar apply: daana_dar.fct__order_line_daily_revenue is published as a view and is now declared as a table. Apply cannot change a published view to a table, or a table to a view, in place; nothing was written. Drop the published object from daana_dar (DROP VIEW or DROP TABLE) and apply again, or keep the kind it is published as

Declare the materialization before the output's first apply.

On PostgreSQL, a table cannot be rebuilt while a view reads it. Apply therefore drops the views of the same apply that read the table, rebuilds it, and creates those views again. A view that this apply does not create is not dropped: your own view over a DAR table, or the view of a document that is not in the input. Apply then refuses before anything is written and names the view. Apply that document together with the table's document, or drop your own view, apply, and create it again.

Every apply rebuilds each table in its input, so on PostgreSQL every apply also drops and creates again the DAR views that read such a table, directly or through another view. Privileges granted on those views (GRANT) are lost with the drop: grant them again after each apply. This already holds for a DAR table, which is dropped and created on each apply. Before this change, a DAR view kept its privileges, because CREATE OR REPLACE VIEW keeps them; a view that reads no DAR table still does.

If an apply fails after it has rebuilt a table and before it has created the views that read it again, those views are absent until an apply succeeds. Applying again creates them.

Quit DuckDB with .quit and move to the directory that holds bookstore. Create a separate, disposable project and load its DAB before applying any DAR documents:

Run in terminal

daana init bookstore-table --example bookstore --checkpoint ch5
cd bookstore-table
daana install && daana deploy && daana execute

These commands load the chapter 5 DAB in bookstore-table; they do not create DAR outputs. Create dar/order_line.yaml there from the declaration and checks above, with the original name daily_revenue_amount and no_day_above_80_usd at severity: warn. Add materialize: table to daily_revenue before its first apply:

  daily_revenue:                      # fct__order_line_daily_revenue
    kind: fact.consolidated
    materialize: table
    # ... as above ...

Then run daana dar apply dar/ --connection duckdb. Its summary counts the table:

Warning: DAR data-quality check "no_day_above_80_usd" warned for entity:order_line output "fct__order_line_daily_revenue"
Applied 4 objects (3 views, 1 table) after 2 checks to daana_dar

Open the database read-only with duckdb -readonly bookstore.duckdb. List the objects in daana_dar and their types:

Run in DuckDB

SELECT table_name, table_type
FROM information_schema.tables
WHERE table_schema = 'daana_dar'
ORDER BY 1;

Expected output

table_nametable_type
dim__order_lineVIEW
dim__order_line__latestVIEW
fct__order_lineVIEW
fct__order_line_daily_revenueBASE TABLE

The other three objects are views.

Compare the daily revenue table with the line fact:

Run in DuckDB

SELECT (SELECT count(*) FROM daana_dar.fct__order_line_daily_revenue) AS days_in_daily_revenue,
       (SELECT sum(daily_revenue_amount) FROM daana_dar.fct__order_line_daily_revenue) AS daily_revenue_total,
       (SELECT daily_revenue_amount FROM daana_dar.fct__order_line_daily_revenue WHERE order_date = DATE '2024-11-06') AS revenue_2024_11_06,
       (SELECT count(*) FROM daana_dar.fct__order_line) AS lines_in_line_fact,
       (SELECT sum(order_line_amount_amount) FROM daana_dar.fct__order_line) AS line_fact_total,
       (SELECT count(*) FROM daana_dar.fct__order_line WHERE order_line_amount_amount IS NULL) AS lines_without_amount;

daily_revenue_total is this query's name for the table's sum.

Expected output

days_in_daily_revenuedaily_revenue_totalrevenue_2024_11_06lines_in_line_factline_fact_totallines_without_amount
16762.8800000082.5900000031762.880000000

The daily revenue table and line fact both total 762.88, and the table has 16 days.

Quit DuckDB with .quit. Load the changed source data with daana init . --example bookstore --load-data ch7-missing-discount, then run daana execute. Here . selects the current project and --load-data ch7-missing-discount runs the supplied batch that removes one line's discount. Open the database read-only again with duckdb -readonly bookstore.duckdb and run the same query to compare the daily revenue table with the line fact:

Expected output

days_in_daily_revenuedaily_revenue_totalrevenue_2024_11_06lines_in_line_factline_fact_totallines_without_amount
16762.8800000082.5900000031741.140000001

The line fact, which is a view, now sums to 741.14, but the daily revenue table still holds 762.88 over 16 days because execution does not refresh it.

Quit DuckDB with .quit. Run daana dar apply dar/ --connection duckdb again to refresh the table and run the checks. The apply exits with status 0 without a warning. Open the database read-only again with duckdb -readonly bookstore.duckdb and run the same query to compare the totals after this apply:

Expected output

days_in_daily_revenuedaily_revenue_totalrevenue_2024_11_06lines_in_line_factline_fact_totallines_without_amount
16741.1400000060.8500000031741.140000001

The table now holds 741.14, matching the line fact. The daily checks pass despite the missing line amount, as explained above. Run an apply after each execution when tables need to be refreshed and output checks need to run.

Go back to the last good outputs

Reapplying the previous documents restores their column names and definitions. Quit DuckDB with .quit and return to the original bookstore project, where the failed apply left daily_revenue_total. Restore the saved document with daily_revenue_amount, no_day_above_80_usd at severity: warn, and no materialize: table entry.

Apply the restored documents:

Run in terminal

daana dar apply dar/ --connection duckdb

The terminal prints the warning and the applied line, which the output below shows.

Expected output

Warning: DAR data-quality check "no_day_above_80_usd" warned for entity:order_line output "fct__order_line_daily_revenue"
Applied 4 objects (4 views) after 2 checks to daana_dar

The warning does not fail the apply, so the command exits with status 0.

The view has daily_revenue_amount again and returns 762.88 over 16 days. This revision was already active in the ledger, so reapplying it adds nothing there.

An output declared as a table from its first apply is restored the same way, with its previous columns and a fresh read of the DAB. Restoring a declaration does not restore earlier source values: the table is rebuilt from the DAB's current data.

Preview without a warehouse

A dry run shows the generated SQL without opening the target database. --dry-run compiles the documents against the local model in dab/model.yaml; the connection profile selects the SQL dialect. Preview the plan and look for the dialect, schema and SQL for each object:

Run in terminal

daana dar apply dar/ --dry-run --connection duckdb

The command prints a JSON plan with "dialect": "duckdb", "schema": "daana_dar" and SQL for all four objects. It also runs when the project directory has no database file. The plan previews the SQL but does not run the output checks against data, and it is not bound to a target database, so it cannot be applied.

Without --connection, the dry run's dialect is postgres, although daana.yaml names the duckdb profile. With these output checks still in the document, that dry run exits with status 2 because over: output checks for postgres are not implemented. With the initial declaration, which has no checks, it prints a plan.

These examples show publication, check failures, recovery and preview on DuckDB. Passing checks do not prove that every line has an amount, and a failed check does not undo publication. The Dataform path generates SQLX for Dataform to run separately and does not support these output checks; continue with Generate DAR for Dataform.