Skip to content

Table.alter() resolves foreign keys in the caller's namespace, not the table's declaration context #1602

Closed

Description

@dimitri-yatsenko

Summary

With no context argument, Table.alter() resolves the definition's foreign keys in the caller's frame (table.py:321-324). Called from any module other than the one that declared the table, such as a migration script or a notebook that imports the pipeline module, alter() fails for every table with a foreign key unless the caller passes context= explicitly. The table already holds its declaration context (schemas.py:295), and Part.alter() falls back to it (user_tables.py:260-262); other tables do not.

Reproduction

DataJoint 2.3.5.dev8 (master, a00b89f), MySQL 8.0.46, Python 3.11.

i3_pipeline.py:

import datajoint as dj

schema = dj.Schema("scratch_alter")

@schema
class Item(dj.Manual):
    definition = """
    item : int32
    """

@schema
class Measurement(dj.Manual):
    definition = """
    -> Item
    ---
    value : float32
    """

i3.py, run after the tables are declared:

import i3_pipeline

i3_pipeline.Measurement.definition = """
-> Item
---
value : float64
"""
i3_pipeline.Measurement.alter(prompt=False)

Output:

  File "i3.py", line 8, in <module>
  File "src/datajoint/table.py", line 326, in alter
  File "src/datajoint/declare.py", line 795, in alter
  File "src/datajoint/declare.py", line 460, in prepare_declare
  File "src/datajoint/declare.py", line 260, in compile_foreign_key
    raise DataJointError("Foreign key reference %s could not be resolved" % result.ref_table)
datajoint.errors.DataJointError: Foreign key reference Item could not be resolved

i3_pipeline.Measurement.alter(prompt=False, context=vars(i3_pipeline)) succeeds.

Expected behavior

Without context, alter() resolves names in self.declaration_context, as Part.alter() does, and falls back to the caller's frame only when the table has none. The table then alters the same way wherever alter() is called from.

Activity

  1. added
    bugIndicates an unexpected problem or unintended behavior
    on Oct 17, 2026
  2. added this to the v2.3.5 milestone on Oct 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIndicates an unexpected problem or unintended behavior

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions