Repository navigation
Description
A time-boxed proof of concept, to be picked up later. Its product is a written report, not shipped code. It runs after the ES6 conversion and must report before the list of v5 breaking changes is closed.
Intention
alasql turns each SQL statement into JavaScript source text and makes functions from it with new Function, the first time the statement runs. Precompile means doing that step while the user's application is being built, and shipping the result as ordinary JavaScript. With the tagged template planned for v5, the SQL of a call site is a constant in the user's source:
const adults = alasql`SELECT name FROM ${people} WHERE age > ${18}`;A bundler plugin can find each tagged query, compile it during the build and replace the call with the compiled statement. What that gives, most important first:
- No
new Functionat run time. alasql could then run under a strict Content-Security-Policy, in Manifest V3 extensions and on Cloudflare Workers (Could be useful in Cloudflare Workers #1218, Content Security Policy (CSP) blocks eval() #1482, Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script... #1489, EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive #1667, EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive #1861). - The parser can leave the bundle. It is 362 KB of the 829 KB unminified build.
- SQL syntax errors show up at build time.
- The first call costs nothing. Parse and compile take about 0.14 ms per statement today.
Baseline: under node --disallow-code-generation-from-strings, SELECT and INSERT fail with Code generation from strings disallowed. CREATE TABLE and alasql.parse work. A precompiled application has to pass with that switch on.
The worry
The usual pattern is the normal engine during development and precompiled code in the production build. Then the people who use alasql test one thing and ship another. If the two differ, they find out in production, in a build step they cannot easily inspect. The worry is for the people using alasql, not for this repository. So the feature is only worth having if a difference between the two paths is impossible by construction, or loud.
Findings so far (v4.20.0)
The existing alasql/precompile module (#2169) has its own copy of the query loop. compileToJS(sql) takes three generated functions (selectfn, wherefn, orderfn) as text and wraps them in a loop of its own. It does not use the engine's runner. Sixteen statements were each run through the engine and through compileToJS, on the same data:
- Same result (7):
WHERE+ORDER BY, function calls,SELECT *,DISTINCT,ORDER BY … LIMIT,CASE/LIKE, a user-defined function. - Wrong result, no error (6):
SELECT VALUE,SELECT COLUMN, aggregates,GROUP BY(returns the source rows),UNION(keeps duplicates), window functions. - Throws (3):
JOIN, a subquery inWHERE,INSERT.
Also, the example turns the returned string into a function with new Function(...) when the application runs. So it skips parsing, but new Function is still there. The work did prove the first half of the idea: the generated functions can be lifted out as text.
A compiled statement is small. It has three parts:
- 4 to 7 functions made by
new Function, 736 to 2,646 bytes in total. They have no closure, sotoString()gives the whole function. - About 27 data fields.
- A call into the engine's runner,
queryfninsrc/38query.js. The runner cannot be reached from outside today's single-closure build.
Compile needs things that do not exist at build time. It needs the tables (Table does not exist) and their columns. It needs options that change the generated code (the cache key already carries joinstar; dialect modules will add more). It may need the parameters too; that is still to be checked.
Code generation is spread out. There are 81 new Function sites in 26 source files.
A tagged call site is constant. Its fixed text is the same object on every run, and a ${} is never pasted into the SQL text. The one exception is a name in brackets (ORDER BY [${col}]), which changes the SQL per name.
The principle to test: one compiler, two moments
Precompile runs the engine's own compiler earlier and writes down what it produced. The engine's own runner executes it. There is no second implementation of anything. From that:
- Never a different answer, only a refusal. A statement the plugin cannot handle stays a run-time compile, and the build warns. In a build without the compiler, it is a build error.
- The same path in development and in the build. The plugin is on in both. At 0.14 ms per statement there is no speed reason for anything else.
- A version lock. The generated code carries the alasql version and the dialect. A mismatch throws.
- A verify mode for users. In their own tests, each precompiled statement also compiles at run time, and any difference fails the test.
- alasql's own test suite through the precompile path in CI.
Decided for v5: compileToJS is correct or it refuses
A silently wrong result is not acceptable in v5. In 5.0, compileToJS either runs a statement through the engine's own runner (the principle above) or throws for a statement it cannot handle. Returning code that gives different rows, with no error, is removed. The second option alone is a guard: a check that throws compileToJS does not support GROUP BY and so on, instead of returning code that gives wrong rows. It is the minimum. It is a breaking change in error behaviour, which is why it belongs to 5.0.
When
After the ES6 conversion. Before it, the runner and the parts around it cannot be imported, and the PoC would spend its time on build glue. The conversion is not allowed to change behaviour, so nothing the PoC finds would change how the conversion is done. The PoC also needs the tag and re-entrant statements (#2596) to exist.
Before 5.0's breaking list closes. The PoC may find that the engine needs a breaking change: how tables are resolved at compile time, which options may change generated code, or the shape of a compiled statement.
Questions the PoC must answer
- Can every compiled statement be written out and read back? Which fields are data and which are references? Output: a table per statement type.
- Does the read-back statement give the same results through the engine's runner? Add a test-only mode where every statement goes compile → write out → read back → run. Output: pass, fail and skip counts against the normal run.
- Does a precompiled sample application run with
--disallow-code-generation-from-strings? If not, list thenew Functionsites still reached. - What is needed at build time for queries that name tables? Try a schema file. What happens when the run-time schema differs?
- What does a runtime without parser and compiler weigh? Today's minified build is 516 KB.
- How does the plugin find call sites, including the tag under the name
sqlor renamed? - What would have to change in the engine, and is any of it breaking?
Steps
- Export the runner. Write
toSource(statement)and the function that reads it back. Try one source withWHERE, aJOINwithGROUP BY, and anINSERT. - Run the test suite through that round trip. Classify each failure.
- Write the smallest plugin for one bundler (esbuild). Build a sample application of about ten queries, in development and production modes.
- Run the sample with code generation forbidden, and measure the bundle.
- Add verify mode and the version lock, then try to break them on purpose.
- Write the report.
Exit criteria
- Go: the round trip passes the suite except for a named list of statement types. The sample runs with code generation forbidden. The engine changes are listed.
- Go, narrower: only statements whose sources are all interpolated (
FROM ${rows}) can be precompiled. This still gives an eval-free build for applications written that way. - No: a large class of statements needs a second run loop. Then precompile stays an opt-in helper, and the eval-free goal moves to an interpreter that walks the syntax tree (a 5.x topic).
Not in scope: making the engine free of new Function for SQL that arrives at run time; TypeScript types from SQL; plugins for every bundler.
Open
- Who runs it, and is a two-week box right?
- In a build without the compiler, is "a statement that cannot be precompiled is a build error" the rule?
Related: #2169 (compileToJS), #2596 (re-entrant statements), #1218, #1482.
Activity