Skip to content

Compilation Pipeline

The driver that takes a QueryObject through resolution, planning and generation, plus the star-schema planner, join graph and code generator it calls.

Compiler Pipeline

orionbelt.compiler.pipeline.CompilationPipeline

Orchestrates: Query → Resolution → Planning → AST → SQL.

Source code in src/orionbelt/compiler/pipeline.py
class CompilationPipeline:
    """Orchestrates: Query → Resolution → Planning → AST → SQL."""

    def __init__(self) -> None:
        self._resolver = QueryResolver()
        self._star_planner = StarSchemaPlanner()
        self._cfl_planner = CFLPlanner()
        self._raw_planner = RawPlanner()

    @staticmethod
    def detect_replication(resolved: ResolvedQuery, model: SemanticModel) -> None:
        """Phase 1.5: fanout detection, and which measures need deduplicating.

        A method rather than inline because a *sub*-query needs the same phase:
        ``filter_wrap`` plans a filterContext measure's scan in its own right,
        and skipping this left a measure on the one side of a replicating join
        summed once per row of the many side - the exact overcount the pass
        exists to prevent, in a query where nothing said so.
        """
        # Skipped for CFL: its join steps span facts a union queries
        # independently, so the check would refuse a query the union answers.
        # The per-leg equivalent lives in the CFL planner, which is where a
        # leg's own joins are known.
        if resolved.requires_cfl:
            return
        detect_fanout(resolved, model)
        # Forward many-to-one joins replicate the *one* side, which
        # `detect_fanout` treats as safe. Flag any measure sourced from a
        # replicated object so the `grain_dedup` pass aggregates it over
        # deduplicated rows instead of the flattened join.
        if not resolved.is_raw:
            dedup_plan = detect_dedup_measures(resolved, model)
            # A filterContext measure is not this plan's to deduplicate: it is
            # computed by a scan of its own, which runs this same phase for
            # itself. Leaving it in built a dedup CTE for a column the final
            # projection takes from elsewhere.
            isolated = {m.name for m in resolved.measures if m.filter_context is not None} | {
                name
                for name, comp in resolved.metric_components.items()
                if comp.filter_context is not None
            }
            resolved.dedup_measures = {
                k: v for k, v in dedup_plan.measures.items() if k not in isolated
            }
            resolved.dedup_components = {
                k: v for k, v in dedup_plan.components.items() if k not in isolated
            }

    def compile(
        self,
        query: QueryObject,
        model: SemanticModel,
        dialect_name: str,
    ) -> CompilationResult:
        """Compile a query to SQL for the specified dialect."""
        # Create dialect first so resolution and planning share one
        # ``qualify_table`` — the EXISTS filter operator needs it during
        # resolution to render the correlated subquery's FROM clause.
        dialect = DialectRegistry.get(dialect_name)
        # The registry hands out a fresh dialect per compile, so the model's
        # calendar can be set on it without leaking into another query.
        if model.settings is not None:
            dialect.week_start = model.settings.week_start

        def qualify_table(obj: DataObject) -> str:
            # Guarded rather than trusting ``code`` to be non-empty: a nested
            # object without the fallback has no table, and an unguarded empty
            # code renders as FROM "" (#342 review).
            obj.require_table_source()
            return dialect.format_table_ref(obj.database, obj.schema_name, obj.code)

        # Phase 1: Resolution
        resolved = self._resolver.resolve(query, model, qualify_table=qualify_table)

        # Phase 1.5: Fanout detection (skip for CFL — each fact queried independently)
        self.detect_replication(resolved, model)

        # Phase 2: Planning (raw / star schema / CFL)
        use_cfl = resolved.requires_cfl or resolved.dimensions_exclude
        if resolved.is_raw:
            plan = self._raw_planner.plan(
                resolved,
                model,
                qualify_table=qualify_table,
                dialect=dialect,
                union_by_name=dialect.capabilities.supports_union_all_by_name,
            )
        elif use_cfl:
            plan = self._cfl_planner.plan(
                resolved,
                model,
                qualify_table=qualify_table,
                union_by_name=dialect.capabilities.supports_union_all_by_name,
                dialect=dialect,
            )
        else:
            plan = self._star_planner.plan(
                resolved, model, qualify_table=qualify_table, dialect=dialect
            )

        # Phase 2.3 – 2.6: Aggregate-mode passes (filter context, PoP,
        # totals, cumulative, window) plus HAVING projection cleanup. Raw
        # mode has no measures, so the passes are no-ops and skipped
        # entirely for clarity. Pass ordering and the feature-compatibility
        # rules live in ``compiler/passes.py``.
        if resolved.is_raw:
            wrapped_ast = plan.ast
        else:
            ctx = CompileContext(
                resolved=resolved,
                model=model,
                dialect=dialect,
                qualify_table=qualify_table,
                query=query,
            )
            wrapped_ast = apply_aggregate_passes(plan.ast, ctx)

        # Phase 3: Dialect-specific SQL rendering
        codegen = CodeGenerator(dialect)
        sql = codegen.generate(wrapped_ast)

        # Phase 4: SQL validation (non-blocking)
        validation_errors = validate_sql(sql, dialect_name)
        sql_valid = len(validation_errors) == 0
        warnings = resolved.warnings
        if not sql_valid:
            warnings = warnings + [
                warning(
                    code=WarningCode.SQL_VALIDATION,
                    message=f"SQL validation: {e}",
                )
                for e in validation_errors
            ]

        # Phase 4b: scope check (non-blocking). Syntax is not the only way a
        # statement can be wrong: an expression left behind in a query that
        # wraps it parses clean and fails at the database, naming a data object
        # from the model as if the model were at fault (#358). Kept separate
        # from ``sql_valid``, which answers whether sqlglot could parse it.
        stray_tables = out_of_scope_tables(wrapped_ast)
        if stray_tables:
            named = ", ".join(sorted(stray_tables))
            warnings = warnings + [
                warning(
                    code=WarningCode.OUT_OF_SCOPE_TABLE,
                    message=(
                        f"Compiled SQL references {named} in the outermost query, "
                        f"which its FROM does not provide"
                    ),
                    hint=(
                        "The statement will be rejected by the database. This is a "
                        "compiler defect rather than a model one - please report the "
                        "query and model."
                    ),
                    context={"tables": sorted(stray_tables)},
                )
            ]

        # Build explain plan
        explain = self._build_explain(resolved, model, use_cfl, plan)

        # Compute deduplicated physical tables touched by the query
        physical_tables = _compute_physical_tables(resolved, query, model)

        return CompilationResult(
            sql=sql,
            dialect=dialect_name,
            physical_tables=physical_tables,
            resolved=ResolvedInfo(
                fact_tables=resolved.fact_tables,
                dimensions=[d.name for d in resolved.dimensions],
                measures=[m.name for m in resolved.measures],
            ),
            warnings=warnings,
            sql_valid=sql_valid,
            explain=explain,
        )

    @staticmethod
    def _q(name: str) -> str:
        """Quote an identifier for explain output."""
        return f'"{name}"'

    def _build_explain(
        self,
        resolved: ResolvedQuery,
        model: SemanticModel,
        use_cfl: bool,
        plan: QueryPlan,
    ) -> ExplainPlan:
        """Build the explain plan from resolution results."""
        q = self._q

        # Planner choice
        if resolved.is_raw:
            planner = "Raw"
            distinct_note = " with DISTINCT" if resolved.distinct else ""
            planner_reason = (
                f"Raw-mode projection of physical columns{distinct_note} — "
                f"no aggregation, no GROUP BY"
            )
        elif use_cfl:
            if resolved.dimensions_exclude:
                planner = "CFL"
                planner_reason = (
                    "dimensionsExclude anti-join — "
                    "CROSS JOIN of distinct values EXCEPT existing combinations"
                )
            else:
                planner = "CFL"
                sources = ", ".join(q(s) for s in sorted(resolved.measure_source_objects))
                planner_reason = (
                    f"Measures reference independent fact tables ({sources}) — "
                    f"Composite Fact Layer merges them via UNION ALL"
                )
        else:
            planner = "Star Schema"
            planner_reason = (
                "All requested objects are reachable from a single base via directed joins"
            )

        # Base object — explain should reflect actual selection logic
        base = resolved.base_object
        if resolved.measure_source_objects:
            if use_cfl and len(resolved.measure_source_objects) > 1:
                base_reason = (
                    "Not applicable — each CFL leg uses its own common root (see cfl_legs)"
                )
            elif len(resolved.measure_source_objects) > 1:
                sources = ", ".join(q(s) for s in sorted(resolved.measure_source_objects))
                base_reason = (
                    f"{q(base)} selected as base — most connected fact table "
                    f"among measure sources ({sources})"
                )
            else:
                base_reason = f"{q(base)} selected as base — sole measure source object"
        elif len(resolved.required_objects) > 1:
            base_reason = (
                f"{q(base)} selected as base — common root that can reach "
                f"all required objects via directed joins"
            )
        else:
            base_reason = f"{q(base)} selected as base for single-object query"

        # Joins — for CFL queries the per-leg joins are more informative,
        # so only include resolution-level joins for star schema queries.
        explain_joins: list[ExplainJoin] = []
        if not use_cfl:
            for step in resolved.join_steps:
                join_cols = [
                    f"{fc} = {tc}"
                    for fc, tc in zip(step.from_columns, step.to_columns, strict=True)
                ]
                if step.reversed:
                    reason = (
                        f"Reversed join from {q(step.from_object)} to {q(step.to_object)} — "
                        f"original join was defined in the opposite direction"
                    )
                else:
                    reason = (
                        f"Join {q(step.from_object)}{q(step.to_object)} to include "
                        f"columns needed by the query"
                    )
                explain_joins.append(
                    ExplainJoin(
                        from_object=step.from_object,
                        to_object=step.to_object,
                        join_columns=join_cols,
                        reason=reason,
                        cardinality=step.cardinality.value,
                    )
                )

        # CFL leg details
        cfl_leg_explains: list[ExplainCflLeg] = []
        for leg in plan.cfl_legs:
            cfl_leg_explains.append(
                ExplainCflLeg(
                    measure_source=leg.measure_source,
                    common_root=leg.common_root,
                    reason=leg.reason,
                    measures=leg.measures,
                    joins=leg.joins,
                )
            )

        return ExplainPlan(
            planner=planner,
            planner_reason=planner_reason,
            base_object=base,
            base_object_reason=base_reason,
            joins=explain_joins,
            where_filter_count=len(resolved.where_filters),
            having_filter_count=len(resolved.having_filters),
            has_totals=resolved.has_totals,
            has_grain_overrides=resolved.has_grain_overrides,
            has_filter_context=resolved.has_filter_context,
            has_cumulative=resolved.has_cumulative,
            has_pop=resolved.has_pop,
            has_window=resolved.has_window,
            cfl_legs=cfl_leg_explains,
        )

compile(query, model, dialect_name)

Compile a query to SQL for the specified dialect.

Source code in src/orionbelt/compiler/pipeline.py
def compile(
    self,
    query: QueryObject,
    model: SemanticModel,
    dialect_name: str,
) -> CompilationResult:
    """Compile a query to SQL for the specified dialect."""
    # Create dialect first so resolution and planning share one
    # ``qualify_table`` — the EXISTS filter operator needs it during
    # resolution to render the correlated subquery's FROM clause.
    dialect = DialectRegistry.get(dialect_name)
    # The registry hands out a fresh dialect per compile, so the model's
    # calendar can be set on it without leaking into another query.
    if model.settings is not None:
        dialect.week_start = model.settings.week_start

    def qualify_table(obj: DataObject) -> str:
        # Guarded rather than trusting ``code`` to be non-empty: a nested
        # object without the fallback has no table, and an unguarded empty
        # code renders as FROM "" (#342 review).
        obj.require_table_source()
        return dialect.format_table_ref(obj.database, obj.schema_name, obj.code)

    # Phase 1: Resolution
    resolved = self._resolver.resolve(query, model, qualify_table=qualify_table)

    # Phase 1.5: Fanout detection (skip for CFL — each fact queried independently)
    self.detect_replication(resolved, model)

    # Phase 2: Planning (raw / star schema / CFL)
    use_cfl = resolved.requires_cfl or resolved.dimensions_exclude
    if resolved.is_raw:
        plan = self._raw_planner.plan(
            resolved,
            model,
            qualify_table=qualify_table,
            dialect=dialect,
            union_by_name=dialect.capabilities.supports_union_all_by_name,
        )
    elif use_cfl:
        plan = self._cfl_planner.plan(
            resolved,
            model,
            qualify_table=qualify_table,
            union_by_name=dialect.capabilities.supports_union_all_by_name,
            dialect=dialect,
        )
    else:
        plan = self._star_planner.plan(
            resolved, model, qualify_table=qualify_table, dialect=dialect
        )

    # Phase 2.3 – 2.6: Aggregate-mode passes (filter context, PoP,
    # totals, cumulative, window) plus HAVING projection cleanup. Raw
    # mode has no measures, so the passes are no-ops and skipped
    # entirely for clarity. Pass ordering and the feature-compatibility
    # rules live in ``compiler/passes.py``.
    if resolved.is_raw:
        wrapped_ast = plan.ast
    else:
        ctx = CompileContext(
            resolved=resolved,
            model=model,
            dialect=dialect,
            qualify_table=qualify_table,
            query=query,
        )
        wrapped_ast = apply_aggregate_passes(plan.ast, ctx)

    # Phase 3: Dialect-specific SQL rendering
    codegen = CodeGenerator(dialect)
    sql = codegen.generate(wrapped_ast)

    # Phase 4: SQL validation (non-blocking)
    validation_errors = validate_sql(sql, dialect_name)
    sql_valid = len(validation_errors) == 0
    warnings = resolved.warnings
    if not sql_valid:
        warnings = warnings + [
            warning(
                code=WarningCode.SQL_VALIDATION,
                message=f"SQL validation: {e}",
            )
            for e in validation_errors
        ]

    # Phase 4b: scope check (non-blocking). Syntax is not the only way a
    # statement can be wrong: an expression left behind in a query that
    # wraps it parses clean and fails at the database, naming a data object
    # from the model as if the model were at fault (#358). Kept separate
    # from ``sql_valid``, which answers whether sqlglot could parse it.
    stray_tables = out_of_scope_tables(wrapped_ast)
    if stray_tables:
        named = ", ".join(sorted(stray_tables))
        warnings = warnings + [
            warning(
                code=WarningCode.OUT_OF_SCOPE_TABLE,
                message=(
                    f"Compiled SQL references {named} in the outermost query, "
                    f"which its FROM does not provide"
                ),
                hint=(
                    "The statement will be rejected by the database. This is a "
                    "compiler defect rather than a model one - please report the "
                    "query and model."
                ),
                context={"tables": sorted(stray_tables)},
            )
        ]

    # Build explain plan
    explain = self._build_explain(resolved, model, use_cfl, plan)

    # Compute deduplicated physical tables touched by the query
    physical_tables = _compute_physical_tables(resolved, query, model)

    return CompilationResult(
        sql=sql,
        dialect=dialect_name,
        physical_tables=physical_tables,
        resolved=ResolvedInfo(
            fact_tables=resolved.fact_tables,
            dimensions=[d.name for d in resolved.dimensions],
            measures=[m.name for m in resolved.measures],
        ),
        warnings=warnings,
        sql_valid=sql_valid,
        explain=explain,
    )

Star Schema Planner

orionbelt.compiler.star.StarSchemaPlanner

Plans star-schema queries: single fact base with dimension joins.

Source code in src/orionbelt/compiler/star.py
class StarSchemaPlanner:
    """Plans star-schema queries: single fact base with dimension joins."""

    def plan(
        self,
        resolved: ResolvedQuery,
        model: SemanticModel,
        qualify_table: Callable[[DataObject], str] | None = None,
        dialect: Dialect | None = None,
    ) -> QueryPlan:
        builder = QueryBuilder()
        graph = JoinGraph(model, use_path_names=resolved.use_path_names or None)

        def qualify(obj: DataObject) -> str:
            return qualify_table(obj) if qualify_table else obj.qualified_code

        base_object = model.data_objects.get(resolved.base_object)
        if not base_object:
            return QueryPlan(ast=builder.build())

        base_alias = resolved.base_object

        # Anchored measures: aggregate each independent fact they read to the
        # key it shares with the anchor, so it joins back many-to-one instead of
        # pairing rows that do not correspond. Planned up front because the
        # measure projection below has to read the conformed columns rather than
        # the foreign fact's own, which this plan is what renames.
        conformed_facts, conformed_exprs = plan_conformed_facts(resolved, model, qualify)
        # Recorded for the wrappers that run after planning: each re-projects a
        # measure's aggregate into its own CTE, and the resolved expression they
        # would otherwise use still names the foreign fact's table.
        resolved.projected_expressions = conformed_exprs

        # SELECT: dimensions (apply time grain truncation if specified)
        grouping_dim_aliases: list[str] = []
        for dim in resolved.dimensions:
            col: Expr = make_dimension_expr(model, dim, dialect)
            builder.select(AliasedExpr(expr=col, alias=dim.name))
            if resolved.grouping is not None:
                grouping_dim_aliases.append(dim.name)

        # SELECT: measures (aggregated) — for metrics, substitute component refs
        settings = model.settings
        measure_exprs: dict[str, Expr] = {}
        # A metric inlines its components' expressions, so a conformed component
        # has to be substituted in its rewritten form - the raw one still names
        # the foreign fact's own table, which the conformed plan does not join.
        metric_components = {
            name: (
                replace(component, expression=conformed_exprs[name])
                if name in conformed_exprs
                else component
            )
            for name, component in resolved.metric_components.items()
        }
        for measure in resolved.measures:
            if measure.component_measures:
                expr: Expr = _substitute_measure_refs(measure.expression, metric_components)
                metric = model.metrics.get(measure.name)
                if metric and dialect:
                    resolved_type = resolve_metric_data_type(metric, settings)
                    if resolved_type:
                        expr = dialect.cast_to_obml_type(expr, resolved_type)
                builder.select(AliasedExpr(expr=expr, alias=measure.name))
            else:
                expr = conformed_exprs.get(measure.name, measure.expression)
                model_measure = model.effective_measures.get(measure.name)
                if model_measure and dialect:
                    expr = cast_measure_to_resolved_type(
                        expr, model_measure, settings, dialect, model
                    )
                builder.select(AliasedExpr(expr=expr, alias=measure.name))
            measure_exprs[measure.name] = expr

        # FROM: base fact table
        builder.from_(qualify(base_object), alias=base_alias)

        # Conformed facts join first: one row per shared key, so many-to-one and
        # no fanout onto the anchor's grain.
        for fact in conformed_facts:
            builder.join(
                table=fact.select,
                on=fact.on,
                join_type=conformed_join_type(),
                alias=fact.alias,
            )

        # JOINs: dimension and intermediate tables
        joined = {base_alias}
        for step in resolved.join_steps:
            # Determine which side of the step needs to be joined
            if step.to_object not in joined:
                new_object = step.to_object
            elif step.from_object not in joined:
                new_object = step.from_object
            else:
                continue  # both already joined
            obj = model.data_objects.get(new_object)
            if not obj:
                continue
            emit_join_step(
                builder=builder,
                step=step,
                new_object=new_object,
                obj=obj,
                graph=graph,
                qualify=qualify,
                dialect=dialect,
                warnings=resolved.warnings,
            )
            joined.add(new_object)

        # WHERE
        for wf in resolved.where_filters:
            builder.where(wf.expression)

        # GROUP BY (all dimension columns, with time grain if applicable).
        # Stash the per-dim group-by expression by alias so GROUPING() below
        # can reuse the SAME expression — Postgres rejects GROUPING(<alias>)
        # with "column does not exist" and requires the group-key expression.
        group_by_exprs: dict[str, Expr] = {}
        for dim in resolved.dimensions:
            gb_col: Expr = make_dimension_expr(model, dim, dialect)
            builder.group_by(gb_col)
            group_by_exprs[dim.name] = gb_col

        # GROUPING() flag columns + grouping modifier (rollup/cube)
        if resolved.grouping is not None and grouping_dim_aliases:
            builder.grouping(resolved.grouping.value)
            for alias in grouping_dim_aliases:
                gb_arg = group_by_exprs.get(alias) or ColumnRef(name=alias)
                flag_col = FunctionCall(name="GROUPING", args=[gb_arg])
                builder.select(AliasedExpr(expr=flag_col, alias=_grouping_flag_alias(alias)))

        # HAVING — expand alias references to actual CAST'd aggregate expressions.
        # A predicate on a measure some later wrapper finishes with a window
        # function is left out entirely: at this level only the pre-window
        # aggregate exists, so evaluating it here filters the wrong value.
        # ``PASS_HAVING_WINDOW`` applies those once, over the windowed rows.
        # Withholding them here rather than stripping them per wrapper is what
        # keeps every wrapper composition correct — each one copies or rebuilds
        # ``ast.having`` differently, and any that kept a stale copy would
        # filter pre-window behind the pass's back.
        from orionbelt.compiler.having_hoist import windowed_aliases

        deferred = windowed_aliases(resolved)
        for hf in resolved.having_filters:
            if hf.referenced_fields & deferred:
                continue
            builder.having(_expand_measure_refs(hf.expression, measure_exprs))

        # ORDER BY (use alias for time-grained dimensions)
        grained_cols: dict[tuple[str, str | None], str] = {
            (d.source_column, d.object_name): d.name for d in resolved.dimensions if d.grain
        }
        for expr, desc, nulls in resolved.order_by_exprs:
            if isinstance(expr, ColumnRef) and (expr.name, expr.table) in grained_cols:
                expr = ColumnRef(name=grained_cols[(expr.name, expr.table)])
            builder.order_by(expr, desc=desc, nulls_last=_nulls_last(nulls))

        # LIMIT / OFFSET
        if resolved.limit is not None:
            builder.limit(resolved.limit)
        if resolved.offset is not None:
            builder.offset(resolved.offset)

        return QueryPlan(ast=builder.build())

plan(resolved, model, qualify_table=None, dialect=None)

