Repository navigation
Description
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.toJSinsrc/select/select.js) generatesalasql.utils.flatArray(this.queriesfn[i](this.params, null, p))[0]. - IN and NOT IN (
Op.toJSinsrc/expression/expression.js) generate a cached and an uncached lookup and pick one on every row fromquery.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.toJSinsrc/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). isCorrelatedincompileQuerieslooks for an outer table name only in WHERE and the select list.queryfn(src/select/queryfn.js) clearssubqueryCacheand fillsqueriesdata, which nothing reads.- A subquery in FROM or JOIN reads its rows through
subqueryDatafn(src/select/from.js), APPLY throughapplyselect(src/select/join.js), a view throughviewDatafnwithout a callback, and a CTE throughw.select.execute(..., cb)inexecuteWith(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
-
Add
src/select/subquery.jswith 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)sharesparams,dband the root, and holds the outer row inouter. The modifier goes in the run state, asas()inqueryfn.jsdoes for set-operation parts, not on the compiled query. -
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.
ExistsValuegives EXISTS.compileQueriesbuilds aSubqueryper entry. -
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.everyand.someon.get(this.ctx, p).values. EXISTS generates.get(this.ctx, p). Keepthisandthis.queryas each reader has it, keep the group row(this.groupSources.get(g) || g), and make the test insrc/select/join.jsmatch the new text.hasuses aSetwhen the result is cached andindexOfwhen it is not. -
Decide correlation from the binding. Where
Column.toJS(src/expression/expression.js) hasbind.read, a read whosescopeis above 0 setssc.correlated = trueon its scope and the scopes between it and the one it reads. Also callbind.columnandbind.readin thelookupJSpath when a scope exists, so the arguments of a FROM function are seen. After compiling a subquery,correlatedisnq.query.columnScope.correlated. A bare outer name that 4.x reads from the inner source (rulenotOuter, Correlated subquery with an unqualified outer column returns no rows #2644) does not mark. RemoveisCorrelated,subqueryCache,queriesdataandisCorrelatedincopyQuery. -
Cache policy, fixed at compile time.
- In a SELECT, an uncorrelated subquery runs once per run of the statement, keyed by the
Subqueryobject inctx.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.
- In a SELECT, an uncorrelated subquery runs once per run of the statement, keyed by the
-
EXISTS stops at the first row. With
firstRowin the run state,doJoin(src/select/dojoin.js) setsquery.stoppedafter the first row it adds, and its loop and the extra pass for LEFT JOIN stop.canStopis false when the subquery has GROUP BY or aggregates (groupfn), a set operation, an OFFSET or a sorted join (joinsorted). AddfirstRowandstoppedtocopyQuery.
(b) One table source
- Add
tableSource(compiled)tosrc/select/subquery.jswith 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)}.openruns the subquery with a callback and gives its rows, or a promise of them when a source is asynchronous. Turn it intodatafnwith the adapter of Give file sources one source interface that opens rows for a run and reports errors in one place #2677. - Use it for a subquery in FROM and JOIN (replacing
subqueryDatafn), for APPLY (with the outer row), for views (viewDatafnkeeps compiling on first use and after a schema change) and for the CTE bodies inexecuteWith. The recursive CTE loop keeps its own runs. FROM keeps itsdirtyColumnsrule forcolumns, and JOIN keeps its own.
What stays the same
- Every result, column name and error text, except An IN or NOT IN subquery whose only outer column is in JOIN ON or in a FROM function reuses the result of the first outer row #3143 and A view over a file source throws Data source number 0 in undefined #3144.
- A scalar subquery with several rows gives the first value of the first row, with several columns the first column, and with no rows
undefined. IN reads the first column (IN with a subquery of two columns uses the first column: x IN (SELECT x, y FROM t1) #2757). - A scalar, IN or EXISTS subquery over an asynchronous source still gets no rows (IndexedDB - SELECT + where EXISTS(SELECT ...) - Error #1130). A correlated subquery in UPDATE or DELETE still throws (A correlated subquery in the WHERE of UPDATE or DELETE throws a TypeError #2792). A correlation in HAVING still gives no rows.
- In UPDATE and DELETE, scalar and EXISTS subqueries still run per row (UPDATE with an uncorrelated scalar or EXISTS subquery sees rows the statement already changed #3145 stays as it is).
- Graph statements (
src/graph/) andInsert.toJScall the whole statement.
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.jsreadscorrelatedfrom 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,subqueryCacheandqueriesdatano 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.
Activity