Skip to content

Implement Diagram.trace() for upstream restriction propagation #1423

@dimitri-yatsenko

Description

@dimitri-yatsenko

Summary

Implement Diagram.trace(table_expr) as the upstream mirror of Diagram.cascade() — walking the FK graph upward from a restricted table expression, propagating the key restriction through every ancestor with OR convergence.

Context

Discussion: #1232
Related: #242 (farfetch), PR #1407 (graph-driven cascade)

PR #1407 delivered downstream graph operations (Diagram.cascade() and Diagram.restrict()). The upstream direction is missing — users cannot programmatically walk the FK graph upward to find which ancestor entities contributed to a given result.

Design

Diagram.trace(table_expr) constructs a restricted upstream diagram:

trace = dj.Diagram.trace(MyChild & key)
trace.counts()          # entity counts per ancestor table
trace[Session]          # pre-restricted Session QueryExpression
trace[Session].fetch1("session_date")
trace[ExtractTraces].to_arrays("trace")
  • Direction: upstream (child → ancestors)
  • Convergence: OR — an ancestor entity is included if reachable through any FK path
  • trace[TableClass]: returns the ancestor table pre-restricted through the FK join path
  • trace.counts(): entity counts per ancestor table
  • trace.heading(): all attributes across ancestor tables, grouped by table

Convergence rules

Method Direction Convergence Question
cascade downstream OR What's affected if this is deleted?
restrict downstream AND What satisfies all these conditions?
trace upstream OR What contributed to this result?

Restriction propagation (inverse of cascade)

For edge Parent→Child with attr_map, trace reverses the propagation: project child FK values back onto parent primary keys.

Implementation notes

  • Reuses existing Diagram infrastructure: dependency graph, attr_map handling, topological ordering, cross-schema discovery from Implement graph-driven cascade delete and restrict on Diagram #1407
  • trace[TableClass] via __getitem__ — only table classes accepted
  • Returns standard QueryExpression objects — all existing query operators (join, aggr, proj, restrict) and fetch methods work unchanged

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureIndicates new features

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions