DuckDB Extension
QuickJS
Run JavaScript expressions and functions inside DuckDB SQL with QuickJS. Pass row values as arguments or return arrays through the table function.
On this page
In the DuckDB 2.0 build, quickjs_eval passes SQL values as native JavaScript values (numbers, BigInt, Date, Uint8Array, arrays, objects) instead of strings, returns SQL NULL for undefined, awaits promises, and bounds scripts with the quickjs_memory_limit and quickjs_timeout_ms settings. See Changes in the DuckDB 2.0 release.
Sample data for the examples
Each browser example starts with these sample tables; sample files are shared across examples on this page. Run this setup first when trying the examples in your own DuckDB session.
-- Fixtures for quickjs cookbook / technical-details / functions.json examples.
-- Small, deterministic, idempotent. Backs snippets that read from `events`
-- (raw event rows with a JSON `payload` column) and `transformed_events`
-- (the result-shaped table that holds an `extracted` JSON column).
CREATE OR REPLACE TABLE events (
id INTEGER,
event_type TEXT,
payload TEXT
);
INSERT INTO events VALUES
(1, 'login', '{"event":"login","user":"alice","meta":{"device":"phone","os":"ios"}}'),
(2, 'purchase', '{"event":"purchase","user":"bob","amount":42.50,"meta":{"item":"book","os":"android","currency":"USD"}}'),
(3, 'login', '{"event":"login","user":"carol","meta":{"device":"laptop","os":"linux"}}');
CREATE OR REPLACE TABLE transformed_events (
id INTEGER,
extracted JSON
);
INSERT INTO transformed_events VALUES
(1, '{"user":"alice","os":"ios"}'),
(2, '{"user":"bob","os":"android"}');
Use JavaScript for a transformation inside SQL
QuickJS embeds a JavaScript engine in DuckDB. You pass SQL values to JavaScript expressions or functions and use their results in the surrounding query. A table form can turn a returned array into rows.
Use it when you already have JavaScript transformation logic or need to handle a custom structure. The embedded engine is not a Node.js process, so Node-specific modules are not automatically available. Ordinary SQL remains useful for operations DuckDB already expresses directly.
Example
Call JavaScript with SQL values
The SQL values become arguments to the JavaScript function. QuickJS returns its result as JSON.
Tested with DuckDB 1.5.6. Browser examples use Haybarn-Wasm 2.0.0-rc12.
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://duckdb-extensions.query.farm';
INSTALL quickjs FROM query_farm;
LOAD quickjs FROM query_farm;
WITH values_to_scale(n) AS (VALUES (3), (7))
SELECT n, quickjs_eval('(value) => value * 2', n) AS doubled
FROM values_to_scale
ORDER BY n;
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://haybarn-extensions.query.farm';
INSTALL quickjs FROM query_farm;
LOAD quickjs FROM query_farm;
WITH values_to_scale(n) AS (VALUES (3), (7))
SELECT n, quickjs_eval('(value) => value * 2', n) AS doubled
FROM values_to_scale
ORDER BY n;
INSTALL quickjs FROM community;
LOAD quickjs;
WITH values_to_scale(n) AS (VALUES (3), (7))
SELECT n, quickjs_eval('(value) => value * 2', n) AS doubled
FROM values_to_scale
ORDER BY n;
Expected result
| n | doubled |
|---|---|
| 3 | 6 |
| 7 | 14 |
Use DuckDB expressions for simple arithmetic in real queries. This small example shows the argument boundary for JavaScript logic that SQL does not already provide.
Common tasks
Deep Dive
Technical Details
What you can do with one query
The magic moment — when SQL doesn’t have the right primitive, drop into JavaScript inline:
SELECT id, quickjs_eval( '(payload) => { const d = JSON.parse(payload); if (d.event === "purchase") { return { user: d.user, amount: d.amount, ccy: d.meta?.currency ?? "USD" }; } return { user: d.user, event: d.event }; }', payload ) AS extractedFROM events;quickjs_eval hands each row’s payload to the arrow function, runs it inside the embedded QuickJS-NG engine, and returns the result as JSON — ready to chain into ->> extractors or UNNEST. Conditional shapes that turn into a tower of CASE and json_extract in pure SQL stay short and readable here.
Row-by-row JavaScript is genuinely slower than vectorized SQL. Reach for QuickJS when you actually need expressiveness JavaScript provides — conditional JSON reshaping, text munging beyond regex, custom parsing — not as a first resort.
- If DuckDB’s scalar functions, the
json_*family, or regex functions cover your transform, they will be substantially faster. - This is fine for ETL and ad-hoc analytics over millions of rows. It is not the right tool for an interactive dashboard that runs the same UDF against a billion-row fact table on every refresh.
- Don’t
quickjs_evaluntrusted JavaScript in a multi-tenant context. QuickJS has no I/O surface, but it isn’t hardened against adversarial source.
If your snippet is small and type-driven, the sibling evalexpr_rhai extension embeds Rhai — a more constrained language that tends to integrate more cleanly with SQL types. Worth comparing.
Two surfaces
The extension exposes the same engine two ways. The right one depends on what you want back.
quickjs — used after SELECT, evaluates a JS expression and returns a VARCHAR:
SELECT quickjs('2 + 2'); -- '4'SELECT quickjs('"hello".toUpperCase()'); -- 'HELLO'The same name used after FROM is the table form — JS returns an array, DuckDB unpacks it into rows:
SELECT * FROM quickjs('[1, 2, 3].map(x => x * x)');-- 1, 4, 9quickjs_eval — calls a JS function with positional arguments and returns the result as JSON. This is the form to use for per-row UDFs:
SELECT quickjs_eval('(a, b) => a + b', 5, 3); -- 8 (JSON)Argument binding
Positional arguments to the table form of quickjs are exposed inside the snippet as arg0, arg1, … . parsed_arg0 holds arg0 parsed as JSON when arg0 is a string containing valid JSON, and arg0 itself otherwise, so the snippet doesn’t have to call JSON.parse:
SELECT *FROM quickjs('parsed_arg0.map(x => x * arg1)', '[1, 2, 3, 4, 5]', 3);-- 3, 6, 9, 12, 15The table form’s code runs as a script: its result is the value of the last expression, so it may declare variables and loop before producing the array.
SELECT * FROM quickjs('const out = []; for (const x of arg0) out.push(x * x); out', [1, 2, 3]);-- 1, 4, 9For quickjs_eval, arguments map to the function’s formal parameters — no argN aliasing. In the DuckDB 2.0 build both functions hand SQL values to JavaScript as native values:
| SQL type | JavaScript value |
|---|---|
TINYINT … BIGINT, unsigned and HUGEINT integers |
number; BigInt when the magnitude exceeds 2^53 − 1, so no digits are lost |
FLOAT, DOUBLE, DECIMAL |
number |
VARCHAR, JSON |
string (JSON text is not parsed automatically) |
BOOLEAN |
boolean |
DATE, TIMESTAMP, TIMESTAMPTZ, TIMESTAMP_S/MS/NS |
Date (UTC, millisecond precision); infinite values arrive as strings |
BLOB |
Uint8Array |
LIST, ARRAY |
array |
STRUCT, MAP |
object (MAP keys are stringified) |
UNION |
the active member’s value |
NULL |
null |
anything else (UUID, INTERVAL, ENUM, TIME, …) |
its string form |
SELECT quickjs_eval('(tags, user) => tags.map(t => user.name + ":" + t)', ['a', 'b'], {'name': 'duck'});-- ["duck:a","duck:b"]Results go back through JSON.stringify. BigInt values serialize as JSON numbers, and a result with no JSON form (undefined, a function, a symbol) is SQL NULL. A returned Promise — for example from an async function — is awaited; a rejection becomes an error.
What’s in the language
The extension links QuickJS-NG, an actively-maintained fork of Fabrice Bellard’s QuickJS. It implements the bulk of the ECMAScript specification — arrow functions, destructuring, let/const, Map/Set, Promise, modern Array / String / Object methods, template literals, optional chaining, nullish coalescing.
There is no browser layer and no Node API surface — no fetch, no fs, no process, no require. This is a pure language runtime, by design. If your snippet needs network or filesystem access, do it in DuckDB’s own httpfs / file readers and pass the resulting value into the JS as an argument.
Performance shape
In the DuckDB 2.0 build, quickjs_eval keeps one JavaScript runtime, context and compiled function per worker thread and recompiles only when the script text changes, so the per-row cost is the call itself — around a microsecond for a small arrow function (200,000 rows of (x) => x * 2 take about 0.2 s). Because the context is reused, globals a function mutates persist between the rows one thread processes; don’t rely on that state.
The scalar quickjs gives each row a fresh context so declarations never collide between rows. Creating a context costs on the order of 100 µs, so use quickjs_eval for per-row work and keep quickjs for one-off expressions.
The standard playbook:
- Start in pure SQL. If the scalar function reference or
json_*family covers it, you’re done. - If regex isn’t expressive enough or
CASEchains are getting unreadable, reach for QuickJS. - If the snippet is small and type-driven (numbers, strings, simple records), benchmark against
evalexpr_rhai— Rhai’s tighter SQL-type integration sometimes wins.
Resource limits
The DuckDB 2.0 build bounds every script so a bad snippet fails the query instead of taking down the process:
| Setting | Default | Effect |
|---|---|---|
quickjs_memory_limit |
'256MB' |
Maximum heap of each QuickJS runtime (one per thread and query). Accepts DuckDB memory sizes; 'none' disables it. Exceeding it raises InternalError: out of memory (quickjs_memory_limit is …). |
quickjs_timeout_ms |
0 (off) |
Maximum wall-clock time of one evaluation: one row of quickjs / quickjs_eval, or the whole table form. |
SET quickjs_timeout_ms = 1000;SET quickjs_memory_limit = '64MB';Independently of these settings, a running script stops when the query is cancelled (Ctrl-C, interrupt()) or exceeds DuckDB’s max_execution_time. Unbounded recursion or deeply nested input raises RangeError: Maximum call stack size exceeded; the stack limit is sized to the native thread stack the query actually runs on.
The JavaScript environment has no filesystem, network, process or module loader access, so the functions keep working when enable_external_access is false.
Changes in the DuckDB 2.0 release
- Native argument types.
quickjs_evaland table-form arguments arrive as numbers, BigInt, Date, Uint8Array, arrays and objects (see Argument binding). Earlier builds passed SMALLINT, TINYINT, DECIMAL, dates, lists and structs as strings, soquickjs_eval('(x) => x + 1', 1::SMALLINT)returned"11"; it now returns2. Snippets that called string methods on such arguments need updating. undefinedis SQL NULL.quickjs_evalused to return the textundefinedin its JSON column.- NULL arguments reach JavaScript as
nullinstead of being stringified. - Table form runs as a script. Multi-statement code works, and
parsed_arg0falls back toarg0whenarg0is not valid JSON instead of failing. - Promises are awaited instead of being returned as
{}. - Lone UTF-16 surrogates in results are replaced with U+FFFD rather than producing invalid UTF-8.
Also new in the DuckDB 2.0 build:
- Crash fixes: returning or throwing a
Symboland deep recursion no longer crash DuckDB. - Limits and cancellation:
quickjs_memory_limit,quickjs_timeout_ms,max_execution_timeand Ctrl-C (see Resource limits). - Performance:
quickjs_evalreuses its compiled function per thread instead of building a new engine for every row — over 100× faster on per-row workloads. - QuickJS-NG 0.18.0.
Reference
Extension Contents
Quick reference to all available functions and settings organized by category.
| Name | Type | Description |
|---|---|---|
|
Configuration
|
||
| quickjs_memory_limit | Object type: Setting | Maximum heap size of each QuickJS runtime (one per thread and query), e.g. |
| quickjs_timeout_ms | Object type: Setting | Maximum wall-clock time in milliseconds of a single QuickJS evaluation (one row of quickjs()/quickjs_eval(), or the whole quickjs table function). |
|
Execute
Run JavaScript code from SQL — |
||
| quickjs() | Object type: Scalar function | Evaluate JavaScript code and return its completion value (the value of the last expression or statement). |
| quickjs_eval() | Object type: Scalar function | Call a JavaScript function with the given arguments and return its result as JSON. |
No extension contents match that search.
API Reference
Function Reference
Configuration
Settings
Configure the quickjs extension behavior using these settings.
quickjs_memory_limit
Maximum heap size of each QuickJS runtime (one per thread and query), e.g. '256MB'. 'none' disables the limit.
256MB
quickjs_timeout_ms
Maximum wall-clock time in milliseconds of a single QuickJS evaluation (one row of quickjs()/quickjs_eval(), or the whole quickjs table function). 0 disables the timeout.
0
Practical Examples
Cookbook
Real-world recipes and patterns for common use cases.
When to use QuickJS
JavaScript inside SQL isn’t a goal — it’s an escape hatch. Reach for QuickJS when:
- JSON-munging is awkward in SQL alone (deeply nested fields, conditional shapes, computed keys).
- A regex doesn’t quite cut it and you want imperative control flow.
- You have an existing JS library snippet (validation, parsing, formatting) and don’t want to rewrite it.
Don’t reach for it for:
- Anything DuckDB has a native function for. Native primitives are 10–100× faster.
- Long-running computation. QuickJS is fast for an embedded interpreter; it’s still slower than vectorized SQL. In the DuckDB 2.0 build, cap runaway scripts with
SET quickjs_timeout_ms = 1000(heap is capped byquickjs_memory_limit, 256MB by default). - Untrusted input in a multi-tenant context. Even sandboxed JS engines have a history of escapes.
Scalar form
SELECT quickjs('2 + 2'); -- '4'SELECT quickjs('let m = "Hello, World!"; m'); -- 'Hello, World!'SELECT quickjs_eval('(a, b) => a + b', 5, 3); -- 8 (JSON)For string literals with nested quotes, prefer assigning to a JS variable first to avoid SQL parser confusion. Each row of the scalar quickjs runs in a fresh context, so let declarations never collide between rows.
Table form (array → rows)
SELECT * FROM quickjs('[1, 2, 3, 4, 5]');-- 5 rowsPass parameters and have JS return a transformed array:
-- arg0 = raw param, parsed_arg0 = JSON.parse(arg0) when arg0 is a JSON string (otherwise arg0)SELECT *FROM quickjs('parsed_arg0.map(x => x * arg1)', '[1, 2, 3, 4, 5]', 3);-- → 3, 6, 9, 12, 15Custom JSON parsing
When you need conditional shapes the standard json_* functions can’t express, QuickJS-as-a-JSON-parser shines:
SELECT id, event_type, quickjs_eval( '(event_type, payload) => { const d = JSON.parse(payload); if (event_type === "login") { return { user: d.user, device: d.meta.device, os: d.meta.os }; } else if (event_type === "purchase") { return { user: d.user, item: d.meta.item, amount: d.amount }; } else { return null; } }', event_type, payload ) AS extractedFROM events;The result column holds JSON; chain it through json_extract_* or pull fields directly:
SELECT extracted->>'$.user' AS user, extracted->>'$.os' AS osFROM transformed_events;Pass lists, structs and dates directly
In the DuckDB 2.0 build, quickjs_eval receives SQL values as native JavaScript values — no JSON.parse or string splitting needed:
SELECT quickjs_eval('(xs) => xs.reduce((a, b) => a + b, 0) / xs.length', [2, 4, 9]); -- 5SELECT quickjs_eval('(d) => d.toISOString().slice(0, 7)', DATE '2024-07-04'); -- "2024-07"Return undefined to produce SQL NULL:
SELECT quickjs_eval('(s) => s.includes("@") ? s.split("@")[1] : undefined', 'nobody') IS NULL; -- truePerformance
QuickJS-NG is one of the smallest and fastest embedded JS engines available — but you’re still paying interpretation cost per row. In the DuckDB 2.0 build quickjs_eval compiles its function once per thread, so a small arrow function costs around a microsecond per row: 100K rows take roughly 0.1 seconds. The scalar quickjs builds a fresh context for every row (around 100 µs each), so prefer quickjs_eval for per-row work.
Where possible, prefer:
- Native DuckDB scalar functions.
- The
json_*family for JSON. - QuickJS only when 1 and 2 don’t fit.
Platform Support
Compatibility
Extension availability may vary by platform and DuckDB version. Check below to ensure this extension supports your environment before installation.
Quick Facts
Platforms
DuckDB 2.0.0
- Linux x86_64aarch64
- Linux (musl) Not available
- macOS Apple Silicon
- Windows x86_64x86_64 (MinGW)
- WASM Not available
Compiled binary sizes
| Platform | Architecture | Size |
|---|---|---|
| Linux | x86_64 | 4.55 MB |
| Linux | aarch64 | 3.87 MB |
| macOS | Apple Silicon | 3.27 MB |
| Windows | x86_64 | 10.71 MB |
| Windows | x86_64 (MinGW) | 18.43 MB |
Compressed download sizes for the release shown above.
DuckDB & Haybarn
Release calendar- DuckDB v2.0.0 Query.Farm repository Supported
- Haybarn v1.5.6 Built-in community repository Supported
Browser examples use Haybarn-Wasm 2.0.0-rc12.
Checked .
Learn and explore
Tutorials and articles
Writing about QuickJS: how it works, what changed, and why.
-
QuickJS for DuckDB 2.0: pass real values to JavaScript
QuickJS for DuckDB 2.0 passes lists, structs, dates, and large integers as native JavaScript values, with memory limits, timeouts, and fixes for crashing scripts.