Source code in src/orionbelt/compiler/star.py
def plan(
    self,
    resolved: ResolvedQuery,
    model: SemanticModel,
    qualify_table: Callable[[DataObject], str] | None = None,
    dialect: Dialect | None = None,
) -> QueryPlan:
    builder = QueryBuilder()
    graph = JoinGraph(model, use_path_names=resolved.use_path_names or None)

    def qualify(obj: DataObject) -> str:
        return qualify_table(obj) if qualify_table else obj.qualified_code

    base_object = model.data_objects.get(resolved.base_object)
    if not base_object:
        return QueryPlan(ast=builder.build())

    base_alias = resolved.base_object

    # Anchored measures: aggregate each independent fact they read to the
    # key it shares with the anchor, so it joins back many-to-one instead of
    # pairing rows that do not correspond. Planned up front because the
    # measure projection below has to read the conformed columns rather than
    # the foreign fact's own, which this plan is what renames.
    conformed_facts, conformed_exprs = plan_conformed_facts(resolved, model, qualify)
    # Recorded for the wrappers that run after planning: each re-projects a
    # measure's aggregate into its own CTE, and the resolved expression they
    # would otherwise use still names the foreign fact's table.
    resolved.projected_expressions = conformed_exprs

    # SELECT: dimensions (apply time grain truncation if specified)
    grouping_dim_aliases: list[str] = []
    for dim in resolved.dimensions:
        col: Expr = make_dimension_expr(model, dim, dialect)
        builder.select(AliasedExpr(expr=col, alias=dim.name))
        if resolved.grouping is not None:
            grouping_dim_aliases.append(dim.name)

    # SELECT: measures (aggregated) — for metrics, substitute component refs
    settings = model.settings
    measure_exprs: dict[str, Expr] = {}
    # A metric inlines its components' expressions, so a conformed component
    # has to be substituted in its rewritten form - the raw one still names
    # the foreign fact's own table, which the conformed plan does not join.
    metric_components = {
        name: (
            replace(component, expression=conformed_exprs[name])
            if name in conformed_exprs
            else component
        )
        for name, component in resolved.metric_components.items()
    }
    for measure in resolved.measures:
        if measure.component_measures:
            expr: Expr = _substitute_measure_refs(measure.expression, metric_components)
            metric = model.metrics.get(measure.name)
            if metric and dialect:
                resolved_type = resolve_metric_data_type(metric, settings)
                if resolved_type:
                    expr = dialect.cast_to_obml_type(expr, resolved_type)
            builder.select(AliasedExpr(expr=expr, alias=measure.name))
        else:
            expr = conformed_exprs.get(measure.name, measure.expression)
            model_measure = model.effective_measures.get(measure.name)
            if model_measure and dialect:
                expr = cast_measure_to_resolved_type(
                    expr, model_measure, settings, dialect, model
                )
            builder.select(AliasedExpr(expr=expr, alias=measure.name))
        measure_exprs[measure.name] = expr

    # FROM: base fact table
    builder.from_(qualify(base_object), alias=base_alias)

    # Conformed facts join first: one row per shared key, so many-to-one and
    # no fanout onto the anchor's grain.
    for fact in conformed_facts:
        builder.join(
            table=fact.select,
            on=fact.on,
            join_type=conformed_join_type(),
            alias=fact.alias,
        )

    # JOINs: dimension and intermediate tables
    joined = {base_alias}
    for step in resolved.join_steps:
        # Determine which side of the step needs to be joined
        if step.to_object not in joined:
            new_object = step.to_object
        elif step.from_object not in joined:
            new_object = step.from_object
        else:
            continue  # both already joined
        obj = model.data_objects.get(new_object)
        if not obj:
            continue
        emit_join_step(
            builder=builder,
            step=step,
            new_object=new_object,
            obj=obj,
            graph=graph,
            qualify=qualify,
            dialect=dialect,
            warnings=resolved.warnings,
        )
        joined.add(new_object)

    # WHERE
    for wf in resolved.where_filters:
        builder.where(wf.expression)

    # GROUP BY (all dimension columns, with time grain if applicable).
    # Stash the per-dim group-by expression by alias so GROUPING() below
    # can reuse the SAME expression — Postgres rejects GROUPING(<alias>)
    # with "column does not exist" and requires the group-key expression.
    group_by_exprs: dict[str, Expr] = {}
    for dim in resolved.dimensions:
        gb_col: Expr = make_dimension_expr(model, dim, dialect)
        builder.group_by(gb_col)
        group_by_exprs[dim.name] = gb_col

    # GROUPING() flag columns + grouping modifier (rollup/cube)
    if resolved.grouping is not None and grouping_dim_aliases:
        builder.grouping(resolved.grouping.value)
        for alias in grouping_dim_aliases:
            gb_arg = group_by_exprs.get(alias) or ColumnRef(name=alias)
            flag_col = FunctionCall(name="GROUPING", args=[gb_arg])
            builder.select(AliasedExpr(expr=flag_col, alias=_grouping_flag_alias(alias)))

    # HAVING — expand alias references to actual CAST'd aggregate expressions.
    # A predicate on a measure some later wrapper finishes with a window
    # function is left out entirely: at this level only the pre-window
    # aggregate exists, so evaluating it here filters the wrong value.
    # ``PASS_HAVING_WINDOW`` applies those once, over the windowed rows.
    # Withholding them here rather than stripping them per wrapper is what
    # keeps every wrapper composition correct — each one copies or rebuilds
    # ``ast.having`` differently, and any that kept a stale copy would
    # filter pre-window behind the pass's back.
    from orionbelt.compiler.having_hoist import windowed_aliases

    deferred = windowed_aliases(resolved)
    for hf in resolved.having_filters:
        if hf.referenced_fields & deferred:
            continue
        builder.having(_expand_measure_refs(hf.expression, measure_exprs))

    # ORDER BY (use alias for time-grained dimensions)
    grained_cols: dict[tuple[str, str | None], str] = {
        (d.source_column, d.object_name): d.name for d in resolved.dimensions if d.grain
    }
    for expr, desc, nulls in resolved.order_by_exprs:
        if isinstance(expr, ColumnRef) and (expr.name, expr.table) in grained_cols:
            expr = ColumnRef(name=grained_cols[(expr.name, expr.table)])
        builder.order_by(expr, desc=desc, nulls_last=_nulls_last(nulls))

    # LIMIT / OFFSET
    if resolved.limit is not None:
        builder.limit(resolved.limit)
    if resolved.offset is not None:
        builder.offset(resolved.offset)

    return QueryPlan(ast=builder.build())

CFL Planner

orionbelt.compiler.cfl.CFLPlanner

Plans Composite Fact Layer queries: conformed dimensions + fact stitching.

Uses a UNION ALL strategy: 1. Each fact leg SELECTs conformed dimensions + its own measures (NULL for others) 2. UNION ALL combines the legs into a single CTE 3. Outer query aggregates over the union, grouping by conformed dimensions

Source code in src/orionbelt/compiler/cfl.py
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
class CFLPlanner:
    """Plans Composite Fact Layer queries: conformed dimensions + fact stitching.

    Uses a UNION ALL strategy:
    1. Each fact leg SELECTs conformed dimensions + its own measures (NULL for others)
    2. UNION ALL combines the legs into a single CTE
    3. Outer query aggregates over the union, grouping by conformed dimensions
    """

    def plan(
        self,
        resolved: ResolvedQuery,
        model: SemanticModel,
        qualify_table: Callable[[DataObject], str] | None = None,
        union_by_name: bool = False,
        dialect: Dialect | None = None,
    ) -> QueryPlan:
        """Plan a CFL query."""
        self._validate_fanout(resolved, model)

        # dimensionsExclude: EXCEPT-based anti-join pattern
        if resolved.dimensions_exclude:
            return self._plan_dimensions_exclude(resolved, model, qualify_table, dialect)

        # Group measures by their source object
        measures_by_object, cross_fact = self._group_measures_by_object(resolved, model)

        # Dimension-only CFL: no measures but dimensions on independent branches.
        # Create leg groupings from connecting fact tables.
        if not measures_by_object and not cross_fact and resolved.requires_cfl:
            measures_by_object = self._group_dimensions_into_legs(resolved, model)

        # A dimension no leg can reach is projected by none of them, and the
        # union then has no such column for the outer SELECT to group on. Under
        # ``UNION ALL BY NAME`` that is not even a NULL pad - the padding fills
        # a column *some* leg supplies, and this one has no supplier at all - so
        # the query compiled to SQL naming a column that does not exist.
        self._reject_unreachable_dimensions(measures_by_object, resolved, model)

        if len(measures_by_object) <= 1 and not cross_fact:
            # Single fact — delegate to star schema. Resolution let this query
            # past the reachability check because it looked multi-fact, and a
            # star has to serve every dimension from one root, so check now
            # that the leg left standing can.
            from orionbelt.compiler.star import StarSchemaPlanner

            return StarSchemaPlanner().plan(
                resolved, model, qualify_table=qualify_table, dialect=dialect
            )

        # Every multi-column aggregate reads its arguments from one row: a
        # two-column statistic (CORR/COVAR_*/REGR_*) correlates a pair, a
        # multi-column COUNT DISTINCT counts observed tuples. A leg that owns
        # all the arguments carries them as separate columns and the outer
        # query rebuilds the aggregate over them, so a multi-fact query costs
        # such a measure nothing.
        #
        # What none of them survives is having their arguments on data objects
        # no single leg reaches — the definition of ``cross_fact``. UNION ALL
        # stacks facts rather than joining them, so each leg supplies one
        # column and NULL-pads the rest, and no row ever carries a complete
        # set. The statistics then return NULL over zero pairs, and the tuple
        # count concatenates a NULL into every row and returns 0 — a wrong
        # answer rather than a failure, which is the reason to refuse here
        # rather than let it compile.
        #
        # Metric components count: a metric is planned by inlining its
        # components' aggregates, so ``{[Cross Corr]}`` reaches the same
        # rebuild — it just used to arrive there without passing the guard.
        cross_fact_names = {m.name for m in cross_fact} if cross_fact else set()
        for measure in (*resolved.measures, *resolved.metric_components.values()):
            if measure.name in cross_fact_names and self._is_multi_field(measure):
                agg = measure.aggregation.lower() if measure.aggregation else ""
                raise UnsupportedAggregationForCFLError(measure.name, agg)

        # Ordered aggregates now carry their sort key through the union as a
        # column of its own, so the outer re-aggregation can order by it. That
        # only works where the leg owning the measure can actually reach the
        # sort column's object — otherwise the leg has nothing to project, and
        # the aggregate would come back in an arbitrary order. Refuse those.
        #
        # A cross-fact measure has no single owning leg, so an ordering on one
        # is refused outright. Metric components are covered because they are
        # planned into legs like any other measure.
        self._validate_ordered_aggregates(resolved, model, measures_by_object, cross_fact)

        # Multi-fact: UNION ALL strategy
        return self._plan_union_all(
            resolved,
            model,
            measures_by_object,
            cross_fact,
            qualify_table=qualify_table,
            union_by_name=union_by_name,
            dialect=dialect,
        )

    def _validate_ordered_aggregates(
        self,
        resolved: ResolvedQuery,
        model: SemanticModel,
        measures_by_object: dict[str, list[ResolvedMeasure]],
        cross_fact: list[ResolvedMeasure] | None,
    ) -> None:
        """Refuse ordered aggregates whose sort key their own leg cannot reach."""
        graph = JoinGraph(model, use_path_names=resolved.use_path_names or None)
        owner: dict[str, str] = {}
        for obj_name, measures in measures_by_object.items():
            for measure in measures:
                owner[measure.name] = obj_name

        candidates = list(measures_by_object.values())
        if cross_fact:
            candidates.append(cross_fact)
        for measures in candidates:
            for measure in measures:
                item = self._within_group_item(measure)
                if item is None:
                    continue
                sort_objects: set[str] = set()
                cfl_projection.collect_table_refs(item.expr, sort_objects)
                if not sort_objects:
                    continue
                leg_object = owner.get(measure.name)
                reachable: set[str] = (
                    graph.descendants_without_unnest(leg_object) | {leg_object}
                    if leg_object is not None
                    else set()
                )
                unreachable = sort_objects - reachable
                if unreachable:
                    raise WithinGroupNotSupportedInCFLError(measure.name, sorted(unreachable)[0])

    def _validate_fanout(self, resolved: ResolvedQuery, model: SemanticModel) -> None:
        """Validate that grain is compatible and no fanout will occur."""
        errors: list[str] = []

        for dim in resolved.dimensions:
            if dim.object_name not in model.data_objects:
                errors.append(
                    f"Dimension '{dim.name}' references unknown data object '{dim.object_name}'"
                )

        if errors:
            raise FanoutError("; ".join(errors))

    def _group_measures_by_object(
        self,
        resolved: ResolvedQuery,
        model: SemanticModel,
    ) -> tuple[dict[str, list[ResolvedMeasure]], list[ResolvedMeasure]]:
        """Group measures by their primary source object."""
        return cfl_projection.group_measures_by_object(self, resolved, model)

    @staticmethod
    def _reject_unreachable_dimensions(
        measures_by_object: dict[str, list[ResolvedMeasure]],
        resolved: ResolvedQuery,
        model: SemanticModel,
    ) -> None:
        """Refuse a dimension **no** leg can produce.

        A query looks multi-fact while its measures span facts, and resolution
        skips the reachability check on that basis - the union answers it, each
        leg projecting the dimensions it reaches and NULL-padding the rest. That
        only works while some leg reaches it. One that none does is projected by
        none of them, so there is no column in the union for the outer SELECT to
        name, and where the legs collapse to one the star this delegates to
        would project a column from a table it does not select from. The same
        refusal resolution would have raised.

        Reachability is measured without crossing a containment edge: a leg is
        built out of tables and has no unnest to reach a nested object with, nor
        anything sitting behind one.
        """
        roots = set(measures_by_object) or {resolved.base_object}
        graph = JoinGraph(model, use_path_names=resolved.use_path_names or None)
        reachable = {
            name for root in roots for name in (graph.descendants_without_unnest(root) | {root})
        }
        root = sorted(roots)[0]
        unreachable = sorted(
            {dim.object_name for dim in resolved.dimensions if dim.object_name not in reachable}
        )
        if not unreachable:
            return
        raise ResolutionError(
            [
                SemanticError(
                    code="UNREACHABLE_REQUIRED_OBJECT",
                    message=(
                        f"Data object '{name}' is required by the query but cannot be "
                        f"reached from base '{root}' via directed joins. Many-to-one joins "
                        f"are forward-only; reverse traversal would inflate row counts. Add "
                        f"an explicit join from '{root}' (or an intermediate object) to "
                        f"'{name}', or split the query so each fact is queried "
                        f"independently."
                    ),
                    path="select",
                )
                for name in unreachable
            ]
        )

    @staticmethod
    def _group_dimensions_into_legs(
        resolved: ResolvedQuery,
        model: SemanticModel,
    ) -> dict[str, list[ResolvedMeasure]]:
        """Group dimensions into CFL legs for dimension-only queries."""
        return cfl_projection.group_dimensions_into_legs(resolved, model)

    @staticmethod
    def _is_multi_field(measure: ResolvedMeasure) -> bool:
        """Check if a measure has multiple field args (e.g. COUNT(a, b))."""
        return cfl_projection.is_multi_field(measure)

    @staticmethod
    def _resolve_union_alignment_type(
        measure: ResolvedMeasure,
        model: SemanticModel,
        dialect: Dialect | None = None,
    ) -> str | None:
        """The type every UNION leg agrees on for *measure*'s column."""
        return cfl_projection.resolve_union_alignment_type(measure, model, dialect)

    def _resolve_owning_leg_cast_type(
        self,
        measure: ResolvedMeasure,
        model: SemanticModel,
        dialect: Dialect | None = None,
    ) -> str | None:
        return cfl_projection.resolve_owning_leg_cast_type(measure, model, dialect)

    @staticmethod
    def _resolve_null_type_for_field(
        measure: ResolvedMeasure,
        field_idx: int,
        model: SemanticModel,
        dialect: Dialect | None = None,
    ) -> str | None:
        """Resolve the SQL type for NULL padding in CFL UNION ALL legs."""
        return cfl_projection.resolve_null_type_for_field(measure, field_idx, model, dialect)

    @staticmethod
    def _unwrap_aggregation(measure: ResolvedMeasure) -> Expr:
        """Extract the inner expression from an aggregated measure."""
        return cfl_projection.unwrap_aggregation(measure)

    def _build_outer_metric_expr(
        self,
        metric: ResolvedMeasure,
        resolved: ResolvedQuery,
        cte_name: str,
    ) -> Expr:
        """Build the outer query expression for a metric."""
        return cfl_projection.build_outer_metric_expr(self, metric, resolved, cte_name)

    def _substitute_outer_refs(self, expr: Expr, resolved: ResolvedQuery, cte_name: str) -> Expr:
        """Recursively substitute measure refs with outer aggregations."""
        return cfl_projection.substitute_outer_refs(self, expr, resolved, cte_name)

    @staticmethod
    def _collect_table_refs(expr: Expr, tables: set[str]) -> None:
        """Recursively collect table names from ColumnRef nodes."""
        cfl_projection.collect_table_refs(expr, tables)

    @staticmethod
    def _leg_projects_argument(
        measure: ResolvedMeasure,
        arg: Expr,
        obj_name: str,
        this_measure_names: set[str],
    ) -> bool:
        """Whether this leg supplies *arg* of a multi-field measure, or NULL-pads it.

        A leg that **owns** the measure projects every argument, full stop.
        Grouping already put the measure here because one root reaches all the
        objects its arguments read (``_single_leg_root``), and this leg is that
        root, so a joined column (``corr(Returns.Qty, Calendar.Month)``), a
        computed column expanding to one, and a computed column that reads no
        column at all (``One: {expression: '1'}``) are each as projectable here
        as a bare own-table reference. Nothing else projects them, so any test
        this applies can only take an argument away from the one leg that could
        have supplied it.

        Two narrower rules were tried and both lost arguments this way. Matching
        a bare ``ColumnRef`` on this exact object dropped joined and computed
        columns; also demanding the argument reference *some* table dropped
        constant expressions, whose reference set is empty. In both cases the
        owning leg NULL-padded its own measure's argument, so the tuple count
        counted a column of NULLs and returned 0, and a two-column statistic -
        NULL unless every argument is present - returned NULL, on the dialects
        that pad explicitly; the ones using ``UNION ALL BY NAME`` failed to bind
        instead. A wrong number is the worse half of that.

        A **cross-fact** measure is the other case: no single leg reaches all its
        arguments, so each leg takes the ones rooted in its own fact and the rest
        are padded. A conformed dimension is reachable from every leg, so the
        stricter own-object rule is what keeps two legs from both claiming it.
        """
        if measure.name in this_measure_names:
            return True
        return isinstance(arg, ColumnRef) and arg.table == obj_name

    @staticmethod
    def _within_group_item(measure: ResolvedMeasure) -> OrderByItem | None:
        """The sort key a leg must carry, or ``None`` if it need not carry one."""
        return cfl_projection.within_group_item(measure)

    @staticmethod
    def _remap_cfl_order_by(expr: Expr, resolved: ResolvedQuery, model: SemanticModel) -> Expr:
        """Remap ORDER BY expressions to use CTE aliases for the outer query."""
        return cfl_projection.remap_cfl_order_by(expr, resolved, model)

    def _plan_union_all(
        self,
        resolved: ResolvedQuery,
        model: SemanticModel,
        measures_by_object: dict[str, list[ResolvedMeasure]],
        cross_fact: list[ResolvedMeasure] | None = None,
        qualify_table: Callable[[DataObject], str] | None = None,
        union_by_name: bool = False,
        dialect: Dialect | None = None,
    ) -> QueryPlan:
        """UNION ALL strategy: stack fact legs with NULL padding, aggregate outside.

        When *union_by_name* is True (DuckDB, Snowflake) each leg only emits
        the columns it actually has — the database fills missing columns with
        NULL automatically via ``UNION ALL BY NAME``.
        """
        graph = JoinGraph(model, use_path_names=resolved.use_path_names or None)

        def qualify(obj: DataObject) -> str:
            return qualify_table(obj) if qualify_table else obj.qualified_code

        # Internal composite columns (multi-field arguments, ordered-aggregate
        # sort keys), allocated once so the legs that project them, the legs
        # that NULL-pad them and the outer re-aggregation all agree — and so
        # none of them shadows a column the composite already carries under a
        # user-facing name.
        aliases = cfl_projection.composite_aliases(resolved)

        # Anchored measures are conformed the same way the star planner does
        # it, but the subqueries are joined inside the leg that owns the
        # measure rather than into one shared FROM.
        conformed_facts, conformed_exprs = plan_conformed_facts(resolved, model, qualify)
        facts_by_measure: dict[str, list[ConformedFact]] = {}
        for fact in conformed_facts:
            facts_by_measure.setdefault(fact.measure_name, []).append(fact)

        # Collect all measures across all objects + cross-fact measures
        all_measures: list[ResolvedMeasure] = []
        for measures in measures_by_object.values():
            all_measures.extend(measures)
        if cross_fact:
            all_measures.extend(cross_fact)

        # Collect data objects referenced by WHERE filters — each leg
        # must join these tables so the filter predicates are valid.
        filter_objects: set[str] = set()
        for wf in resolved.where_filters:
            self._collect_table_refs(wf.expression, filter_objects)
            # An EXISTS body correlates to an outer table, which the walk above
            # cannot see: the body is a Select, not an expression. Each leg
            # emits that body in its own WHERE, so each leg has to join it.
            cfl_projection.collect_correlated_tables(wf.expression, filter_objects)

        # Build one SELECT per fact object group.
        # Each leg computes its own LCA (least common ancestor) as the lead
        # table — the graph-central node that can reach all dimension objects
        # and the measure's source object with minimal hops.
        union_legs: list[Select] = []
        leg_infos: list[CflLegInfo] = []
        dedup_offenders: dict[str, str] = {}
        for obj_name, measures in measures_by_object.items():
            leg_builder = QueryBuilder()
            this_measure_names = {m.name for m in measures}

            # Compute reachability from this leg's fact object upfront.
            # Deliberately not ``descendants``: a leg is a star built out of
            # tables and cannot carry an unnest, so a nested object and anything
            # behind one are out of its reach however ordinary their own joins.
            reachable = graph.descendants_without_unnest(obj_name) | {obj_name}

            # Collect table references from this leg's own-measure
            # expressions. A measure like ``Electronics Sales`` is
            # defined as ``SUM(CASE WHEN Products.productcat = …
            # THEN Sales.salesamount END)`` — the CASE condition
            # references Products, which must be joined into this
            # leg's FROM. Without this, the generated SQL emits
            # ``"Products"."productcat"`` against a FROM clause that
            # only has Sales + Clients, and the database raises
            # "missing FROM-clause entry for table Products".
            measure_expr_objects: set[str] = set()
            for m in measures:
                self._collect_table_refs(m.expression, measure_expr_objects)
            # A conformed fact is reached by a GROUP BY subquery joined below,
            # not by a join from this leg's lead, so it must not become a join
            # requirement: doing so would join the raw fact and fan the leg out.
            for m in measures:
                for fact in facts_by_measure.get(m.name, ()):
                    measure_expr_objects.discard(fact.object_name)
            if cross_fact:
                for m in cross_fact:
                    if m.name in this_measure_names:
                        self._collect_table_refs(m.expression, measure_expr_objects)

            # A leg's FROM is its *lead*, not its key: the common root of the
            # key and what that key reaches. Where the key is a measure's source
            # on the one side of a join - ``Products``, reaching nothing - the
            # lead is the ``Sales`` that reaches both, and dimensions the lead
            # can produce were being NULL-padded on the grounds that the key
            # could not. Every row of the leg then collapsed into one NULL
            # group. Widen the reachability to the lead where a lead covering
            # the query's dimensions exists at all; where none does, the facts
            # really are independent and the padding below is right.
            wanted = (
                {dim.object_name for dim in resolved.dimensions}
                | {obj_name}
                | filter_objects
                | measure_expr_objects
            )
            wide_lead = graph.find_common_root(wanted)
            wide_reach = (
                graph.descendants_without_unnest(wide_lead) | {wide_lead} if wide_lead else set()
            )
            if wide_lead and obj_name in wide_reach:
                reachable = wide_reach

            # SELECT conformed dimensions — only emit real column refs for
            # dimensions reachable from this leg's fact AND whose `via:`
            # waypoint (if any) is also reachable from this leg's fact.
            # Role-playing dimensions tied to a different fact via `via:`
            # are NULL-padded so each leg only projects the values that
            # belong to its own fact.
            for dim in resolved.dimensions:
                via_ok = dim.via is None or dim.via in reachable
                if dim.object_name in reachable and via_ok:
                    col: Expr = make_dimension_expr(model, dim, dialect)
                    leg_builder.select(AliasedExpr(expr=col, alias=dim.name))
                elif not union_by_name:
                    model_dim = model.dimensions.get(dim.name)
                    dim_type = model_dim.result_type.value if model_dim else None
                    col = Cast(Literal.null(), type_name=dim_type) if dim_type else Literal.null()
                    leg_builder.select(AliasedExpr(expr=col, alias=dim.name))

            # SELECT this fact's measures (raw expressions, no aggregation).
            # When union_by_name is True, skip NULL padding for other facts'
            # measures — the database fills them automatically.
            for m in all_measures:
                if self._is_multi_field(m):
                    # The aggregate, not the expression: a declared default
                    # wraps it in a COALESCE whose second argument is the
                    # default itself, which is not one of the aggregate's.
                    assert isinstance(m.aggregate, FunctionCall)
                    for i, arg in enumerate(m.aggregate.args):
                        alias = aliases.multi_field[m.name][i]
                        if self._leg_projects_argument(m, arg, obj_name, this_measure_names):
                            leg_builder.select(AliasedExpr(expr=arg, alias=alias))
                        elif not union_by_name:
                            null_type = self._resolve_null_type_for_field(m, i, model)
                            null_expr: Expr = (
                                Cast(Literal.null(), type_name=null_type)
                                if null_type
                                else Literal.null()
                            )
                            leg_builder.select(AliasedExpr(expr=null_expr, alias=alias))
                elif m.name in this_measure_names:
                    own_expr: Expr = self._unwrap_aggregation(
                        replace(m, expression=conformed_exprs[m.name])
                        if m.name in conformed_exprs
                        else m
                    )
                    # Whether this leg casts the measure it owns belongs to
                    # ``resolve_owning_leg_cast_type``, which states the rule
                    # and the measurements behind it. Deliberately not restated
                    # here: this spot carried a second copy, it went stale when
                    # #313 changed the rule, and the copy still read as
                    # authoritative while ClickHouse could not run a CFL query
                    # at all (#339). One statement, in the function that
                    # decides.
                    own_type_name = self._resolve_owning_leg_cast_type(m, model, dialect)
                    if own_type_name:
                        own_expr = Cast(expr=own_expr, type_name=own_type_name)
                    leg_builder.select(AliasedExpr(expr=own_expr, alias=m.name))
                    # An ordered aggregate's sort key rides along as its own
                    # column so the outer re-aggregation can order by it.
                    wg_item = self._within_group_item(m)
                    if wg_item is not None:
                        leg_builder.select(
                            AliasedExpr(expr=wg_item.expr, alias=aliases.within_group[m.name])
                        )
                elif not union_by_name:
                    model_measure = model.measures.get(m.name)
                    null_type_name = self._resolve_union_alignment_type(m, model, dialect)
                    if null_type_name is None and model_measure:
                        null_type_name = model_measure.result_type.value
                    null_expr = (
                        Cast(Literal.null(), type_name=null_type_name)
                        if null_type_name
                        else Literal.null()
                    )
                    leg_builder.select(AliasedExpr(expr=null_expr, alias=m.name))
                    # Pad the sort-key column too, so every leg agrees on the
                    # union's column list.
                    if self._within_group_item(m) is not None:
                        leg_builder.select(
                            AliasedExpr(expr=Literal.null(), alias=aliases.within_group[m.name])
                        )

            # Determine the common root for this leg:
            # the deepest directed ancestor that can reach all dimension
            # objects, measure's source object, filter-referenced objects,
            # and any objects referenced by this leg's measure expressions.
            # Only include dimensions reachable from this leg's fact object.
            leg_required = {
                dim.object_name for dim in resolved.dimensions if dim.object_name in reachable
            }
            leg_required.add(obj_name)
            # Only filter objects this leg can actually reach. A nested one it
            # never can - the leg has no unnest to reach it with - and a static
            # model filter naming one is documented as skipped rather than
            # fatal, which is what dropping it here delivers: the applicability
            # check below then leaves the predicate out, instead of
            # ``build_join_condition`` raising on a step with no columns.
            leg_required.update(filter_objects & reachable)
            # Include objects referenced by measure expressions, but only
            # those reachable from this leg's fact — cross-fact filter
            # tables would otherwise pull unrelated facts into the leg.
            leg_required.update(measure_expr_objects & reachable)
            lead = graph.find_common_root(leg_required)
            lead_obj = model.data_objects.get(lead)

            # FROM: the lead (LCA) table
            if lead_obj:
                leg_builder.from_(qualify(lead_obj), alias=lead)

            # Conformed facts for the anchored measures this leg owns: one row
            # per shared key, so many-to-one and no fanout onto the leg's grain.
            for m in measures:
                for fact in facts_by_measure.get(m.name, ()):
                    leg_builder.join(
                        table=fact.select,
                        on=fact.on,
                        join_type=conformed_join_type(),
                        alias=fact.alias,
                    )

            # JOINs: all required objects reachable from the lead
            join_targets = leg_required - {lead}
            steps: list[JoinStep] = []
            if join_targets:
                steps = graph.find_join_path(
                    {lead},
                    leg_required,
                    via_constraints=resolved.via_constraints or None,
                )
                # Dedupe by alias so a dim reachable through multiple
                # paths within one leg emits only one JOIN — postgres
                # rejects "table specified more than once" when two
                # role-played dims resolve to the same target object.
                joined_aliases: set[str] = {lead}
                for step in steps:
                    if step.to_object in joined_aliases:
                        continue
                    target_object = model.data_objects.get(step.to_object)
                    if target_object:
                        on_expr = graph.build_join_condition(step)
                        leg_builder.join(
                            table=qualify(target_object),
                            on=on_expr,
                            join_type=step.join_type,
                            alias=step.to_object,
                        )
                        joined_aliases.add(step.to_object)

            # A measure sourced from an object this leg's own joins replicate
            # is summed once per row of the many side. Resolution cannot see
            # that: its join steps are the base object's, and the step that
            # replicates lives inside a leg. The union has no per-leg grain to
            # deduplicate at either - the legs project the values to aggregate
            # rather than aggregating them - so this is refused rather than
            # answered with a plausible number in the right group.
            leg_dedup = detect_dedup_measures(
                replace(resolved, join_steps=steps, base_object=lead, measures=measures),
                model,
            )
            dedup_offenders.update(leg_dedup.measures)
            dedup_offenders.update(leg_dedup.components)

            # Capture leg info for explain
            leg_join_strs = (
                [f"{s.from_object}{s.to_object}" for s in steps] if join_targets else []
            )
            if lead == obj_name:
                leg_reason = (
                    f'"{lead}" is the measure source — '
                    f"all required dimension objects are reachable from it"
                )
            else:
                leg_reason = (
                    f'"{lead}" is the deepest common root that can reach '
                    f'measure source "{obj_name}" and all reachable dimension objects'
                )
            leg_infos.append(
                CflLegInfo(
                    measure_source=obj_name,
                    common_root=lead,
                    reason=leg_reason,
                    measures=[m.name for m in measures],
                    joins=leg_join_strs,
                )
            )

            # Apply WHERE filters to each leg
            for wf in resolved.where_filters:
                leg_builder.where(wf.expression)

            union_legs.append(leg_builder.build())

        if dedup_offenders:
            listed = ", ".join(f"'{name}'" for name in sorted(dedup_offenders))
            raise ResolutionError(
                [
                    SemanticError(
                        code="INCOMPATIBLE_COMBINATION",
                        message=(
                            f"Measure(s) {listed} are sourced from an object whose rows this "
                            f"query's joins replicate, so they must be aggregated over "
                            f"deduplicated rows. This query spans facts that cannot be "
                            f"joined, so it is planned as a UNION ALL whose legs project the "
                            f"values to aggregate rather than aggregating them, leaving no "
                            f"per-leg grain to deduplicate at."
                        ),
                        path="select.measures",
                        hint=(
                            "Query the measure without the measures from the other fact, or "
                            "set allowFanOut: true to aggregate the duplicated rows as-is."
                        ),
                        context={"measures": sorted(dedup_offenders)},
                    )
                ]
            )

        # Create the UNION ALL CTE
        cte_name = "composite_01"
        union_cte = CTE(name=cte_name, query=UnionAll(queries=union_legs))
        # All ColumnRefs that resolve to raw CTE columns inside outer-query
        # aggregate functions are qualified with *cte_name*. ClickHouse otherwise
        # resolves bare identifiers to sibling SELECT aliases first — when those
        # aliases are themselves aggregates (the case for measures and metrics
        # in the outer SELECT), it rejects the resulting nested aggregate as
        # ``ILLEGAL_AGGREGATION``. The qualification is harmless on dialects
        # that resolve column-first.

        # Build outer query: aggregate over the composite CTE
        outer_builder = QueryBuilder()

        # SELECT dimensions.  Coalesce groups emit COALESCE(d1, d2, ...) once
        # under the alias; plain dims keep their original column reference.
        emitted_coalesce_aliases: set[str] = set()
        coalesce_groups: dict[str, list[str]] = {}
        for d in resolved.dimensions:
            if d.coalesce_alias:
                coalesce_groups.setdefault(d.coalesce_alias, []).append(d.name)
        for dim in resolved.dimensions:
            if dim.coalesce_alias:
                if dim.coalesce_alias in emitted_coalesce_aliases:
                    continue
                emitted_coalesce_aliases.add(dim.coalesce_alias)
                outer_builder.select(
                    AliasedExpr(
                        expr=FunctionCall(
                            name="COALESCE",
                            args=[
                                ColumnRef(name=member)
                                for member in coalesce_groups[dim.coalesce_alias]
                            ],
                        ),
                        alias=dim.coalesce_alias,
                    )
                )
            else:
                outer_builder.select(
                    AliasedExpr(
                        expr=ColumnRef(name=dim.name),
                        alias=dim.name,
                    )
                )

        # SELECT aggregated measures and metrics
        # First, aggregate every measure from the UNION ALL legs. This
        # includes component measures pulled in only to feed a metric
        # (e.g. Total Returns / Total Purchases behind Return Rate /
        # Gross Margin). We still compute their aggregate expression and
        # record it in ``outer_measure_exprs`` so HAVING can reference any
        # measure, but we only PROJECT the measures the caller actually
        # requested — otherwise the result carries extra columns the
        # consumer never asked for, which Postgres-federation clients
        # (Dremio) reject as an unexpected dataset shape.
        settings = model.settings
        requested_measure_names = {rm.name for rm in resolved.measures}
        seen_measure_names: set[str] = set()
        outer_measure_exprs: dict[str, Expr] = {}
        for m in all_measures:
            seen_measure_names.add(m.name)
            # Shared with the metric projection so the two cannot drift: this
            # picks the rebuild that matches how the legs projected the measure
            # (concatenated argument columns, or its own single column) and
            # reapplies DISTINCT, the LISTAGG separator and any withinGroup
            # ordering over the sort key the legs carried.
            agg_expr: Expr = cfl_projection.build_outer_measure_expr(m, cte_name, aliases)
            # Apply CAST for resolved data_type (effective_measures so
            # multi-fact synthesized counts get the same integer CAST as
            # declared count measures).
            model_measure = model.effective_measures.get(m.name)
            if model_measure and dialect:
                # Same path as the star planner. Here the argument is the union
                # column rather than the source, which is still the right thing
                # to average: the legs project pre-aggregation rows.
                agg_expr = cast_measure_to_resolved_type(
                    agg_expr, model_measure, settings, dialect, model
                )
            if m.name in requested_measure_names:
                outer_builder.select(AliasedExpr(expr=agg_expr, alias=m.name))
            outer_measure_exprs[m.name] = agg_expr

        # Then, add metric expressions that combine component measures
        for m in resolved.measures:
            if m.component_measures and m.name not in seen_measure_names:
                metric_expr: Expr = self._build_outer_metric_expr(m, resolved, cte_name)
                metric = model.metrics.get(m.name)
                if metric and dialect:
                    resolved_type = resolve_metric_data_type(metric, settings)
                    if resolved_type:
                        metric_expr = dialect.cast_to_obml_type(metric_expr, resolved_type)
                outer_builder.select(AliasedExpr(expr=metric_expr, alias=m.name))
                outer_measure_exprs[m.name] = metric_expr

        # Recorded for the wrappers that run after planning. Each of them
        # re-projects some measure's aggregate into a CTE of its own, and every
        # such CTE selects from the composite below - where the fact tables the
        # resolved expressions name are not in scope, so rebuilding from those
        # produces SQL that does not bind.
        resolved.projected_expressions = dict(outer_measure_exprs)
        resolved.composite_cte = cte_name

        outer_builder.from_(cte_name, alias=cte_name)

        # GROUP BY dimensions.  Coalesce groups group by the COALESCE expression
        # itself (most dialects accept either the alias or the expression; the
        # expression is portable across all eight supported dialects).
        grouped_coalesce_aliases: set[str] = set()
        for dim in resolved.dimensions:
            if dim.coalesce_alias:
                if dim.coalesce_alias in grouped_coalesce_aliases:
                    continue
                grouped_coalesce_aliases.add(dim.coalesce_alias)
                outer_builder.group_by(
                    FunctionCall(
                        name="COALESCE",
                        args=[
                            ColumnRef(name=member) for member in coalesce_groups[dim.coalesce_alias]
                        ],
                    )
                )
            else:
                outer_builder.group_by(ColumnRef(name=dim.name))

        # GROUPING() flag columns + grouping modifier (rollup/cube) — outer query only
        # so subtotal rows compose correctly over the unioned facts (the
        # individual UNION ALL legs stay at detail grain).
        if resolved.grouping is not None and resolved.dimensions:
            outer_builder.grouping(resolved.grouping.value)
            flag_aliases: list[str] = []
            for dim in resolved.dimensions:
                alias_name = dim.coalesce_alias or dim.name
                if alias_name in flag_aliases:
                    continue
                flag_aliases.append(alias_name)
            for alias in flag_aliases:
                flag_col = FunctionCall(name="GROUPING", args=[ColumnRef(name=alias)])
                outer_builder.select(AliasedExpr(expr=flag_col, alias=_grouping_flag_alias(alias)))

        # HAVING — expand alias references to actual CAST'd aggregate expressions.
        # A predicate on a measure a later wrapper finishes with a window
        # function is withheld, exactly as ``star.py`` withholds it: only the
        # pre-window aggregate exists here, so evaluating it would filter the
        # wrong value, and ``PASS_HAVING_WINDOW`` applies it over the windowed
        # rows instead. CFL is picked by the planner before any pass runs, so
        # the window pass lands on ``composite_01`` just as it lands on a
        # wrapper's CTE - this is the multi-fact half of the same rule.
        from orionbelt.compiler.having_hoist import windowed_aliases

        deferred = windowed_aliases(resolved)
        for hf in resolved.having_filters:
            if hf.referenced_fields & deferred:
                continue
            outer_builder.having(_expand_cfl_measure_refs(hf.expression, outer_measure_exprs))

        # ORDER BY and LIMIT — remap to CTE aliases
        for expr, desc, nulls in resolved.order_by_exprs:
            outer_builder.order_by(
                self._remap_cfl_order_by(expr, resolved, model),
                desc=desc,
                nulls_last=_nulls_last(nulls),
            )
        if resolved.limit is not None:
            outer_builder.limit(resolved.limit)
        if resolved.offset is not None:
            outer_builder.offset(resolved.offset)

        outer_select = outer_builder.build()

        # Attach CTE
        final = Select(
            columns=outer_select.columns,
            from_=outer_select.from_,
            joins=outer_select.joins,
            where=outer_select.where,
            group_by=outer_select.group_by,
            having=outer_select.having,
            order_by=outer_select.order_by,
            limit=outer_select.limit,
            offset=outer_select.offset,
            ctes=[union_cte],
            grouping=outer_select.grouping,
        )

        return QueryPlan(ast=final, cfl_legs=leg_infos)

    # -- dimensionsExclude: EXCEPT-based anti-join ----------------------------

    def _plan_dimensions_exclude(
        self,
        resolved: ResolvedQuery,
        model: SemanticModel,
        qualify_table: Callable[[DataObject], str] | None = None,
        dialect: Dialect | None = None,
    ) -> QueryPlan:
        """Plan a dimensionsExclude query using EXCEPT pattern."""
        return cfl_exclude.plan_dimensions_exclude(self, resolved, model, qualify_table, dialect)

    @staticmethod
    def _partition_dimensions(
        resolved: ResolvedQuery,
        graph: JoinGraph,
    ) -> list[list[ResolvedDimension]]:
        """Partition dimensions into groups on independent branches."""
        return cfl_exclude.partition_dimensions(resolved, graph)

    @staticmethod
    def _build_group_distinct_select(
        dims: list[ResolvedDimension],
        model: SemanticModel,
        graph: JoinGraph,
        qualify: Callable[[DataObject], str],
        via_constraints: dict[str, str] | None = None,
        dialect: Dialect | None = None,
    ) -> Select:
        """Build SELECT DISTINCT (via GROUP BY) for a group of dimensions."""
        return cfl_exclude.build_group_distinct_select(
            dims, model, graph, qualify, via_constraints=via_constraints, dialect=dialect
        )

    def _build_existing_pairs_select(
        self,
        resolved: ResolvedQuery,
        model: SemanticModel,
        graph: JoinGraph,
        qualify: Callable[[DataObject], str],
        dialect: Dialect | None = None,
    ) -> Select:
        """Build SELECT for existing dimension combinations via fact-table joins."""
        return cfl_exclude.build_existing_pairs_select(
            self, resolved, model, graph, qualify, dialect
        )

plan(resolved, model, qualify_table=None, union_by_name=False, dialect=None)

Plan a CFL query.

Source code in src/orionbelt/compiler/cfl.py
def plan(
    self,
    resolved: ResolvedQuery,
    model: SemanticModel,
    qualify_table: Callable[[DataObject], str] | None = None,
    union_by_name: bool = False,
    dialect: Dialect | None = None,
) -> QueryPlan:
    """Plan a CFL query."""
    self._validate_fanout(resolved, model)

    # dimensionsExclude: EXCEPT-based anti-join pattern
    if resolved.dimensions_exclude:
        return self._plan_dimensions_exclude(resolved, model, qualify_table, dialect)

    # Group measures by their source object
    measures_by_object, cross_fact = self._group_measures_by_object(resolved, model)

    # Dimension-only CFL: no measures but dimensions on independent branches.
    # Create leg groupings from connecting fact tables.
    if not measures_by_object and not cross_fact and resolved.requires_cfl:
        measures_by_object = self._group_dimensions_into_legs(resolved, model)

    # A dimension no leg can reach is projected by none of them, and the
    # union then has no such column for the outer SELECT to group on. Under
    # ``UNION ALL BY NAME`` that is not even a NULL pad - the padding fills
    # a column *some* leg supplies, and this one has no supplier at all - so
    # the query compiled to SQL naming a column that does not exist.
    self._reject_unreachable_dimensions(measures_by_object, resolved, model)

    if len(measures_by_object) <= 1 and not cross_fact:
        # Single fact — delegate to star schema. Resolution let this query
        # past the reachability check because it looked multi-fact, and a
        # star has to serve every dimension from one root, so check now
        # that the leg left standing can.
        from orionbelt.compiler.star import StarSchemaPlanner

        return StarSchemaPlanner().plan(
            resolved, model, qualify_table=qualify_table, dialect=dialect
        )

    # Every multi-column aggregate reads its arguments from one row: a
    # two-column statistic (CORR/COVAR_*/REGR_*) correlates a pair, a
    # multi-column COUNT DISTINCT counts observed tuples. A leg that owns
    # all the arguments carries them as separate columns and the outer
    # query rebuilds the aggregate over them, so a multi-fact query costs
    # such a measure nothing.
    #
    # What none of them survives is having their arguments on data objects
    # no single leg reaches — the definition of ``cross_fact``. UNION ALL
    # stacks facts rather than joining them, so each leg supplies one
    # column and NULL-pads the rest, and no row ever carries a complete
    # set. The statistics then return NULL over zero pairs, and the tuple
    # count concatenates a NULL into every row and returns 0 — a wrong
    # answer rather than a failure, which is the reason to refuse here
    # rather than let it compile.
    #
    # Metric components count: a metric is planned by inlining its
    # components' aggregates, so ``{[Cross Corr]}`` reaches the same
    # rebuild — it just used to arrive there without passing the guard.
    cross_fact_names = {m.name for m in cross_fact} if cross_fact else set()
    for measure in (*resolved.measures, *resolved.metric_components.values()):
        if measure.name in cross_fact_names and self._is_multi_field(measure):
            agg = measure.aggregation.lower() if measure.aggregation else ""
            raise UnsupportedAggregationForCFLError(measure.name, agg)

    # Ordered aggregates now carry their sort key through the union as a
    # column of its own, so the outer re-aggregation can order by it. That
    # only works where the leg owning the measure can actually reach the
    # sort column's object — otherwise the leg has nothing to project, and
    # the aggregate would come back in an arbitrary order. Refuse those.
    #
    # A cross-fact measure has no single owning leg, so an ordering on one
    # is refused outright. Metric components are covered because they are
    # planned into legs like any other measure.
    self._validate_ordered_aggregates(resolved, model, measures_by_object, cross_fact)

    # Multi-fact: UNION ALL strategy
    return self._plan_union_all(
        resolved,
        model,
        measures_by_object,
        cross_fact,
        qualify_table=qualify_table,
        union_by_name=union_by_name,
        dialect=dialect,
    )

