-
-
Notifications
You must be signed in to change notification settings - Fork 482
Expand file tree
/
Copy pathexplain.js
More file actions
47 lines (40 loc) · 1.12 KB
/
Copy pathexplain.js
File metadata and controls
47 lines (40 loc) · 1.12 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
'use strict';
module.exports = function explain(sql) {
if (typeof sql !== 'string') throw new TypeError('Expected first argument to be a string');
const explainSql = sql.trim().toUpperCase().startsWith('EXPLAIN')
? sql
: `EXPLAIN ${sql}`;
const stmt = this.prepare(explainSql);
try {
return stmt.all();
} catch (e) {
if (e.message && (e.message.includes('Too few parameter') || e.message.includes('Missing named parameter'))) {
const namedParams = sql.match(/:(\w+)|@(\w+)|\$(\w+)/g);
if (namedParams && namedParams.length > 0) {
const params = {};
for (const param of namedParams) {
const name = param.substring(1);
params[name] = null;
}
return stmt.all(params);
}
let low = 1;
let high = 100;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
try {
return stmt.all(Array(mid).fill(null));
} catch (err) {
if (err.message && err.message.includes('Too few')) {
low = mid + 1;
} else if (err.message && err.message.includes('Too many')) {
high = mid - 1;
} else {
throw err;
}
}
}
}
throw e;
}
};