Skip to content

dj.U(X) & Q and dj.U(X).aggr can put NULL into a primary key #1708

Open

Description

@dimitri-yatsenko

Problem

dj.U(X) & Q and dj.U(X).aggr(Q, ...) make X the primary key of the result without checking whether any attribute of X can be null in Q. Heading.set_primary_key "performs no error checking". When an attribute of X is nullable in Q, the result:

  • has a NULL in a primary-key attribute, and
  • for aggr, gets a NULL group from GROUP BY.

Either way, a query result violates entity integrity.

Reproduction

DataJoint 2.3.5.dev, MySQL 8.0:

@schema
class Subject(dj.Manual):
    definition = """
    subject_id : int32
    ---
    nickname = null : varchar(16)
    """

@schema
class Session(dj.Manual):
    definition = """
    -> Subject
    session : int32
    """

Subject.insert([(1, "a"), (2, None)])
Session.insert([(1, 1), (1, 2)])
>>> (dj.U("nickname") & Subject).to_dicts()
[{'nickname': 'a'}, {'nickname': None}]          # NULL in the primary key
>>> dj.U("nickname").aggr(Subject, n="count(*)").to_dicts()
[{'nickname': 'a', 'n': 1}, {'nickname': None, 'n': 1}]   # a NULL group

An attribute can be nullable in Q in three ways:

  • it is declared nullable;
  • extend or a union padded it with NULLs;
  • a left-join aggregation computed it.

Why fixing dj.U is enough

We audited where each operator gets its result key:

  • restriction and complementary restriction: from the left operand;
  • projection: from the operand, possibly renamed;
  • join: from the operands' keys, by the join rule;
  • extend, aggr, union, key_source: from an operand's key.

In every case except one, the key comes from an operand's key, and key attributes are never null. dj.U(X) is the only operator that puts non-key attributes into a key. Fixing it closes the gap.

Proposed rule: rows null on X match nothing

U(X) is the entity set of all non-null combinations of values of X. U(X) & Q is restriction of U(X) by Q, and a NULL matches nothing, as it already does in joins and, after #1663, in complements. So a row of Q that is null on any attribute of X matches no element of U(X) and drops out. The same holds for U(X).aggr(Q, ...): a row of Q that is null on X joins no group.

The result can therefore have fewer rows than the number of distinct values of X in Q, because NULL is not one of those values. dj.U() (empty X) is unaffected and still returns one row, even when Q is empty.

The first version of this issue proposed refusing a nullable X when the query is built. Filtering is better, for two reasons:

  • Keys are non-null by construction, whatever the heading says about nullability. A refusal would be only as safe as the nullable flags it checks, and those flags are currently wrong for derived headings (see the table below). With filtering, a wrong flag can no longer put NULL into a key.
  • It needs no special rule. Filtering is what the general matching rule already implies, so dj.U needs no separate acceptance check.

The cost is that the NULL group disappears without an error. To count it, query it explicitly:

dj.U().aggr(Q & "x IS NULL", n="count(*)")

Implementation

In U.__and__ and U.aggr, add x IS NOT NULL to the WHERE clause for every attribute of X, before DISTINCT or GROUP BY. Add it unconditionally: it costs nothing, and it does not depend on nullability tracking.

Optional: correct nullability in derived headings

Filtering no longer depends on these flags, but other features read them, and several are wrong today:

Where Today Should be
proj computed attributes (Heading.select, compute_attrs) nullable=False nullable=True
aggr computed attributes nullable=False nullable=True (avg, sum, max and the like are NULL over an empty group)
extend / left join (Heading.join) B's attributes keep B's flags B's attributes outside A's heading are nullable (padded)
union secondaries keep their flags every secondary attribute is nullable (padded on one side)
A - B — keeps A's flags: a row whose matched attribute is NULL matches nothing and stays in A - B
inner join, A & B — matched namesakes may be marked non-null, since NULL never matches

These corrections can go in a separate issue.

Tests

  • U(X) & Q and U(X).aggr(Q) exclude rows that are null on X, for each of these kinds of X:
    • a declared-nullable attribute;
    • an attribute padded by extend;
    • an attribute padded by a union;
    • a mix of key and nullable attributes.
  • No result row has NULL in its primary key.
  • len(dj.U("x") & Q) equals the number of distinct non-null values of x in Q.
  • dj.U().aggr(Q) on an empty Q still returns one row.

Behavior change

Code that groups by a nullable attribute now omits the row whose primary key would be NULL. The release notes should say so and show how to query the NULL group explicitly.

Activity

  1. added
    bugIndicates an unexpected problem or unintended behavior
    on Nov 20, 2026
  2. dimitri-yatsenko commented on Nov 21, 2026

    @dimitri-yatsenko
    MemberAuthor

    Revised the proposal: dj.U(X) & Q and dj.U(X).aggr now exclude rows that are null on X, rather than refusing a nullable X at declaration. Filtering follows from the general matching rule (NULL matches nothing, as in joins and, after #1663, complements) and keeps result keys non-null by construction. Refusal would be only as safe as the nullable flags on derived headings, which are currently wrong for extend, union, and computed attributes. Correcting those flags remains worthwhile but is now optional (see the table in the description). The rule matches the Relational Workflow Model specification.

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

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions