Skip to content

Write Entry Rows from make()

A make() may add rows to entry tables (dj.Manual) as well as to its own table, when a foreign key from those rows to the job would be wrong or impossible. This page shows how: turn on origin capture, write the rows, handle rows that already exist, and clean up. For when to do this and why, see Writing to Entry Tables from make().

Turn on origin capture

The rows a make() writes into an entry table have no foreign key back to the job, so the job's table and key are recorded in the hidden _prov attribute instead. Turn capture on where the deployment sets credentials and stores, before the tables are declared:

export DJ_PROVENANCE_CAPTURE=true

Tables declared while capture was off have no _prov column and record nothing. Add it with datajoint.deploy.add_prov_column; see Record Data Origin.

Fan-out ingestion

One ingestion step reads one source and creates rows in several tables that carry no foreign key back to it, such as parsing one acquisition file into Subject, Session, and Recording records:

The fan-out ingestion pattern. On the left, RecordingFile, a green rounded box for the Manual tier with its name underlined, joined by a thick navy line without an arrowhead to Ingest, a blue ellipse for the Imported tier whose name is not underlined โ€” the edge is thick because Ingest declares only a foreign key to RecordingFile, so that key covers its whole primary key, and the name is plain because it introduces no key attribute of its own. From Ingest, three dashed navy arrows fan out to the right under the label "insert + source_file", each ending at a green rounded Manual box with an underlined name: Subject, Session and Recording. The arrowheads mark these as writes rather than dependencies, since a dependency edge carries none, and a note reads "no foreign key back to Ingest". A legend keys the Imported and Manual tiers, distinguishes a dependency (no arrowhead) from a write that is not a dependency, and notes that an underlined name introduces a primary-key attribute of its own.The fan-out ingestion pattern. On the left, RecordingFile, a green rounded box for the Manual tier with its name underlined, joined by a thick navy line without an arrowhead to Ingest, a blue ellipse for the Imported tier whose name is not underlined โ€” the edge is thick because Ingest declares only a foreign key to RecordingFile, so that key covers its whole primary key, and the name is plain because it introduces no key attribute of its own. From Ingest, three dashed navy arrows fan out to the right under the label "insert + source_file", each ending at a green rounded Manual box with an underlined name: Subject, Session and Recording. The arrowheads mark these as writes rather than dependencies, since a dependency edge carries none, and a note reads "no foreign key back to Ingest". A legend keys the Imported and Manual tiers, distinguishes a dependency (no arrowhead) from a write that is not a dependency, and notes that an underlined name introduces a primary-key attribute of its own.

dj.Diagram shows Subject, Session, and Recording as unconnected nodes, because there is no foreign key for it to follow. The dashed arrows are the writes that the dependency graph does not record.

@schema
class RecordingFile(dj.Manual):        # the source record
    definition = """
    file_id : int32
    ---
    path    : varchar(255)
    """

@schema
class Ingest(dj.Imported):
    definition = """
    -> RecordingFile
    """

    def make(self, key):
        meta = parse(RecordingFile & key)
        # several entry tables, none of them a child of Ingest
        Subject.insert1({**meta.subject, "source_file": key["file_id"]})
        Session.insert1({**meta.session, "source_file": key["file_id"]})
        Recording.insert1({**meta.recording, "source_file": key["file_id"]})
        self.insert1(key)

Each written row records Ingest and its key in _prov. Keep the source_file attribute as well wherever downstream code follows a row back to its file: _prov cannot be joined or restricted like an ordinary attribute. A runnable version is in examples/fan_out_provenance.py.

Declining the foreign key here is deliberate. Binding Subject and Session to a fast-changing ingestion step would turn every change to how data is loaded into a schema migration, and every row would carry whichever loader existed when it was created. When the produced rows are instead a result computed from the source, make them a Computed or Imported child of it, and keep the traceability the foreign key gives.

Iterative computations

A computation that refines an estimate step by step writes each next estimate into the entry table it reads from. The table graph has no cycle (Problem โ†’ Estimate โ†’ Refine), and the loop runs through the data:

@schema
class Problem(dj.Manual):
    definition = """
    problem_id : int32
    ---
    target     : float64     # the number whose square root is wanted
    """

@schema
class Estimate(dj.Manual):
    definition = """
    -> Problem
    iteration  : int32       # 0 for the starting guess; k + 1 is written by Refine k
    ---
    x          : float64     # the estimate at this iteration
    """

@schema
class Refine(dj.Computed):
    definition = """
    -> Estimate
    ---
    change     : float64     # |x(k + 1) - x(k)|
    """

    def make(self, key):
        target = (Problem & key).fetch1("target")
        x = (Estimate & key).fetch1("x")
        x_next = (x + target / x) / 2          # one Newton step toward sqrt(target)
        change = abs(x_next - x)
        if change > 1e-12:                     # not converged: register the next iterate
            Estimate.insert1({**key, "iteration": key["iteration"] + 1, "x": x_next})
        self.insert1({**key, "change": change})

Start each problem with an iteration 0, then populate until no job is left:

Problem.insert1({"problem_id": 1, "target": 2.0})
Estimate.insert1({"problem_id": 1, "iteration": 0, "x": 1.0})

while Refine.populate()["success_count"]:
    pass

populate() reads the keys to run once, at the start, so each call advances every unfinished problem by one step. The rows written during a call are picked up by the next one. The make() decides when to stop by not writing a next iterate.

The key written is derived from the job's key (iteration + 1), so a re-run of the same job targets the same row. The iteration attribute is the modeled link back to the step that wrote it, and _prov records the Refine job. A runnable version is in examples/iterative_entry_writes.py.

Handle rows that already exist

A row a job writes can already be there: the job's own row was deleted and the job runs again, someone entered the row directly, or two jobs target the same key. Choose what happens:

Error. A plain insert1 raises DuplicateError. The whole make() is rolled back, including the job's own row, and populate() raises the error (with reserve_jobs=True, the job is also marked as an error in the jobs table). Use it when an existing row means something is wrong.

Verify. Insert the row if it is absent; if it is present, check that it holds the same values, and raise an error if it does not. insert has no option for this, so write the check in your code, for example as a helper:

def insert1_or_verify(table, row):
    """Insert row, or check that the stored row with the same primary key equals it."""
    key = {name: row[name] for name in table.primary_key}
    stored = table & key
    if not stored:
        table.insert1(row)
        return
    stored = stored.fetch1()
    differs = {name: (stored[name], value) for name, value in row.items() if stored[name] != value}
    if differs:
        raise dj.DataJointError(f"{table.__name__} {key} exists with different values (stored, new): {differs}")
    def make(self, key):
        ...
        if change > 1e-12:
            insert1_or_verify(Estimate, {**key, "iteration": key["iteration"] + 1, "x": x_next})
        self.insert1({**key, "change": change})

A re-run that reproduces the stored row now succeeds and leaves its _prov unchanged; a re-run that would produce a different row stops with an error that shows the difference. The values are compared as DataJoint returns them, so pass them in the same types (a datetime.date, not a date string). Compare arrays with numpy.array_equal rather than !=, and floating-point results with a tolerance if the computation is not exactly reproducible.

Skip. insert1(row, skip_duplicates=True) keeps the stored row, with its values and its _prov, and reports nothing, even when the new values differ. Use it only when the new row is certain to equal the stored one.

Replace. insert1(row, replace=True) deletes the stored row and inserts the new one, which gets a new _prov. The database refuses it if any other row depends on the stored row, such as the Refine row computed from an Estimate. Use it only to correct a row that nothing has been computed from.

replace=True on PostgreSQL

On PostgreSQL, insert(..., replace=True) currently fails with a syntax error (datajoint-python#1780). Delete the stored row and insert the new one instead.

Clean up after deleting a job's rows

Deleting a job's row does not delete the entry rows it wrote, because no foreign key connects them. Delete them yourself, through the modeled attribute. To repeat the iterative computation of problem 1 from iteration 3:

# The estimates after iteration 3; deleting them also deletes their Refine rows
(Estimate & {"problem_id": 1} & "iteration > 3").delete()
# The step that wrote iteration 4
(Refine & {"problem_id": 1, "iteration": 3}).delete()

The next populate() runs step 3 again and writes a new iteration 4. If only the Refine row is deleted, the re-run finds iteration 4 already stored, and the choice above decides what happens.

Find the rows a job wrote

When there is no modeled attribute to restrict on, restrict on _prov. The condition must be written as a string, because a dict restriction cannot reach a hidden attribute:

# MySQL
Estimate & f"JSON_VALUE(_prov, '$.context.table') = '{Refine.full_table_name}'"
Estimate & "JSON_VALUE(_prov, '$.context.key.iteration') = 2"

# PostgreSQL
Estimate & f"jsonb_extract_path_text(_prov, 'context', 'table') = '{Refine.full_table_name}'"
Estimate & "jsonb_extract_path_text(_prov, 'context', 'key', 'iteration') = '2'"

To read the _prov value itself, use SQL until 2.4; see Record Data Origin.

See also