Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions __tests__/duckdb/loaders/csv-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,23 @@ describe('loaders/csv-file', () => {
]);
});

it('honors an explicit reader schema with auto detection disabled', async () => {
const csvPath = await writeTempFile('id\n001\n', 'csv');
try {
engine = new DuckDBEngine(getLLMConfig());
await engine.load({
type: 'csv-file',
options: { path: csvPath, options: { auto_detect: false, header: true, columns: { id: 'VARCHAR' } } },
});

expect((await engine.execute('SELECT id FROM data')).data).toEqual([{ id: '001' }]);
} finally {
await engine?.dispose();
engine = null;
await removeTempFile(csvPath);
}
});

it('reads GB18030 Chinese with automatic extension loading disabled', async () => {
// GB18030 bytes for "name\n中文\n".
const csvPath = await writeTempFile(Buffer.from('6e616d650ad6d0cec40a', 'hex'), 'csv');
Expand Down
16 changes: 16 additions & 0 deletions __tests__/duckdb/loaders/json-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,22 @@ describe('loaders/json-file', () => {
}
});

it('detects the layout of a JSON array with explicit column types', async () => {
const file = await writeTempFile('[{"id":"001"},{"id":"002"}]', 'json');
try {
engine = new DuckDBEngine(getLLMConfig());
await engine.load({
type: 'json-file',
options: { path: file, options: { auto_detect: false, columns: { id: 'VARCHAR' } } },
});
expect((await engine.execute('SELECT id FROM data ORDER BY id')).data).toEqual([{ id: '001' }, { id: '002' }]);
} finally {
await engine?.dispose();
engine = null;
await removeTempFile(file);
}
});

it('loads a JSON file with a complete schema and original column order', async () => {
engine = new DuckDBEngine(getLLMConfig());
await engine.load({ type: 'json-file', options: { path: path.join(__dirname, '../../datasets/customers.json') } });
Expand Down
9 changes: 5 additions & 4 deletions __tests__/duckdb/loaders/mongodb.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,11 @@ describe.skipIf(process.env.AVA_MONGODB_TEST !== '1')('loaders/mongodb', () => {

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

// ── customers ──────────────────────────────────────────────
Expand Down
17 changes: 16 additions & 1 deletion __tests__/duckdb/loaders/mysql.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,23 @@
import { describe, it, expect, afterEach } from 'vitest';
import { describe, it, expect, afterEach, vi } from 'vitest';

import { DuckDBEngine } from '../../../src/duckdb/engine';
import { loadMySQL } from '../../../src/duckdb/loaders/mysql';
import { getLLMConfig } from '../../test-utils';

it('installs the MySQL extension before loading it and attaching the source read-only', async () => {
const source = await loadMySQL({ host: 'localhost', database: 'analytics' });
const conn = {
run: vi.fn().mockResolvedValue(undefined),
runAndReadAll: vi.fn().mockResolvedValue({ getRowObjectsJson: () => [] }),
};

await source.register(conn);

expect(conn.run).toHaveBeenNthCalledWith(1, 'INSTALL mysql');
expect(conn.run).toHaveBeenNthCalledWith(2, 'LOAD mysql');
expect(conn.run).toHaveBeenLastCalledWith(expect.stringContaining('(TYPE mysql, READ_ONLY)'));
});

describe.skipIf(process.env.AVA_MYSQL_TEST !== '1')('loaders/mysql', () => {
let engine: DuckDBEngine | null = null;

Expand Down
4 changes: 2 additions & 2 deletions __tests__/duckdb/util/__snapshots__/schema.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ exports[`getDuckDBSchema > discovers replaced view definitions and preserves col
"views": [
{
"name": "current_view",
"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")",
"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")",
},
],
},
Expand Down Expand Up @@ -291,7 +291,7 @@ exports[`getDuckDBSchema > preserves CTEs, joins, aggregates, windows and nested
"views": [
{
"name": "sales.report AS "quoted",
"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")",
"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")",
},
{
"name": "top customers",
Expand Down
2 changes: 1 addition & 1 deletion __tests__/duckdb/util/file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ describe('duckdb/util/file', () => {
expect(conn.run.mock.calls.map(([sql]) => sql)).toEqual([
'INSTALL encodings',
'LOAD encodings',
'CREATE OR REPLACE VIEW "data" AS SELECT * FROM read_csv(\'/tmp/data.csv\', auto_detect=true, "encoding"=\'gb18030\')',
'CREATE OR REPLACE VIEW "data" AS SELECT * FROM read_csv(\'/tmp/data.csv\', "encoding"=\'gb18030\')',
]);
});

Expand Down
5 changes: 5 additions & 0 deletions __tests__/query/duckdb-sql.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ describe('DuckDB SQL validation', () => {
it.each([
'SELECT 1 AS n UNION SELECT 1 AS n',
'SELECT 1 AS n UNION ALL BY NAME SELECT 1 AS n',
'WITH RECURSIVE seq(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM seq WHERE n < 3) SELECT * FROM seq',
"SELECT 9223372036854775807 AS n, '中文😀; -- literal' AS text",
'SELECT list_transform([1, 2, 3], lambda x : x * 2)',
'SELECT [x * 2 FOR x IN [1, 2, 3]]',
'SELECT 1e2 AS n, typeof(1e2) AS kind',
'SELECT (1e-1 + 1e-1 + 1e-1) = 0.3 AS matches',
Expand Down Expand Up @@ -97,6 +99,9 @@ describe('DuckDB SQL validation', () => {
'DROP TABLE orders',
"COPY (SELECT 1) TO '/tmp/ava-must-not-write'",
'WITH q AS (DELETE FROM orders RETURNING *) SELECT * FROM q',
'WITH q AS (INSERT INTO orders VALUES (1) RETURNING *) SELECT * FROM q',
'SELECT * FROM (WITH q AS (UPDATE orders SET id = 1 RETURNING *) SELECT * FROM q)',
"WITH q AS (COPY (SELECT 1) TO '/tmp/ava-must-not-write') SELECT * FROM q",
"SELECT 1 INTO '/tmp/ava-must-not-write'",
'SELECT 1 FOR UPDATE',
'SET enable_external_access = true',
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
"@antv/event-emitter": "^0.1.3",
"@clickhouse/client": "^1.23.1",
"@clickhouse/parser": "0.3.0",
"@duckdb/node-api": "^1.5.5-r.5",
"@duckdb/node-api": "^2.0.0-r.1",
"@supabase/pg-parser": "^0.1.7",
"adm-zip": "^0.6.1",
"ai": "^7.0.112",
Expand Down
2 changes: 1 addition & 1 deletion src/contracts/source/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const jsonReadOptionsSchema = z
field_appearance_threshold: z.number().optional(),
/** Include filename in SELECT *. Default false; also available as a virtual column */
filename: z.boolean().optional(),
/** Input layout. read_json defaults to auto-detection */
/** Input layout. AVA defaults to 'auto', even with column inference disabled. */
format: z.enum(['auto', 'unstructured', 'newline_delimited', 'array']).optional(),
/** Read Hive partitions from paths. Default auto-detected */
hive_partitioning: z.boolean().optional(),
Expand Down
2 changes: 1 addition & 1 deletion src/duckdb/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ export class DuckDBEngine implements AnalysisEngine {
const query = await this.dialect.validateDSL(sql);
const timeoutMs = this.engineOptions.queryTimeoutMs ?? DEFAULT_QUERY_TIMEOUT_MS;
// query() parses the original source; a quoted constant keeps its own parameters unbound.
// https://duckdb.org/docs/1.5/guides/sql_features/query_and_query_table_functions
// https://duckdb.org/docs/2.0/guides/sql_features/query_and_query_table_functions
const reader = await runWithTimeout(
conn.runAndReadAll(`SELECT * FROM query(${sqlStringLiteral(query)}) LIMIT ${maxRows(options) + 1}`),
timeoutMs,
Expand Down
4 changes: 1 addition & 3 deletions src/duckdb/loaders/mysql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,8 @@ export async function loadMySQL(options: MySQLSourceOptions, alias = ATTACH_ALIA
return {
register: async (conn, namespace) => {
try {
await conn.run('INSTALL mysql');
await conn.run('LOAD mysql');
// Workaround for https://github.com/duckdb/duckdb-mysql/issues/266: DuckDB 1.5's aggregate
// pushdown to MySQL fails on queries through the generated views. Not needed after upgrading to 2.0.
await conn.run('SET mysql_aggregate_pushdown_enabled = FALSE');
// READ_ONLY keeps the analysis read-only against the source database
await conn.run(
`ATTACH '${escapeSql(buildConnectionString(attachOptions))}' AS ${sqlIdentifier(
Expand Down
9 changes: 5 additions & 4 deletions src/duckdb/util/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,13 @@ export function fileSource(
await conn.run('INSTALL encodings');
await conn.run('LOAD encodings');
}
// csv/json default to auto_detect=true; a user-supplied auto_detect
// overrides it because DuckDB applies later duplicate options over earlier ones.
const sniff = format === 'parquet' ? '' : `, auto_detect=true${serializeOptions(options)}`;
// Infer the JSON layout independently of the caller's column schema.
const jsonFormat = options && 'format' in options ? options.format : undefined;
const readerOptions = format === 'json' ? { ...options, format: jsonFormat ?? 'auto' } : options;
const readOptions = format === 'parquet' ? '' : serializeOptions(readerOptions);
const view = sqlQualifiedName('data', namespace);
await conn.run(
`CREATE OR REPLACE VIEW ${view} AS SELECT * FROM ${READ_FN[format]}('${escapeSql(path)}'${sniff})`
`CREATE OR REPLACE VIEW ${view} AS SELECT * FROM ${READ_FN[format]}('${escapeSql(path)}'${readOptions})`
);
return ['data'];
},
Expand Down
39 changes: 33 additions & 6 deletions src/query/duckdb-sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,38 @@ import { stringifyDataModel } from '../util/data-model';
import type { DuckDBInstance } from '@duckdb/node-api';
import type { TranslationResult, QueryDialect, LLMConfig, DataModel } from '../types';

const READ_ONLY_QUERY_NODES = new Set(['SELECT_NODE', 'SET_OPERATION_NODE', 'RECURSIVE_CTE_NODE', 'CTE_NODE']);

function isReadOnlyQuery(root: unknown): boolean {
if (!root || typeof root !== 'object' || !('cte_map' in root)) return false;

const pending: object[] = [root];
while (pending.length) {
const node = pending.pop()!;
// DuckDB serializes cte_map on every query node, including DuckDB 2.0's write nodes.
if (
'cte_map' in node &&
(!('type' in node) || typeof node.type !== 'string' || !READ_ONLY_QUERY_NODES.has(node.type))
) {
return false;
}
for (const child of Object.values(node)) {
if (child && typeof child === 'object') pending.push(child);
}
}
return true;
}

export class DuckDBSQLDialect implements QueryDialect {
readonly id = 'duckdb-sql';

// Identifier quoting and set semantics follow the DuckDB SQL reference.
// https://duckdb.org/docs/1.5/sql/dialect/keywords_and_identifiers
// https://duckdb.org/docs/1.5/sql/query_syntax/setops
// https://duckdb.org/docs/2.0/sql/dialect/keywords_and_identifiers
// https://duckdb.org/docs/2.0/sql/query_syntax/setops
readonly rules = `Use read-only SELECT queries (WITH is allowed).
Use the exact table references and column names from the data model, joining tables when needed. Use double quotes for identifier components that need quoting and single quotes for strings.
Use DuckDB SQL syntax and functions appropriate to the column types. UNION removes duplicates and UNION ALL preserves them; align columns by position, or explicitly choose UNION BY NAME to align them by name.`;
Use DuckDB 2.0 SQL syntax and functions appropriate to the column types. Write lambdas as lambda x : expression.
UNION removes duplicates and UNION ALL preserves them; align columns by position, or explicitly choose UNION BY NAME to align them by name.`;

private parserInstance: Promise<DuckDBInstance> | undefined;

Expand Down Expand Up @@ -72,12 +95,16 @@ export class DuckDBSQLDialect implements QueryDialect {
try {
// The official serializer accepts SELECTs, including their CTEs and subqueries, without binding tables.
// User SQL is a bound value; only the serializer runs in this data-free instance.
// https://duckdb.org/docs/1.5/data/json/sql_to_and_from_json
// https://duckdb.org/docs/2.0/data/json/sql_to_and_from_json
const reader = await connection.runAndReadAll('SELECT json_serialize_sql(CAST(? AS VARCHAR)) AS ast', [sql]);
const serialized = reader.getRowObjectsJson()[0]?.ast;
if (typeof serialized !== 'string') throw new Error('Missing DuckDB SQL validation result');
const ast = JSON.parse(serialized) as { error: boolean; error_message?: string; statements?: unknown[] };
if (ast.error !== false || ast.statements?.length !== 1) {
const ast = JSON.parse(serialized) as {
error: boolean;
error_message?: string;
statements?: { node?: unknown }[];
};
if (ast.error !== false || ast.statements?.length !== 1 || !isReadOnlyQuery(ast.statements[0]?.node)) {
throw new Error(
`DuckDB query must contain exactly one read-only SELECT statement${
ast.error_message ? `: ${ast.error_message}` : ''
Expand Down
Loading