Macro Reference
All dbt macros in Konsolidat, organized by file. 16 macro files under dbt_project/macros/ (15 plus source_adapters/d365_account_types.sql). Read against the code on 2026-11-05.
dimension_helpers.sql
Macros driven by var('dimensions') in dbt_project.yml. The list is generated from konsol's Dimension doctype and may be empty (konsol#230). Each dimension is a dict with keys name, source_column, label, cube_type, in_budget.
Every list-rendering macro takes two extra parameters since konsolidat#220: trailing=true emits a comma after the list, leading=true before it, only when the list is non-empty. Use them instead of a literal comma next to the macro, so a site with no dimensions does not render a dangling comma.
get_dimensions()
Returns var('dimensions').
get_budget_dimensions()
Returns only the dimensions with in_budget: true. The budget models (gold_spread_budget, gold_scenario_trial_balance, the variance models, stg_budget_entries) pass dims=get_budget_dimensions().
dim_select(prefix='', dims=none, trailing=false, leading=false)
Comma-separated SELECT list of dimension columns.
select data_area_id, {{ dim_select('gl.', trailing=true) }} sum(amount)
-- Output: data_area_id, gl.dim_cost_center, gl.dim_department, gl.dim_business_unit, sum(amount)
-- With no dimensions: data_area_id, sum(amount)
dim_group_by(prefix='', dims=none, trailing=false, leading=false)
Same list for GROUP BY. Typical: group by data_area_id{{ dim_group_by(leading=true) }}.
dim_join_on(left, right, dims=none)
and left.dim = right.dim for every dimension.
dim_coalesce(left, right, dims=none)
coalesce(left.dim, right.dim) as dim for every dimension (FULL OUTER JOIN results).
dim_partition_by(prefix='', dims=none, trailing=false, leading=false)
The list for a window partition by. Typical: partition by data_area_id, main_account{{ dim_partition_by(leading=true) }}.
dim_empty_strings(dims=none, trailing=false, leading=false)
'' as dim for every dimension: the non-entity layers of gold_fully_consolidated_tb (IC eliminations, CTA, topside, equity method, deal journals).
dim_harmonize_select(raw_alias='unioned', map_prefix='dmap_', dims=none)
Harmonised SELECT expressions for the canonical staging models: per dimension a multiIf that takes the entity-specific Published mapping's canonical_value, else the ERP-wide default's (entity = ''), else the raw value (konsol#111). Uses an empty-string check, not coalesce: a ClickHouse LEFT JOIN fills a miss with '', not NULL. Emits a trailing comma.
dim_harmonize_joins(erp_source_col, raw_alias='unioned', map_prefix='dmap_', dims=none, entity_col=none)
Two LEFT JOINs per dimension against source('epm_staging', 'dimension_mappings') (status = 'Published', matched on dimension, erp_source, source_value): one on entity = <entity_col> (default <raw_alias>.entity_id), one on entity = ''. Two joins rather than one OR predicate so a value with both rows cannot fan the fact rows out.
dim_select_from_source(prefix='', dims=none, trailing=false, leading=false)
Casts each dimension's source_column to its name: toString(assumeNotNull(coalesce(prefix.source_column, ''))) as dim. Used by the bronze models, including bronze_trial_balance_submissions, which substitutes '' for a dimension whose raw column konsol has not created yet.
measure_helpers.sql
Driven by var('base_measures') (keys name, expression, label, cube_type), also konsol-generated.
measure_select()
expression as name for every measure: sum(debit_amount) as period_debit, sum(credit_amount) as period_credit, sum(debit_amount) - sum(credit_amount) as period_net_amount, count(*) as transaction_count on the demo. Used by gold_trial_balance and gold_trial_balance_by_partner.
measure_passthrough(prefix='')
prefix.name for every measure, for the models that pass the trial-balance measures through.
db_adapter.sql
ClickHouse-specific casts and helpers. All casts wrap assumeNotNull().
| Macro | Output |
|---|---|
cast_to_string(expr) | toString(assumeNotNull(expr)) |
cast_to_int64(expr) | toInt64(assumeNotNull(expr)) |
cast_to_int8(expr) | toInt8(assumeNotNull(expr)) |
cast_to_uint16(expr) | toUInt16(assumeNotNull(expr)) |
cast_to_uint8(expr) | toUInt8(assumeNotNull(expr)) |
cast_to_float64(expr) | toFloat64(assumeNotNull(expr)) |
cast_to_date(expr) | toDate(assumeNotNull(expr)) |
cast_to_datetime(expr) | toDateTime(assumeNotNull(expr)) |
cast_to_decimal128(expr, scale) | toDecimal128(toString(round(assumeNotNull(expr), scale)), scale): rounds to the scale first, then goes through text, so a float such as 0.29 does not truncate to 0.28 (konsolidat#191) |
extract_year(expr) | toYear(expr) |
extract_month(expr) | toMonth(expr) |
build_date_from_year_period(year_expr, period_expr) | The first of month P, with P clamped to 1..12 (OPN = January, CLS = December) so period 13 cannot become 1970-01-01 (konsolidat#177) |
latest_value_by(val_expr, key_expr) | argMax(val, key) |
string_pad_left(expr, len, ch) | lpad(expr, len, ch) |
epm_config(order_by='tuple()') | {'engine': 'MergeTree()', 'order_by': order_by} on ClickHouse, {} otherwise |
erp_sources.sql
empty_relation(columns)
A row-less select with exactly the given (name, ClickHouse type) columns, each defaultValueOfTypeName(type), where 0. The canonical staging models and the D365-only bronze models return it when their ERP is not in var('erp_sources') (konsolidat#207), so downstream models keep building with the right column types.
governed_chart.sql
The group chart of accounts governed in konsol (Main Account → epm_staging.main_accounts, konsol#182).
governed_chart_relation()
The table's relation, or none when it does not exist yet (a volume konsol has not upgraded), so this project can deploy before konsol creates it.
governed_chart_problems()
One row per (main_account, problem) silver cannot use: Published duplicates that disagree on any column; a leaf whose statement_section is neither Profit and Loss nor Balance Sheet; an fx_method outside closing / average / historical; a P&L account at the historical rate or a balance-sheet account at the average rate. Shared by the guard and assert_governed_chart_declarations_usable.
governed_chart_guard()
silver_main_accounts' pre_hook: raises, naming the first 50 problems, before the table is replaced.
governed_rates.sql
The FX contract (decided 13 Sep 2026, konsolidat#93 / konsol#103): epm_staging.group_exchange_rates.rate is the TRUE rate (units of to_currency per 1 from_currency), published by konsol; the warehouse never scales or inverts it.
rate_period_map()
(fiscal_year, fiscal_period) → (rate_year, rate_period) from epm_staging.fiscal_periods: a Closing period maps to its year's last Regular period, every other period to itself (konsolidat#199). One definition shared by the guard, the coverage test and gold_consolidated_trial_balance.
governed_translated_keys(scoped=true)
The distinct (from currency, group currency, rate year, rate period) keys the consolidated trial balance translates, from gold_trial_balance, silver_entity_currencies, gold_entity_ownership and the group roots; with the run's period_filter / scope_filter when scoped.
governed_rate_gaps(scoped=true)
Those keys whose governed rates are not usable, with the reason: missing (no approved Closing and Average), duplicate, invalid (zero, negative, not finite), implausible (more than 10× from the ISO Currency reference magnitudes, when both are known).
governed_rate_guard()
gold_consolidated_trial_balance's first pre_hook: raises with the first 50 gaps, before the scope's DELETE, so a missing rate leaves the table as it was.
fx_precheck()
deploy.sh's pre-step check, run with dbt show --inline "{{ fx_precheck() }}": one line per finding, marked FX_TABLE_MISSING, FX_NOTHING_BUILT, FX_GAPS_TOTAL <n> or FX_GAP <key> <reason>.
fx_magnitude.sql
The #138 magnitude rule, one formula for the ERP-feed test (assert_exchange_rate_sane_magnitude), the governed-rate test (assert_governed_rate_sane) and the guard. Kept in step with konsol's group_rates.magnitude_problem.
| Macro | Purpose |
|---|---|
fx_reference_magnitudes() | CTE body: currency_code, usd_log10 from epm_gold.currencies for currencies that have a reference |
fx_has_reference(code, usd_log10) | not (isNaN(usd_log10) or (usd_log10 = 0 and code != 'USD')) |
fx_is_implausible(rate, from_log10, to_log10) | abs(log10(rate) - (to_log10 - from_log10)) > 1 (more than one decade off) |
fx_magnitude_problem(rate, from_ccy, to_ccy, from_log10, to_log10, refs='ref_mag') | '' when plausible, else the reason (not a finite number, not positive, no reference magnitude for X, more than 10x from the reference magnitudes) |
fx_reference_column_present() | True when epm_gold.currencies has usd_log10 (an older volume may not), so tests return a warn row instead of erroring |
erp_rate_quotes_relation() | silver_exchange_rates' relation, or none when it has not been built (a trial-balance-only site) |
ic_helpers.sql
Intercompany helpers (konsolidat#148, konsol#159). An account is intercompany because konsol's Intercompany Account doctype flags it (epm_staging.intercompany_accounts).
| Macro | Purpose |
|---|---|
ic_account_map() | One row per intercompany account with its counterpart ('' in the table means the same account); both directions of a pair |
ic_nci_placeholder() | The literal 'NCI': the pseudo-account a group posts its NCI line to until it declares nci_account on its root |
ic_group_nci_accounts() | One row per group root: declared_nci_account (reads the column only if present) |
ic_nci_account_or_placeholder(declared) | The declared account when non-empty, else the placeholder |
ic_partner_slices() | gold_consolidated_trial_balance summed per (group, entity, partner, account, period) at 100% (translated) and local; the IC tests recompute from it |
ic_expected_pair_values() | Each gold_ic_reconciliation row's two sides recomputed from the slices on the row's basis (balance to date or period movement; 0 on a left row) |
materiality.sql
materiality_floor()
The half-cent (0.005) below which an amount is treated as zero when posting or reconciling (konsolidat#209). One definition; tests/test_materiality_literal.py keeps the literal out of every other model, macro and test.
orchestrator_filters.sql
Run-scope filters for konsol's orchestrator (Period Close). Both are opt-in: with no var they render nothing and a full build is unchanged.
period_filter(year_col='fiscal_year', period_col='fiscal_period', include_period=true)
and year_col = <fiscal_year> and, unless include_period=false, and period_col = <fiscal_period> from the fiscal_year / fiscal_period vars. Cumulative models (YTD) pass include_period=false so every earlier period of the year stays in the window.
scope_filter(data_area_col='data_area_id')
and data_area_col in (...) resolving the entity_scope var against gold_consolidation_hierarchy: an entity code matches itself; a group code matches every descendant through the materialised path (slash-bounded LIKE patterns, _ and % escaped). Single quotes in the var are escaped.
_require_period_int(val, name)
Private: raises a compiler error when a run var is not a non-negative integer, so a misconfigured run fails loudly instead of being coerced to 0.
ownership_resolution.sql
ownership_resolution_ctes(periods_cte, p='')
Emits the chain of CTEs behind gold_entity_ownership (<p>ancestry, <p>ownership, <p>ancestry_periods, <p>entity_windows, <p>links, <p>resolved, <p>resolution) for the (entity, year, period, period_date) rows of periods_cte: the link closure from epm_staging.consolidation_ancestry, the epm_staging.ownership_periods row in force at the date per link (ASOF, end_date checked), the effective share (the sum over paths of the product of each path's dated link percentages, konsol#117), the immediate owner_group, the method (the weakest link's, or a Consolidation Method Declaration where several paths do not settle it, method_source), has_complete_chain and outside_ownership_window. gold_ic_reconciliation calls it with p='own_' on a period spine of its own.
prorate_period_amount.sql
prorate_period_amount(amount_expr, acquisition_date_expr, year_expr, period_expr)
amount × fraction: 1.0 when there is no acquisition date (<= 1900-01-01) or the acquisition is before the period; 0.0 when it is on or after the period end; otherwise days from the acquisition to the period end over days in the period. The period end is addMonths(period start, 1) (a mid-December acquisition no longer prorates P12 to 0, #176/#177).
reporting_hierarchy_helpers.sql
| Macro | Purpose |
|---|---|
tb_dimension_long_sql(tb_alias='tb') | gold_trial_balance unpivoted one row per declared dimension (hierarchy_dimension, dimension_member_code), non-empty values only; with no dimensions a typed row-less select (konsolidat#220) |
budget_dimension_long_sql(budget_alias='b') | The same over gold_spread_budget, budget dimensions |
variance_dimension_long_sql(var_alias='v') | The same over gold_variance_analysis, budget dimensions |
hierarchy_measure_sums(prefix='') | sum(prefix.measure) as measure for every base measure |
variance_measure_sums(prefix='') | sum(actual_amount), sum(budget_amount), sum(variance_abs) |
sync_watermark.sql
sync_watermark_upgrade()
Run from on-run-start: when epm_staging.sync_watermark's sorting key lacks reconcile_run_id, issues the same ALTER TABLE ... ADD COLUMN ... MODIFY ORDER BY konsol's ensure_reference_tables() issues (konsolidat#246), so assert_staging_not_stale never reads a column that is not there. Only when missing: an ALTER that changes nothing would still move the table's modification time, which the test measures its grace from.
cluster.sql
ClickHouse cluster-sharding support. Opt-in and off by default: activated by var('cluster_enabled') with the cluster profile target. When disabled every macro returns the literal it replaces, so single-node compiled SQL is unchanged.
| Macro | Behaviour |
|---|---|
cluster_enabled() | var('cluster_enabled', false) as a bool |
cluster_name() | 'konsol_cluster' when enabled, else none (no ON CLUSTER) |
cluster_zk_path() | Keeper path template /clickhouse/tables/{shard}/{database}/{table} |
cluster_sharding_key(col='data_area_id') | cityHash64(col): a legal entity lives on one shard |
cluster_engine(base_engine) | The Replicated* variant of a MergeTree-family engine when enabled; unchanged otherwise |
cluster_sharded_tables() | The (database, table) pairs that get a Distributed overlay: bronze_general_journal_account_entries, bronze_general_journal_entries, gold_trial_balance |
create_distributed_tables(...) | dbt run-operation: CREATE TABLE IF NOT EXISTS <table> as Distributed(...) over <table>_local for each sharded table; no-op when disabled |
drop_distributed_tables(...) | Drops the overlay tables (not the _local ones); no-op when disabled |
Only the three sharded tables carry cluster_engine() / cluster_name() in their config today. See the admin guide's cluster setup page for the procedure.
source_adapters/d365_account_types.sql
map_account_type(column)
Maps D365 MainAccountType values (numeric or string) to readable labels; ERPNext root_type values arrive in the same column and Income reads as Revenue.
| Input | Output |
|---|---|
'0' / 'ProfitAndLoss' | 'Profit and loss' |
'1' / 'Revenue' / 'Income' | 'Revenue' |
'2' / 'Expense' | 'Expense' |
'3' / 'BalanceSheet' | 'Balance sheet' |
'4' / 'Asset' | 'Asset' |
'5' / 'Liability' | 'Liability' |
'6' / 'Equity' | 'Equity' |
'7' / 'Total' | 'Total' |
| Other | Passthrough |
Used by the ERP account adapters. Since konsol#182 silver_main_accounts takes account types from the governed chart, not from this mapping.
Removed macros
The cost-allocation engine macros (single-step, multistep, reciprocal and tiered, and the driver resolver) were removed with the feature (konsol#264; konsolidat de468fa). The correlated-subquery currency converter and the seed-backed period-ownership resolvers were replaced by the governed rates and gold_entity_ownership (F2, konsolidat#93).