diff --git a/src/datajoint/condition.py b/src/datajoint/condition.py index e9b6cdbfe..2e625479f 100644 --- a/src/datajoint/condition.py +++ b/src/datajoint/condition.py @@ -220,6 +220,17 @@ def __init__(self, restriction: Any) -> None: self.restriction = restriction +class _RestrictionAttributes(set): + """ + Attribute names collected by ``make_condition``. + + ``exact`` is False once a string condition is read: its names come from + ``extract_column_names``, which parses the SQL text and can miss some. + """ + + exact = True + + def assert_join_compatibility( expr1: QueryExpression, expr2: QueryExpression, @@ -428,6 +439,8 @@ def combine_conditions(negate, conditions): # restrict by string if isinstance(condition, str): columns.update(extract_column_names(condition)) + if isinstance(columns, _RestrictionAttributes): + columns.exact = False return combine_conditions(negate, conditions=[condition.strip().replace("%", "%%")]) # escape %, see issue #376 # restrict by AndList diff --git a/src/datajoint/diagram.py b/src/datajoint/diagram.py index 598d36d51..0ebd1e679 100644 --- a/src/datajoint/diagram.py +++ b/src/datajoint/diagram.py @@ -166,7 +166,8 @@ def _has_subquery(condition): def _seed_restriction(table_expr): """ - Return a traversal seed's restriction and the attributes it names. + Return a traversal seed's restriction, the attributes it names, and + whether those attributes are known exactly. Two kinds of seed are replaced by the primary keys they select: @@ -184,12 +185,12 @@ def _seed_restriction(table_expr): query; restrict by the keys in batches if that becomes a problem. """ if table_expr._top is not None or any(_has_subquery(c) for c in table_expr.restriction): - return AndList([table_expr.keys()]), set(table_expr.primary_key) + return AndList([table_expr.keys()]), set(table_expr.primary_key), True # The seed's conditions are compiled SQL, with each % already escaped as %% # for the driver. The traversal applies them again through restrict(), which # escapes again, so the escape is undone here. restriction = AndList(c.replace("%%", "%") if isinstance(c, str) else c for c in table_expr.restriction) - return restriction, set(table_expr.restriction_attributes) + return restriction, set(table_expr.restriction_attributes), table_expr._restriction_attributes_exact class Diagram(nx.MultiDiGraph): # noqa: C901 @@ -254,6 +255,7 @@ def __init__(self, source, context=None) -> None: self._cascade_restrictions = {k: copy.copy(v) for k, v in source._cascade_restrictions.items()} self._restrict_conditions = {k: copy.copy(v) for k, v in source._restrict_conditions.items()} self._restriction_attrs = {k: set(v) for k, v in source._restriction_attrs.items()} + self._inexact_attrs = set(source._inexact_attrs) super().__init__(source) return @@ -281,6 +283,7 @@ def __init__(self, source, context=None) -> None: self._cascade_restrictions = {} self._restrict_conditions = {} self._restriction_attrs = {} + self._inexact_attrs = set() # nodes whose restriction may name attributes not in _restriction_attrs # Enumerate nodes from all the items in the list self.nodes_to_show = set() @@ -505,6 +508,7 @@ def cascade(cls, table_expr, part_integrity="enforce"): result._cascade_restrictions = {} result._restrict_conditions = {} result._restriction_attrs = {} + result._inexact_attrs = set() # Include seed + all descendants descendants = set(nx.descendants(result, node)) | {node} @@ -512,9 +516,11 @@ def cascade(cls, table_expr, part_integrity="enforce"): result._expanded_nodes = set(descendants) # Seed restriction - restriction, restriction_attrs = _seed_restriction(table_expr) + restriction, restriction_attrs, exact = _seed_restriction(table_expr) result._cascade_restrictions[node] = [restriction] if restriction else [] result._restriction_attrs[node] = restriction_attrs + if not exact: + result._inexact_attrs.add(node) # Propagate downstream result._propagate_restrictions(node, mode="cascade", part_integrity=part_integrity) @@ -590,6 +596,7 @@ def trace(cls, table_expr): result._cascade_restrictions = {} # trace uses cascade-shape storage (OR semantics) result._restrict_conditions = {} result._restriction_attrs = {} + result._inexact_attrs = set() result._mode = "trace" # Include seed + all ancestors @@ -598,9 +605,11 @@ def trace(cls, table_expr): result._expanded_nodes = set(ancestors) # Seed restriction - restriction, restriction_attrs = _seed_restriction(table_expr) + restriction, restriction_attrs, exact = _seed_restriction(table_expr) result._cascade_restrictions[node] = [restriction] if restriction else [] result._restriction_attrs[node] = restriction_attrs + if not exact: + result._inexact_attrs.add(node) # Propagate upstream result._propagate_restrictions_upstream(node) @@ -799,9 +808,11 @@ def restrict(self, table_expr): if node not in result.nodes(): raise DataJointError(f"Table {node} is not in the diagram.") # Seed restriction (AND accumulation) - restriction, restriction_attrs = _seed_restriction(table_expr) + restriction, restriction_attrs, exact = _seed_restriction(table_expr) result._restrict_conditions.setdefault(node, AndList()).extend(restriction) result._restriction_attrs.setdefault(node, set()).update(restriction_attrs) + if not exact: + result._inexact_attrs.add(node) # Propagate downstream result._propagate_restrictions(node, mode="restrict") return result @@ -937,10 +948,13 @@ def _apply_propagation_rule( another foreign key would select child rows by that attribute instead of by the parent rows they reference. A secondary foreign key may be NULL, and then the child row references no parent row at all. + Copying also requires the restriction's attributes to be known exactly: + those of a string condition are parsed from its SQL text. """ child_pk = self.nodes[child_node].get("primary_key", set()) + exact = parent_ft.full_table_name not in self._inexact_attrs - if not aliased and parent_attrs and parent_attrs <= set(attr_map) <= child_pk: + if exact and not aliased and parent_attrs and parent_attrs <= set(attr_map) <= child_pk: # Rule 1: copy parent restriction directly parent_restr = restrictions.get( parent_ft.full_table_name, @@ -1001,11 +1015,13 @@ def _apply_propagation_rule_upward( ``copy_allowed=False`` disables Rule 1, so the parent is restricted to the rows that the restricted child rows actually reference. Copying the child's condition would also select parent rows that no child row - references. + references. Rule 1 also requires the child restriction's attributes to + be known exactly, as in the forward rule. """ parent_pk = self.nodes[parent_node].get("primary_key", set()) + exact = child_ft.full_table_name not in self._inexact_attrs - if copy_allowed and not aliased and child_attrs and child_attrs <= parent_pk: + if copy_allowed and exact and not aliased and child_attrs and child_attrs <= parent_pk: # Backward Rule 1: copy child restriction directly child_restr = restrictions.get( child_ft.full_table_name, @@ -1110,6 +1126,7 @@ def _propagate_part_to_master(self, part_node, master_name, mode, restrictions): node: ( copy.copy(restrictions[node]) if node in restrictions else None, set(self._restriction_attrs[node]) if node in self._restriction_attrs else None, + node in self._inexact_attrs, ) for node in intermediates } @@ -1166,8 +1183,9 @@ def _propagate_part_to_master(self, part_node, master_name, mode, restrictions): # included with zero matches in counts/iter. restrictions[master_name] = [False] self._restriction_attrs.setdefault(master_name, set()) + self._inexact_attrs.discard(master_name) # now a literal primary-key condition - for node, (restriction, attrs) in saved.items(): + for node, (restriction, attrs, inexact) in saved.items(): if restriction is None: restrictions.pop(node, None) else: @@ -1176,6 +1194,10 @@ def _propagate_part_to_master(self, part_node, master_name, mode, restrictions): self._restriction_attrs.pop(node, None) else: self._restriction_attrs[node] = attrs + if inexact: + self._inexact_attrs.add(node) + else: + self._inexact_attrs.discard(node) return any_propagated @@ -1266,6 +1288,7 @@ def prune(self): if len(result._restricted_table(node)) == 0: result._restrict_conditions.pop(node) result._restriction_attrs.pop(node, None) + result._inexact_attrs.discard(node) result.nodes_to_show.discard(node) else: # Unrestricted: check physical row counts diff --git a/src/datajoint/expression.py b/src/datajoint/expression.py index ca2b9be1b..b01750e4f 100644 --- a/src/datajoint/expression.py +++ b/src/datajoint/expression.py @@ -7,6 +7,7 @@ from .condition import ( AndList, Not, + _RestrictionAttributes, Top, assert_join_compatibility, extract_column_names, @@ -48,6 +49,7 @@ class QueryExpression: _restriction = None _restriction_attributes = None + _restriction_attributes_exact = True # False once a string condition names the attributes _joins = [] # list of (is_left: bool, using_attrs: list[str]) for each join _original_heading = None # heading before projections @@ -237,7 +239,7 @@ def restrict(self, restriction, semantic_check=True): QueryExpression A new QueryExpression with the restriction applied. """ - attributes = set() + attributes = _RestrictionAttributes() if isinstance(restriction, Top): if self._top is None: # No existing Top — apply new one directly @@ -274,6 +276,7 @@ def restrict(self, restriction, semantic_check=True): result._restriction = AndList(self.restriction) # copy to preserve the original result.restriction.append(new_condition) result.restriction_attributes.update(attributes) + result._restriction_attributes_exact = result._restriction_attributes_exact and attributes.exact return result def restrict_in_place(self, restriction): diff --git a/tests/integration/test_cascade_overdelete.py b/tests/integration/test_cascade_overdelete.py index e63ce1d6d..f2d492e54 100644 --- a/tests/integration/test_cascade_overdelete.py +++ b/tests/integration/test_cascade_overdelete.py @@ -325,3 +325,166 @@ class Use(dj.Manual): (Label & "name LIKE '50%'").delete(prompt=False) assert sorted(Label.to_arrays("label_id").tolist()) == [2, 3] assert sorted(Use.to_arrays("label_id").tolist()) == [2, 3] + + +def _string_seed_schema(schema): + """Parent and Child both have a secondary attribute ``notes``. Child's + ``notes`` is unrelated to its parent's.""" + + @schema + class Parent(dj.Manual): + definition = """ + subject : varchar(16) + --- + notes : varchar(8) + """ + + @schema + class Child(dj.Manual): + definition = """ + -> Parent + trial : int32 + --- + notes : varchar(8) + """ + + return Parent, Child + + +# A string condition's attribute names are read from its SQL text. Each form +# names `notes` in a way that reading leaves out; the value is the subject the +# condition selects by name. +STRING_FORMS = {"uppercase name": "a", "literal ending in backslash": "a\\"} + + +def _string_condition(table, form): + """Select subject ``STRING_FORMS[form]``, and subject ``w`` where ``notes = '1'``.""" + adapter = table.connection.adapter + literal = adapter.quote_string(STRING_FORMS[form]) + notes = "NOTES" if form == "uppercase name" else adapter.quote_identifier("notes") + return f"subject = {literal} OR ({notes} = '1' AND subject = 'w')" + + +def _insert_string_seed_rows(Parent, Child, a): + Parent.insert([(a, "1"), ("w", "1"), ("z", "2")]) + Child.insert([(a, 1, "2"), (a, 2, "1"), ("w", 1, "2"), ("z", 1, "1")]) + + +@pytest.mark.parametrize("form", list(STRING_FORMS)) +def test_cascade_string_restriction_projects_through_parent(schema_by_backend, form): + """A cascade from a string-restricted seed selects every child of the + selected parents, whatever the children's own attributes of the same name.""" + Parent, Child = _string_seed_schema(schema_by_backend) + a = STRING_FORMS[form] + _insert_string_seed_rows(Parent, Child, a) + + seed = Parent & _string_condition(Parent, form) + assert sorted(seed.to_arrays("subject").tolist()) == sorted([a, "w"]) + assert not seed._restriction_attributes_exact + + counts = dj.Diagram.cascade(seed).counts() + assert counts[Parent.full_table_name] == 2 + assert counts[Child.full_table_name] == 3 + + seed.delete(prompt=False) + assert Parent.to_arrays("subject").tolist() == ["z"] + assert Child.to_arrays("subject").tolist() == ["z"] + + +def test_cascade_dict_restriction_is_copied_to_child(schema_by_backend): + """A dict restriction names its attributes exactly, so the child receives + the parent's condition itself rather than a projection of the parent.""" + Parent, Child = _string_seed_schema(schema_by_backend) + _insert_string_seed_rows(Parent, Child, "a") + + seed = Parent & {"subject": "a"} + assert seed._restriction_attributes_exact + + diagram = dj.Diagram.cascade(seed) + parent_restriction = diagram._cascade_restrictions[Parent.full_table_name] + assert diagram._cascade_restrictions[Child.full_table_name] == parent_restriction + assert diagram.counts()[Child.full_table_name] == 2 + + seed.delete(prompt=False) + assert sorted(Parent.to_arrays("subject").tolist()) == ["w", "z"] + assert sorted(Child.to_arrays("subject").tolist()) == ["w", "z"] + + +@pytest.mark.parametrize("form", list(STRING_FORMS)) +def test_restrict_string_restriction_projects_through_parent(schema_by_backend, form): + """``Diagram.restrict`` selects every child of the selected parents.""" + Parent, Child = _string_seed_schema(schema_by_backend) + _insert_string_seed_rows(Parent, Child, STRING_FORMS[form]) + + restricted = dj.Diagram(schema_by_backend).restrict(Parent & _string_condition(Parent, form)) + counts = restricted.counts() + assert counts[Parent.full_table_name] == 2 + assert counts[Child.full_table_name] == 3 + + +@pytest.mark.parametrize("form", list(STRING_FORMS)) +def test_trace_string_restriction_projects_through_child(schema_by_backend, form): + """``trace`` from a string-restricted child selects the parents those child + rows reference, whatever the parents' own attributes of the same name.""" + Parent, Child = _string_seed_schema(schema_by_backend) + a = STRING_FORMS[form] + Parent.insert([(a, "2"), ("w", "1"), ("z", "1")]) + Child.insert([(a, 1, "1"), ("w", 1, "2"), ("z", 1, "2")]) + + seed = Child & _string_condition(Child, form) + assert seed.to_arrays("subject").tolist() == [a] + + traced = dj.Diagram.trace(seed) + assert traced[Parent.full_table_name].to_arrays("subject").tolist() == [a] + + +def test_part_cascade_string_restriction_lifts_to_master(schema_by_backend): + """With part_integrity="cascade", a string-restricted part seed lifts to the + masters of the selected part rows and cascades to all of their parts.""" + + @schema_by_backend + class Master(dj.Manual): + definition = """ + subject : varchar(16) + --- + notes : varchar(8) + """ + + class P(dj.Part): + definition = """ + -> master + p_id : int32 + --- + notes : varchar(8) + """ + + form = "uppercase name" + a = STRING_FORMS[form] + Master.insert([(a, "2"), ("w", "1"), ("z", "1")]) + Master.P.insert([(a, 1, "1"), (a, 2, "2"), ("w", 1, "2"), ("z", 1, "1")]) + + seed = Master.P & _string_condition(Master.P, form) + assert seed.to_arrays("subject").tolist() == [a, a] + + counts = dj.Diagram.cascade(seed, part_integrity="cascade").counts() + assert counts[Master.full_table_name] == 1 + assert counts[Master.P.full_table_name] == 2 + + seed.delete(prompt=False, part_integrity="cascade") + assert sorted(Master.to_arrays("subject").tolist()) == ["w", "z"] + assert sorted(Master.P.to_arrays("subject").tolist()) == ["w", "z"] + + +def test_trace_string_seed_selects_referenced_parents(schema_by_backend): + """``trace`` from a string-restricted child selects only the parents that + the selected child rows reference. A dict seed is copied to the parent + as a condition, so it selects every parent row that satisfies it.""" + Parent, Child = _string_seed_schema(schema_by_backend) + Parent.insert([("a", "1"), ("b", "1"), ("c", "1")]) + Child.insert([("a", 1, "1")]) + + string_seed = Child & "subject < 'c'" + assert len(dj.Diagram.trace(string_seed)[Parent.full_table_name]) == 1 + + dict_seed = Child & [{"subject": "a"}, {"subject": "b"}] + assert len(dj.Diagram.trace(dict_seed)[Parent.full_table_name]) == 2