-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparquetSql.js
More file actions
174 lines (156 loc) · 6.35 KB
/
parquetSql.js
File metadata and controls
174 lines (156 loc) · 6.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import { asyncBufferFromFile, asyncBufferFromUrl, parquetMetadataAsync } from 'hyparquet'
import { compressors } from 'hyparquet-compressors'
import { collect, executeSql, parseSql, planSql } from 'squirreling'
import { parquetDataSource } from 'hyperparam'
import { markdownTable } from './markdownTable.js'
const maxRows = 100
/**
* Recursively collect table names from all Scan/Count nodes in a query plan.
*
* @param {import('squirreling').QueryPlan} plan
* @returns {Set<string>}
*/
function scanTables(plan) {
/** @type {Set<string>} */
const tables = new Set()
/** @param {import('squirreling').QueryPlan} node */
function walk(node) {
if (!node) return
if (node.type === 'Scan' || node.type === 'Count') {
tables.add(node.table)
} else if ('child' in node) {
walk(node.child)
}
if ('left' in node) walk(node.left)
if ('right' in node) walk(node.right)
}
walk(plan)
return tables
}
/**
* Build an AsyncDataSource for a file path or URL.
*
* @param {string} file
* @returns {Promise<import('squirreling').AsyncDataSource>}
*/
async function fileToDataSource(file) {
const asyncBuffer = file.startsWith('http://') || file.startsWith('https://')
? await asyncBufferFromUrl({ url: file })
: await asyncBufferFromFile(file)
const metadata = await parquetMetadataAsync(asyncBuffer)
return parquetDataSource(asyncBuffer, metadata, compressors)
}
/**
* Execute a SQL query by extracting table names from the plan and loading them
* as parquet data sources. Returns a formatted result string.
*
* @param {string} query
* @param {boolean} [truncate]
* @returns {Promise<string>}
*/
export async function runSqlQuery(query, truncate = true) {
const startTime = performance.now()
const ast = parseSql({ query })
const plan = planSql({ query: ast })
const tableNames = scanTables(plan)
/** @type {Record<string, import('squirreling').AsyncDataSource>} */
const tables = {}
await Promise.all([...tableNames].map(async name => {
tables[name] = await fileToDataSource(name)
}))
const results = await collect(executeSql({ tables, query }))
const queryTime = (performance.now() - startTime) / 1000
if (results.length === 0) {
return `Query executed successfully but returned no results in ${queryTime.toFixed(1)} seconds.`
}
const rowCount = results.length
const maxChars = truncate ? 1000 : 10000
let content = `Query returned ${rowCount} row${rowCount === 1 ? '' : 's'} in ${queryTime.toFixed(1)} seconds.\n\n`
content += markdownTable(results.slice(0, maxRows), maxChars)
if (rowCount > maxRows) {
content += `\n\n... and ${rowCount - maxRows} more row${rowCount - maxRows === 1 ? '' : 's'} (showing first ${maxRows} rows)`
}
return content
}
/**
* @import { ToolHandler } from '../types.d.ts'
* @type {ToolHandler}
*/
export const parquetSql = {
emoji: '🛢️',
tool: {
type: 'function',
name: 'parquet_sql',
description: 'Execute SQL queries against a parquet file using ANSI SQL syntax.'
+ ' Cell values are truncated by default to 1000 characters (or 10,000 if truncate=false).'
+ ' If a cell is truncated due to length, the column header will say "(truncated)".'
+ ' You can get subsequent pages of long text by using SUBSTR on long columns.'
+ ' Examples:'
+ '\n - `SELECT * FROM table LIMIT 10`'
+ '\n - `SELECT "First Name", "Last Name" FROM table WHERE age > 30 ORDER BY age DESC`.'
+ '\n - `SELECT country, COUNT(*) as total FROM table GROUP BY country`.'
+ '\n - `SELECT SUBSTR(long_column, 10001, 20000) as short_column FROM table`.',
parameters: {
type: 'object',
properties: {
file: {
type: 'string',
description: 'The parquet file to query either local file path or url.',
},
query: {
type: 'string',
description: 'The SQL query string. Use standard SQL syntax with WHERE clauses, ORDER BY, LIMIT, GROUP BY, aggregate functions, etc. Wrap column names containing spaces in double quotes: "column name". String literals should be single-quoted. Always use "table" as the table name in your FROM clause.',
},
truncate: {
type: 'boolean',
description: 'Whether to truncate long string values in the results. If true (default), each string cell is limited to 1000 characters. If false, each string cell is limited to 10,000 characters.',
},
},
required: ['file', 'query'],
},
},
/**
* @param {Record<string, unknown>} args
* @returns {Promise<string>}
*/
async handleToolCall({ file, query, truncate = true }) {
if (typeof file !== 'string') {
throw new Error('Expected file to be a string')
}
if (typeof query !== 'string' || query.trim().length === 0) {
throw new Error('Query parameter must be a non-empty string')
}
try {
const startTime = performance.now()
// Load parquet file and create data source
const asyncBuffer = file.startsWith('http://') || file.startsWith('https://')
? await asyncBufferFromUrl({ url: file })
: await asyncBufferFromFile(file)
const metadata = await parquetMetadataAsync(asyncBuffer)
const table = parquetDataSource(asyncBuffer, metadata, compressors)
// Execute SQL query
const results = await collect(executeSql({ tables: { table }, query }))
const queryTime = (performance.now() - startTime) / 1000
// Handle empty results
if (results.length === 0) {
return `Query executed successfully but returned no results in ${queryTime.toFixed(1)} seconds.`
}
// Format results
const rowCount = results.length
const displayRows = results.slice(0, maxRows)
// Determine max characters per string cell based on truncate parameter
const maxChars = truncate ? 1000 : 10000
// Convert to formatted string
let content = `Query returned ${rowCount} row${rowCount === 1 ? '' : 's'} in ${queryTime.toFixed(1)} seconds.`
content += '\n\n'
content += markdownTable(displayRows, maxChars)
if (rowCount > maxRows) {
content += `\n\n... and ${rowCount - maxRows} more row${rowCount - maxRows === 1 ? '' : 's'} (showing first ${maxRows} rows)`
}
return content
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
return `SQL query failed: ${message}`
}
},
}