Skip to content

23. Track Plan Changes with a Snapshot

Difficulty: Medium · Topic: Snapshots

{{ source('app', 'accounts') }} holds only the current state of each account (account_id, plan, seats, updated_at): when an account upgrades, its row is overwritten and updated_at moves forward. Finance needs the history: which plan each account was on, and when.

Write the snapshot accounts_snapshot (all four columns) so that dbt snapshot keeps one row per version of each account, dated by the account's own updated_at: dbt_valid_from when the version started, dbt_valid_to when it was replaced (null for the current one).

Graded over several snapshot runs (a month apart) against the same table. dbt also adds dbt_scd_id (a hash), which is left out of the comparison.

Graded over several runs against the same table, like a real schedule: 3 tests, including hidden edge cases. The table after every run must match.

Run 1 (at 2024-01-02 06:00:00)

{{ source('app', 'accounts') }}

account_idplanseatsupdated_at
1free12024-01-01 09:00:00
2pro52024-01-01 10:00:00

Expected table after run 1

account_idplanseatsupdated_atdbt_updated_atdbt_valid_fromdbt_valid_to
1free12024-01-01 09:00:002024-01-01 09:00:002024-01-01 09:00:00null
2pro52024-01-01 10:00:002024-01-01 10:00:002024-01-01 10:00:00null

Run 2 (at 2024-02-02 06:00:00)

{{ source('app', 'accounts') }}

account_idplanseatsupdated_at
1pro32024-02-01 08:00:00
2pro52024-01-01 10:00:00
3free12024-02-01 12:00:00

Expected table after run 2

account_idplanseatsupdated_atdbt_updated_atdbt_valid_fromdbt_valid_to
1free12024-01-01 09:00:002024-01-01 09:00:002024-01-01 09:00:002024-02-01 08:00:00
2pro52024-01-01 10:00:002024-01-01 10:00:002024-01-01 10:00:00null
1pro32024-02-01 08:00:002024-02-01 08:00:002024-02-01 08:00:00null
3free12024-02-01 12:00:002024-02-01 12:00:002024-02-01 12:00:00null

Run 3 (at 2024-03-02 06:00:00)

{{ source('app', 'accounts') }}

account_idplanseatsupdated_at
1pro102024-03-01 08:00:00
2team82024-03-01 09:00:00
3free12024-02-01 12:00:00

Expected table after run 3

account_idplanseatsupdated_atdbt_updated_atdbt_valid_fromdbt_valid_to
1free12024-01-01 09:00:002024-01-01 09:00:002024-01-01 09:00:002024-02-01 08:00:00
2pro52024-01-01 10:00:002024-01-01 10:00:002024-01-01 10:00:002024-03-01 09:00:00
1pro32024-02-01 08:00:002024-02-01 08:00:002024-02-01 08:00:002024-03-01 08:00:00
3free12024-02-01 12:00:002024-02-01 12:00:002024-02-01 12:00:00null
1pro102024-03-01 08:00:002024-03-01 08:00:002024-03-01 08:00:00null
2team82024-03-01 09:00:002024-03-01 09:00:002024-03-01 09:00:00null

Hints

Hint 1A snapshot file wraps one SELECT in {% snapshot accounts_snapshot %} ... {% endsnapshot %}, with a config() call inside.
Hint 2The source has a column that changes whenever the row changes: that is the timestamp strategy, strategy='timestamp', updated_at='updated_at'.
Hint 3dbt needs to know what one row is: unique_key='account_id'.

Learn the concepts

More dbt problems

All dbt problems