diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index a3f2bc5c8..79f5b86b3 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -54,6 +54,27 @@ jobs: DJ_TEST_MYSQL_IMAGE: ${{ matrix.mysql-image }} run: pixi run -e ${{ matrix.environment }} test-cov + # Subquery pruning (#1665) is on by default; keep the fallback path working + # while the prune_subqueries switch exists. + test-no-pruning: + runs-on: ubuntu-latest + name: test (test-py314, mysql=datajoint/mysql:8.0, prune_subqueries=False) + steps: + - uses: actions/checkout@v4 + + - name: Set up pixi + uses: prefix-dev/setup-pixi@v0.9.3 + with: + cache: true + locked: false + environments: test-py314 + + - name: Run tests + env: + DJ_TEST_MYSQL_IMAGE: datajoint/mysql:8.0 + DJ_PRUNE_SUBQUERIES: "0" + run: pixi run -e test-py314 test + # Unit tests run without containers (faster feedback) unit-tests: runs-on: ubuntu-latest diff --git a/src/datajoint/autopopulate.py b/src/datajoint/autopopulate.py index 1738b52e5..64ce68e6e 100644 --- a/src/datajoint/autopopulate.py +++ b/src/datajoint/autopopulate.py @@ -796,8 +796,9 @@ def progress(self, *restrictions: Any, display: bool = False) -> tuple[int, int] else: # Build a single query that computes both total and remaining # Using LEFT JOIN with COUNT(DISTINCT) to handle 1:many relationships - todo_sql = todo.make_sql() - target_sql = self.make_sql() + # select only the attributes the counting query below refers to + todo_sql = todo.proj().make_sql() + target_sql = self.make_sql(common_attrs) # Get adapter for backend-specific quoting adapter = self.connection.adapter diff --git a/src/datajoint/expression.py b/src/datajoint/expression.py index 1b5f5ac9e..86d6376f1 100644 --- a/src/datajoint/expression.py +++ b/src/datajoint/expression.py @@ -102,11 +102,47 @@ def primary_key(self): _subquery_alias_count = count() # count for alias names used in the FROM clause - def from_clause(self): + def _level_text(self, fields): + """ + SQL text of this level, apart from its subqueries: the select list, WHERE, + ORDER BY, and USING lists. Any attribute of a subquery that this level uses + is named somewhere in it. + """ + adapter = self.connection.adapter + parts = [self.heading.as_sql(fields or self.heading.names, adapter=adapter), self.sorting_clauses()] + parts += map(str, self.restriction) + parts += (a for _, using_attrs in self._joins for a in using_attrs) + return " ".join(parts) + + def _required_fields(self, words): + """ + Attributes an enclosing query needs from this expression used as a subquery: + the primary key, which keeps rows distinct, plus any attribute whose name is + among ``words``. Names are matched as whole words of the enclosing SQL, which + may keep an attribute that is not needed but never drops one that is. + """ + if self._top: + words = words | _words(self.sorting_clauses()) + return [n for n in self.heading.names if n in self.primary_key or n.lower() in words] + + def from_clause(self, fields=None): + """ + The FROM clause, with each subquery rendered as SQL. + + Parameters + ---------- + fields : list, optional + Attributes this level selects. With ``config["prune_subqueries"]``, each + subquery selects only the attributes this level uses. + """ adapter = self.connection.adapter + words = _words(self._level_text(fields)) if self.connection._config["prune_subqueries"] else None support = ( ( - "({}) as {}".format(src.make_sql(), adapter.quote_identifier(f"${next(self._subquery_alias_count):x}")) + "({}) as {}".format( + src.make_sql(None if words is None else src._required_fields(words)), + adapter.quote_identifier(f"${next(self._subquery_alias_count):x}"), + ) if isinstance(src, QueryExpression) else src ) @@ -161,7 +197,7 @@ def make_sql(self, fields=None): return "SELECT {distinct}{fields} FROM {from_}{where}{sorting}".format( distinct="DISTINCT " if self._distinct else "", fields=self.heading.as_sql(fields or self.heading.names, adapter=self.connection.adapter), - from_=self.from_clause(), + from_=self.from_clause(fields), where=self.where_clause(), sorting=self.sorting_clauses(), ) @@ -1160,18 +1196,14 @@ def __len__(self): # Build COUNT query - PostgreSQL requires different syntax for multi-column DISTINCT adapter = result.connection.adapter + fields = result.heading.as_sql(result.primary_key, include_aliases=False, adapter=adapter) + from_ = result.from_clause(result.primary_key) if has_left_join or len(result.primary_key) > 1: # Use subquery with DISTINCT for multi-column primary keys (backend-agnostic) - fields = result.heading.as_sql(result.primary_key, include_aliases=False, adapter=adapter) - query = ( - f"SELECT count(*) FROM (" - f"SELECT DISTINCT {fields} FROM {result.from_clause()}{result.where_clause()}" - f") AS distinct_count" - ) + query = f"SELECT count(*) FROM (SELECT DISTINCT {fields} FROM {from_}{result.where_clause()}) AS distinct_count" else: # Single column - can use count(DISTINCT col) directly - fields = result.heading.as_sql(result.primary_key, include_aliases=False, adapter=adapter) - query = f"SELECT count(DISTINCT {fields}) FROM {result.from_clause()}{result.where_clause()}" + query = f"SELECT count(DISTINCT {fields}) FROM {from_}{result.where_clause()}" return result.connection.query(query).fetchone()[0] @@ -1188,7 +1220,9 @@ def __bool__(self): """ return bool( self.connection.query( - "SELECT EXISTS(SELECT 1 FROM {from_}{where})".format(from_=self.from_clause(), where=self.where_clause()) + "SELECT EXISTS(SELECT 1 FROM {from_}{where})".format( + from_=self.from_clause(self.primary_key), where=self.where_clause() + ) ).fetchone()[0] ) @@ -1352,8 +1386,29 @@ def create(cls, groupby, group, keep_all_rows=False): def where_clause(self): return "" if not self._left_restrict else " WHERE (%s)" % ")AND(".join(str(s) for s in self._left_restrict) + def _level_text(self, fields): + # also the pre-GROUP BY WHERE, HAVING, and GROUP BY + return " ".join( + [ + super()._level_text(fields), + *map(str, self._left_restrict or []), + *(self._grouping_attributes or []), + ] + ) + + def _required_fields(self, words): + """ + As for QueryExpression, plus the attributes HAVING refers to, which must stay + in the same SELECT list. Without GROUP BY, all attributes are kept: dropping + every aggregate would return one row per input row instead of one row. + """ + if not self.primary_key: + return None + return super()._required_fields(words | _words(" ".join(map(str, self.restriction)))) + def make_sql(self, fields=None): adapter = self.connection.adapter + from_ = self.from_clause(fields) fields = self.heading.as_sql(fields or self.heading.names, adapter=adapter) assert self._grouping_attributes or not self.restriction distinct = set(self.heading.names) == set(self.primary_key) @@ -1367,7 +1422,7 @@ def make_sql(self, fields=None): inner_sql = "SELECT {distinct}{fields} FROM {from_}{where}{group_by}".format( distinct="DISTINCT " if distinct else "", fields=fields, - from_=self.from_clause(), + from_=from_, where=self.where_clause(), group_by=" GROUP BY {}".format(", ".join(adapter.quote_identifier(col) for col in self._grouping_attributes)), ) @@ -1380,7 +1435,7 @@ def make_sql(self, fields=None): return "SELECT {distinct}{fields} FROM {from_}{where}{group_by}{sorting}".format( distinct="DISTINCT " if distinct else "", fields=fields, - from_=self.from_clause(), + from_=from_, where=self.where_clause(), group_by=( "" @@ -1395,10 +1450,12 @@ def make_sql(self, fields=None): def __len__(self): alias = self.connection.adapter.quote_identifier(f"${next(self._subquery_alias_count):x}") - return self.connection.query(f"SELECT count(1) FROM ({self.make_sql()}) {alias}").fetchone()[0] + sql = self.make_sql(self._required_fields(set())) + return self.connection.query(f"SELECT count(1) FROM ({sql}) {alias}").fetchone()[0] def __bool__(self): - return bool(self.connection.query("SELECT EXISTS({sql})".format(sql=self.make_sql())).fetchone()[0]) + sql = self.make_sql(self._required_fields(set())) + return bool(self.connection.query(f"SELECT EXISTS({sql})").fetchone()[0]) class Union(QueryExpression): @@ -1429,23 +1486,37 @@ def create(cls, arg1, arg2): result._support = [arg1, arg2] return result - def make_sql(self): + def make_sql(self, fields=None): + """ + Make the SQL for the union. + + Parameters + ---------- + fields : list, optional + Attributes to select, in order. Defaults to all attributes. Both + branches select the same list so that columns line up by position. + """ arg1, arg2 = self._support - if not arg1.heading.secondary_attributes and not arg2.heading.secondary_attributes: - # no secondary attributes: use UNION DISTINCT - fields = arg1.primary_key + fields = list(fields or self.heading.names) + if not any(f in self.heading.secondary_attributes for f in fields): + # only key attributes requested: UNION removes duplicates alias_name = f"_u{next(self.__count)}{self.sorting_clauses()}" alias_quoted = self.connection.adapter.quote_identifier(alias_name) - sql1 = arg1.make_sql() if isinstance(arg1, Union) else arg1.make_sql(fields) - sql2 = arg2.make_sql() if isinstance(arg2, Union) else arg2.make_sql(fields) + # an Aggregation's HAVING may refer to aliases outside `fields`, so select from it as a subquery + sql1, sql2 = ( + (arg.make_subquery() if isinstance(arg, Aggregation) else arg).make_sql(fields) for arg in (arg1, arg2) + ) return f"SELECT * FROM (({sql1}) UNION ({sql2})) as {alias_quoted}" - # with secondary attributes, use union of left join with anti-restriction - fields = self.heading.names + # with secondary attributes: left join of arg1 with arg2, plus the rows of arg2 + # whose keys are not in arg1 (complement of restriction). sql1 = arg1.join(arg2, left=True).make_sql(fields) sql2 = (arg2 - arg1).proj(..., **{k: "NULL" for k in arg1.heading.secondary_attributes}).make_sql(fields) - return "({sql1}) UNION ({sql2})".format(sql1=sql1, sql2=sql2) + # The two branches have disjoint primary keys, so when the primary key is selected + # no row can repeat and UNION ALL skips the comparison of whole rows (blobs included). + union = "UNION ALL" if set(self.primary_key) <= set(fields) else "UNION" + return f"({sql1}) {union} ({sql2})" - def from_clause(self): + def from_clause(self, fields=None): """The union does not use a FROM clause.""" raise NotImplementedError("Union does not use a FROM clause") @@ -1454,11 +1525,17 @@ def where_clause(self): raise NotImplementedError("Union does not use a WHERE clause") def __len__(self): + # rows of a union are unique by primary key, so counting keys suffices alias = self.connection.adapter.quote_identifier(f"${next(QueryExpression._subquery_alias_count):x}") - return self.connection.query(f"SELECT count(1) FROM ({self.make_sql()}) {alias}").fetchone()[0] + sql = self.make_sql(self.primary_key) + return self.connection.query(f"SELECT count(1) FROM ({sql}) {alias}").fetchone()[0] def __bool__(self): - return bool(self.connection.query("SELECT EXISTS({sql})".format(sql=self.make_sql())).fetchone()[0]) + if not self._top: + # a union is non-empty when either operand is + return any(bool(arg) for arg in self._support) + sql = self.make_sql(self.primary_key) + return bool(self.connection.query(f"SELECT EXISTS({sql})").fetchone()[0]) class U: @@ -1577,6 +1654,11 @@ def aggr(self, group, **named_attributes): aggregate = aggr # alias for aggr +def _words(sql): + """The set of lowercase words in an SQL fragment, quoted identifiers included.""" + return set(re.findall(r"\w+", sql.lower())) + + def _flatten_attribute_list(primary_key, attrs): """ Flatten an attribute list, replacing "KEY" with primary key attributes. diff --git a/src/datajoint/settings.py b/src/datajoint/settings.py index 0929f301d..094d645cf 100644 --- a/src/datajoint/settings.py +++ b/src/datajoint/settings.py @@ -430,6 +430,16 @@ class Config(BaseSettings): loglevel: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = Field(default="INFO", validation_alias="DJ_LOG_LEVEL") safemode: bool = True + prune_subqueries: bool = Field( + default=True, + validation_alias="DJ_PRUNE_SUBQUERIES", + description="If True (default), nested subqueries select only the attributes their enclosing query uses " + "(the primary key plus any attribute it names). Avoids carrying unused columns, such as blobs, " + "through subqueries the database materializes (ORDER BY/LIMIT, GROUP BY, UNION). Set to False " + "to render every nested subquery with all of its attributes, as before 2.4. Applies to query " + "expressions built after the setting changes. *New in 2.4*.", + ) + ignore_config_file: bool = Field( default=False, validation_alias="DJ_IGNORE_CONFIG_FILE", diff --git a/src/datajoint/table.py b/src/datajoint/table.py index 2c8a4adaa..6c170ff18 100644 --- a/src/datajoint/table.py +++ b/src/datajoint/table.py @@ -385,10 +385,15 @@ def alter(self, prompt=True, context=None): if prompt: logger.info("Table altered") - def from_clause(self): + def from_clause(self, fields=None): """ Return the FROM clause of SQL SELECT statements. + Parameters + ---------- + fields : list, optional + Ignored: a table has no subqueries to narrow. + Returns ------- str diff --git a/tests/integration/test_subquery_narrowing.py b/tests/integration/test_subquery_narrowing.py new file mode 100644 index 000000000..8ce00812d --- /dev/null +++ b/tests/integration/test_subquery_narrowing.py @@ -0,0 +1,193 @@ +""" +Union and Aggregation select only the attributes their callers need. + +Covers Union.make_sql(fields), restriction by a Union, insert from a Union, +and the narrowed len()/bool() of Union and Aggregation, on both backends. +""" + +import pytest + +import datajoint as dj + + +@pytest.fixture +def schema_narrow(connection_by_backend, backend, prefix): + schema = dj.Schema(f"{prefix}_narrow_{backend}", connection=connection_by_backend) + + @schema + class Subject(dj.Manual): + definition = """ + subject_id : int32 + --- + subject_name : varchar(16) + """ + + @schema + class Session(dj.Manual): + definition = """ + -> Subject + session_id : int32 + --- + note : varchar(16) + """ + + @schema + class NoteA(dj.Manual): + definition = """ + -> Subject + --- + a_val : int32 + a_blob : bytes + """ + + @schema + class NoteB(dj.Manual): + definition = """ + -> Subject + --- + b_val : int32 + """ + + @schema + class Target(dj.Manual): + definition = """ + -> Subject + --- + a_val = null : int32 + b_val = null : int32 + """ + + Subject.insert([(i, f"s{i}") for i in range(1, 6)]) + Session.insert([(1, 1, "x"), (1, 2, "x"), (1, 3, "x"), (2, 1, "x"), (3, 1, "x"), (3, 2, "x"), (5, 1, "x")]) + NoteA.insert([(1, 10, b"\x00" * 100), (2, 20, b"\x01" * 100), (3, 30, b"\x02" * 100)]) + NoteB.insert([(3, 300), (4, 400)]) + yield dict(Subject=Subject, Session=Session, NoteA=NoteA, NoteB=NoteB, Target=Target) + schema.drop(prompt=False) + + +@pytest.mark.backend_agnostic +def test_union_with_secondary_attributes(schema_narrow): + s = schema_narrow + u = s["NoteA"].proj("a_val") + s["NoteB"] + rows = {r["subject_id"]: (r["a_val"], r["b_val"]) for r in u.to_dicts()} + assert rows == {1: (10, None), 2: (20, None), 3: (30, 300), 4: (None, 400)} + assert len(u) == 4 + assert bool(u) + assert bool(u & "subject_id > 3") + assert not bool(u & "subject_id > 4") + + +@pytest.mark.backend_agnostic +def test_union_selected_fields(schema_narrow): + s = schema_narrow + u = s["NoteA"] + s["NoteB"] + assert sorted(u.to_arrays("b_val").tolist(), key=lambda v: (v is None, v)) == [300, 400, None, None] + assert sorted(u.keys(), key=lambda k: k["subject_id"]) == [{"subject_id": i} for i in (1, 2, 3, 4)] + sql = u.make_sql(["subject_id", "b_val"]) + assert "a_blob" not in sql and "UNION ALL" in sql + + +@pytest.mark.backend_agnostic +def test_restrict_by_union(schema_narrow): + s = schema_narrow + u = s["NoteA"].proj("a_val") + s["NoteB"] + assert set((s["Subject"] & u).to_arrays("subject_id")) == {1, 2, 3, 4} + assert set((s["Subject"] - u).to_arrays("subject_id")) == {5} + assert len(s["Session"] & (u & "b_val > 350")) == 0 + assert len(s["Session"] & (u & "a_val >= 20")) == 3 + + +@pytest.mark.backend_agnostic +def test_insert_from_union(schema_narrow): + s = schema_narrow + s["Target"].insert(s["NoteA"].proj("a_val") + s["NoteB"]) + rows = {r["subject_id"]: (r["a_val"], r["b_val"]) for r in s["Target"].to_dicts()} + assert rows == {1: (10, None), 2: (20, None), 3: (30, 300), 4: (None, 400)} + + +@pytest.mark.backend_agnostic +def test_union_with_having_operand(schema_narrow): + """A key-only union whose operand is an Aggregation restricted by HAVING.""" + s = schema_narrow + busy = s["Subject"].aggr(s["Session"], n="count(*)") & "n > 1" # subjects 1, 3 + u = busy + s["NoteB"] # subjects 1, 3, 4 + assert len(u) == 3 + assert set(u.to_arrays("subject_id")) == {1, 3, 4} + assert bool(u) + + +@pytest.mark.backend_agnostic +def test_aggregation_len_and_bool(schema_narrow): + s = schema_narrow + agg = s["Subject"].aggr(s["Session"], ..., n="count(*)") + assert len(agg) == 5 + assert len(agg & "n > 1") == 2 + assert len(agg & "n > 5") == 0 + assert bool(agg & "n > 2") + assert not bool(agg & "n > 3") + top = agg & dj.Top(limit=2, order_by="n DESC") + assert len(top) == 2 # ORDER BY n keeps n in the counted SELECT + assert bool(top) + # no GROUP BY: a single row + assert len(dj.U().aggr(s["Session"], n="count(*)")) == 1 + + +# --- config["prune_subqueries"]: nested subqueries select only what the enclosing query uses --- + +PRUNING_CASES = { + "top restricted": lambda s: (s["NoteA"] & dj.Top(2, "a_val DESC")) & "a_val > 15", + "top reordered": lambda s: (s["NoteA"] & dj.Top(3, "a_val DESC")) & dj.Top(2, "subject_id"), + "join of three": lambda s: (s["Subject"] * s["Session"] * s["NoteA"]).proj(), + "aggr joined": lambda s: (s["NoteA"].aggr(s["Session"], ..., n="count(*)") * s["NoteB"]).proj("n", "b_val"), + "aggr having": lambda s: s["Subject"] & (s["NoteA"].aggr(s["Session"], ..., n="count(*)", m="max(session_id)") & "n > 1"), + "aggr having proj": lambda s: (s["NoteA"].aggr(s["Session"], ..., n="count(*)") & "n > 1").proj(), + "aggr top": lambda s: (s["NoteA"].aggr(s["Session"], ..., n="count(*)") & dj.Top(2, "n DESC")) * s["Session"], + "aggr no group by": lambda s: dj.U().aggr(s["Session"], n="count(*)", m="max(session_id)"), + "union joined": lambda s: ((s["NoteA"] + s["NoteB"]) * s["Session"]).proj(), + "union restricted": lambda s: ((s["NoteA"] + s["NoteB"]) & "b_val > 100").proj("b_val"), + "union of aggr": lambda s: (s["Subject"].aggr(s["Session"], n="count(*)") & "n > 1") + s["NoteB"], + "restrict by union": lambda s: s["Session"] & ((s["NoteA"] + s["NoteB"]) & "a_val > 15"), + "renamed": lambda s: (s["NoteA"].proj(v="a_val") & "v > 15").proj(), + "computed": lambda s: (s["NoteA"].proj(..., w="a_val * 2") & "w > 30").proj("w"), + "renamed key": lambda s: (s["NoteA"].proj("a_val", sid="subject_id") & "sid > 1") * s["Subject"].proj(sid="subject_id"), + "left join": lambda s: (s["Session"] & dj.Top(5, "session_id")).extend(s["NoteA"]).proj("a_val"), +} + + +def _evaluate(expr): + def plain(v): + return bytes(v) if isinstance(v, memoryview) else v + + rows = sorted(repr(sorted((k, plain(v)) for k, v in r.items())) for r in expr.to_dicts()) + return rows, len(expr), bool(expr) + + +@pytest.mark.backend_agnostic +@pytest.mark.parametrize("case", PRUNING_CASES) +def test_pruning_preserves_results(schema_narrow, case): + make = PRUNING_CASES[case] + with dj.config.override(prune_subqueries=False): + expected = _evaluate(make(schema_narrow)) + with dj.config.override(prune_subqueries=True): + assert _evaluate(make(schema_narrow)) == expected + + +@pytest.mark.backend_agnostic +@pytest.mark.parametrize("case", ["top restricted", "aggr joined", "aggr having proj", "union joined", "union restricted"]) +def test_pruning_drops_unused_blob(schema_narrow, case): + """The outer query selects only keys, so no subquery needs the blob.""" + with dj.config.override(prune_subqueries=False): + assert "a_blob" in PRUNING_CASES[case](schema_narrow).proj().make_sql() + with dj.config.override(prune_subqueries=True): + assert "a_blob" not in PRUNING_CASES[case](schema_narrow).proj().make_sql() + + +@pytest.mark.backend_agnostic +def test_pruning_keeps_having_alias(schema_narrow): + s = schema_narrow + # the restriction's subquery is rendered when it is applied, so build it with pruning on + with dj.config.override(prune_subqueries=True): + expr = s["Subject"] & (s["NoteA"].aggr(s["Session"], ..., n="count(*)", m="max(session_id)") & "n > 1") + sql = expr.make_sql() + assert " as " in sql.lower() and "count(*)" in sql.lower() # n stays for HAVING + assert "max(" not in sql.lower() # m is not used diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py index 1cb535d81..645718d17 100644 --- a/tests/unit/test_settings.py +++ b/tests/unit/test_settings.py @@ -1197,3 +1197,22 @@ def test_backend_field_in_env_var_mapping(self): assert "database.backend" in ENV_VAR_MAPPING assert ENV_VAR_MAPPING["database.backend"] == "DJ_BACKEND" + + +class TestPruneSubqueries: + """Test the prune_subqueries switch (#1665).""" + + def test_default_on(self, monkeypatch): + monkeypatch.delenv("DJ_PRUNE_SUBQUERIES", raising=False) + assert settings.Config().prune_subqueries is True + + @pytest.mark.parametrize("value, expected", [("0", False), ("false", False), ("1", True), ("true", True)]) + def test_env_var(self, monkeypatch, value, expected): + monkeypatch.setenv("DJ_PRUNE_SUBQUERIES", value) + assert settings.Config().prune_subqueries is expected + + def test_override(self): + original = dj.config.prune_subqueries + with dj.config.override(prune_subqueries=not original): + assert dj.config["prune_subqueries"] is (not original) + assert dj.config.prune_subqueries is original