Skip to content

Compile every subquery to one form with a kind and correlation from the binding, and read FROM subqueries, views and CTEs through one table source #3164

Backlog
0 of 2 issues completed

Description

@mathiasrw

What happens today

Each kind of subquery has its own path for the shape of the result, the cache and asynchronous sources.

  • A scalar subquery (Select.toJS in src/select/select.js) generates alasql.utils.flatArray(this.queriesfn[i](this.params, null, p))[0].
  • IN and NOT IN (Op.toJS in src/expression/expression.js) generate a cached and an uncached lookup and pick one on every row from query.isCorrelated (Review #2281 for code improvements: IN subquery caching decided per row #2645).
  • ALL, SOME and ANY run the subquery on every row.
  • EXISTS (ExistsValue.toJS in src/select/exists.js) runs the whole subquery on every row, also when it does not use the outer row (Review #1939 for code improvements: EXISTS runs its whole subquery for every outer row #2678).
  • isCorrelated in compileQueries looks for an outer table name only in WHERE and the select list.
  • queryfn (src/select/queryfn.js) clears subqueryCache and fills queriesdata, which nothing reads.
  • A subquery in FROM or JOIN reads its rows through subqueryDatafn (src/select/from.js), APPLY through applyselect (src/select/join.js), a view through viewDatafn without a callback, and a CTE through w.select.execute(..., cb) in executeWith (src/statements/with.js).

With 200 rows in t and in u, SELECT COUNT(*) FROM t WHERE EXISTS (SELECT 1 FROM u WHERE cnt(x) > 0) calls the user function cnt 40,000 times.

This also fixes #3143 and #3144.

What to change

Two pull requests, in this order.

(a) One compiled form with a kind

  1. Add src/select/subquery.js with a class for a compiled subquery.

    class Subquery {
      constructor(statement, kind, correlated, cache) { ... }
      // the rows of one run, on a child of the run context of #2667
      run(ctx, outer, cb) {
        return this.statement(ctx.params, cb, outer,
          {modifier: 'RECORDSET', ctx: ctx.child(outer), firstRow: this.kind === 'EXISTS' && this.canStop});
      }
      get(ctx, outer) { ... } // the kind's value, cached on ctx.root.caches when this.cache
    }
    const kinds = {
      SCALAR: rs => flatArray(rs)[0],
      IN: rs => { const values = flatArray(rs); return {values, has: ...}; },
      EXISTS: rs => rs.data.length > 0,
    };

    ctx.child(outer) shares params, db and the root, and holds the outer row in outer. The modifier goes in the run state, as as() in queryfn.js does for set-operation parts, not on the compiled query.

  2. Give each subquery its kind where the parser adds it to its SELECT's list (Give each SELECT its own list of subqueries from parsing on #2666). The scalar rule gives SCALAR. IN, NOT IN, ALL, SOME and ANY give IN. ExistsValue gives EXISTS. compileQueries builds a Subquery per entry.

  3. Change the readers. Scalar generates this.queriesfn[i].get(this.ctx, p). IN generates .get(this.ctx, p).has(v) and NOT IN its negation. ALL, SOME and ANY call .every and .some on .get(this.ctx, p).values. EXISTS generates .get(this.ctx, p). Keep this and this.query as each reader has it, keep the group row (this.groupSources.get(g) || g), and make the test in src/select/join.js match the new text. has uses a Set when the result is cached and indexOf when it is not.

  4. Decide correlation from the binding. Where Column.toJS (src/expression/expression.js) has bind.read, a read whose scope is above 0 sets sc.correlated = true on its scope and the scopes between it and the one it reads. Also call bind.column and bind.read in the lookupJS path when a scope exists, so the arguments of a FROM function are seen. After compiling a subquery, correlated is nq.query.columnScope.correlated. A bare outer name that 4.x reads from the inner source (rule notOuter, Correlated subquery with an unqualified outer column returns no rows #2644) does not mark. Remove isCorrelated, subqueryCache, queriesdata and isCorrelated in copyQuery.

  5. Cache policy, fixed at compile time.

    • In a SELECT, an uncorrelated subquery runs once per run of the statement, keyed by the Subquery object in ctx.root.caches. A correlated one runs per call.
    • A subquery that calls RANDOM, NEWID, UUID, GEN_RANDOM_UUID, NOW, GETDATE or CURRENT_TIMESTAMP runs per call. User functions count as deterministic.
    • In the statement-level list of UPDATE, DELETE, INSERT VALUES, SET, IF, WHILE and PRINT, IN and NOT IN stay cached per run and the other kinds run per call.
    • A statement without a run context builds one per call.
  6. EXISTS stops at the first row. With firstRow in the run state, doJoin (src/select/dojoin.js) sets query.stopped after the first row it adds, and its loop and the extra pass for LEFT JOIN stop. canStop is false when the subquery has GROUP BY or aggregates (groupfn), a set operation, an OFFSET or a sorted join (joinsorted). Add firstRow and stopped to copyQuery.

(b) One table source

  1. Add tableSource(compiled) to src/select/subquery.js with the interface of Give file sources one source interface that opens rows for a run and reports errors in one place #2677, {columns, open(ctx, outer)}. open runs the subquery with a callback and gives its rows, or a promise of them when a source is asynchronous. Turn it into datafn with the adapter of Give file sources one source interface that opens rows for a run and reports errors in one place #2677.
  2. Use it for a subquery in FROM and JOIN (replacing subqueryDatafn), for APPLY (with the outer row), for views (viewDatafn keeps compiling on first use and after a schema change) and for the CTE bodies in executeWith. The recursive CTE loop keeps its own runs. FROM keeps its dirtyColumns rule for columns, and JOIN keeps its own.

What stays the same

Done when

  • A new test file named after this issue covers scalar, IN, NOT IN, ALL, ANY and EXISTS, each uncorrelated and correlated through WHERE, ON, the select list, a nested subquery and a FROM function argument. Results are checked against SQLite where SQLite has the query.
  • The same file counts calls of a user function. An uncorrelated subquery runs once per run, a correlated one once per outer row, and EXISTS reads one row. SELECT (SELECT RANDOM()) gives a new value per row. The UPDATE of UPDATE with an uncorrelated scalar or EXISTS subquery sees rows the statement already changed #3145 keeps its result.
  • test/test2280.js reads correlated from the new object.
  • For (b), the test file reads a view, a FROM subquery, a JOIN subquery and a CTE over a CSV file with alasql.promise, with a time limit.
  • The generated code holds no correlation test, and isCorrelated, subqueryCache and queriesdata no longer exist.
  • test/performance/ shows no slowdown on Node for a correlated subquery.
  • The full test suite and the CI checks (dialect test, parity check, run-state check, binding check) pass, and the pull request lists every parity difference.

Fixes

Fixes #3143, #3144.

Depends on

#2666, #2667, #2677

Sub-issues

Sub-issues

0 of 2 Issues completed
Loading 2 sub-issues

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions