-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathquery.js
218 lines (184 loc) · 5.7 KB
/
query.js
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import { DuckDBInstance } from '@duckdb/node-api';
import path from 'path';
import fs from 'fs';
class QueryClient {
constructor(baseDir = './data') {
this.baseDir = baseDir;
this.db = null;
this.defaultTimeRange = 10 * 60 * 1000000000; // 10 minutes in nanoseconds
}
async initialize() {
try {
this.db = await DuckDBInstance.create(':memory:');
console.log('Initialized DuckDB for querying');
} catch (error) {
console.error('Failed to initialize DuckDB:', error);
throw error;
}
}
async findRelevantFiles(type, timeRange) {
const files = [];
const writers = await fs.promises.readdir(this.baseDir);
for (const writer of writers) {
const typePath = path.join(
this.baseDir,
writer,
'dbs',
'hep-0',
`hep_${type}-0`
);
try {
// Always read fresh metadata
const metadataPath = path.join(typePath, 'metadata.json');
const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8'));
// Only use files that exist and match time range
const relevantFiles = metadata.files.filter(file => {
// Skip files that don't exist
if (!fs.existsSync(file.path)) {
return false;
}
const { start, end } = timeRange;
const fileStart = file.min_time;
const fileEnd = file.max_time;
return (!start || fileEnd >= start) && (!end || fileStart <= end);
});
files.push(...relevantFiles);
} catch (error) {
if (error.code !== 'ENOENT') {
console.error(`Error reading metadata for type ${type} in ${writer}:`, error);
}
}
}
return files.sort((a, b) => a.min_time - b.min_time);
}
parseQuery(sql) {
// Extract SELECT columns
const selectMatch = sql.match(/SELECT\s+(.*?)\s+FROM/i);
const columns = selectMatch ? selectMatch[1].trim() : '*';
// Extract type/measurement name
const fromMatch = sql.match(/FROM\s+([a-zA-Z0-9_]+)/i);
let type = null;
if (fromMatch) {
const tableName = fromMatch[1];
// Check if it's a HEP type (hep_NUMBER)
const hepMatch = tableName.match(/^hep_(\d+)$/i);
if (hepMatch) {
type = parseInt(hepMatch[1]);
} else {
// It's a Line Protocol measurement name
type = tableName;
}
}
// Extract time range
const timeMatch = sql.match(/time\s*(>=|>|<=|<|=)\s*'([^']+)'/i);
let timeRange;
if (timeMatch) {
const operator = timeMatch[1];
const timestamp = new Date(timeMatch[2]).getTime() * 1000000;
const now = Date.now() * 1000000;
switch (operator) {
case '>=':
case '>':
timeRange = { start: timestamp, end: now };
break;
case '<=':
case '<':
timeRange = { start: null, end: timestamp };
break;
case '=':
timeRange = { start: timestamp, end: timestamp };
break;
}
} else {
// Default to last 10 minutes
const now = Date.now() * 1000000;
timeRange = {
start: now - this.defaultTimeRange,
end: now
};
}
// Extract additional WHERE conditions
const whereClause = sql.match(/WHERE\s+(.*?)(?:\s+(?:ORDER|GROUP|LIMIT|$))/i);
let conditions = '';
if (whereClause) {
conditions = whereClause[1].replace(/time\s*(>=|>|<=|<|=)\s*'[^']+'\s*(AND|OR)?/i, '').trim();
if (conditions) conditions = `AND ${conditions}`;
}
// Extract ORDER BY, LIMIT, etc.
const orderMatch = sql.match(/ORDER\s+BY\s+(.*?)(?:\s+(?:LIMIT|$))/i);
const limitMatch = sql.match(/LIMIT\s+(\d+)/i);
const orderBy = orderMatch ? `ORDER BY ${orderMatch[1]}` : '';
const limit = limitMatch ? `LIMIT ${limitMatch[1]}` : '';
return {
columns,
type,
timeRange,
conditions,
orderBy,
limit
};
}
async query(sql) {
if (!this.db) {
throw new Error('QueryClient not initialized');
}
try {
const parsed = this.parseQuery(sql);
if (!parsed.type) {
throw new Error('Could not determine type from query');
}
const files = await this.findRelevantFiles(parsed.type, parsed.timeRange);
if (!files.length) {
return [];
}
const connection = await this.db.connect();
try {
const query = `
SELECT ${parsed.columns}
FROM read_parquet([${files.map(f => `'${f.path}'`).join(', ')}])
${parsed.timeRange ? `WHERE timestamp >= TIMESTAMP '${new Date(parsed.timeRange.start / 1000000).toISOString()}'
AND timestamp <= TIMESTAMP '${new Date(parsed.timeRange.end / 1000000).toISOString()}'` : ''}
${parsed.conditions}
${parsed.orderBy}
${parsed.limit}
`;
const reader = await connection.runAndReadAll(query);
return reader.getRows().map(row => {
const obj = {};
reader.columnNames().forEach((col, i) => {
obj[col] = row[i];
});
return obj;
});
} finally {
await connection.close();
}
} catch (error) {
console.error('Query error:', error);
throw error;
}
}
async close() {
// Nothing to clean up
}
}
// Example usage:
async function main() {
const client = new QueryClient();
await client.initialize();
try {
const result = await client.query(`
SELECT * FROM hep_1
WHERE time >= '2025-02-08T19:00:00'
AND time < '2025-02-08T20:00:00'
LIMIT 10
`);
console.log('Query result:', result);
} finally {
await client.close();
}
}
if (require.main === module) {
main().catch(console.error);
}
export default QueryClient;