Building an Index Before Looking Up References

A first pass can index records, and a second can resolve references regardless of where their targets appear in the input.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a forward reference
  2. Set a duplicate rule
  3. Allow an input reference to point forward
  4. Validate relationship constraints after lookup

Trace a forward reference

A row about item A refers to item B, which occurs later. Looking up B before storing the later row fails. Index all IDs first and then resolve links. Dictionary lookup supplies the operation for each reference.

Set a duplicate rule

If two rows use the same ID, blindly replacing one can alter references. Reject duplicates or define ownership explicitly. A keyed in-memory join shows the complementary question for a referenced key that is never defined.[1]

Allow an input reference to point forward

Consider rows declaring A's parent as C, declaring B, then declaring C. A one-pass resolver encounters C too early unless it records deferred work. A first pass can build all three ID entries, and a second validates A's target. Check duplicate IDs while constructing the index because an overwritten entry can make the outcome depend on row order. See dictionary lookups.

Validate relationship constraints after lookup

Resolving every parent ID still does not prove the result is a tree. The references A to C and C to A both resolve but form a cycle. Use a traversal that detects cycles if the relationship forbids them. Test one forward reference, a missing parent and a cycle with all identifiers present. If the input is a generator, preserve required fields or reopen a stable source for the second pass. See iterator exhaustion.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