Join Graph

orionbelt.compiler.graph.JoinGraph

Graph of data objects (nodes) and relationships (edges) for join path resolution.

Source code in src/orionbelt/compiler/graph.py
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
class JoinGraph:
    """Graph of data objects (nodes) and relationships (edges) for join path resolution."""

    def __init__(
        self,
        model: SemanticModel,
        use_path_names: list[UsePathName] | None = None,
    ) -> None:
        self._graph: nx.Graph[str] = nx.Graph()
        self._directed: nx.DiGraph[str] = nx.DiGraph()
        # Path-finding graph: many-to-one is forward-only (would cause fanout
        # in reverse); one-to-one and many-to-many are bidirectional.
        self._traversable: nx.DiGraph[str] = nx.DiGraph()
        self._model = model
        self._build(model, use_path_names)

    def _build(
        self,
        model: SemanticModel,
        use_path_names: list[UsePathName] | None = None,
    ) -> None:
        """Build the graph from the semantic model.

        Secondary joins are only included when their pathName is requested
        via *use_path_names*.  When a secondary override is active for a
        ``(source, target)`` pair, the primary join for that pair is excluded.
        """
        for name in model.data_objects:
            self._graph.add_node(name)
            self._directed.add_node(name)
            self._traversable.add_node(name)

        active_overrides = path_overrides(use_path_names)

        for obj_name, obj in model.data_objects.items():
            for join in obj.joins:
                if join.join_to not in model.data_objects:
                    continue
                # A nested object's declared join to its own parent is the
                # ``code`` fallback's join, not a second route: containment
                # already connects the two, and adding both would put a cycle
                # between them. Its columns are folded onto the nested edge
                # below, which is where the fallback reads them from.
                if obj.nested_in is not None and join.join_to == obj.nested_in.data_object:
                    continue
                pair = (obj_name, join.join_to)

                if join.secondary:
                    # Only include if this secondary join's pathName is active
                    if pair in active_overrides and active_overrides[pair] == join.path_name:
                        self._add_edge(obj_name, join)
                else:
                    # Primary join: skip if an active override exists for this pair
                    if pair not in active_overrides:
                        self._add_edge(obj_name, join)

        for obj_name, obj in model.data_objects.items():
            if obj.nested_in is not None and obj.nested_in.data_object in model.data_objects:
                self._add_nested_edge(obj_name, obj)

    def _add_edge(self, obj_name: str, join: object) -> None:
        """Add an edge to the undirected, directed, and traversable graphs.

        The traversable graph is used by :meth:`find_join_path` to enforce
        the rule "many-to-one is never bidirectional": walking such a join
        backwards would multiply rows of the source table, so only forward
        traversal is allowed.  One-to-one and many-to-many joins remain
        bidirectional in the traversable graph.
        """
        from orionbelt.models.semantic import DataObjectJoin

        assert isinstance(join, DataObjectJoin)
        self._graph.add_edge(
            obj_name,
            join.join_to,
            columns_from=join.columns_from,
            columns_to=join.columns_to,
            cardinality=join.join_type,
            source_object=obj_name,
            required=join.required,
        )
        self._directed.add_edge(
            obj_name,
            join.join_to,
            columns_from=join.columns_from,
            columns_to=join.columns_to,
            cardinality=join.join_type,
        )
        self._traversable.add_edge(obj_name, join.join_to)
        if join.join_type != Cardinality.MANY_TO_ONE:
            # Safe to walk backwards: row count is preserved.
            self._traversable.add_edge(join.join_to, obj_name)

    def _add_nested_edge(self, obj_name: str, obj: DataObject) -> None:
        """Add the edge a ``nestedIn`` object declares by containment.

        Oriented **parent to child**, which is the opposite of how the object
        reads: the child is the many side, but only the parent can put it in
        scope, so the parent is what the walk starts from and what
        :meth:`find_common_root` has to answer. Traversal is one-way for the
        same reason - there is nothing to reach by leaving a nested object that
        its parent does not already reach.

        The edge is many-to-one *declared child to parent*, so walking it in the
        direction stored here multiplies the parent's rows. That is exactly what
        an unnest does, and ``nested`` is what tells fanout detection and the
        planner so, since neither the cardinality nor ``reversed`` can say it:
        the multiplication comes out of the FROM clause rather than a predicate.

        ``columns_from`` / ``columns_to`` are the *fallback* join's, oriented
        parent-first to match the edge. They are empty unless the object also
        declares ``code`` and a join to its parent, and are read only where the
        dialect cannot unnest.
        """
        source = obj.nested_in
        if source is None:
            return
        parent = source.data_object
        fallback = next((j for j in obj.joins if j.join_to == parent), None)
        columns_from = list(fallback.columns_to) if fallback else []
        columns_to = list(fallback.columns_from) if fallback else []
        self._graph.add_edge(
            parent,
            obj_name,
            columns_from=columns_from,
            columns_to=columns_to,
            cardinality=Cardinality.MANY_TO_ONE,
            source_object=parent,
            # An empty array keeps its parent row, which is a LEFT join: a
            # charge carrying no labels still contributes its cost to an
            # unfiltered total, and 61% of the rows in a real billing export
            # carry none.
            required=False,
            nested=True,
        )
        self._directed.add_edge(
            parent,
            obj_name,
            columns_from=columns_from,
            columns_to=columns_to,
            cardinality=Cardinality.MANY_TO_ONE,
            nested=True,
        )
        self._traversable.add_edge(parent, obj_name)

    def _unnest_root(self, name: str) -> str:
        """The nearest ancestor of *name* a FROM clause can name.

        Delegates to the model, which is where the same question is asked from
        query resolution - a nested object must not be picked as a base object
        either, and the two answers have to be the same one.
        """
        return self._model.unnest_root(name)

    def descendants(self, node: str) -> set[str]:
        """Return all nodes reachable from *node* via directed join paths."""
        if node not in self._directed:
            return set()
        return nx.descendants(self._directed, node)

    def descendants_without_unnest(self, node: str) -> set[str]:
        """Reachable from *node* without crossing a containment edge.

        What a plan that can only emit **joins** can reach. A CFL leg is one:
        it builds a single-fact star out of tables, and an unnest is not a table
        it can put in a FROM clause. So a nested object is out of reach there,
        and so is anything reachable only *through* one - a dimension a nested
        fact joins onward to is behind an unnest however ordinary its own join
        is, and routing a leg through it produced a join with no columns.
        """
        if node not in self._directed:
            return set()
        reached: set[str] = set()
        frontier = [node]
        while frontier:
            current = frontier.pop()
            for successor in self._directed.successors(current):
                if successor in reached:
                    continue
                if self._directed.edges[current, successor].get("nested"):
                    continue
                reached.add(successor)
                frontier.append(successor)
        return reached

    def find_common_root(self, required_objects: set[str]) -> str:
        """Find the common root for a set of required objects.

        The join graph is a DAG (joins define direction: source → joinTo).
        The common root is the **deepest** node that can reach ALL
        *required_objects* via directed join paths.  "Deepest" = smallest
        descendant set (most specific ancestor, closest to the required nodes).

        In ``returns → sales → customer``, with required ``{customer, item}``,
        the common root is ``sales`` (it can reach both).  With required
        ``{customer, item, returns}``, the common root is ``returns`` (the
        only node that can reach all three).
        """
        required = required_objects & set(self._directed.nodes)
        if len(required) <= 1:
            return self._unnest_root(next(iter(sorted(required)))) if required else ""

        # Find all nodes that can reach ALL required nodes via directed paths
        candidates: list[tuple[str, int]] = []
        for node in self._directed.nodes:
            reachable = nx.descendants(self._directed, node) | {node}
            if required <= reachable:
                candidates.append((node, len(reachable)))

        if not candidates:
            # Fallback: no single directed ancestor covers all —
            # use undirected shortest-path center
            return self._find_center_undirected(required)

        # Pick the deepest ancestor: smallest reachable set that still covers all
        candidates.sort(key=lambda x: (x[1], x[0]))
        return self._unnest_root(candidates[0][0])

    def _find_center_undirected(self, required: set[str]) -> str:
        """Fallback: center of the Steiner tree in the undirected graph."""
        nodes = sorted(required)
        if len(nodes) <= 1:
            return nodes[0] if nodes else ""

        steiner: set[str] = set()
        for i in range(len(nodes)):
            for j in range(i + 1, len(nodes)):
                try:
                    path: list[str] = nx.shortest_path(self._graph, nodes[i], nodes[j])
                    steiner.update(path)
                except nx.NetworkXNoPath:
                    pass

        if not steiner:
            return self._unnest_root(nodes[0])

        # ``nodes`` can span disconnected components — the pairwise loop above
        # simply skips those pairs, so a Steiner node need not reach every
        # required node. Score an unreachable target as worse than any real
        # distance instead of letting ``shortest_path_length`` raise.
        unreachable = len(self._graph.nodes) + 1

        def _eccentricity(node: str) -> int:
            worst: int = 0
            for target in nodes:
                try:
                    # Unweighted graph, so the hop count is always integral;
                    # the stub types it as float to cover weighted callers.
                    worst = max(worst, int(nx.shortest_path_length(self._graph, node, target)))
                except nx.NetworkXNoPath:
                    worst = max(worst, unreachable)
            return worst

        best: str = nodes[0]
        best_max: int = unreachable + 1
        for node in sorted(steiner):
            max_dist = _eccentricity(node)
            if max_dist < best_max:
                best_max = max_dist
                best = node
        return self._unnest_root(best)

    def _hops_from(self, origin: str | None, node: str) -> int:
        """Hops from *origin* to *node* in the traversable graph.

        ``0`` when they are the same or no origin was given, and a value larger
        than any real path when *node* is out of reach — so an unreachable
        source sorts last rather than raising.
        """
        if origin is None or origin == node:
            return 0
        try:
            return int(nx.shortest_path_length(self._traversable, origin, node))
        except (nx.NetworkXNoPath, nx.NodeNotFound):
            return len(self._traversable) + 1

    def role_candidates(
        self,
        from_objects: set[str],
        to_object: str,
        prefer_from: str | None = None,
    ) -> list[list[str]]:
        """The equally-good ways to reach *to_object*, one path each.

        A data object joined by more than one of the objects already in the
        query is reachable by more than one *role* — ``date_dim`` as the sold
        date and as the returned date, ``warehouse`` as the sale's and as the
        inventory's. Which role a plain reference means is a question the model
        cannot answer, so the caller has to know when there is a real choice.

        Candidates are ranked by path length first, then by how far the source
        sits from *prefer_from* (the query's base object). That makes the
        answer both deterministic and principled: the base is what the query is
        anchored on, so the role reached from it directly beats one reached
        through another fact. Ranking by nothing, as this did before, left the
        choice to set iteration order — the same query then compiled to a
        different role from run to run, since string hashing is randomised per
        process.

        Returns every path tied at the best rank that enters *to_object* by a
        *different* join, deduplicated on that last edge: two routes arriving
        on the same key are the same role, however they got there. One element
        means the choice is clear; more than one means it is genuinely
        ambiguous and only the query can resolve it.
        """
        ranked: list[tuple[tuple[int, int, str], list[str]]] = []
        for source in sorted(from_objects):
            if source not in self._traversable or to_object not in self._traversable:
                continue
            lengths = nx.single_source_shortest_path_length(self._traversable, source)
            distance = lengths.get(to_object)
            if distance is None:
                continue
            # What separates one role from another is the *last* edge — which
            # join actually lands on the target. Every predecessor sitting one
            # hop closer to the source is the last edge of some shortest path,
            # so one traversal yields the complete set of roles. Enumerating
            # the paths instead would need a cap, and a cap applied before
            # roles are distinguished can hide one behind many routes that
            # share an entry.
            for entry in sorted(self._traversable.predecessors(to_object)):
                if lengths.get(entry) != distance - 1:
                    continue
                prefix: list[str] = nx.shortest_path(self._traversable, source, entry)
                candidate = [*prefix, to_object]
                rank = (len(candidate), self._hops_from(prefer_from, source), source)
                ranked.append((rank, candidate))
        if not ranked:
            return []

        best = min(rank for rank, _ in ranked)[:2]
        by_entry: dict[tuple[str, str], list[str]] = {}
        for rank, candidate in sorted(ranked):
            if rank[:2] != best:
                continue
            last_edge = (
                (candidate[-2], candidate[-1])
                if len(candidate) > 1
                else (candidate[0], candidate[0])
            )
            by_entry.setdefault(last_edge, candidate)
        return list(by_entry.values())

    def find_join_path(
        self,
        from_objects: set[str],
        to_objects: set[str],
        via_constraints: dict[str, str] | None = None,
        prefer_from: str | None = None,
        ambiguous: dict[str, list[list[str]]] | None = None,
    ) -> list[JoinStep]:
        """Find a minimal join path connecting all required data objects.

        Uses shortest path for each target object from the set of source
        objects, ranked by :meth:`role_candidates` so the choice among several
        reachable roles is deterministic rather than set-order dependent.

        *via_constraints* maps ``target → via``: for constrained targets, only
        the ``via`` object is used as the source so the path is forced through it.
        *prefer_from* is the query's base object, which breaks ties in favour of
        the role it reaches directly.

        A path is still produced when several roles tie, because most callers
        only need *a* join. Pass *ambiguous* to learn about it: each target that
        tied is recorded there with the routes it tied between, so a caller that
        must not guess — query resolution — can refuse instead.
        """
        steps: list[JoinStep] = []
        visited_edges: set[tuple[str, str]] = set()
        via = via_constraints or {}

        # Process via waypoints first so they are in source_list when their
        # constrained targets are processed.
        all_targets = to_objects - from_objects
        via_targets = {t for t in all_targets if t in via}
        non_via_targets = all_targets - via_targets
        via_waypoints = {via[t] for t in via_targets} - from_objects - via_targets
        ordered_targets = sorted(via_waypoints) + sorted(non_via_targets) + sorted(via_targets)

        source_list = list(from_objects)
        # A single starting object *is* the anchor — that is how the planner
        # calls this, from the query's base. Without it the tie-break falls
        # back to the source name, which is deterministic but arbitrary: it
        # bound a date filter to whichever fact sorted first.
        anchor = prefer_from or (next(iter(from_objects)) if len(from_objects) == 1 else None)

        for target in ordered_targets:
            sources = [via[target]] if target in via and via[target] in source_list else source_list
            candidates = self.role_candidates(set(sources), target, prefer_from=anchor)
            if len(candidates) > 1 and ambiguous is not None:
                ambiguous[target] = candidates
            best_path = candidates[0] if candidates else None

            if best_path is None:
                continue

            for i in range(len(best_path) - 1):
                edge = (best_path[i], best_path[i + 1])
                rev_edge = (best_path[i + 1], best_path[i])
                if edge in visited_edges or rev_edge in visited_edges:
                    continue
                visited_edges.add(edge)

                edge_data = self._graph.edges[edge]
                source_object = edge_data.get("source_object", edge[0])

                if source_object == edge[0]:
                    step = JoinStep(
                        from_object=edge[0],
                        to_object=edge[1],
                        from_columns=edge_data["columns_from"],
                        to_columns=edge_data["columns_to"],
                        join_type=_join_type_for(edge_data),
                        cardinality=edge_data["cardinality"],
                        nested=bool(edge_data.get("nested")),
                    )
                else:
                    # Path traverses the edge against its declared direction.
                    # ``JoinStep`` keeps from/to in *declared* order — ``edge[1]``
                    # is the object that declares the join, so it keeps
                    # ``columns_from`` — and records the real traversal
                    # direction in ``reversed``.
                    step = JoinStep(
                        from_object=edge[1],
                        to_object=edge[0],
                        from_columns=edge_data["columns_from"],
                        to_columns=edge_data["columns_to"],
                        join_type=_join_type_for(edge_data),
                        cardinality=edge_data["cardinality"],
                        reversed=True,
                        nested=bool(edge_data.get("nested")),
                    )
                steps.append(step)

            # Add target to sources for subsequent lookups
            if target not in source_list:
                source_list.append(target)

        return steps

    def find_join_path_undirected(
        self,
        from_object: str,
        to_object: str,
    ) -> list[JoinStep]:
        """Find a join path ignoring cardinality direction.

        Unlike :meth:`find_join_path` (which forbids walking many-to-one
        joins backwards to prevent fanout in the outer query), this walker
        considers the join graph as undirected.  It's intended for
        correlated subqueries — EXISTS / NOT EXISTS — where row counts on
        the outer side are unaffected by how many rows the subquery scans.

        Each emitted :class:`JoinStep` is oriented so ``from_object`` is the
        step's predecessor on the path and ``to_object`` is its successor;
        ``from_columns`` / ``to_columns`` are swapped when the underlying
        join edge is traversed against its declared direction.
        """
        if from_object == to_object:
            return []
        if from_object not in self._graph or to_object not in self._graph:
            return []
        try:
            path: list[str] = nx.shortest_path(self._graph, from_object, to_object)
        except nx.NetworkXNoPath:
            return []

        steps: list[JoinStep] = []
        for i in range(len(path) - 1):
            pred, succ = path[i], path[i + 1]
            edge_data = self._graph.edges[(pred, succ)]
            source_object = edge_data.get("source_object", pred)
            if source_object == pred:
                from_cols = edge_data["columns_from"]
                to_cols = edge_data["columns_to"]
                reversed_ = False
            else:
                from_cols = edge_data["columns_to"]
                to_cols = edge_data["columns_from"]
                reversed_ = True
            steps.append(
                JoinStep(
                    from_object=pred,
                    to_object=succ,
                    from_columns=from_cols,
                    to_columns=to_cols,
                    join_type=_join_type_for(edge_data),
                    cardinality=edge_data["cardinality"],
                    reversed=reversed_,
                    nested=bool(edge_data.get("nested")),
                )
            )
        return steps

    def build_join_condition(self, step: JoinStep) -> Expr:
        """Build the ON clause expression for a join step.

        Routes both sides through ``make_column_expr`` so a computed
        join key (``expression:`` instead of ``code:`` on the column)
        inlines its template body. Without this, a join on a computed
        key would render ``"obj"."" = "other"."key"`` and the database
        would error on the zero-length identifier.

        The model's query time zone is deliberately *not* applied here. A join
        asks whether two rows belong together, which no calendar changes: both
        sides would convert identically and the answer would be the same, at
        the cost of wrapping a join key in a function, which is how an index or
        a partition stops being used. Conversion exists so that bucketing and
        display happen in the model's frame, and an ON clause is neither.
        """
        from orionbelt.compiler.resolution import make_column_expr

        conditions: list[Expr] = []
        for from_c, to_c in zip(step.from_columns, step.to_columns, strict=True):
            from_obj = self._model.data_objects.get(step.from_object)
            to_obj = self._model.data_objects.get(step.to_object)
            if from_obj and from_c in from_obj.columns:
                left_expr: Expr = make_column_expr(
                    self._model, step.from_object, from_c, in_query_timezone=False
                )
            else:
                left_expr = ColumnRef(name=from_c, table=step.from_object)
            if to_obj and to_c in to_obj.columns:
                right_expr: Expr = make_column_expr(
                    self._model, step.to_object, to_c, in_query_timezone=False
                )
            else:
                right_expr = ColumnRef(name=to_c, table=step.to_object)
            conditions.append(BinaryOp(left=left_expr, op="=", right=right_expr))

        if not conditions:
            msg = f"Join from '{step.from_object}' to '{step.to_object}' has no join columns"
            raise ValueError(msg)
        result: Expr = conditions[0]
        for cond in conditions[1:]:
            result = BinaryOp(left=result, op="AND", right=cond)
        return result

    def detect_cycles(self) -> list[list[str]]:
        """Detect cyclic join paths."""
        try:
            cycles = list(nx.simple_cycles(self._directed))
            return cycles
        except nx.NetworkXError:
            return []

    def validate_deterministic(self) -> list[SemanticError]:
        """Ensure join paths are deterministic (no ambiguity)."""
        errors: list[SemanticError] = []
        # Check for multiple edges between the same pair of nodes
        for u, v in self._graph.edges():
            if self._graph.number_of_edges(u, v) > 1:
                errors.append(
                    SemanticError(
                        code="AMBIGUOUS_JOIN",
                        message=f"Multiple join paths between '{u}' and '{v}'",
                        path=f"dataObjects.{u}.joins",
                    )
                )
        return errors

find_join_path(from_objects, to_objects, via_constraints=None, prefer_from=None, ambiguous=None)

Find a minimal join path connecting all required data objects.

Uses shortest path for each target object from the set of source objects, ranked by :meth:role_candidates so the choice among several reachable roles is deterministic rather than set-order dependent.

via_constraints maps target → via: for constrained targets, only the via object is used as the source so the path is forced through it. prefer_from is the query's base object, which breaks ties in favour of the role it reaches directly.

A path is still produced when several roles tie, because most callers only need a join. Pass ambiguous to learn about it: each target that tied is recorded there with the routes it tied between, so a caller that must not guess — query resolution — can refuse instead.

Source code in src/orionbelt/compiler/graph.py
def find_join_path(
    self,
    from_objects: set[str],
    to_objects: set[str],
    via_constraints: dict[str, str] | None = None,
    prefer_from: str | None = None,
    ambiguous: dict[str, list[list[str]]] | None = None,
) -> list[JoinStep]:
    """Find a minimal join path connecting all required data objects.

    Uses shortest path for each target object from the set of source
    objects, ranked by :meth:`role_candidates` so the choice among several
    reachable roles is deterministic rather than set-order dependent.

    *via_constraints* maps ``target → via``: for constrained targets, only
    the ``via`` object is used as the source so the path is forced through it.
    *prefer_from* is the query's base object, which breaks ties in favour of
    the role it reaches directly.

    A path is still produced when several roles tie, because most callers
    only need *a* join. Pass *ambiguous* to learn about it: each target that
    tied is recorded there with the routes it tied between, so a caller that
    must not guess — query resolution — can refuse instead.
    """
    steps: list[JoinStep] = []
    visited_edges: set[tuple[str, str]] = set()
    via = via_constraints or {}

    # Process via waypoints first so they are in source_list when their
    # constrained targets are processed.
    all_targets = to_objects - from_objects
    via_targets = {t for t in all_targets if t in via}
    non_via_targets = all_targets - via_targets
    via_waypoints = {via[t] for t in via_targets} - from_objects - via_targets
    ordered_targets = sorted(via_waypoints) + sorted(non_via_targets) + sorted(via_targets)

    source_list = list(from_objects)
    # A single starting object *is* the anchor — that is how the planner
    # calls this, from the query's base. Without it the tie-break falls
    # back to the source name, which is deterministic but arbitrary: it
    # bound a date filter to whichever fact sorted first.
    anchor = prefer_from or (next(iter(from_objects)) if len(from_objects) == 1 else None)

    for target in ordered_targets:
        sources = [via[target]] if target in via and via[target] in source_list else source_list
        candidates = self.role_candidates(set(sources), target, prefer_from=anchor)
        if len(candidates) > 1 and ambiguous is not None:
            ambiguous[target] = candidates
        best_path = candidates[0] if candidates else None

        if best_path is None:
            continue

        for i in range(len(best_path) - 1):
            edge = (best_path[i], best_path[i + 1])
            rev_edge = (best_path[i + 1], best_path[i])
            if edge in visited_edges or rev_edge in visited_edges:
                continue
            visited_edges.add(edge)

            edge_data = self._graph.edges[edge]
            source_object = edge_data.get("source_object", edge[0])

            if source_object == edge[0]:
                step = JoinStep(
                    from_object=edge[0],
                    to_object=edge[1],
                    from_columns=edge_data["columns_from"],
                    to_columns=edge_data["columns_to"],
                    join_type=_join_type_for(edge_data),
                    cardinality=edge_data["cardinality"],
                    nested=bool(edge_data.get("nested")),
                )
            else:
                # Path traverses the edge against its declared direction.
                # ``JoinStep`` keeps from/to in *declared* order — ``edge[1]``
                # is the object that declares the join, so it keeps
                # ``columns_from`` — and records the real traversal
                # direction in ``reversed``.
                step = JoinStep(
                    from_object=edge[1],
                    to_object=edge[0],
                    from_columns=edge_data["columns_from"],
                    to_columns=edge_data["columns_to"],
                    join_type=_join_type_for(edge_data),
                    cardinality=edge_data["cardinality"],
                    reversed=True,
                    nested=bool(edge_data.get("nested")),
                )
            steps.append(step)

        # Add target to sources for subsequent lookups
        if target not in source_list:
            source_list.append(target)

    return steps

