Skip to content

Commit 31bd8fa

Browse files
authored
Upgrade AVA to DuckDB 2.0 (#1120)
* fix(duckdb): serialize reader options once * fix(duckdb): reject writes in CTEs * fix(duckdb): install MySQL extension before loading * test(duckdb): check MongoDB schema keys * feat(duckdb): upgrade the embedded engine to 2.0 * fix(duckdb): allow compatible Node client versions * refactor(duckdb): separate JSON layout from column inference
1 parent 0a90864 commit 31bd8fa

13 files changed

Lines changed: 104 additions & 24 deletions

File tree

‎__tests__/duckdb/loaders/csv-file.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,23 @@ describe('loaders/csv-file', () => {
8080
]);
8181
});
8282

83+
it('honors an explicit reader schema with auto detection disabled', async () => {
84+
const csvPath = await writeTempFile('id\n001\n', 'csv');
85+
try {
86+
engine = new DuckDBEngine(getLLMConfig());
87+
await engine.load({
88+
type: 'csv-file',
89+
options: { path: csvPath, options: { auto_detect: false, header: true, columns: { id: 'VARCHAR' } } },
90+
});
91+
92+
expect((await engine.execute('SELECT id FROM data')).data).toEqual([{ id: '001' }]);
93+
} finally {
94+
await engine?.dispose();
95+
engine = null;
96+
await removeTempFile(csvPath);
97+
}
98+
});
99+
83100
it('reads GB18030 Chinese with automatic extension loading disabled', async () => {
84101
// GB18030 bytes for "name\n中文\n".
85102
const csvPath = await writeTempFile(Buffer.from('6e616d650ad6d0cec40a', 'hex'), 'csv');

‎__tests__/duckdb/loaders/json-file.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,22 @@ describe('loaders/json-file', () => {
4242
}
4343
});
4444

45+
it('detects the layout of a JSON array with explicit column types', async () => {
46+
const file = await writeTempFile('[{"id":"001"},{"id":"002"}]', 'json');
47+
try {
48+
engine = new DuckDBEngine(getLLMConfig());
49+
await engine.load({
50+
type: 'json-file',
51+
options: { path: file, options: { auto_detect: false, columns: { id: 'VARCHAR' } } },
52+
});
53+
expect((await engine.execute('SELECT id FROM data ORDER BY id')).data).toEqual([{ id: '001' }, { id: '002' }]);
54+
} finally {
55+
await engine?.dispose();
56+
engine = null;
57+
await removeTempFile(file);
58+
}
59+
});
60+
4561
it('loads a JSON file with a complete schema and original column order', async () => {
4662
engine = new DuckDBEngine(getLLMConfig());
4763
await engine.load({ type: 'json-file', options: { path: path.join(__dirname, '../../datasets/customers.json') } });

‎__tests__/duckdb/loaders/mongodb.test.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,11 @@ describe.skipIf(process.env.AVA_MONGODB_TEST !== '1')('loaders/mongodb', () => {
3636

3737
// init.js creates three collections; information_schema returns them alphabetically
3838
expect(schema.models.map(({ name }) => name)).toEqual(['customers', 'order notes', 'orders']);
39-
// The DuckDB mongo extension maps MongoDB collections as views — indexes and
40-
// constraints from the source database are not exposed to DuckDB's catalog,
41-
// so both indexes and relations are always empty.
42-
expect(schema.models.every(({ indexes }) => indexes.length === 0)).toBe(true);
39+
// Collection views do not expose MongoDB's keys or relationships.
40+
for (const { primaryKey, uniqueKeys } of schema.models) {
41+
expect(primaryKey).toBeUndefined();
42+
expect(uniqueKeys).toBeUndefined();
43+
}
4344
expect(schema.relationships).toEqual([]);
4445

4546
// ── customers ──────────────────────────────────────────────

‎__tests__/duckdb/loaders/mysql.test.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,23 @@
1-
import { describe, it, expect, afterEach } from 'vitest';
1+
import { describe, it, expect, afterEach, vi } from 'vitest';
22

33
import { DuckDBEngine } from '../../../src/duckdb/engine';
4+
import { loadMySQL } from '../../../src/duckdb/loaders/mysql';
45
import { getLLMConfig } from '../../test-utils';
56

7+
it('installs the MySQL extension before loading it and attaching the source read-only', async () => {
8+
const source = await loadMySQL({ host: 'localhost', database: 'analytics' });
9+
const conn = {
10+
run: vi.fn().mockResolvedValue(undefined),
11+
runAndReadAll: vi.fn().mockResolvedValue({ getRowObjectsJson: () => [] }),
12+
};
13+
14+
await source.register(conn);
15+
16+
expect(conn.run).toHaveBeenNthCalledWith(1, 'INSTALL mysql');
17+
expect(conn.run).toHaveBeenNthCalledWith(2, 'LOAD mysql');
18+
expect(conn.run).toHaveBeenLastCalledWith(expect.stringContaining('(TYPE mysql, READ_ONLY)'));
19+
});
20+
621
describe.skipIf(process.env.AVA_MYSQL_TEST !== '1')('loaders/mysql', () => {
722
let engine: DuckDBEngine | null = null;
823

‎__tests__/duckdb/util/__snapshots__/schema.test.ts.snap‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ exports[`getDuckDBSchema > discovers replaced view definitions and preserves col
143143
"views": [
144144
{
145145
"name": "current_view",
146-
"statement": "SELECT * FROM (WITH RECURSIVE "sequence" (n) AS ((SELECT 1) UNION ALL (SELECT (n + 1) FROM "sequence" WHERE (n < 3)))SELECT n, 'AS ;' FROM "sequence" WHERE (n > 10)) AS "__ava_view"("empty, value", "label AS text")",
146+
"statement": "SELECT * FROM (WITH RECURSIVE "sequence" (n) AS ((SELECT 1) UNION ALL (SELECT (n + 1) FROM "sequence" WHERE (n < 3))) SELECT n, 'AS ;' FROM "sequence" WHERE (n > 10)) AS "__ava_view"("empty, value", "label AS text")",
147147
},
148148
],
149149
},
@@ -291,7 +291,7 @@ exports[`getDuckDBSchema > preserves CTEs, joins, aggregates, windows and nested
291291
"views": [
292292
{
293293
"name": "sales.report AS "quoted",
294-
"statement": "SELECT * FROM (WITH totals AS (SELECT c."name", CAST(COALESCE(sum(o.amount) FILTER (WHERE (o.status = 'paid')), 0) AS INTEGER) AS total FROM customers AS c LEFT JOIN orders AS o ON ((c.id = o.customer_id)) GROUP BY c."name")SELECT "name", total, CAST(row_number() OVER (ORDER BY total DESC, "name") AS INTEGER) FROM totals) AS "__ava_view"("customer, name", "total AS ""net", "position")",
294+
"statement": "SELECT * FROM (WITH totals AS (SELECT c."name", CAST(COALESCE(sum(o.amount) FILTER (WHERE (o.status = 'paid')), 0) AS INTEGER) AS total FROM (customers AS c LEFT JOIN orders AS o ON ((c.id = o.customer_id))) GROUP BY c."name") SELECT "name", total, CAST(row_number() OVER (ORDER BY total DESC, "name") AS INTEGER) FROM totals) AS "__ava_view"("customer, name", "total AS ""net", "position")",
295295
},
296296
{
297297
"name": "top customers",

‎__tests__/duckdb/util/file.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ describe('duckdb/util/file', () => {
1818
expect(conn.run.mock.calls.map(([sql]) => sql)).toEqual([
1919
'INSTALL encodings',
2020
'LOAD encodings',
21-
'CREATE OR REPLACE VIEW "data" AS SELECT * FROM read_csv(\'/tmp/data.csv\', auto_detect=true, "encoding"=\'gb18030\')',
21+
'CREATE OR REPLACE VIEW "data" AS SELECT * FROM read_csv(\'/tmp/data.csv\', "encoding"=\'gb18030\')',
2222
]);
2323
});
2424

‎__tests__/query/duckdb-sql.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,9 @@ describe('DuckDB SQL validation', () => {
6161
it.each([
6262
'SELECT 1 AS n UNION SELECT 1 AS n',
6363
'SELECT 1 AS n UNION ALL BY NAME SELECT 1 AS n',
64+
'WITH RECURSIVE seq(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM seq WHERE n < 3) SELECT * FROM seq',
6465
"SELECT 9223372036854775807 AS n, '中文😀; -- literal' AS text",
66+
'SELECT list_transform([1, 2, 3], lambda x : x * 2)',
6567
'SELECT [x * 2 FOR x IN [1, 2, 3]]',
6668
'SELECT 1e2 AS n, typeof(1e2) AS kind',
6769
'SELECT (1e-1 + 1e-1 + 1e-1) = 0.3 AS matches',
@@ -97,6 +99,9 @@ describe('DuckDB SQL validation', () => {
9799
'DROP TABLE orders',
98100
"COPY (SELECT 1) TO '/tmp/ava-must-not-write'",
99101
'WITH q AS (DELETE FROM orders RETURNING *) SELECT * FROM q',
102+
'WITH q AS (INSERT INTO orders VALUES (1) RETURNING *) SELECT * FROM q',
103+
'SELECT * FROM (WITH q AS (UPDATE orders SET id = 1 RETURNING *) SELECT * FROM q)',
104+
"WITH q AS (COPY (SELECT 1) TO '/tmp/ava-must-not-write') SELECT * FROM q",
100105
"SELECT 1 INTO '/tmp/ava-must-not-write'",
101106
'SELECT 1 FOR UPDATE',
102107
'SET enable_external_access = true',

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@
7474
"@antv/event-emitter": "^0.1.3",
7575
"@clickhouse/client": "^1.23.1",
7676
"@clickhouse/parser": "0.3.0",
77-
"@duckdb/node-api": "^1.5.5-r.5",
77+
"@duckdb/node-api": "^2.0.0-r.1",
7878
"@supabase/pg-parser": "^0.1.7",
7979
"adm-zip": "^0.6.1",
8080
"ai": "^7.0.112",

‎src/contracts/source/json.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export const jsonReadOptionsSchema = z
1717
field_appearance_threshold: z.number().optional(),
1818
/** Include filename in SELECT *. Default false; also available as a virtual column */
1919
filename: z.boolean().optional(),
20-
/** Input layout. read_json defaults to auto-detection */
20+
/** Input layout. AVA defaults to 'auto', even with column inference disabled. */
2121
format: z.enum(['auto', 'unstructured', 'newline_delimited', 'array']).optional(),
2222
/** Read Hive partitions from paths. Default auto-detected */
2323
hive_partitioning: z.boolean().optional(),

‎src/duckdb/engine.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ export class DuckDBEngine implements AnalysisEngine {
182182
const query = await this.dialect.validateDSL(sql);
183183
const timeoutMs = this.engineOptions.queryTimeoutMs ?? DEFAULT_QUERY_TIMEOUT_MS;
184184
// query() parses the original source; a quoted constant keeps its own parameters unbound.
185-
// https://duckdb.org/docs/1.5/guides/sql_features/query_and_query_table_functions
185+
// https://duckdb.org/docs/2.0/guides/sql_features/query_and_query_table_functions
186186
const reader = await runWithTimeout(
187187
conn.runAndReadAll(`SELECT * FROM query(${sqlStringLiteral(query)}) LIMIT ${maxRows(options) + 1}`),
188188
timeoutMs,

0 commit comments

Comments
 (0)