build_join_condition(step)

Build the ON clause expression for a join step.

Routes both sides through make_column_expr so a computed join key (expression: instead of code: on the column) inlines its template body. Without this, a join on a computed key would render "obj"."" = "other"."key" and the database would error on the zero-length identifier.

The model's query time zone is deliberately not applied here. A join asks whether two rows belong together, which no calendar changes: both sides would convert identically and the answer would be the same, at the cost of wrapping a join key in a function, which is how an index or a partition stops being used. Conversion exists so that bucketing and display happen in the model's frame, and an ON clause is neither.

Source code in src/orionbelt/compiler/graph.py
def build_join_condition(self, step: JoinStep) -> Expr:
    """Build the ON clause expression for a join step.

    Routes both sides through ``make_column_expr`` so a computed
    join key (``expression:`` instead of ``code:`` on the column)
    inlines its template body. Without this, a join on a computed
    key would render ``"obj"."" = "other"."key"`` and the database
    would error on the zero-length identifier.

    The model's query time zone is deliberately *not* applied here. A join
    asks whether two rows belong together, which no calendar changes: both
    sides would convert identically and the answer would be the same, at
    the cost of wrapping a join key in a function, which is how an index or
    a partition stops being used. Conversion exists so that bucketing and
    display happen in the model's frame, and an ON clause is neither.
    """
    from orionbelt.compiler.resolution import make_column_expr

    conditions: list[Expr] = []
    for from_c, to_c in zip(step.from_columns, step.to_columns, strict=True):
        from_obj = self._model.data_objects.get(step.from_object)
        to_obj = self._model.data_objects.get(step.to_object)
        if from_obj and from_c in from_obj.columns:
            left_expr: Expr = make_column_expr(
                self._model, step.from_object, from_c, in_query_timezone=False
            )
        else:
            left_expr = ColumnRef(name=from_c, table=step.from_object)
        if to_obj and to_c in to_obj.columns:
            right_expr: Expr = make_column_expr(
                self._model, step.to_object, to_c, in_query_timezone=False
            )
        else:
            right_expr = ColumnRef(name=to_c, table=step.to_object)
        conditions.append(BinaryOp(left=left_expr, op="=", right=right_expr))

    if not conditions:
        msg = f"Join from '{step.from_object}' to '{step.to_object}' has no join columns"
        raise ValueError(msg)
    result: Expr = conditions[0]
    for cond in conditions[1:]:
        result = BinaryOp(left=result, op="AND", right=cond)
    return result

detect_cycles()

Detect cyclic join paths.

Source code in src/orionbelt/compiler/graph.py
def detect_cycles(self) -> list[list[str]]:
    """Detect cyclic join paths."""
    try:
        cycles = list(nx.simple_cycles(self._directed))
        return cycles
    except nx.NetworkXError:
        return []

Code Generator

orionbelt.compiler.codegen.CodeGenerator

Generates SQL from AST using a dialect.

Source code in src/orionbelt/compiler/codegen.py
class CodeGenerator:
    """Generates SQL from AST using a dialect."""

    def __init__(self, dialect: Dialect) -> None:
        self._dialect = dialect

    @property
    def dialect(self) -> Dialect:
        return self._dialect

    def generate(self, ast: Select) -> str:
        """Generate SQL string from AST using the configured dialect."""
        return self._dialect.compile(ast)

generate(ast)

Generate SQL string from AST using the configured dialect.

Source code in src/orionbelt/compiler/codegen.py
def generate(self, ast: Select) -> str:
    """Generate SQL string from AST using the configured dialect."""
    return self._dialect.compile(ast)