@query-doctor/core 0.4.0 → 0.4.1-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +2222 -1964
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +770 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +770 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +2573 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +12 -11
- package/dist/index.d.ts +0 -10
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -2316
- package/dist/index.js.map +0 -1
- package/dist/optimizer/genalgo.d.ts +0 -104
- package/dist/optimizer/genalgo.d.ts.map +0 -1
- package/dist/optimizer/pss-rewriter.d.ts +0 -11
- package/dist/optimizer/pss-rewriter.d.ts.map +0 -1
- package/dist/optimizer/statistics.d.ts +0 -360
- package/dist/optimizer/statistics.d.ts.map +0 -1
- package/dist/sql/analyzer.d.ts +0 -105
- package/dist/sql/analyzer.d.ts.map +0 -1
- package/dist/sql/builder.d.ts +0 -31
- package/dist/sql/builder.d.ts.map +0 -1
- package/dist/sql/database.d.ts +0 -84
- package/dist/sql/database.d.ts.map +0 -1
- package/dist/sql/indexes.d.ts +0 -8
- package/dist/sql/indexes.d.ts.map +0 -1
- package/dist/sql/nudges.d.ts +0 -15
- package/dist/sql/nudges.d.ts.map +0 -1
- package/dist/sql/permutations.d.ts +0 -10
- package/dist/sql/permutations.d.ts.map +0 -1
- package/dist/sql/pg-identifier.d.ts +0 -26
- package/dist/sql/pg-identifier.d.ts.map +0 -1
- package/dist/sql/walker.d.ts +0 -45
- package/dist/sql/walker.d.ts.map +0 -1
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,2573 @@
|
|
|
1
|
+
'use client'
|
|
2
|
+
import { bgMagentaBright, blue, dim, gray, green, magenta, red, strikethrough, yellow } from "colorette";
|
|
3
|
+
import { deparseSync } from "pgsql-deparser";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import dedent from "dedent";
|
|
6
|
+
|
|
7
|
+
//#region src/sql/nudges.ts
|
|
8
|
+
function is$1(node, kind) {
|
|
9
|
+
return kind in node;
|
|
10
|
+
}
|
|
11
|
+
function isANode$1(node) {
|
|
12
|
+
if (typeof node !== "object" || node === null) return false;
|
|
13
|
+
const keys = Object.keys(node);
|
|
14
|
+
return keys.length === 1 && /^[A-Z]/.test(keys[0]);
|
|
15
|
+
}
|
|
16
|
+
/** Operators that require a GiST index for efficient execution */
|
|
17
|
+
const GIST_OPERATORS = new Set(["&&", "-|-"]);
|
|
18
|
+
/** PostGIS / spatial functions that require a GiST index */
|
|
19
|
+
const SPATIAL_FUNCTIONS = new Set([
|
|
20
|
+
"st_intersects",
|
|
21
|
+
"st_contains",
|
|
22
|
+
"st_within",
|
|
23
|
+
"st_dwithin",
|
|
24
|
+
"st_covers",
|
|
25
|
+
"st_coveredby",
|
|
26
|
+
"st_crosses",
|
|
27
|
+
"st_overlaps",
|
|
28
|
+
"st_touches"
|
|
29
|
+
]);
|
|
30
|
+
const JSONB_EXTRACTION_OPS = new Set([
|
|
31
|
+
"->>",
|
|
32
|
+
"->",
|
|
33
|
+
"#>>",
|
|
34
|
+
"#>"
|
|
35
|
+
]);
|
|
36
|
+
function getAExprOpName(node) {
|
|
37
|
+
const nameNode = node.A_Expr.name?.[0];
|
|
38
|
+
if (nameNode && is$1(nameNode, "String") && nameNode.String.sval) return nameNode.String.sval;
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Check if a node is or contains a JSONB extraction expression,
|
|
43
|
+
* unwrapping through TypeCast. Returns the extraction A_Expr if found.
|
|
44
|
+
*/
|
|
45
|
+
function findExtractionExpr(node) {
|
|
46
|
+
if (is$1(node, "A_Expr")) {
|
|
47
|
+
const op = getAExprOpName(node);
|
|
48
|
+
if (op && JSONB_EXTRACTION_OPS.has(op)) {
|
|
49
|
+
if (node.A_Expr.lexpr && hasColumnRefInNode(node.A_Expr.lexpr)) return node;
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (is$1(node, "TypeCast") && node.TypeCast.arg) return findExtractionExpr(node.TypeCast.arg);
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
const ARITHMETIC_OPERATORS = new Set([
|
|
57
|
+
"+",
|
|
58
|
+
"-",
|
|
59
|
+
"*",
|
|
60
|
+
"/",
|
|
61
|
+
"%"
|
|
62
|
+
]);
|
|
63
|
+
const isArithmeticExpr = (node) => {
|
|
64
|
+
if (!node || typeof node !== "object") return false;
|
|
65
|
+
if (!isANode$1(node) || !is$1(node, "A_Expr")) return false;
|
|
66
|
+
if (node.A_Expr.kind !== "AEXPR_OP" || !node.A_Expr.name?.length) return false;
|
|
67
|
+
const opNode = node.A_Expr.name[0];
|
|
68
|
+
if (!is$1(opNode, "String") || !opNode.String.sval) return false;
|
|
69
|
+
return ARITHMETIC_OPERATORS.has(opNode.String.sval);
|
|
70
|
+
};
|
|
71
|
+
const COMPARISON_OPERATORS = new Set([
|
|
72
|
+
"=",
|
|
73
|
+
"<",
|
|
74
|
+
">",
|
|
75
|
+
"<=",
|
|
76
|
+
">=",
|
|
77
|
+
"<>",
|
|
78
|
+
"!="
|
|
79
|
+
]);
|
|
80
|
+
const findFuncCallsOnColumns = (whereClause) => {
|
|
81
|
+
const nudges = [];
|
|
82
|
+
Walker.shallowMatch(whereClause, "FuncCall", (node) => {
|
|
83
|
+
if (node.FuncCall.args && containsColumnRef(node.FuncCall.args)) nudges.push({
|
|
84
|
+
kind: "AVOID_FUNCTIONS_ON_COLUMNS_IN_WHERE",
|
|
85
|
+
severity: "WARNING",
|
|
86
|
+
message: "Avoid using functions on columns in WHERE clause",
|
|
87
|
+
location: node.FuncCall.location
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
Walker.shallowMatch(whereClause, "CoalesceExpr", (node) => {
|
|
91
|
+
if (node.CoalesceExpr.args && containsColumnRef(node.CoalesceExpr.args)) nudges.push({
|
|
92
|
+
kind: "AVOID_FUNCTIONS_ON_COLUMNS_IN_WHERE",
|
|
93
|
+
severity: "WARNING",
|
|
94
|
+
message: "Avoid using functions on columns in WHERE clause",
|
|
95
|
+
location: node.CoalesceExpr.location
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
return nudges;
|
|
99
|
+
};
|
|
100
|
+
const findJsonbExtractionInWhere = (whereClause) => {
|
|
101
|
+
const nudges = [];
|
|
102
|
+
const seen = /* @__PURE__ */ new Set();
|
|
103
|
+
function emit(node) {
|
|
104
|
+
const extraction = findExtractionExpr(node);
|
|
105
|
+
if (extraction && extraction.A_Expr.location !== void 0 && !seen.has(extraction.A_Expr.location)) {
|
|
106
|
+
seen.add(extraction.A_Expr.location);
|
|
107
|
+
nudges.push({
|
|
108
|
+
kind: "CONSIDER_EXPRESSION_INDEX_FOR_JSONB_EXTRACTION",
|
|
109
|
+
severity: "INFO",
|
|
110
|
+
message: "Consider an expression B-tree index for JSONB path extraction",
|
|
111
|
+
location: extraction.A_Expr.location
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function walk(node) {
|
|
116
|
+
if (is$1(node, "A_Expr")) {
|
|
117
|
+
const op = getAExprOpName(node);
|
|
118
|
+
if (op && JSONB_EXTRACTION_OPS.has(op)) return;
|
|
119
|
+
if (node.A_Expr.lexpr) emit(node.A_Expr.lexpr);
|
|
120
|
+
if (node.A_Expr.rexpr) emit(node.A_Expr.rexpr);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (is$1(node, "BoolExpr") && node.BoolExpr.args) {
|
|
124
|
+
for (const arg of node.BoolExpr.args) walk(arg);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
if (is$1(node, "NullTest") && node.NullTest.arg) {
|
|
128
|
+
emit(node.NullTest.arg);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (is$1(node, "BooleanTest") && node.BooleanTest.arg) {
|
|
132
|
+
emit(node.BooleanTest.arg);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (is$1(node, "SubLink") && node.SubLink.testexpr) {
|
|
136
|
+
emit(node.SubLink.testexpr);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
walk(whereClause);
|
|
141
|
+
return nudges;
|
|
142
|
+
};
|
|
143
|
+
const findArithmeticExprsOnColumns = (whereClause) => {
|
|
144
|
+
const nudges = [];
|
|
145
|
+
Walker.shallowMatch(whereClause, "A_Expr", (node) => {
|
|
146
|
+
if (node.A_Expr.kind !== "AEXPR_OP" || !node.A_Expr.name?.length) return;
|
|
147
|
+
const opNode = node.A_Expr.name[0];
|
|
148
|
+
if (!is$1(opNode, "String") || !opNode.String.sval) return;
|
|
149
|
+
if (!COMPARISON_OPERATORS.has(opNode.String.sval)) return;
|
|
150
|
+
const sides = [node.A_Expr.lexpr, node.A_Expr.rexpr];
|
|
151
|
+
for (const side of sides) if (side && isArithmeticExpr(side) && hasColumnRefInNode(side)) {
|
|
152
|
+
const expr = side;
|
|
153
|
+
nudges.push({
|
|
154
|
+
kind: "AVOID_EXPRESSIONS_ON_COLUMNS_IN_WHERE",
|
|
155
|
+
severity: "WARNING",
|
|
156
|
+
message: "Avoid using arithmetic expressions on columns in WHERE clause",
|
|
157
|
+
location: expr.A_Expr.location
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
return nudges;
|
|
162
|
+
};
|
|
163
|
+
/**
|
|
164
|
+
* Detect nudges for a single node during AST traversal.
|
|
165
|
+
* Returns an array of nudges found for this node.
|
|
166
|
+
*/
|
|
167
|
+
function parseNudges(node, stack) {
|
|
168
|
+
const nudges = [];
|
|
169
|
+
if (is$1(node, "SelectStmt")) {
|
|
170
|
+
if (node.SelectStmt.whereClause) {
|
|
171
|
+
nudges.push(...findFuncCallsOnColumns(node.SelectStmt.whereClause));
|
|
172
|
+
nudges.push(...findJsonbExtractionInWhere(node.SelectStmt.whereClause));
|
|
173
|
+
nudges.push(...findArithmeticExprsOnColumns(node.SelectStmt.whereClause));
|
|
174
|
+
}
|
|
175
|
+
const star = node.SelectStmt.targetList?.find((target) => {
|
|
176
|
+
if (!(is$1(target, "ResTarget") && target.ResTarget.val && is$1(target.ResTarget.val, "ColumnRef"))) return false;
|
|
177
|
+
const fields = target.ResTarget.val.ColumnRef.fields;
|
|
178
|
+
if (!fields?.some((field) => is$1(field, "A_Star"))) return false;
|
|
179
|
+
if (fields.length > 1) return false;
|
|
180
|
+
return true;
|
|
181
|
+
});
|
|
182
|
+
if (star) {
|
|
183
|
+
const fromClause = node.SelectStmt.fromClause;
|
|
184
|
+
if (!(fromClause && fromClause.length > 0 && fromClause.every((item) => is$1(item, "RangeSubselect")))) nudges.push({
|
|
185
|
+
kind: "AVOID_SELECT_STAR",
|
|
186
|
+
severity: "INFO",
|
|
187
|
+
message: "Avoid using SELECT *",
|
|
188
|
+
location: star.ResTarget.location
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
for (const target of node.SelectStmt.targetList ?? []) if (is$1(target, "ResTarget") && target.ResTarget.val && is$1(target.ResTarget.val, "SubLink") && target.ResTarget.val.SubLink.subLinkType === "EXPR_SUBLINK") nudges.push({
|
|
192
|
+
kind: "AVOID_SCALAR_SUBQUERY_IN_SELECT",
|
|
193
|
+
severity: "WARNING",
|
|
194
|
+
message: "Avoid correlated scalar subqueries in SELECT; consider rewriting as a JOIN",
|
|
195
|
+
location: target.ResTarget.val.SubLink.location
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
if (is$1(node, "SelectStmt")) {
|
|
199
|
+
if (!stack.some((item) => item === "RangeSubselect" || item === "SubLink" || item === "CommonTableExpr")) {
|
|
200
|
+
if (node.SelectStmt.fromClause && node.SelectStmt.fromClause.length > 0) {
|
|
201
|
+
if (node.SelectStmt.fromClause.some((fromItem) => {
|
|
202
|
+
return is$1(fromItem, "RangeVar") || is$1(fromItem, "JoinExpr") && hasActualTablesInJoin(fromItem);
|
|
203
|
+
})) {
|
|
204
|
+
const fromLocation = node.SelectStmt.fromClause.find((item) => is$1(item, "RangeVar"))?.RangeVar.location;
|
|
205
|
+
if (!node.SelectStmt.whereClause) nudges.push({
|
|
206
|
+
kind: "MISSING_WHERE_CLAUSE",
|
|
207
|
+
severity: "INFO",
|
|
208
|
+
message: "Missing WHERE clause",
|
|
209
|
+
location: fromLocation
|
|
210
|
+
});
|
|
211
|
+
if (!node.SelectStmt.limitCount) nudges.push({
|
|
212
|
+
kind: "MISSING_LIMIT_CLAUSE",
|
|
213
|
+
severity: "INFO",
|
|
214
|
+
message: "Missing LIMIT clause",
|
|
215
|
+
location: fromLocation
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (is$1(node, "SelectStmt")) {
|
|
222
|
+
if (!stack.some((item) => item === "RangeSubselect" || item === "SubLink" || item === "CommonTableExpr") && node.SelectStmt.sortClause && node.SelectStmt.whereClause) {
|
|
223
|
+
const equalityColumns = collectEqualityConstrainedColumns(node.SelectStmt.whereClause);
|
|
224
|
+
for (const sortItem of node.SelectStmt.sortClause) {
|
|
225
|
+
if (!is$1(sortItem, "SortBy") || !sortItem.SortBy.node) continue;
|
|
226
|
+
const sortNode = sortItem.SortBy.node;
|
|
227
|
+
if (!is$1(sortNode, "ColumnRef") || !sortNode.ColumnRef.fields) continue;
|
|
228
|
+
const lastField = sortNode.ColumnRef.fields[sortNode.ColumnRef.fields.length - 1];
|
|
229
|
+
if (!is$1(lastField, "String")) continue;
|
|
230
|
+
const sortCol = lastField.String.sval;
|
|
231
|
+
if (sortCol && equalityColumns.has(sortCol)) nudges.push({
|
|
232
|
+
kind: "NOOP_ORDER_BY",
|
|
233
|
+
severity: "INFO",
|
|
234
|
+
message: "ORDER BY column is constrained to a single value by WHERE clause",
|
|
235
|
+
location: sortNode.ColumnRef.location
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (is$1(node, "SelectStmt") && node.SelectStmt.sortClause) for (const sortItem of node.SelectStmt.sortClause) {
|
|
241
|
+
if (!is$1(sortItem, "SortBy")) continue;
|
|
242
|
+
const sortDir = sortItem.SortBy.sortby_dir ?? "SORTBY_DEFAULT";
|
|
243
|
+
const sortNulls = sortItem.SortBy.sortby_nulls ?? "SORTBY_NULLS_DEFAULT";
|
|
244
|
+
if (sortDir === "SORTBY_DESC" && sortNulls === "SORTBY_NULLS_DEFAULT") {
|
|
245
|
+
if (sortItem.SortBy.node && is$1(sortItem.SortBy.node, "ColumnRef")) {
|
|
246
|
+
const sortColumnName = getLastColumnRefField(sortItem.SortBy.node);
|
|
247
|
+
if (!(sortColumnName !== null && whereHasIsNotNull(node.SelectStmt.whereClause, sortColumnName))) nudges.push({
|
|
248
|
+
kind: "NULLS_FIRST_IN_DESC_ORDER",
|
|
249
|
+
severity: "INFO",
|
|
250
|
+
message: "ORDER BY … DESC sorts NULLs first — add NULLS LAST to push them to the end",
|
|
251
|
+
location: sortItem.SortBy.node.ColumnRef.location
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (is$1(node, "A_Expr")) {
|
|
257
|
+
const isEqualityOp = node.A_Expr.kind === "AEXPR_OP" && node.A_Expr.name && node.A_Expr.name.length > 0 && is$1(node.A_Expr.name[0], "String") && (node.A_Expr.name[0].String.sval === "=" || node.A_Expr.name[0].String.sval === "!=" || node.A_Expr.name[0].String.sval === "<>");
|
|
258
|
+
if (isEqualityOp) {
|
|
259
|
+
const leftIsNull = isNullConstant(node.A_Expr.lexpr);
|
|
260
|
+
const rightIsNull = isNullConstant(node.A_Expr.rexpr);
|
|
261
|
+
if (leftIsNull || rightIsNull) nudges.push({
|
|
262
|
+
kind: "USE_IS_NULL_NOT_EQUALS",
|
|
263
|
+
severity: "WARNING",
|
|
264
|
+
message: "Use IS NULL instead of = or != or <> for NULL comparisons",
|
|
265
|
+
location: node.A_Expr.location
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
const isLikeOp = node.A_Expr.kind === "AEXPR_LIKE" || node.A_Expr.kind === "AEXPR_ILIKE";
|
|
269
|
+
if (isLikeOp && node.A_Expr.rexpr) {
|
|
270
|
+
const patternString = getStringConstantValue(node.A_Expr.rexpr);
|
|
271
|
+
if (patternString && patternString.startsWith("%")) {
|
|
272
|
+
let stringNode;
|
|
273
|
+
if (is$1(node.A_Expr.rexpr, "A_Const")) stringNode = node.A_Expr.rexpr.A_Const;
|
|
274
|
+
nudges.push({
|
|
275
|
+
kind: "AVOID_LEADING_WILDCARD_LIKE",
|
|
276
|
+
severity: "WARNING",
|
|
277
|
+
message: "Leading wildcard in LIKE/ILIKE prevents index usage — consider a GIN trigram index (pg_trgm) or full-text search",
|
|
278
|
+
location: stringNode?.location
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
if (isEqualityOp === false && isLikeOp === false) {
|
|
283
|
+
const gistOpName = node.A_Expr.kind === "AEXPR_OP" && node.A_Expr.name?.[0] && is$1(node.A_Expr.name[0], "String") && node.A_Expr.name[0].String.sval;
|
|
284
|
+
if (gistOpName && GIST_OPERATORS.has(gistOpName)) nudges.push({
|
|
285
|
+
kind: "CONSIDER_GIST_INDEX",
|
|
286
|
+
severity: "INFO",
|
|
287
|
+
message: `Operator "${gistOpName}" benefits from a GiST index for efficient execution`,
|
|
288
|
+
location: node.A_Expr.location
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
if (is$1(node, "SelectStmt") && node.SelectStmt.sortClause) {
|
|
293
|
+
for (const sortItem of node.SelectStmt.sortClause) if (is$1(sortItem, "SortBy") && sortItem.SortBy.node && is$1(sortItem.SortBy.node, "FuncCall") && sortItem.SortBy.node.FuncCall.funcname?.some((name) => is$1(name, "String") && name.String.sval === "random")) nudges.push({
|
|
294
|
+
kind: "AVOID_ORDER_BY_RANDOM",
|
|
295
|
+
severity: "WARNING",
|
|
296
|
+
message: "Avoid using ORDER BY random()",
|
|
297
|
+
location: sortItem.SortBy.node.FuncCall.location
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
if (is$1(node, "SelectStmt") && node.SelectStmt.distinctClause) nudges.push({
|
|
301
|
+
kind: "AVOID_DISTINCT_WITHOUT_REASON",
|
|
302
|
+
severity: "WARNING",
|
|
303
|
+
message: "Avoid using DISTINCT without a reason"
|
|
304
|
+
});
|
|
305
|
+
if (is$1(node, "SelectStmt") && node.SelectStmt.limitOffset) {
|
|
306
|
+
const offsetNode = node.SelectStmt.limitOffset;
|
|
307
|
+
const location = isANode$1(offsetNode) && is$1(offsetNode, "A_Const") ? offsetNode.A_Const.location : void 0;
|
|
308
|
+
nudges.push({
|
|
309
|
+
kind: "AVOID_OFFSET_FOR_PAGINATION",
|
|
310
|
+
severity: "INFO",
|
|
311
|
+
message: "Avoid using OFFSET for pagination",
|
|
312
|
+
location
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
if (is$1(node, "JoinExpr")) {
|
|
316
|
+
if (!node.JoinExpr.quals) nudges.push({
|
|
317
|
+
kind: "MISSING_JOIN_CONDITION",
|
|
318
|
+
severity: "WARNING",
|
|
319
|
+
message: "Missing JOIN condition"
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
if (is$1(node, "SelectStmt") && node.SelectStmt.fromClause && node.SelectStmt.fromClause.length > 1) {
|
|
323
|
+
const tables = node.SelectStmt.fromClause.filter((item) => is$1(item, "RangeVar"));
|
|
324
|
+
if (tables.length > 1) nudges.push({
|
|
325
|
+
kind: "MISSING_JOIN_CONDITION",
|
|
326
|
+
severity: "WARNING",
|
|
327
|
+
message: "Missing JOIN condition",
|
|
328
|
+
location: tables[1].RangeVar.location
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
if (is$1(node, "BoolExpr") && node.BoolExpr.boolop === "OR_EXPR") {
|
|
332
|
+
if (countBoolOrConditions(node) >= 3) nudges.push({
|
|
333
|
+
kind: "CONSIDER_IN_INSTEAD_OF_MANY_ORS",
|
|
334
|
+
severity: "WARNING",
|
|
335
|
+
message: "Consider using IN instead of many ORs",
|
|
336
|
+
location: node.BoolExpr.location
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
if (is$1(node, "BoolExpr") && node.BoolExpr.boolop === "NOT_EXPR") {
|
|
340
|
+
const args = node.BoolExpr.args;
|
|
341
|
+
if (args && args.length === 1) {
|
|
342
|
+
const inner = args[0];
|
|
343
|
+
if (isANode$1(inner) && is$1(inner, "SubLink") && inner.SubLink.subLinkType === "ANY_SUBLINK") nudges.push({
|
|
344
|
+
kind: "PREFER_NOT_EXISTS_OVER_NOT_IN",
|
|
345
|
+
severity: "WARNING",
|
|
346
|
+
message: "Prefer NOT EXISTS over NOT IN (SELECT ...)",
|
|
347
|
+
location: inner.SubLink.location
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
if (is$1(node, "SelectStmt") && node.SelectStmt.havingClause) {
|
|
352
|
+
if (!containsAggregate(node.SelectStmt.havingClause)) {
|
|
353
|
+
const having = node.SelectStmt.havingClause;
|
|
354
|
+
let location;
|
|
355
|
+
if (is$1(having, "A_Expr")) location = having.A_Expr.location;
|
|
356
|
+
else if (is$1(having, "BoolExpr")) location = having.BoolExpr.location;
|
|
357
|
+
nudges.push({
|
|
358
|
+
kind: "PREFER_WHERE_OVER_HAVING_FOR_NON_AGGREGATES",
|
|
359
|
+
severity: "INFO",
|
|
360
|
+
message: "Non-aggregate condition in HAVING should be in WHERE",
|
|
361
|
+
location
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
if (is$1(node, "FuncCall")) {
|
|
366
|
+
const funcName = node.FuncCall.funcname;
|
|
367
|
+
if (funcName && funcName.length === 1 && is$1(funcName[0], "String") && funcName[0].String.sval === "count" && node.FuncCall.args && !node.FuncCall.agg_star && !node.FuncCall.agg_distinct) nudges.push({
|
|
368
|
+
kind: "PREFER_COUNT_STAR_OVER_COUNT_COLUMN",
|
|
369
|
+
severity: "INFO",
|
|
370
|
+
message: "Prefer COUNT(*) over COUNT(column) or COUNT(1) — COUNT(*) counts rows without checking for NULLs. If you need to count non-NULL values, COUNT(column) is correct.",
|
|
371
|
+
location: node.FuncCall.location
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
if (is$1(node, "A_Expr") && node.A_Expr.kind === "AEXPR_OP" && node.A_Expr.name && node.A_Expr.name.length > 0) {
|
|
375
|
+
const opNode = node.A_Expr.name[0];
|
|
376
|
+
const op = is$1(opNode, "String") ? opNode.String.sval : null;
|
|
377
|
+
if (op && isExistenceCheckPattern(node.A_Expr.lexpr, node.A_Expr.rexpr, op)) nudges.push({
|
|
378
|
+
kind: "USE_EXISTS_NOT_COUNT_FOR_EXISTENCE_CHECK",
|
|
379
|
+
severity: "INFO",
|
|
380
|
+
message: "Use EXISTS instead of COUNT for existence checks",
|
|
381
|
+
location: node.A_Expr.location
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
if (is$1(node, "FuncCall")) {
|
|
385
|
+
const funcname = node.FuncCall.funcname?.[0] && is$1(node.FuncCall.funcname[0], "String") && node.FuncCall.funcname[0].String.sval;
|
|
386
|
+
if (funcname && [
|
|
387
|
+
"sum",
|
|
388
|
+
"count",
|
|
389
|
+
"avg",
|
|
390
|
+
"min",
|
|
391
|
+
"max"
|
|
392
|
+
].includes(funcname.toLowerCase())) {
|
|
393
|
+
const firstArg = node.FuncCall.args?.[0];
|
|
394
|
+
if (firstArg && isANode$1(firstArg) && is$1(firstArg, "CaseExpr")) {
|
|
395
|
+
const caseExpr = firstArg.CaseExpr;
|
|
396
|
+
if (caseExpr.args && caseExpr.args.length === 1) {
|
|
397
|
+
const defresult = caseExpr.defresult;
|
|
398
|
+
if (!defresult || isANode$1(defresult) && is$1(defresult, "A_Const") && (defresult.A_Const.isnull !== void 0 || defresult.A_Const.ival !== void 0 && (defresult.A_Const.ival.ival === 0 || defresult.A_Const.ival.ival === void 0))) nudges.push({
|
|
399
|
+
kind: "PREFER_FILTER_OVER_CASE_IN_AGGREGATE",
|
|
400
|
+
severity: "INFO",
|
|
401
|
+
message: "Use FILTER (WHERE ...) instead of CASE inside aggregate functions",
|
|
402
|
+
location: node.FuncCall.location
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
if (is$1(node, "FuncCall") && node.FuncCall.funcname) {
|
|
409
|
+
const lastNameNode = node.FuncCall.funcname[node.FuncCall.funcname.length - 1];
|
|
410
|
+
if (lastNameNode && is$1(lastNameNode, "String") && lastNameNode.String.sval) {
|
|
411
|
+
const funcName = lastNameNode.String.sval.toLowerCase();
|
|
412
|
+
if (SPATIAL_FUNCTIONS.has(funcName)) nudges.push({
|
|
413
|
+
kind: "CONSIDER_GIST_INDEX",
|
|
414
|
+
severity: "INFO",
|
|
415
|
+
message: `Spatial function "${lastNameNode.String.sval}" benefits from a GiST index for efficient execution`,
|
|
416
|
+
location: node.FuncCall.location
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
if (is$1(node, "BoolExpr") && node.BoolExpr.boolop === "NOT_EXPR") {
|
|
421
|
+
const args = node.BoolExpr.args;
|
|
422
|
+
if (args && args.length === 1) {
|
|
423
|
+
const arg = args[0];
|
|
424
|
+
if (isANode$1(arg) && is$1(arg, "SubLink") && arg.SubLink.subLinkType === "EXISTS_SUBLINK" && arg.SubLink.subselect) {
|
|
425
|
+
const subselect = arg.SubLink.subselect;
|
|
426
|
+
if (isANode$1(subselect) && is$1(subselect, "SelectStmt") && subselect.SelectStmt.whereClause) {
|
|
427
|
+
const where = subselect.SelectStmt.whereClause;
|
|
428
|
+
if (isANode$1(where) && is$1(where, "BoolExpr") && where.BoolExpr.boolop === "OR_EXPR") nudges.push({
|
|
429
|
+
kind: "FLATTEN_NOT_EXISTS_OR",
|
|
430
|
+
severity: "INFO",
|
|
431
|
+
message: "Consider splitting NOT EXISTS with OR into separate NOT EXISTS joined by AND",
|
|
432
|
+
location: node.BoolExpr.location
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (is$1(node, "A_Expr")) {
|
|
439
|
+
if (node.A_Expr.kind === "AEXPR_IN") {
|
|
440
|
+
let list;
|
|
441
|
+
if (node.A_Expr.lexpr && is$1(node.A_Expr.lexpr, "List")) list = node.A_Expr.lexpr.List;
|
|
442
|
+
else if (node.A_Expr.rexpr && is$1(node.A_Expr.rexpr, "List")) list = node.A_Expr.rexpr.List;
|
|
443
|
+
if (list?.items && list.items.length >= 10) nudges.push({
|
|
444
|
+
kind: "REPLACE_LARGE_IN_TUPLE_WITH_ANY_ARRAY",
|
|
445
|
+
message: "`in (...)` queries with large tuples can often be replaced with `= ANY($1)` using a single parameter",
|
|
446
|
+
severity: "INFO",
|
|
447
|
+
location: node.A_Expr.location
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
if (is$1(node, "SelectStmt") && node.SelectStmt.op === "SETOP_UNION" && !node.SelectStmt.all) nudges.push({
|
|
452
|
+
kind: "PREFER_UNION_ALL_OVER_UNION",
|
|
453
|
+
severity: "INFO",
|
|
454
|
+
message: "UNION removes duplicates with an implicit sort — use UNION ALL if deduplication is not needed"
|
|
455
|
+
});
|
|
456
|
+
if (is$1(node, "SelectStmt")) {
|
|
457
|
+
const subqueryAliases = /* @__PURE__ */ new Set();
|
|
458
|
+
if (node.SelectStmt.targetList) {
|
|
459
|
+
for (const target of node.SelectStmt.targetList) if (is$1(target, "ResTarget")) {
|
|
460
|
+
if (target.ResTarget.val && is$1(target.ResTarget.val, "SubLink")) {
|
|
461
|
+
if (target.ResTarget.name) subqueryAliases.add(target.ResTarget.name.toLowerCase());
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
if (subqueryAliases.size > 0 && node.SelectStmt.sortClause) {
|
|
466
|
+
for (const sortBy of node.SelectStmt.sortClause) if (is$1(sortBy, "SortBy") && sortBy.SortBy.node) {
|
|
467
|
+
if (is$1(sortBy.SortBy.node, "ColumnRef")) {
|
|
468
|
+
const columnName = extractColumnName(sortBy.SortBy.node);
|
|
469
|
+
if (columnName && subqueryAliases.has(columnName.toLowerCase())) {
|
|
470
|
+
nudges.push({
|
|
471
|
+
kind: "AVOID_SORTING_ON_GENERATED_VALUES",
|
|
472
|
+
severity: "WARNING",
|
|
473
|
+
message: "Be careful sorting on values generated dynamically during query execution - these cannot use indexes and contribute to slower query performance."
|
|
474
|
+
});
|
|
475
|
+
break;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
return nudges;
|
|
482
|
+
}
|
|
483
|
+
function containsColumnRef(args) {
|
|
484
|
+
for (const arg of args) if (hasColumnRefInNode(arg)) return true;
|
|
485
|
+
return false;
|
|
486
|
+
}
|
|
487
|
+
function hasColumnRefInNode(node) {
|
|
488
|
+
if (isANode$1(node) && is$1(node, "ColumnRef")) return true;
|
|
489
|
+
if (typeof node !== "object" || node === null) return false;
|
|
490
|
+
if (Array.isArray(node)) return node.some((item) => hasColumnRefInNode(item));
|
|
491
|
+
if (isANode$1(node)) return hasColumnRefInNode(node[Object.keys(node)[0]]);
|
|
492
|
+
for (const child of Object.values(node)) if (hasColumnRefInNode(child)) return true;
|
|
493
|
+
return false;
|
|
494
|
+
}
|
|
495
|
+
function hasActualTablesInJoin(joinExpr) {
|
|
496
|
+
if (joinExpr.JoinExpr.larg && is$1(joinExpr.JoinExpr.larg, "RangeVar")) return true;
|
|
497
|
+
if (joinExpr.JoinExpr.larg && is$1(joinExpr.JoinExpr.larg, "JoinExpr")) {
|
|
498
|
+
if (hasActualTablesInJoin(joinExpr.JoinExpr.larg)) return true;
|
|
499
|
+
}
|
|
500
|
+
if (joinExpr.JoinExpr.rarg && is$1(joinExpr.JoinExpr.rarg, "RangeVar")) return true;
|
|
501
|
+
if (joinExpr.JoinExpr.rarg && is$1(joinExpr.JoinExpr.rarg, "JoinExpr")) {
|
|
502
|
+
if (hasActualTablesInJoin(joinExpr.JoinExpr.rarg)) return true;
|
|
503
|
+
}
|
|
504
|
+
return false;
|
|
505
|
+
}
|
|
506
|
+
function isNullConstant(node) {
|
|
507
|
+
if (!node || typeof node !== "object") return false;
|
|
508
|
+
if (isANode$1(node) && is$1(node, "A_Const")) return node.A_Const.isnull !== void 0;
|
|
509
|
+
return false;
|
|
510
|
+
}
|
|
511
|
+
function getStringConstantValue(node) {
|
|
512
|
+
if (!node || typeof node !== "object") return null;
|
|
513
|
+
if (isANode$1(node) && is$1(node, "A_Const") && node.A_Const.sval) return node.A_Const.sval.sval || null;
|
|
514
|
+
return null;
|
|
515
|
+
}
|
|
516
|
+
const AGGREGATE_FUNCTIONS = new Set([
|
|
517
|
+
"count",
|
|
518
|
+
"sum",
|
|
519
|
+
"avg",
|
|
520
|
+
"min",
|
|
521
|
+
"max",
|
|
522
|
+
"array_agg",
|
|
523
|
+
"string_agg",
|
|
524
|
+
"bool_and",
|
|
525
|
+
"bool_or",
|
|
526
|
+
"every"
|
|
527
|
+
]);
|
|
528
|
+
function containsAggregate(node) {
|
|
529
|
+
if (!node || typeof node !== "object") return false;
|
|
530
|
+
if (Array.isArray(node)) return node.some(containsAggregate);
|
|
531
|
+
if (isANode$1(node) && is$1(node, "FuncCall")) {
|
|
532
|
+
const funcname = node.FuncCall.funcname;
|
|
533
|
+
if (funcname) {
|
|
534
|
+
for (const f of funcname) if (isANode$1(f) && is$1(f, "String") && AGGREGATE_FUNCTIONS.has(f.String.sval?.toLowerCase() ?? "")) return true;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
if (isANode$1(node)) return containsAggregate(node[Object.keys(node)[0]]);
|
|
538
|
+
for (const child of Object.values(node)) if (containsAggregate(child)) return true;
|
|
539
|
+
return false;
|
|
540
|
+
}
|
|
541
|
+
function getLastColumnRefField(columnRef) {
|
|
542
|
+
const fields = columnRef.ColumnRef.fields;
|
|
543
|
+
if (!fields || fields.length === 0) return null;
|
|
544
|
+
const lastField = fields[fields.length - 1];
|
|
545
|
+
if (isANode$1(lastField) && is$1(lastField, "String")) return lastField.String.sval || null;
|
|
546
|
+
return null;
|
|
547
|
+
}
|
|
548
|
+
function whereHasIsNotNull(whereClause, columnName) {
|
|
549
|
+
if (!whereClause) return false;
|
|
550
|
+
let found = false;
|
|
551
|
+
Walker.shallowMatch(whereClause, "NullTest", (node) => {
|
|
552
|
+
if (node.NullTest.nulltesttype === "IS_NOT_NULL" && node.NullTest.arg && is$1(node.NullTest.arg, "ColumnRef")) {
|
|
553
|
+
if (getLastColumnRefField(node.NullTest.arg) === columnName) found = true;
|
|
554
|
+
}
|
|
555
|
+
});
|
|
556
|
+
return found;
|
|
557
|
+
}
|
|
558
|
+
function isCountFuncCall(node) {
|
|
559
|
+
if (!node || typeof node !== "object") return false;
|
|
560
|
+
if (!isANode$1(node) || !is$1(node, "FuncCall")) return false;
|
|
561
|
+
const fc = node.FuncCall;
|
|
562
|
+
if (!(fc.funcname?.some((n) => is$1(n, "String") && n.String.sval === "count") ?? false)) return false;
|
|
563
|
+
if (fc.agg_star) return true;
|
|
564
|
+
if (fc.args && fc.args.length === 1 && isANode$1(fc.args[0]) && is$1(fc.args[0], "A_Const")) return true;
|
|
565
|
+
return false;
|
|
566
|
+
}
|
|
567
|
+
function isSubLinkWithCount(node) {
|
|
568
|
+
if (!node || typeof node !== "object") return false;
|
|
569
|
+
if (!isANode$1(node) || !is$1(node, "SubLink")) return false;
|
|
570
|
+
const subselect = node.SubLink.subselect;
|
|
571
|
+
if (!subselect || !isANode$1(subselect) || !is$1(subselect, "SelectStmt")) return false;
|
|
572
|
+
const targets = subselect.SelectStmt.targetList;
|
|
573
|
+
if (!targets || targets.length !== 1) return false;
|
|
574
|
+
const target = targets[0];
|
|
575
|
+
if (!isANode$1(target) || !is$1(target, "ResTarget") || !target.ResTarget.val) return false;
|
|
576
|
+
return isCountFuncCall(target.ResTarget.val);
|
|
577
|
+
}
|
|
578
|
+
function isCountExpression(node) {
|
|
579
|
+
return isCountFuncCall(node) || isSubLinkWithCount(node);
|
|
580
|
+
}
|
|
581
|
+
function getIntegerConstantValue(node) {
|
|
582
|
+
if (!node || typeof node !== "object") return null;
|
|
583
|
+
if (!isANode$1(node) || !is$1(node, "A_Const")) return null;
|
|
584
|
+
if (node.A_Const.ival === void 0) return null;
|
|
585
|
+
return node.A_Const.ival.ival ?? 0;
|
|
586
|
+
}
|
|
587
|
+
function isExistenceCheckPattern(lexpr, rexpr, op) {
|
|
588
|
+
if (isCountExpression(lexpr)) {
|
|
589
|
+
const val = getIntegerConstantValue(rexpr);
|
|
590
|
+
if (val !== null) {
|
|
591
|
+
if (op === ">" && val === 0) return true;
|
|
592
|
+
if (op === ">=" && val === 1) return true;
|
|
593
|
+
if ((op === "!=" || op === "<>") && val === 0) return true;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
if (isCountExpression(rexpr)) {
|
|
597
|
+
const val = getIntegerConstantValue(lexpr);
|
|
598
|
+
if (val !== null) {
|
|
599
|
+
if (op === "<" && val === 0) return true;
|
|
600
|
+
if (op === "<=" && val === 1) return true;
|
|
601
|
+
if ((op === "!=" || op === "<>") && val === 0) return true;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
return false;
|
|
605
|
+
}
|
|
606
|
+
function collectEqualityConstrainedColumns(whereClause) {
|
|
607
|
+
const columns = /* @__PURE__ */ new Set();
|
|
608
|
+
function walk(node) {
|
|
609
|
+
if (!node || typeof node !== "object") return;
|
|
610
|
+
if (!isANode$1(node)) return;
|
|
611
|
+
if (is$1(node, "BoolExpr") && node.BoolExpr.boolop === "AND_EXPR" && node.BoolExpr.args) {
|
|
612
|
+
for (const arg of node.BoolExpr.args) walk(arg);
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
if (is$1(node, "A_Expr") && node.A_Expr.kind === "AEXPR_OP") {
|
|
616
|
+
const opName = node.A_Expr.name?.[0];
|
|
617
|
+
if (opName && is$1(opName, "String") && opName.String.sval === "=") {
|
|
618
|
+
addColumnIfConstant(node.A_Expr.lexpr, node.A_Expr.rexpr, columns);
|
|
619
|
+
addColumnIfConstant(node.A_Expr.rexpr, node.A_Expr.lexpr, columns);
|
|
620
|
+
}
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
if (is$1(node, "A_Expr") && node.A_Expr.kind === "AEXPR_IN") {
|
|
624
|
+
const listNode = node.A_Expr.rexpr;
|
|
625
|
+
if (listNode && isANode$1(listNode) && is$1(listNode, "List") && listNode.List.items && listNode.List.items.length === 1) {
|
|
626
|
+
const colNode = node.A_Expr.lexpr;
|
|
627
|
+
if (colNode && isANode$1(colNode) && is$1(colNode, "ColumnRef")) {
|
|
628
|
+
const lastField = colNode.ColumnRef.fields?.[colNode.ColumnRef.fields.length - 1];
|
|
629
|
+
if (lastField && is$1(lastField, "String") && lastField.String.sval) columns.add(lastField.String.sval);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
walk(whereClause);
|
|
635
|
+
return columns;
|
|
636
|
+
}
|
|
637
|
+
function addColumnIfConstant(colSide, constSide, columns) {
|
|
638
|
+
if (!colSide || !constSide || typeof colSide !== "object" || typeof constSide !== "object") return;
|
|
639
|
+
if (!isANode$1(colSide) || !is$1(colSide, "ColumnRef")) return;
|
|
640
|
+
if (!isANode$1(constSide) || !is$1(constSide, "A_Const") && !is$1(constSide, "ParamRef")) return;
|
|
641
|
+
const fields = colSide.ColumnRef.fields;
|
|
642
|
+
if (!fields || fields.length === 0) return;
|
|
643
|
+
const lastField = fields[fields.length - 1];
|
|
644
|
+
if (is$1(lastField, "String") && lastField.String.sval) columns.add(lastField.String.sval);
|
|
645
|
+
}
|
|
646
|
+
function extractColumnName(node) {
|
|
647
|
+
if (!node.ColumnRef.fields || node.ColumnRef.fields.length === 0) return null;
|
|
648
|
+
const lastField = node.ColumnRef.fields[node.ColumnRef.fields.length - 1];
|
|
649
|
+
if (is$1(lastField, "String") && lastField.String.sval) return lastField.String.sval;
|
|
650
|
+
return null;
|
|
651
|
+
}
|
|
652
|
+
function countBoolOrConditions(node) {
|
|
653
|
+
if (node.BoolExpr.boolop !== "OR_EXPR" || !node.BoolExpr.args) return 1;
|
|
654
|
+
let count = 0;
|
|
655
|
+
for (const arg of node.BoolExpr.args) if (isANode$1(arg) && is$1(arg, "BoolExpr") && arg.BoolExpr.boolop === "OR_EXPR") count += countBoolOrConditions(arg);
|
|
656
|
+
else count += 1;
|
|
657
|
+
return count;
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* Extract the major version number from a PostgreSQL version string.
|
|
661
|
+
* PostgreSQL encodes versions as XXYYZZ where XX is major, YY is minor, ZZ is patch.
|
|
662
|
+
* e.g. "170000" → 17, "160004" → 16, "120000" → 12
|
|
663
|
+
*/
|
|
664
|
+
function parseMajorVersion(versionNum) {
|
|
665
|
+
return Math.floor(parseInt(versionNum, 10) / 1e4);
|
|
666
|
+
}
|
|
667
|
+
/**
|
|
668
|
+
* Produce version-aware nudges by checking existing nudges against the
|
|
669
|
+
* user's PostgreSQL major version. Returns upgrade recommendations
|
|
670
|
+
* when a query pattern would benefit from a newer version.
|
|
671
|
+
*/
|
|
672
|
+
function parseVersionNudges(nudges, majorVersion) {
|
|
673
|
+
const versionNudges = [];
|
|
674
|
+
if (majorVersion < 17 && nudges.some((n) => n.kind === "AVOID_DISTINCT_WITHOUT_REASON")) versionNudges.push({
|
|
675
|
+
kind: "UPGRADE_DISTINCT_PG17",
|
|
676
|
+
severity: "INFO",
|
|
677
|
+
message: "PostgreSQL 17 introduces hash-based DISTINCT, which can significantly speed up queries using DISTINCT"
|
|
678
|
+
});
|
|
679
|
+
return versionNudges;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
//#endregion
|
|
683
|
+
//#region \0@oxc-project+runtime@0.112.0/helpers/typeof.js
|
|
684
|
+
function _typeof(o) {
|
|
685
|
+
"@babel/helpers - typeof";
|
|
686
|
+
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
|
|
687
|
+
return typeof o;
|
|
688
|
+
} : function(o) {
|
|
689
|
+
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
|
|
690
|
+
}, _typeof(o);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
//#endregion
|
|
694
|
+
//#region \0@oxc-project+runtime@0.112.0/helpers/toPrimitive.js
|
|
695
|
+
function toPrimitive(t, r) {
|
|
696
|
+
if ("object" != _typeof(t) || !t) return t;
|
|
697
|
+
var e = t[Symbol.toPrimitive];
|
|
698
|
+
if (void 0 !== e) {
|
|
699
|
+
var i = e.call(t, r || "default");
|
|
700
|
+
if ("object" != _typeof(i)) return i;
|
|
701
|
+
throw new TypeError("@@toPrimitive must return a primitive value.");
|
|
702
|
+
}
|
|
703
|
+
return ("string" === r ? String : Number)(t);
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
//#endregion
|
|
707
|
+
//#region \0@oxc-project+runtime@0.112.0/helpers/toPropertyKey.js
|
|
708
|
+
function toPropertyKey(t) {
|
|
709
|
+
var i = toPrimitive(t, "string");
|
|
710
|
+
return "symbol" == _typeof(i) ? i : i + "";
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
//#endregion
|
|
714
|
+
//#region \0@oxc-project+runtime@0.112.0/helpers/defineProperty.js
|
|
715
|
+
function _defineProperty(e, r, t) {
|
|
716
|
+
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
|
|
717
|
+
value: t,
|
|
718
|
+
enumerable: !0,
|
|
719
|
+
configurable: !0,
|
|
720
|
+
writable: !0
|
|
721
|
+
}) : e[r] = t, e;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
//#endregion
|
|
725
|
+
//#region src/sql/walker.ts
|
|
726
|
+
/**
|
|
727
|
+
* Walks the AST of a sql query and extracts query metadata.
|
|
728
|
+
* This pattern is used to segregate the mutable state that's more common for the
|
|
729
|
+
* AST walking process from the rest of the analyzer.
|
|
730
|
+
*/
|
|
731
|
+
var Walker = class Walker {
|
|
732
|
+
constructor(query) {
|
|
733
|
+
this.query = query;
|
|
734
|
+
_defineProperty(this, "tableMappings", /* @__PURE__ */ new Map());
|
|
735
|
+
_defineProperty(this, "tempTables", /* @__PURE__ */ new Set());
|
|
736
|
+
_defineProperty(this, "highlights", []);
|
|
737
|
+
_defineProperty(this, "indexRepresentations", /* @__PURE__ */ new Set());
|
|
738
|
+
_defineProperty(this, "indexesToCheck", []);
|
|
739
|
+
_defineProperty(this, "highlightPositions", /* @__PURE__ */ new Set());
|
|
740
|
+
_defineProperty(this, "seenReferences", /* @__PURE__ */ new Map());
|
|
741
|
+
_defineProperty(this, "shadowedAliases", []);
|
|
742
|
+
_defineProperty(this, "nudges", []);
|
|
743
|
+
}
|
|
744
|
+
walk(root) {
|
|
745
|
+
this.tableMappings = /* @__PURE__ */ new Map();
|
|
746
|
+
this.tempTables = /* @__PURE__ */ new Set();
|
|
747
|
+
this.highlights = [];
|
|
748
|
+
this.indexRepresentations = /* @__PURE__ */ new Set();
|
|
749
|
+
this.indexesToCheck = [];
|
|
750
|
+
this.highlightPositions = /* @__PURE__ */ new Set();
|
|
751
|
+
this.seenReferences = /* @__PURE__ */ new Map();
|
|
752
|
+
this.shadowedAliases = [];
|
|
753
|
+
this.nudges = [];
|
|
754
|
+
Walker.traverse(root, (node, stack) => {
|
|
755
|
+
const nodeNudges = parseNudges(node, stack);
|
|
756
|
+
this.nudges = [...this.nudges, ...nodeNudges];
|
|
757
|
+
if (is(node, "CommonTableExpr")) {
|
|
758
|
+
if (node.CommonTableExpr.ctename) this.tempTables.add(node.CommonTableExpr.ctename);
|
|
759
|
+
}
|
|
760
|
+
if (is(node, "RangeSubselect")) {
|
|
761
|
+
if (node.RangeSubselect.alias?.aliasname) this.tempTables.add(node.RangeSubselect.alias.aliasname);
|
|
762
|
+
}
|
|
763
|
+
if (is(node, "NullTest")) {
|
|
764
|
+
if (node.NullTest.arg && node.NullTest.nulltesttype && is(node.NullTest.arg, "ColumnRef")) this.add(node.NullTest.arg, { where: { nulltest: node.NullTest.nulltesttype } });
|
|
765
|
+
}
|
|
766
|
+
if (is(node, "RangeVar") && node.RangeVar.relname) {
|
|
767
|
+
const columnReference = {
|
|
768
|
+
text: node.RangeVar.relname,
|
|
769
|
+
start: node.RangeVar.location,
|
|
770
|
+
quoted: false
|
|
771
|
+
};
|
|
772
|
+
if (node.RangeVar.schemaname) columnReference.schema = node.RangeVar.schemaname;
|
|
773
|
+
this.tableMappings.set(node.RangeVar.relname, columnReference);
|
|
774
|
+
if (node.RangeVar.alias?.aliasname) {
|
|
775
|
+
const aliasName = node.RangeVar.alias.aliasname;
|
|
776
|
+
const existingMapping = this.tableMappings.get(aliasName);
|
|
777
|
+
const part = {
|
|
778
|
+
text: node.RangeVar.relname,
|
|
779
|
+
start: node.RangeVar.location,
|
|
780
|
+
quoted: true,
|
|
781
|
+
alias: aliasName
|
|
782
|
+
};
|
|
783
|
+
if (node.RangeVar.schemaname) part.schema = node.RangeVar.schemaname;
|
|
784
|
+
if (existingMapping) {
|
|
785
|
+
if (!(node.RangeVar.relname?.startsWith("pg_") ?? false)) console.warn(`Ignoring alias ${aliasName} as it shadows an existing mapping for ${existingMapping.text}. We currently do not support alias shadowing.`);
|
|
786
|
+
this.shadowedAliases.push(part);
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
this.tableMappings.set(aliasName, part);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
if (is(node, "SortBy")) {
|
|
793
|
+
if (node.SortBy.node && is(node.SortBy.node, "ColumnRef")) this.add(node.SortBy.node, { sort: {
|
|
794
|
+
dir: node.SortBy.sortby_dir ?? "SORTBY_DEFAULT",
|
|
795
|
+
nulls: node.SortBy.sortby_nulls ?? "SORTBY_NULLS_DEFAULT"
|
|
796
|
+
} });
|
|
797
|
+
}
|
|
798
|
+
if (is(node, "JoinExpr") && node.JoinExpr.quals) {
|
|
799
|
+
if (is(node.JoinExpr.quals, "A_Expr")) {
|
|
800
|
+
if (node.JoinExpr.quals.A_Expr.lexpr && is(node.JoinExpr.quals.A_Expr.lexpr, "ColumnRef")) this.add(node.JoinExpr.quals.A_Expr.lexpr);
|
|
801
|
+
if (node.JoinExpr.quals.A_Expr.rexpr && is(node.JoinExpr.quals.A_Expr.rexpr, "ColumnRef")) this.add(node.JoinExpr.quals.A_Expr.rexpr);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
if (is(node, "A_Expr") && node.A_Expr.kind === "AEXPR_OP") {
|
|
805
|
+
const opName = node.A_Expr.name?.[0] && is(node.A_Expr.name[0], "String") && node.A_Expr.name[0].String.sval;
|
|
806
|
+
if (opName && (opName === "@>" || opName === "?" || opName === "?|" || opName === "?&")) {
|
|
807
|
+
const jsonbOperator = opName;
|
|
808
|
+
if (node.A_Expr.lexpr && is(node.A_Expr.lexpr, "ColumnRef")) this.add(node.A_Expr.lexpr, { jsonbOperator });
|
|
809
|
+
if (node.A_Expr.rexpr && is(node.A_Expr.rexpr, "ColumnRef")) this.add(node.A_Expr.rexpr, { jsonbOperator });
|
|
810
|
+
}
|
|
811
|
+
if (opName && (opName === "&&" || opName === "-|-")) {
|
|
812
|
+
const gistOperator = opName;
|
|
813
|
+
if (node.A_Expr.lexpr && is(node.A_Expr.lexpr, "ColumnRef")) this.add(node.A_Expr.lexpr, { gistOperator });
|
|
814
|
+
if (node.A_Expr.rexpr && is(node.A_Expr.rexpr, "ColumnRef")) this.add(node.A_Expr.rexpr, { gistOperator });
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
if (is(node, "ColumnRef")) {
|
|
818
|
+
for (let i = 0; i < stack.length; i++) {
|
|
819
|
+
if (stack[i] === "returningList" && stack[i + 1] === "ResTarget" && stack[i + 2] === "val" && stack[i + 3] === "ColumnRef") {
|
|
820
|
+
this.add(node, { ignored: true });
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
if (stack[i + 1] === "targetList" && stack[i + 2] === "ResTarget" && stack[i + 3] === "val" && stack[i + 4] === "ColumnRef") {
|
|
824
|
+
this.add(node, { ignored: true });
|
|
825
|
+
return;
|
|
826
|
+
}
|
|
827
|
+
if (stack[i] === "FuncCall" && stack[i + 1] === "args") {
|
|
828
|
+
this.add(node, { ignored: true });
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
this.add(node);
|
|
833
|
+
}
|
|
834
|
+
});
|
|
835
|
+
return {
|
|
836
|
+
highlights: this.highlights,
|
|
837
|
+
indexRepresentations: this.indexRepresentations,
|
|
838
|
+
indexesToCheck: this.indexesToCheck,
|
|
839
|
+
shadowedAliases: this.shadowedAliases,
|
|
840
|
+
tempTables: this.tempTables,
|
|
841
|
+
tableMappings: this.tableMappings,
|
|
842
|
+
nudges: this.nudges
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
add(node, options) {
|
|
846
|
+
if (!node.ColumnRef.location) {
|
|
847
|
+
console.error(`Node did not have a location. Skipping`, node);
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
if (!node.ColumnRef.fields) {
|
|
851
|
+
console.error(node);
|
|
852
|
+
throw new Error("Column reference must have fields");
|
|
853
|
+
}
|
|
854
|
+
let ignored = options?.ignored ?? false;
|
|
855
|
+
let runningLength = node.ColumnRef.location;
|
|
856
|
+
const parts = node.ColumnRef.fields.map((field, i, length) => {
|
|
857
|
+
if (!is(field, "String") || !field.String.sval) {
|
|
858
|
+
const out = deparseSync(field);
|
|
859
|
+
ignored = true;
|
|
860
|
+
return {
|
|
861
|
+
quoted: out.startsWith("\""),
|
|
862
|
+
text: out,
|
|
863
|
+
start: runningLength
|
|
864
|
+
};
|
|
865
|
+
}
|
|
866
|
+
const start = runningLength;
|
|
867
|
+
const size = field.String.sval?.length ?? 0;
|
|
868
|
+
let quoted = false;
|
|
869
|
+
if (node.ColumnRef.location !== void 0) {
|
|
870
|
+
if (this.query[runningLength] === "\"") quoted = true;
|
|
871
|
+
}
|
|
872
|
+
const isLastIteration = i === length.length - 1;
|
|
873
|
+
runningLength += size + (isLastIteration ? 0 : 1) + (quoted ? 2 : 0);
|
|
874
|
+
return {
|
|
875
|
+
text: field.String.sval,
|
|
876
|
+
start,
|
|
877
|
+
quoted
|
|
878
|
+
};
|
|
879
|
+
});
|
|
880
|
+
const end = runningLength;
|
|
881
|
+
if (this.highlightPositions.has(node.ColumnRef.location)) return;
|
|
882
|
+
this.highlightPositions.add(node.ColumnRef.location);
|
|
883
|
+
const highlighted = `${this.query.slice(node.ColumnRef.location, end)}`;
|
|
884
|
+
const seen = this.seenReferences.get(highlighted);
|
|
885
|
+
if (!ignored) this.seenReferences.set(highlighted, (seen ?? 0) + 1);
|
|
886
|
+
const ref = {
|
|
887
|
+
frequency: seen ?? 1,
|
|
888
|
+
representation: highlighted,
|
|
889
|
+
parts,
|
|
890
|
+
ignored: ignored ?? false,
|
|
891
|
+
position: {
|
|
892
|
+
start: node.ColumnRef.location,
|
|
893
|
+
end
|
|
894
|
+
}
|
|
895
|
+
};
|
|
896
|
+
if (options?.sort) ref.sort = options.sort;
|
|
897
|
+
if (options?.where) ref.where = options.where;
|
|
898
|
+
if (options?.jsonbOperator) ref.jsonbOperator = options.jsonbOperator;
|
|
899
|
+
if (options?.gistOperator) ref.gistOperator = options.gistOperator;
|
|
900
|
+
this.highlights.push(ref);
|
|
901
|
+
}
|
|
902
|
+
/**
|
|
903
|
+
* Descend only into shallow combinators of a node such as
|
|
904
|
+
* - And
|
|
905
|
+
* - Or
|
|
906
|
+
* - Not
|
|
907
|
+
* - ::typecast
|
|
908
|
+
* without deep traversing into subqueries. Useful for checking members
|
|
909
|
+
* of a `WHERE` clause
|
|
910
|
+
*/
|
|
911
|
+
static shallowMatch(expr, kind, callback) {
|
|
912
|
+
if (is(expr, kind)) {
|
|
913
|
+
callback(expr);
|
|
914
|
+
return;
|
|
915
|
+
}
|
|
916
|
+
if (is(expr, "BoolExpr") && expr.BoolExpr.args) {
|
|
917
|
+
for (const arg of expr.BoolExpr.args) Walker.shallowMatch(arg, kind, callback);
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
if (is(expr, "A_Expr")) {
|
|
921
|
+
if (expr.A_Expr.lexpr) Walker.shallowMatch(expr.A_Expr.lexpr, kind, callback);
|
|
922
|
+
if (expr.A_Expr.rexpr) Walker.shallowMatch(expr.A_Expr.rexpr, kind, callback);
|
|
923
|
+
return;
|
|
924
|
+
}
|
|
925
|
+
if (is(expr, "NullTest") && expr.NullTest.arg) {
|
|
926
|
+
Walker.shallowMatch(expr.NullTest.arg, kind, callback);
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
929
|
+
if (is(expr, "BooleanTest") && expr.BooleanTest.arg) {
|
|
930
|
+
Walker.shallowMatch(expr.BooleanTest.arg, kind, callback);
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
if (is(expr, "SubLink") && expr.SubLink.testexpr) {
|
|
934
|
+
Walker.shallowMatch(expr.SubLink.testexpr, kind, callback);
|
|
935
|
+
return;
|
|
936
|
+
}
|
|
937
|
+
if (is(expr, "TypeCast") && expr.TypeCast.arg) {
|
|
938
|
+
Walker.shallowMatch(expr.TypeCast.arg, kind, callback);
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
static traverse(node, callback) {
|
|
943
|
+
Walker.doTraverse(node, [], callback);
|
|
944
|
+
}
|
|
945
|
+
static doTraverse(node, stack, callback) {
|
|
946
|
+
if (isANode(node)) callback(node, [...stack, getNodeKind(node)]);
|
|
947
|
+
if (typeof node !== "object" || node === null) return;
|
|
948
|
+
if (Array.isArray(node)) {
|
|
949
|
+
for (const item of node) if (isANode(item)) Walker.doTraverse(item, stack, callback);
|
|
950
|
+
} else if (isANode(node)) {
|
|
951
|
+
const keys = Object.keys(node);
|
|
952
|
+
Walker.doTraverse(node[keys[0]], [...stack, getNodeKind(node)], callback);
|
|
953
|
+
} else for (const [key, child] of Object.entries(node)) Walker.doTraverse(child, [...stack, key], callback);
|
|
954
|
+
}
|
|
955
|
+
};
|
|
956
|
+
function is(node, kind) {
|
|
957
|
+
return kind in node;
|
|
958
|
+
}
|
|
959
|
+
function getNodeKind(node) {
|
|
960
|
+
return Object.keys(node)[0];
|
|
961
|
+
}
|
|
962
|
+
function isANode(node) {
|
|
963
|
+
if (typeof node !== "object" || node === null) return false;
|
|
964
|
+
const keys = Object.keys(node);
|
|
965
|
+
return keys.length === 1 && /^[A-Z]/.test(keys[0]);
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
//#endregion
|
|
969
|
+
//#region src/sql/analyzer.ts
|
|
970
|
+
const ignoredIdentifier = "__qd_placeholder";
|
|
971
|
+
/**
|
|
972
|
+
* Analyzes a query and returns a list of column references that
|
|
973
|
+
* should be indexed.
|
|
974
|
+
*
|
|
975
|
+
* This should be instantiated once per analyzed query.
|
|
976
|
+
*/
|
|
977
|
+
var Analyzer = class {
|
|
978
|
+
constructor(parser) {
|
|
979
|
+
this.parser = parser;
|
|
980
|
+
}
|
|
981
|
+
async analyze(query, formattedQuery) {
|
|
982
|
+
const ast = await this.parser(query);
|
|
983
|
+
if (!ast.stmts) throw new Error("Query did not have any statements. This should probably never happen?");
|
|
984
|
+
const stmt = ast.stmts[0].stmt;
|
|
985
|
+
if (!stmt) throw new Error("Query did not have any statements. This should probably never happen?");
|
|
986
|
+
const { highlights, indexRepresentations, indexesToCheck, shadowedAliases, tempTables, tableMappings, nudges } = new Walker(query).walk(stmt);
|
|
987
|
+
const sortedHighlights = highlights.sort((a, b) => b.position.end - a.position.end);
|
|
988
|
+
let currQuery = query;
|
|
989
|
+
for (const highlight of sortedHighlights) {
|
|
990
|
+
const parts = this.resolveTableAliases(highlight.parts, tableMappings);
|
|
991
|
+
if (parts.length === 0) {
|
|
992
|
+
console.error(highlight);
|
|
993
|
+
throw new Error("Highlight must have at least one part");
|
|
994
|
+
}
|
|
995
|
+
let color;
|
|
996
|
+
let skip = false;
|
|
997
|
+
if (highlight.ignored) {
|
|
998
|
+
color = (x) => dim(strikethrough(x));
|
|
999
|
+
skip = true;
|
|
1000
|
+
} else if (parts.length === 2 && tempTables.has(parts[0].text) && !tableMappings.has(parts[0].text)) {
|
|
1001
|
+
color = blue;
|
|
1002
|
+
skip = true;
|
|
1003
|
+
} else color = bgMagentaBright;
|
|
1004
|
+
const queryRepr = highlight.representation;
|
|
1005
|
+
const queryBeforeMatch = currQuery.slice(0, highlight.position.start);
|
|
1006
|
+
const queryAfterToken = currQuery.slice(highlight.position.end);
|
|
1007
|
+
currQuery = `${queryBeforeMatch}${color(queryRepr)}${this.colorizeKeywords(queryAfterToken, color)}`;
|
|
1008
|
+
if (indexRepresentations.has(queryRepr)) skip = true;
|
|
1009
|
+
if (!skip) {
|
|
1010
|
+
indexesToCheck.push(highlight);
|
|
1011
|
+
indexRepresentations.add(queryRepr);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
const referencedTables = [];
|
|
1015
|
+
for (const value of tableMappings.values()) if (!value.alias) referencedTables.push({
|
|
1016
|
+
schema: value.schema,
|
|
1017
|
+
table: value.text
|
|
1018
|
+
});
|
|
1019
|
+
const { tags, queryWithoutTags } = this.extractSqlcommenter(query);
|
|
1020
|
+
const formattedQueryWithoutTags = formattedQuery ? this.extractSqlcommenter(formattedQuery).queryWithoutTags : void 0;
|
|
1021
|
+
return {
|
|
1022
|
+
indexesToCheck,
|
|
1023
|
+
ansiHighlightedQuery: currQuery,
|
|
1024
|
+
referencedTables,
|
|
1025
|
+
shadowedAliases,
|
|
1026
|
+
tags,
|
|
1027
|
+
queryWithoutTags,
|
|
1028
|
+
formattedQueryWithoutTags,
|
|
1029
|
+
nudges
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
deriveIndexes(tables, discovered, referencedTables) {
|
|
1033
|
+
/**
|
|
1034
|
+
* There are 3 different kinds of parts a col reference can have
|
|
1035
|
+
* {a} = just a column within context. Find out the table
|
|
1036
|
+
* {a, b} = a column reference with a table reference. There's still ambiguity here
|
|
1037
|
+
* with what the schema could be in case there are 2 tables with the same name in different schemas.
|
|
1038
|
+
* {a, b, c} = a column reference with a table reference and a schema reference.
|
|
1039
|
+
* This is the best case scenario.
|
|
1040
|
+
*/
|
|
1041
|
+
const allIndexes = [];
|
|
1042
|
+
const seenIndexes = /* @__PURE__ */ new Set();
|
|
1043
|
+
function addIndex(index) {
|
|
1044
|
+
const key = `"${index.schema}":"${index.table}":"${index.column}"`;
|
|
1045
|
+
if (seenIndexes.has(key)) return;
|
|
1046
|
+
seenIndexes.add(key);
|
|
1047
|
+
allIndexes.push(index);
|
|
1048
|
+
}
|
|
1049
|
+
const matchingTables = this.filterReferences(referencedTables, tables);
|
|
1050
|
+
for (const colReference of discovered) {
|
|
1051
|
+
const partsCount = colReference.parts.length;
|
|
1052
|
+
const columnOnlyReference = partsCount === 1;
|
|
1053
|
+
const tableReference = partsCount === 2;
|
|
1054
|
+
const fullReference = partsCount === 3;
|
|
1055
|
+
if (columnOnlyReference) {
|
|
1056
|
+
const [column] = colReference.parts;
|
|
1057
|
+
const referencedColumn = this.normalize(column);
|
|
1058
|
+
for (const table of matchingTables) {
|
|
1059
|
+
if (!this.hasColumn(table, referencedColumn)) continue;
|
|
1060
|
+
const index = {
|
|
1061
|
+
schema: table.schemaName,
|
|
1062
|
+
table: table.tableName,
|
|
1063
|
+
column: referencedColumn
|
|
1064
|
+
};
|
|
1065
|
+
if (colReference.sort) index.sort = colReference.sort;
|
|
1066
|
+
if (colReference.where) index.where = colReference.where;
|
|
1067
|
+
if (colReference.jsonbOperator) index.jsonbOperator = colReference.jsonbOperator;
|
|
1068
|
+
if (colReference.gistOperator) index.gistOperator = colReference.gistOperator;
|
|
1069
|
+
addIndex(index);
|
|
1070
|
+
}
|
|
1071
|
+
} else if (tableReference) {
|
|
1072
|
+
const [table, column] = colReference.parts;
|
|
1073
|
+
const referencedTable = this.normalize(table);
|
|
1074
|
+
const referencedColumn = this.normalize(column);
|
|
1075
|
+
for (const matchingTable of matchingTables) {
|
|
1076
|
+
if (!this.hasColumn(matchingTable, referencedColumn)) continue;
|
|
1077
|
+
const index = {
|
|
1078
|
+
schema: matchingTable.schemaName,
|
|
1079
|
+
table: referencedTable,
|
|
1080
|
+
column: referencedColumn
|
|
1081
|
+
};
|
|
1082
|
+
if (colReference.sort) index.sort = colReference.sort;
|
|
1083
|
+
if (colReference.where) index.where = colReference.where;
|
|
1084
|
+
if (colReference.jsonbOperator) index.jsonbOperator = colReference.jsonbOperator;
|
|
1085
|
+
if (colReference.gistOperator) index.gistOperator = colReference.gistOperator;
|
|
1086
|
+
addIndex(index);
|
|
1087
|
+
}
|
|
1088
|
+
} else if (fullReference) {
|
|
1089
|
+
const [schema, table, column] = colReference.parts;
|
|
1090
|
+
const index = {
|
|
1091
|
+
schema: this.normalize(schema),
|
|
1092
|
+
table: this.normalize(table),
|
|
1093
|
+
column: this.normalize(column)
|
|
1094
|
+
};
|
|
1095
|
+
if (colReference.sort) index.sort = colReference.sort;
|
|
1096
|
+
if (colReference.where) index.where = colReference.where;
|
|
1097
|
+
if (colReference.jsonbOperator) index.jsonbOperator = colReference.jsonbOperator;
|
|
1098
|
+
if (colReference.gistOperator) index.gistOperator = colReference.gistOperator;
|
|
1099
|
+
addIndex(index);
|
|
1100
|
+
} else {
|
|
1101
|
+
console.error("Column reference has too many parts. The query is malformed", colReference);
|
|
1102
|
+
continue;
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
return allIndexes;
|
|
1106
|
+
}
|
|
1107
|
+
filterReferences(referencedTables, tables) {
|
|
1108
|
+
const matchingTables = [];
|
|
1109
|
+
for (const referencedTable of referencedTables) {
|
|
1110
|
+
const refs = tables.filter(({ tableName, schemaName }) => {
|
|
1111
|
+
let schemaMatches = true;
|
|
1112
|
+
if (referencedTable.schema) schemaMatches = schemaName === referencedTable.schema;
|
|
1113
|
+
return schemaMatches && tableName === referencedTable.table;
|
|
1114
|
+
});
|
|
1115
|
+
matchingTables.push(...refs);
|
|
1116
|
+
}
|
|
1117
|
+
return matchingTables;
|
|
1118
|
+
}
|
|
1119
|
+
hasColumn(table, columnName) {
|
|
1120
|
+
return table.columns?.some((column) => column.columnName === columnName) ?? false;
|
|
1121
|
+
}
|
|
1122
|
+
colorizeKeywords(query, color) {
|
|
1123
|
+
return query.replace(/(^\s+)(asc|desc)?(\s+(nulls first|nulls last))?/i, (_, pre, dir, spaceNulls, nulls) => {
|
|
1124
|
+
return `${pre}${dir ? color(dir) : ""}${nulls ? spaceNulls.replace(nulls, color(nulls)) : ""}`;
|
|
1125
|
+
}).replace(/(^\s+)(is (null|not null))/i, (_, pre, nulltest) => {
|
|
1126
|
+
return `${pre}${color(nulltest)}`;
|
|
1127
|
+
});
|
|
1128
|
+
}
|
|
1129
|
+
/**
|
|
1130
|
+
* Resolves aliases such as `a.b` to `x.b` if `a` is a known
|
|
1131
|
+
* alias to a table called x.
|
|
1132
|
+
*
|
|
1133
|
+
* Ignores all other combination of parts such as `a.b.c`
|
|
1134
|
+
*/
|
|
1135
|
+
resolveTableAliases(parts, tableMappings) {
|
|
1136
|
+
if (parts.length !== 2) return parts;
|
|
1137
|
+
const tablePart = parts[0];
|
|
1138
|
+
const mapping = tableMappings.get(tablePart.text);
|
|
1139
|
+
if (mapping) parts[0] = mapping;
|
|
1140
|
+
return parts;
|
|
1141
|
+
}
|
|
1142
|
+
normalize(columnReference) {
|
|
1143
|
+
return columnReference.quoted ? columnReference.text : columnReference.text.toLowerCase();
|
|
1144
|
+
}
|
|
1145
|
+
extractSqlcommenter(query) {
|
|
1146
|
+
const trimmedQuery = query.trimEnd();
|
|
1147
|
+
const startPosition = trimmedQuery.lastIndexOf("/*");
|
|
1148
|
+
const endPosition = trimmedQuery.lastIndexOf("*/");
|
|
1149
|
+
if (startPosition === -1 || endPosition === -1) return {
|
|
1150
|
+
tags: [],
|
|
1151
|
+
queryWithoutTags: trimmedQuery
|
|
1152
|
+
};
|
|
1153
|
+
const queryWithoutTags = trimmedQuery.slice(0, startPosition);
|
|
1154
|
+
const tagString = trimmedQuery.slice(startPosition + 2, endPosition).trim();
|
|
1155
|
+
if (!tagString || typeof tagString !== "string") return {
|
|
1156
|
+
tags: [],
|
|
1157
|
+
queryWithoutTags
|
|
1158
|
+
};
|
|
1159
|
+
const tags = [];
|
|
1160
|
+
for (const match of tagString.split(",")) {
|
|
1161
|
+
const [key, value] = match.split("=");
|
|
1162
|
+
if (!key || !value) {
|
|
1163
|
+
if (tags.length > 0) console.warn(`Invalid sqlcommenter tag: ${match} in comment: ${tagString}. Ignoring`);
|
|
1164
|
+
continue;
|
|
1165
|
+
}
|
|
1166
|
+
try {
|
|
1167
|
+
let sliceStart = 0;
|
|
1168
|
+
if (value.startsWith("'")) sliceStart = 1;
|
|
1169
|
+
let sliceEnd = value.length;
|
|
1170
|
+
if (value.endsWith("'")) sliceEnd -= 1;
|
|
1171
|
+
const decoded = decodeURIComponent(value.slice(sliceStart, sliceEnd));
|
|
1172
|
+
tags.push({
|
|
1173
|
+
key: key.trim(),
|
|
1174
|
+
value: decoded
|
|
1175
|
+
});
|
|
1176
|
+
} catch (err) {
|
|
1177
|
+
console.error(err);
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
return {
|
|
1181
|
+
tags,
|
|
1182
|
+
queryWithoutTags
|
|
1183
|
+
};
|
|
1184
|
+
}
|
|
1185
|
+
};
|
|
1186
|
+
|
|
1187
|
+
//#endregion
|
|
1188
|
+
//#region src/sql/database.ts
|
|
1189
|
+
const PostgresVersion = z.string().brand("PostgresVersion");
|
|
1190
|
+
/**
|
|
1191
|
+
* Drops a disabled index. Rollsback if it fails for any reason
|
|
1192
|
+
* @returns Did dropping the index succeed?
|
|
1193
|
+
*/
|
|
1194
|
+
async function dropIndex(tx, index) {
|
|
1195
|
+
try {
|
|
1196
|
+
await tx.exec(`
|
|
1197
|
+
savepoint idx_drop;
|
|
1198
|
+
drop index if exists ${index} cascade;
|
|
1199
|
+
`);
|
|
1200
|
+
return true;
|
|
1201
|
+
} catch {
|
|
1202
|
+
await tx.exec(`rollback to idx_drop`);
|
|
1203
|
+
return false;
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
//#endregion
|
|
1208
|
+
//#region src/sql/indexes.ts
|
|
1209
|
+
function isIndexSupported(index) {
|
|
1210
|
+
return index.index_type === "btree" || index.index_type === "gin" || index.index_type === "gist";
|
|
1211
|
+
}
|
|
1212
|
+
/**
|
|
1213
|
+
* Doesn't necessarily decide whether the index can be dropped but can be
|
|
1214
|
+
* used to not even try dropping indexes that _definitely_ cannot be dropped
|
|
1215
|
+
*/
|
|
1216
|
+
function isIndexProbablyDroppable(index) {
|
|
1217
|
+
return !index.is_primary && !index.is_unique;
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
//#endregion
|
|
1221
|
+
//#region src/sql/builder.ts
|
|
1222
|
+
var PostgresQueryBuilder = class PostgresQueryBuilder {
|
|
1223
|
+
constructor(query) {
|
|
1224
|
+
this.query = query;
|
|
1225
|
+
_defineProperty(this, "commands", {});
|
|
1226
|
+
_defineProperty(this, "isIntrospection", false);
|
|
1227
|
+
_defineProperty(this, "explainFlags", []);
|
|
1228
|
+
_defineProperty(this, "_preamble", 0);
|
|
1229
|
+
_defineProperty(this, "parameters", {});
|
|
1230
|
+
_defineProperty(this, "limitSubstitution", void 0);
|
|
1231
|
+
}
|
|
1232
|
+
get preamble() {
|
|
1233
|
+
return this._preamble;
|
|
1234
|
+
}
|
|
1235
|
+
static createIndex(definition, name) {
|
|
1236
|
+
if (name) return new PostgresQueryBuilder(`create index "${name}" on ${definition};`);
|
|
1237
|
+
return new PostgresQueryBuilder(`create index on ${definition};`);
|
|
1238
|
+
}
|
|
1239
|
+
enable(command, value = true) {
|
|
1240
|
+
const commandString = `enable_${command}`;
|
|
1241
|
+
if (value) this.commands[commandString] = "on";
|
|
1242
|
+
else this.commands[commandString] = "off";
|
|
1243
|
+
return this;
|
|
1244
|
+
}
|
|
1245
|
+
withQuery(query) {
|
|
1246
|
+
this.query = query;
|
|
1247
|
+
return this;
|
|
1248
|
+
}
|
|
1249
|
+
introspect() {
|
|
1250
|
+
this.isIntrospection = true;
|
|
1251
|
+
return this;
|
|
1252
|
+
}
|
|
1253
|
+
explain(flags) {
|
|
1254
|
+
this.explainFlags = flags;
|
|
1255
|
+
return this;
|
|
1256
|
+
}
|
|
1257
|
+
parameterize(parameters) {
|
|
1258
|
+
Object.assign(this.parameters, parameters);
|
|
1259
|
+
return this;
|
|
1260
|
+
}
|
|
1261
|
+
replaceLimit(limit) {
|
|
1262
|
+
this.limitSubstitution = limit;
|
|
1263
|
+
return this;
|
|
1264
|
+
}
|
|
1265
|
+
build() {
|
|
1266
|
+
let commands = this.generateSetCommands();
|
|
1267
|
+
commands += this.generateExplain().query;
|
|
1268
|
+
if (this.isIntrospection) commands += " -- @qd_introspection";
|
|
1269
|
+
return commands;
|
|
1270
|
+
}
|
|
1271
|
+
/** Return the "set a=b" parts of the command in the query separate from the explain select ... part */
|
|
1272
|
+
buildParts() {
|
|
1273
|
+
const commands = this.generateSetCommands();
|
|
1274
|
+
const explain = this.generateExplain();
|
|
1275
|
+
this._preamble = explain.preamble;
|
|
1276
|
+
if (this.isIntrospection) explain.query += " -- @qd_introspection";
|
|
1277
|
+
return {
|
|
1278
|
+
commands,
|
|
1279
|
+
query: explain.query
|
|
1280
|
+
};
|
|
1281
|
+
}
|
|
1282
|
+
generateSetCommands() {
|
|
1283
|
+
let commands = "";
|
|
1284
|
+
for (const key in this.commands) {
|
|
1285
|
+
const value = this.commands[key];
|
|
1286
|
+
commands += `set local ${key}=${value};\n`;
|
|
1287
|
+
}
|
|
1288
|
+
return commands;
|
|
1289
|
+
}
|
|
1290
|
+
generateExplain() {
|
|
1291
|
+
let finalQuery = "";
|
|
1292
|
+
if (this.explainFlags.length > 0) finalQuery += `explain (${this.explainFlags.join(", ")}) `;
|
|
1293
|
+
const query = this.substituteQuery();
|
|
1294
|
+
const semicolon = query.endsWith(";") ? "" : ";";
|
|
1295
|
+
const preamble = finalQuery.length;
|
|
1296
|
+
finalQuery += `${query}${semicolon}`;
|
|
1297
|
+
return {
|
|
1298
|
+
query: finalQuery,
|
|
1299
|
+
preamble
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
substituteQuery() {
|
|
1303
|
+
let query = this.query;
|
|
1304
|
+
if (this.limitSubstitution !== void 0) query = query.replace(/limit\s+\$\d+/g, `limit ${this.limitSubstitution}`);
|
|
1305
|
+
for (const [key, value] of Object.entries(this.parameters)) query = query.replaceAll(`\\$${key}`, value.toString());
|
|
1306
|
+
return query;
|
|
1307
|
+
}
|
|
1308
|
+
};
|
|
1309
|
+
|
|
1310
|
+
//#endregion
|
|
1311
|
+
//#region src/sql/pg-identifier.ts
|
|
1312
|
+
/**
|
|
1313
|
+
* Represents an identifier in postgres that is subject
|
|
1314
|
+
* to quoting rules. The {@link toString} rule behaves
|
|
1315
|
+
* exactly like calling `select quote_ident($1)` in postgres
|
|
1316
|
+
*/
|
|
1317
|
+
var PgIdentifier = class PgIdentifier {
|
|
1318
|
+
constructor(value, quoted) {
|
|
1319
|
+
this.value = value;
|
|
1320
|
+
this.quoted = quoted;
|
|
1321
|
+
}
|
|
1322
|
+
/**
|
|
1323
|
+
* Constructs an identifier from a single part (column or table name).
|
|
1324
|
+
* When quoting identifiers like `select table.col` use {@link fromParts} instead
|
|
1325
|
+
*/
|
|
1326
|
+
static fromString(identifier) {
|
|
1327
|
+
const identifierRegex = /^[a-z_][a-z0-9_]*$/;
|
|
1328
|
+
const match = identifier.match(/^"(.+)"$/);
|
|
1329
|
+
if (match) {
|
|
1330
|
+
const value = match[1];
|
|
1331
|
+
return new PgIdentifier(value, !identifierRegex.test(value) || this.reservedKeywords.has(value.toLowerCase()));
|
|
1332
|
+
}
|
|
1333
|
+
return new PgIdentifier(identifier, !identifierRegex.test(identifier) || this.reservedKeywords.has(identifier.toLowerCase()));
|
|
1334
|
+
}
|
|
1335
|
+
/**
|
|
1336
|
+
* Quotes parts of an identifier like `select schema.table.col`.
|
|
1337
|
+
* A separate function is necessary because postgres will treat
|
|
1338
|
+
* `select "HELLO.WORLD"` as a column name. It has to be like
|
|
1339
|
+
* `select "HELLO"."WORLD"` instead.
|
|
1340
|
+
*/
|
|
1341
|
+
static fromParts(...identifiers) {
|
|
1342
|
+
return new PgIdentifier(identifiers.map((identifier) => {
|
|
1343
|
+
if (typeof identifier === "string") return PgIdentifier.fromString(identifier);
|
|
1344
|
+
else return identifier;
|
|
1345
|
+
}).join("."), false);
|
|
1346
|
+
}
|
|
1347
|
+
toString() {
|
|
1348
|
+
if (this.quoted) return `"${this.value.replace(/"/g, "\"\"")}"`;
|
|
1349
|
+
return this.value;
|
|
1350
|
+
}
|
|
1351
|
+
toJSON() {
|
|
1352
|
+
return this.toString();
|
|
1353
|
+
}
|
|
1354
|
+
};
|
|
1355
|
+
_defineProperty(PgIdentifier, "reservedKeywords", new Set([
|
|
1356
|
+
"all",
|
|
1357
|
+
"analyse",
|
|
1358
|
+
"analyze",
|
|
1359
|
+
"and",
|
|
1360
|
+
"any",
|
|
1361
|
+
"array",
|
|
1362
|
+
"as",
|
|
1363
|
+
"asc",
|
|
1364
|
+
"asymmetric",
|
|
1365
|
+
"authorization",
|
|
1366
|
+
"between",
|
|
1367
|
+
"bigint",
|
|
1368
|
+
"binary",
|
|
1369
|
+
"bit",
|
|
1370
|
+
"boolean",
|
|
1371
|
+
"both",
|
|
1372
|
+
"case",
|
|
1373
|
+
"cast",
|
|
1374
|
+
"char",
|
|
1375
|
+
"character",
|
|
1376
|
+
"check",
|
|
1377
|
+
"coalesce",
|
|
1378
|
+
"collate",
|
|
1379
|
+
"collation",
|
|
1380
|
+
"column",
|
|
1381
|
+
"concurrently",
|
|
1382
|
+
"constraint",
|
|
1383
|
+
"create",
|
|
1384
|
+
"cross",
|
|
1385
|
+
"current_catalog",
|
|
1386
|
+
"current_date",
|
|
1387
|
+
"current_role",
|
|
1388
|
+
"current_schema",
|
|
1389
|
+
"current_time",
|
|
1390
|
+
"current_timestamp",
|
|
1391
|
+
"current_user",
|
|
1392
|
+
"dec",
|
|
1393
|
+
"decimal",
|
|
1394
|
+
"default",
|
|
1395
|
+
"deferrable",
|
|
1396
|
+
"desc",
|
|
1397
|
+
"distinct",
|
|
1398
|
+
"do",
|
|
1399
|
+
"else",
|
|
1400
|
+
"end",
|
|
1401
|
+
"except",
|
|
1402
|
+
"exists",
|
|
1403
|
+
"extract",
|
|
1404
|
+
"false",
|
|
1405
|
+
"fetch",
|
|
1406
|
+
"float",
|
|
1407
|
+
"for",
|
|
1408
|
+
"foreign",
|
|
1409
|
+
"freeze",
|
|
1410
|
+
"from",
|
|
1411
|
+
"full",
|
|
1412
|
+
"grant",
|
|
1413
|
+
"greatest",
|
|
1414
|
+
"group",
|
|
1415
|
+
"grouping",
|
|
1416
|
+
"having",
|
|
1417
|
+
"ilike",
|
|
1418
|
+
"in",
|
|
1419
|
+
"initially",
|
|
1420
|
+
"inner",
|
|
1421
|
+
"inout",
|
|
1422
|
+
"int",
|
|
1423
|
+
"integer",
|
|
1424
|
+
"intersect",
|
|
1425
|
+
"interval",
|
|
1426
|
+
"into",
|
|
1427
|
+
"is",
|
|
1428
|
+
"isnull",
|
|
1429
|
+
"join",
|
|
1430
|
+
"json",
|
|
1431
|
+
"json_array",
|
|
1432
|
+
"json_arrayagg",
|
|
1433
|
+
"json_exists",
|
|
1434
|
+
"json_object",
|
|
1435
|
+
"json_objectagg",
|
|
1436
|
+
"json_query",
|
|
1437
|
+
"json_scalar",
|
|
1438
|
+
"json_serialize",
|
|
1439
|
+
"json_table",
|
|
1440
|
+
"json_value",
|
|
1441
|
+
"lateral",
|
|
1442
|
+
"leading",
|
|
1443
|
+
"least",
|
|
1444
|
+
"left",
|
|
1445
|
+
"like",
|
|
1446
|
+
"limit",
|
|
1447
|
+
"localtime",
|
|
1448
|
+
"localtimestamp",
|
|
1449
|
+
"merge_action",
|
|
1450
|
+
"national",
|
|
1451
|
+
"natural",
|
|
1452
|
+
"nchar",
|
|
1453
|
+
"none",
|
|
1454
|
+
"normalize",
|
|
1455
|
+
"not",
|
|
1456
|
+
"notnull",
|
|
1457
|
+
"null",
|
|
1458
|
+
"nullif",
|
|
1459
|
+
"numeric",
|
|
1460
|
+
"offset",
|
|
1461
|
+
"on",
|
|
1462
|
+
"only",
|
|
1463
|
+
"or",
|
|
1464
|
+
"order",
|
|
1465
|
+
"out",
|
|
1466
|
+
"outer",
|
|
1467
|
+
"overlaps",
|
|
1468
|
+
"overlay",
|
|
1469
|
+
"placing",
|
|
1470
|
+
"position",
|
|
1471
|
+
"precision",
|
|
1472
|
+
"primary",
|
|
1473
|
+
"real",
|
|
1474
|
+
"references",
|
|
1475
|
+
"returning",
|
|
1476
|
+
"right",
|
|
1477
|
+
"row",
|
|
1478
|
+
"select",
|
|
1479
|
+
"session_user",
|
|
1480
|
+
"setof",
|
|
1481
|
+
"similar",
|
|
1482
|
+
"smallint",
|
|
1483
|
+
"some",
|
|
1484
|
+
"substring",
|
|
1485
|
+
"symmetric",
|
|
1486
|
+
"system_user",
|
|
1487
|
+
"table",
|
|
1488
|
+
"tablesample",
|
|
1489
|
+
"then",
|
|
1490
|
+
"time",
|
|
1491
|
+
"timestamp",
|
|
1492
|
+
"to",
|
|
1493
|
+
"trailing",
|
|
1494
|
+
"treat",
|
|
1495
|
+
"trim",
|
|
1496
|
+
"true",
|
|
1497
|
+
"union",
|
|
1498
|
+
"unique",
|
|
1499
|
+
"user",
|
|
1500
|
+
"using",
|
|
1501
|
+
"values",
|
|
1502
|
+
"varchar",
|
|
1503
|
+
"variadic",
|
|
1504
|
+
"verbose",
|
|
1505
|
+
"when",
|
|
1506
|
+
"where",
|
|
1507
|
+
"window",
|
|
1508
|
+
"with",
|
|
1509
|
+
"xmlattributes",
|
|
1510
|
+
"xmlconcat",
|
|
1511
|
+
"xmlelement",
|
|
1512
|
+
"xmlexists",
|
|
1513
|
+
"xmlforest",
|
|
1514
|
+
"xmlnamespaces",
|
|
1515
|
+
"xmlparse",
|
|
1516
|
+
"xmlpi",
|
|
1517
|
+
"xmlroot",
|
|
1518
|
+
"xmlserialize",
|
|
1519
|
+
"xmltable"
|
|
1520
|
+
]));
|
|
1521
|
+
|
|
1522
|
+
//#endregion
|
|
1523
|
+
//#region src/sql/permutations.ts
|
|
1524
|
+
/**
|
|
1525
|
+
* Create permutations of the array while sorting it from
|
|
1526
|
+
* largest permutation to smallest.
|
|
1527
|
+
*
|
|
1528
|
+
* This is important when generating index permutations as
|
|
1529
|
+
* postgres happens to prefer indexes with the latest
|
|
1530
|
+
* creation date when the cost of using 2 are the same
|
|
1531
|
+
**/
|
|
1532
|
+
function permutationsWithDescendingLength(arr) {
|
|
1533
|
+
const collected = [];
|
|
1534
|
+
function collect(path, rest) {
|
|
1535
|
+
for (let i = 0; i < rest.length; i++) {
|
|
1536
|
+
const nextRest = [...rest.slice(0, i), ...rest.slice(i + 1)];
|
|
1537
|
+
const nextPath = [...path, rest[i]];
|
|
1538
|
+
collected.push(nextPath);
|
|
1539
|
+
collect(nextPath, nextRest);
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
collect([], arr);
|
|
1543
|
+
collected.sort((a, b) => b.length - a.length);
|
|
1544
|
+
return collected;
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
//#endregion
|
|
1548
|
+
//#region src/optimizer/genalgo.ts
|
|
1549
|
+
var IndexOptimizer = class IndexOptimizer {
|
|
1550
|
+
constructor(db, statistics, existingIndexes, config = {}) {
|
|
1551
|
+
this.db = db;
|
|
1552
|
+
this.statistics = statistics;
|
|
1553
|
+
this.existingIndexes = existingIndexes;
|
|
1554
|
+
this.config = config;
|
|
1555
|
+
}
|
|
1556
|
+
async run(builder, indexes, beforeQuery) {
|
|
1557
|
+
const baseExplain = await this.testQueryWithStats(builder, async (tx) => {
|
|
1558
|
+
if (beforeQuery) await beforeQuery(tx);
|
|
1559
|
+
});
|
|
1560
|
+
const baseCost = Number(baseExplain.Plan["Total Cost"]);
|
|
1561
|
+
if (baseCost === 0) return {
|
|
1562
|
+
kind: "zero_cost_plan",
|
|
1563
|
+
explainPlan: baseExplain.Plan
|
|
1564
|
+
};
|
|
1565
|
+
const toCreate = this.indexesToCreate(indexes);
|
|
1566
|
+
const finalExplain = await this.testQueryWithStats(builder, async (tx) => {
|
|
1567
|
+
if (beforeQuery) await beforeQuery(tx);
|
|
1568
|
+
for (const permutation of toCreate) {
|
|
1569
|
+
const createIndex = PostgresQueryBuilder.createIndex(permutation.definition, permutation.name).introspect().build();
|
|
1570
|
+
await tx.exec(createIndex);
|
|
1571
|
+
}
|
|
1572
|
+
});
|
|
1573
|
+
const finalCost = Number(finalExplain.Plan["Total Cost"]);
|
|
1574
|
+
if (this.config.debug) console.dir(finalExplain, { depth: null });
|
|
1575
|
+
const deltaPercentage = (baseCost - finalCost) / baseCost * 100;
|
|
1576
|
+
if (finalCost < baseCost) console.log(` 🎉🎉🎉 ${green(`+${deltaPercentage.toFixed(2).padStart(5, "0")}%`)}`);
|
|
1577
|
+
else if (finalCost > baseCost) console.log(`${red(`-${Math.abs(deltaPercentage).toFixed(2).padStart(5, "0")}%`)} ${gray("If there's a better index, we haven't tried it")}`);
|
|
1578
|
+
const baseIndexes = this.findUsedIndexes(baseExplain.Plan);
|
|
1579
|
+
const finalIndexes = this.findUsedIndexes(finalExplain.Plan);
|
|
1580
|
+
const triedIndexes = new Map(toCreate.map((index) => [index.name.toString(), index]));
|
|
1581
|
+
this.replaceUsedIndexesWithDefinition(finalExplain.Plan, triedIndexes);
|
|
1582
|
+
return {
|
|
1583
|
+
kind: "ok",
|
|
1584
|
+
baseCost,
|
|
1585
|
+
finalCost,
|
|
1586
|
+
newIndexes: finalIndexes.newIndexes,
|
|
1587
|
+
existingIndexes: baseIndexes.existingIndexes,
|
|
1588
|
+
triedIndexes,
|
|
1589
|
+
baseExplainPlan: baseExplain.Plan,
|
|
1590
|
+
explainPlan: finalExplain.Plan
|
|
1591
|
+
};
|
|
1592
|
+
}
|
|
1593
|
+
async runWithoutIndexes(builder) {
|
|
1594
|
+
return await this.testQueryWithStats(builder, async (tx) => {
|
|
1595
|
+
await this.dropExistingIndexes(tx);
|
|
1596
|
+
});
|
|
1597
|
+
}
|
|
1598
|
+
/**
|
|
1599
|
+
* Given the current indexes in the optimizer, transform them in some
|
|
1600
|
+
* way to change which indexes will be assumed to exist when optimizing
|
|
1601
|
+
*
|
|
1602
|
+
* @example
|
|
1603
|
+
* ```
|
|
1604
|
+
* // resets indexes
|
|
1605
|
+
* optimizer.transformIndexes(() => [])
|
|
1606
|
+
*
|
|
1607
|
+
* // adds new index
|
|
1608
|
+
* optimizer.transformIndexes(indexes => [...indexes, newIndex])
|
|
1609
|
+
* ```
|
|
1610
|
+
*/
|
|
1611
|
+
transformIndexes(f) {
|
|
1612
|
+
this.existingIndexes = f(this.existingIndexes);
|
|
1613
|
+
return this;
|
|
1614
|
+
}
|
|
1615
|
+
/**
|
|
1616
|
+
* Postgres has a limit of 63 characters for index names.
|
|
1617
|
+
* So we use this to make sure we don't derive it from a list of columns that can
|
|
1618
|
+
* overflow that limit.
|
|
1619
|
+
*/
|
|
1620
|
+
indexName() {
|
|
1621
|
+
const indexName = IndexOptimizer.prefix + Math.random().toString(36).substring(2, 16);
|
|
1622
|
+
return PgIdentifier.fromString(indexName);
|
|
1623
|
+
}
|
|
1624
|
+
indexAlreadyExists(table, columns) {
|
|
1625
|
+
return this.existingIndexes.find((index) => index.index_type === "btree" && index.table_name === table && index.index_columns.length === columns.length && index.index_columns.every((c, i) => {
|
|
1626
|
+
if (columns[i].column !== c.name) return false;
|
|
1627
|
+
if (columns[i].where) return false;
|
|
1628
|
+
if (columns[i].sort) switch (columns[i].sort.dir) {
|
|
1629
|
+
case "SORTBY_DEFAULT":
|
|
1630
|
+
case "SORTBY_ASC":
|
|
1631
|
+
if (c.order !== "ASC") return false;
|
|
1632
|
+
break;
|
|
1633
|
+
case "SORTBY_DESC":
|
|
1634
|
+
if (c.order !== "DESC") return false;
|
|
1635
|
+
break;
|
|
1636
|
+
}
|
|
1637
|
+
return true;
|
|
1638
|
+
}));
|
|
1639
|
+
}
|
|
1640
|
+
/**
|
|
1641
|
+
* Derive the list of indexes [tableA(X, Y, Z), tableB(H, I, J)]
|
|
1642
|
+
**/
|
|
1643
|
+
indexesToCreate(rootCandidates) {
|
|
1644
|
+
const btreeCandidates = rootCandidates.filter((c) => !c.jsonbOperator && !c.gistOperator);
|
|
1645
|
+
const ginCandidates = rootCandidates.filter((c) => c.jsonbOperator);
|
|
1646
|
+
const gistCandidates = rootCandidates.filter((c) => c.gistOperator);
|
|
1647
|
+
const nextStage = [];
|
|
1648
|
+
const permutedIndexes = this.groupPotentialIndexColumnsByTable(btreeCandidates);
|
|
1649
|
+
for (const permutation of permutedIndexes.values()) {
|
|
1650
|
+
const { table: rawTable, schema: rawSchema, columns } = permutation;
|
|
1651
|
+
const permutations = permutationsWithDescendingLength(columns);
|
|
1652
|
+
for (const columns of permutations) {
|
|
1653
|
+
const schema = PgIdentifier.fromString(rawSchema);
|
|
1654
|
+
const table = PgIdentifier.fromString(rawTable);
|
|
1655
|
+
if (this.indexAlreadyExists(table.toString(), columns)) continue;
|
|
1656
|
+
const indexName = this.indexName();
|
|
1657
|
+
const definition = this.toDefinition({
|
|
1658
|
+
table,
|
|
1659
|
+
schema,
|
|
1660
|
+
columns
|
|
1661
|
+
}).raw;
|
|
1662
|
+
nextStage.push({
|
|
1663
|
+
name: indexName,
|
|
1664
|
+
schema: schema.toString(),
|
|
1665
|
+
table: table.toString(),
|
|
1666
|
+
columns,
|
|
1667
|
+
definition
|
|
1668
|
+
});
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
const ginGroups = this.groupGinCandidatesByColumn(ginCandidates);
|
|
1672
|
+
for (const group of ginGroups.values()) {
|
|
1673
|
+
const { schema: rawSchema, table: rawTable, column, operators } = group;
|
|
1674
|
+
const schema = PgIdentifier.fromString(rawSchema);
|
|
1675
|
+
const table = PgIdentifier.fromString(rawTable);
|
|
1676
|
+
const opclass = operators.some((op) => op === "?" || op === "?|" || op === "?&") ? void 0 : "jsonb_path_ops";
|
|
1677
|
+
if (this.ginIndexAlreadyExists(table.toString(), column)) continue;
|
|
1678
|
+
const indexName = this.indexName();
|
|
1679
|
+
const candidate = {
|
|
1680
|
+
schema: rawSchema,
|
|
1681
|
+
table: rawTable,
|
|
1682
|
+
column
|
|
1683
|
+
};
|
|
1684
|
+
const definition = this.toGinDefinition({
|
|
1685
|
+
table,
|
|
1686
|
+
schema,
|
|
1687
|
+
column: PgIdentifier.fromString(column),
|
|
1688
|
+
opclass
|
|
1689
|
+
});
|
|
1690
|
+
nextStage.push({
|
|
1691
|
+
name: indexName,
|
|
1692
|
+
schema: schema.toString(),
|
|
1693
|
+
table: table.toString(),
|
|
1694
|
+
columns: [candidate],
|
|
1695
|
+
definition,
|
|
1696
|
+
indexMethod: "gin",
|
|
1697
|
+
opclass
|
|
1698
|
+
});
|
|
1699
|
+
}
|
|
1700
|
+
const gistGroups = this.groupGistCandidatesByColumn(gistCandidates);
|
|
1701
|
+
for (const group of gistGroups.values()) {
|
|
1702
|
+
const { schema: rawSchema, table: rawTable, column } = group;
|
|
1703
|
+
const schema = PgIdentifier.fromString(rawSchema);
|
|
1704
|
+
const table = PgIdentifier.fromString(rawTable);
|
|
1705
|
+
if (this.gistIndexAlreadyExists(table.toString(), column)) continue;
|
|
1706
|
+
const indexName = this.indexName();
|
|
1707
|
+
const candidate = {
|
|
1708
|
+
schema: rawSchema,
|
|
1709
|
+
table: rawTable,
|
|
1710
|
+
column
|
|
1711
|
+
};
|
|
1712
|
+
const definition = this.toGistDefinition({
|
|
1713
|
+
table,
|
|
1714
|
+
schema,
|
|
1715
|
+
column: PgIdentifier.fromString(column)
|
|
1716
|
+
});
|
|
1717
|
+
nextStage.push({
|
|
1718
|
+
name: indexName,
|
|
1719
|
+
schema: schema.toString(),
|
|
1720
|
+
table: table.toString(),
|
|
1721
|
+
columns: [candidate],
|
|
1722
|
+
definition,
|
|
1723
|
+
indexMethod: "gist"
|
|
1724
|
+
});
|
|
1725
|
+
}
|
|
1726
|
+
return nextStage;
|
|
1727
|
+
}
|
|
1728
|
+
toDefinition({ schema, table, columns }) {
|
|
1729
|
+
const make = (col, order, _where, _keyword) => {
|
|
1730
|
+
let fullyQualifiedTable;
|
|
1731
|
+
if (schema.toString() === "public") fullyQualifiedTable = table;
|
|
1732
|
+
else fullyQualifiedTable = PgIdentifier.fromParts(schema, table);
|
|
1733
|
+
return `${fullyQualifiedTable}(${columns.map((c) => {
|
|
1734
|
+
const column = PgIdentifier.fromString(c.column);
|
|
1735
|
+
const direction = c.sort && this.sortDirection(c.sort);
|
|
1736
|
+
const nulls = c.sort && this.nullsOrder(c.sort);
|
|
1737
|
+
let sort = col(column.toString());
|
|
1738
|
+
if (direction) sort += ` ${order(direction)}`;
|
|
1739
|
+
if (nulls) sort += ` ${order(nulls)}`;
|
|
1740
|
+
return sort;
|
|
1741
|
+
}).join(", ")})`;
|
|
1742
|
+
};
|
|
1743
|
+
const id = (a) => a;
|
|
1744
|
+
return {
|
|
1745
|
+
raw: make(id, id, id, id),
|
|
1746
|
+
colored: make(green, yellow, magenta, blue)
|
|
1747
|
+
};
|
|
1748
|
+
}
|
|
1749
|
+
toGinDefinition({ schema, table, column, opclass }) {
|
|
1750
|
+
let fullyQualifiedTable;
|
|
1751
|
+
if (schema.toString() === "public") fullyQualifiedTable = table;
|
|
1752
|
+
else fullyQualifiedTable = PgIdentifier.fromParts(schema, table);
|
|
1753
|
+
const opclassSuffix = opclass ? ` ${opclass}` : "";
|
|
1754
|
+
return `${fullyQualifiedTable} using gin (${column}${opclassSuffix})`;
|
|
1755
|
+
}
|
|
1756
|
+
toGistDefinition({ schema, table, column }) {
|
|
1757
|
+
let fullyQualifiedTable;
|
|
1758
|
+
if (schema.toString() === "public") fullyQualifiedTable = table;
|
|
1759
|
+
else fullyQualifiedTable = PgIdentifier.fromParts(schema, table);
|
|
1760
|
+
return `${fullyQualifiedTable} using gist (${column})`;
|
|
1761
|
+
}
|
|
1762
|
+
groupGinCandidatesByColumn(candidates) {
|
|
1763
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1764
|
+
for (const c of candidates) {
|
|
1765
|
+
if (!c.jsonbOperator) continue;
|
|
1766
|
+
const key = `${c.schema}.${c.table}.${c.column}`;
|
|
1767
|
+
const existing = groups.get(key);
|
|
1768
|
+
if (existing) {
|
|
1769
|
+
if (!existing.operators.includes(c.jsonbOperator)) existing.operators.push(c.jsonbOperator);
|
|
1770
|
+
} else groups.set(key, {
|
|
1771
|
+
schema: c.schema,
|
|
1772
|
+
table: c.table,
|
|
1773
|
+
column: c.column,
|
|
1774
|
+
operators: [c.jsonbOperator]
|
|
1775
|
+
});
|
|
1776
|
+
}
|
|
1777
|
+
return groups;
|
|
1778
|
+
}
|
|
1779
|
+
ginIndexAlreadyExists(table, column) {
|
|
1780
|
+
return this.existingIndexes.find((index) => index.index_type === "gin" && index.table_name === table && index.index_columns.some((c) => c.name === column));
|
|
1781
|
+
}
|
|
1782
|
+
groupGistCandidatesByColumn(candidates) {
|
|
1783
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1784
|
+
for (const c of candidates) {
|
|
1785
|
+
if (!c.gistOperator) continue;
|
|
1786
|
+
const key = `${c.schema}.${c.table}.${c.column}`;
|
|
1787
|
+
if (!groups.has(key)) groups.set(key, {
|
|
1788
|
+
schema: c.schema,
|
|
1789
|
+
table: c.table,
|
|
1790
|
+
column: c.column
|
|
1791
|
+
});
|
|
1792
|
+
}
|
|
1793
|
+
return groups;
|
|
1794
|
+
}
|
|
1795
|
+
gistIndexAlreadyExists(table, column) {
|
|
1796
|
+
return this.existingIndexes.find((index) => index.index_type === "gist" && index.table_name === table && index.index_columns.some((c) => c.name === column));
|
|
1797
|
+
}
|
|
1798
|
+
/**
|
|
1799
|
+
* Drop indexes that can be dropped. Ignore the ones that can't
|
|
1800
|
+
*/
|
|
1801
|
+
async dropExistingIndexes(tx) {
|
|
1802
|
+
for (const index of this.existingIndexes) {
|
|
1803
|
+
if (!isIndexProbablyDroppable(index)) continue;
|
|
1804
|
+
await dropIndex(tx, PgIdentifier.fromParts(index.schema_name, index.index_name));
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
whereClause(c, col, keyword) {
|
|
1808
|
+
if (!c.where) return "";
|
|
1809
|
+
if (c.where.nulltest === "IS_NULL") return `${col(`"${c.column}"`)} is ${keyword("null")}`;
|
|
1810
|
+
if (c.where.nulltest === "IS_NOT_NULL") return `${col(`"${c.column}"`)} is not ${keyword("null")}`;
|
|
1811
|
+
return "";
|
|
1812
|
+
}
|
|
1813
|
+
nullsOrder(s) {
|
|
1814
|
+
if (!s.nulls) return "";
|
|
1815
|
+
switch (s.nulls) {
|
|
1816
|
+
case "SORTBY_NULLS_FIRST": return "nulls first";
|
|
1817
|
+
case "SORTBY_NULLS_LAST": return "nulls last";
|
|
1818
|
+
default: return "";
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
sortDirection(s) {
|
|
1822
|
+
if (!s.dir) return "";
|
|
1823
|
+
switch (s.dir) {
|
|
1824
|
+
case "SORTBY_DESC": return "desc";
|
|
1825
|
+
case "SORTBY_ASC": return "asc";
|
|
1826
|
+
default: return "";
|
|
1827
|
+
}
|
|
1828
|
+
}
|
|
1829
|
+
async testQueryWithStats(builder, f, options) {
|
|
1830
|
+
try {
|
|
1831
|
+
await this.db.transaction(async (tx) => {
|
|
1832
|
+
await f?.(tx);
|
|
1833
|
+
await this.statistics.restoreStats(tx);
|
|
1834
|
+
const flags = ["format json"];
|
|
1835
|
+
if (options && !options.genericPlan) {
|
|
1836
|
+
flags.push("analyze");
|
|
1837
|
+
if (this.config.trace) flags.push("trace");
|
|
1838
|
+
} else flags.push("generic_plan");
|
|
1839
|
+
const { commands, query } = builder.explain(flags).buildParts();
|
|
1840
|
+
await tx.exec(commands);
|
|
1841
|
+
const explain = (await tx.exec(query, options?.params))[0]["QUERY PLAN"][0];
|
|
1842
|
+
throw new RollbackError(explain);
|
|
1843
|
+
});
|
|
1844
|
+
} catch (error) {
|
|
1845
|
+
if (error instanceof RollbackError) return error.value;
|
|
1846
|
+
throw error;
|
|
1847
|
+
}
|
|
1848
|
+
throw new Error("Unreachable");
|
|
1849
|
+
}
|
|
1850
|
+
groupPotentialIndexColumnsByTable(indexes) {
|
|
1851
|
+
const tableColumns = /* @__PURE__ */ new Map();
|
|
1852
|
+
for (const index of indexes) {
|
|
1853
|
+
const existing = tableColumns.get(`${index.schema}.${index.table}`);
|
|
1854
|
+
if (existing) existing.columns.push(index);
|
|
1855
|
+
else tableColumns.set(`${index.schema}.${index.table}`, {
|
|
1856
|
+
table: index.table,
|
|
1857
|
+
schema: index.schema,
|
|
1858
|
+
columns: [index]
|
|
1859
|
+
});
|
|
1860
|
+
}
|
|
1861
|
+
return tableColumns;
|
|
1862
|
+
}
|
|
1863
|
+
findUsedIndexes(explain) {
|
|
1864
|
+
const newIndexes = /* @__PURE__ */ new Set();
|
|
1865
|
+
const existingIndexes = /* @__PURE__ */ new Set();
|
|
1866
|
+
const prefix = IndexOptimizer.prefix;
|
|
1867
|
+
walkExplain(explain, (stage) => {
|
|
1868
|
+
const indexName = stage["Index Name"];
|
|
1869
|
+
if (indexName) if (indexName.startsWith(prefix)) newIndexes.add(indexName);
|
|
1870
|
+
else if (indexName.includes(prefix)) {
|
|
1871
|
+
const actualName = indexName.substring(indexName.indexOf(prefix));
|
|
1872
|
+
newIndexes.add(actualName);
|
|
1873
|
+
} else existingIndexes.add(indexName);
|
|
1874
|
+
});
|
|
1875
|
+
return {
|
|
1876
|
+
newIndexes,
|
|
1877
|
+
existingIndexes
|
|
1878
|
+
};
|
|
1879
|
+
}
|
|
1880
|
+
replaceUsedIndexesWithDefinition(explain, triedIndexes) {
|
|
1881
|
+
walkExplain(explain, (stage) => {
|
|
1882
|
+
const indexName = stage["Index Name"];
|
|
1883
|
+
if (typeof indexName === "string") {
|
|
1884
|
+
const recommendation = triedIndexes.get(indexName);
|
|
1885
|
+
if (recommendation) stage["Index Name"] = recommendation.definition;
|
|
1886
|
+
}
|
|
1887
|
+
});
|
|
1888
|
+
}
|
|
1889
|
+
};
|
|
1890
|
+
_defineProperty(IndexOptimizer, "prefix", "__qd_");
|
|
1891
|
+
function walkExplain(explain, f) {
|
|
1892
|
+
function go(plan) {
|
|
1893
|
+
f(plan);
|
|
1894
|
+
if (plan.Plans) for (const p of plan.Plans) go(p);
|
|
1895
|
+
}
|
|
1896
|
+
go(explain);
|
|
1897
|
+
}
|
|
1898
|
+
var RollbackError = class {
|
|
1899
|
+
constructor(value) {
|
|
1900
|
+
this.value = value;
|
|
1901
|
+
}
|
|
1902
|
+
};
|
|
1903
|
+
const PROCEED = Symbol("PROCEED");
|
|
1904
|
+
const SKIP = Symbol("SKIP");
|
|
1905
|
+
|
|
1906
|
+
//#endregion
|
|
1907
|
+
//#region src/optimizer/statistics.ts
|
|
1908
|
+
const StatisticsSource = z.union([z.object({
|
|
1909
|
+
kind: z.literal("path"),
|
|
1910
|
+
path: z.string().min(1)
|
|
1911
|
+
}), z.object({ kind: z.literal("inline") })]);
|
|
1912
|
+
const ExportedStatsStatistics = z.object({
|
|
1913
|
+
stawidth: z.number(),
|
|
1914
|
+
stainherit: z.boolean().default(false),
|
|
1915
|
+
stadistinct: z.number(),
|
|
1916
|
+
stanullfrac: z.number(),
|
|
1917
|
+
stakind1: z.number().min(0),
|
|
1918
|
+
stakind2: z.number().min(0),
|
|
1919
|
+
stakind3: z.number().min(0),
|
|
1920
|
+
stakind4: z.number().min(0),
|
|
1921
|
+
stakind5: z.number().min(0),
|
|
1922
|
+
staop1: z.string(),
|
|
1923
|
+
staop2: z.string(),
|
|
1924
|
+
staop3: z.string(),
|
|
1925
|
+
staop4: z.string(),
|
|
1926
|
+
staop5: z.string(),
|
|
1927
|
+
stacoll1: z.string(),
|
|
1928
|
+
stacoll2: z.string(),
|
|
1929
|
+
stacoll3: z.string(),
|
|
1930
|
+
stacoll4: z.string(),
|
|
1931
|
+
stacoll5: z.string(),
|
|
1932
|
+
stanumbers1: z.array(z.number()).nullable(),
|
|
1933
|
+
stanumbers2: z.array(z.number()).nullable(),
|
|
1934
|
+
stanumbers3: z.array(z.number()).nullable(),
|
|
1935
|
+
stanumbers4: z.array(z.number()).nullable(),
|
|
1936
|
+
stanumbers5: z.array(z.number()).nullable(),
|
|
1937
|
+
stavalues1: z.array(z.any()).nullable(),
|
|
1938
|
+
stavalues2: z.array(z.any()).nullable(),
|
|
1939
|
+
stavalues3: z.array(z.any()).nullable(),
|
|
1940
|
+
stavalues4: z.array(z.any()).nullable(),
|
|
1941
|
+
stavalues5: z.array(z.any()).nullable()
|
|
1942
|
+
});
|
|
1943
|
+
const ExportedStatsColumns = z.object({
|
|
1944
|
+
columnName: z.string(),
|
|
1945
|
+
stats: ExportedStatsStatistics.nullable()
|
|
1946
|
+
});
|
|
1947
|
+
const ExportedStatsIndex = z.object({
|
|
1948
|
+
indexName: z.string(),
|
|
1949
|
+
relpages: z.number(),
|
|
1950
|
+
reltuples: z.number(),
|
|
1951
|
+
relallvisible: z.number(),
|
|
1952
|
+
relallfrozen: z.number().optional()
|
|
1953
|
+
});
|
|
1954
|
+
const ExportedStatsV1 = z.object({
|
|
1955
|
+
tableName: z.string(),
|
|
1956
|
+
schemaName: z.string(),
|
|
1957
|
+
relpages: z.number(),
|
|
1958
|
+
reltuples: z.number(),
|
|
1959
|
+
relallvisible: z.number(),
|
|
1960
|
+
relallfrozen: z.number().optional(),
|
|
1961
|
+
columns: z.array(ExportedStatsColumns).nullable(),
|
|
1962
|
+
indexes: z.array(ExportedStatsIndex)
|
|
1963
|
+
});
|
|
1964
|
+
const ExportedStats = z.union([ExportedStatsV1]);
|
|
1965
|
+
const StatisticsMode = z.discriminatedUnion("kind", [z.object({
|
|
1966
|
+
kind: z.literal("fromAssumption"),
|
|
1967
|
+
reltuples: z.number().min(0),
|
|
1968
|
+
relpages: z.number().min(0)
|
|
1969
|
+
}), z.object({
|
|
1970
|
+
kind: z.literal("fromStatisticsExport"),
|
|
1971
|
+
stats: z.array(ExportedStats),
|
|
1972
|
+
source: StatisticsSource
|
|
1973
|
+
})]);
|
|
1974
|
+
const DEFAULT_RELTUPLES = 1e4;
|
|
1975
|
+
const DEFAULT_RELPAGES = 1;
|
|
1976
|
+
var Statistics = class Statistics {
|
|
1977
|
+
constructor(db, postgresVersion, ownMetadata, statsMode) {
|
|
1978
|
+
this.db = db;
|
|
1979
|
+
this.postgresVersion = postgresVersion;
|
|
1980
|
+
this.ownMetadata = ownMetadata;
|
|
1981
|
+
_defineProperty(this, "mode", void 0);
|
|
1982
|
+
_defineProperty(this, "exportedMetadata", void 0);
|
|
1983
|
+
if (statsMode) {
|
|
1984
|
+
this.mode = statsMode;
|
|
1985
|
+
if (statsMode.kind === "fromStatisticsExport") this.exportedMetadata = statsMode.stats;
|
|
1986
|
+
} else this.mode = Statistics.defaultStatsMode;
|
|
1987
|
+
}
|
|
1988
|
+
static statsModeFromAssumption({ reltuples, relpages }) {
|
|
1989
|
+
return {
|
|
1990
|
+
kind: "fromAssumption",
|
|
1991
|
+
reltuples,
|
|
1992
|
+
relpages
|
|
1993
|
+
};
|
|
1994
|
+
}
|
|
1995
|
+
/**
|
|
1996
|
+
* Create a statistic mode from stats exported from another database
|
|
1997
|
+
**/
|
|
1998
|
+
static statsModeFromExport(stats) {
|
|
1999
|
+
return {
|
|
2000
|
+
kind: "fromStatisticsExport",
|
|
2001
|
+
source: { kind: "inline" },
|
|
2002
|
+
stats
|
|
2003
|
+
};
|
|
2004
|
+
}
|
|
2005
|
+
static async fromPostgres(db, statsMode) {
|
|
2006
|
+
const version = await db.serverNum();
|
|
2007
|
+
return new Statistics(db, version, await Statistics.dumpStats(db, version, "full"), statsMode);
|
|
2008
|
+
}
|
|
2009
|
+
restoreStats(tx) {
|
|
2010
|
+
return this.restoreStats17(tx);
|
|
2011
|
+
}
|
|
2012
|
+
approximateTotalRows() {
|
|
2013
|
+
if (!this.exportedMetadata) return 0;
|
|
2014
|
+
let totalRows = 0;
|
|
2015
|
+
for (const table of this.exportedMetadata) totalRows += table.reltuples;
|
|
2016
|
+
return totalRows;
|
|
2017
|
+
}
|
|
2018
|
+
/**
|
|
2019
|
+
* We have to cast stavaluesN to the correct type
|
|
2020
|
+
* This derives that type for us so it can be used in `array_in`
|
|
2021
|
+
*/
|
|
2022
|
+
stavalueKind(values) {
|
|
2023
|
+
if (!values || values.length === 0) return null;
|
|
2024
|
+
const [elem] = values;
|
|
2025
|
+
if (typeof elem === "number") return "real";
|
|
2026
|
+
else if (typeof elem === "boolean") return "boolean";
|
|
2027
|
+
return "text";
|
|
2028
|
+
}
|
|
2029
|
+
/**
|
|
2030
|
+
* PostgreSQL's anyarray columns in pg_statistic can hold arrays of arrays
|
|
2031
|
+
* for columns with array types (e.g. text[], int4[]). These create
|
|
2032
|
+
* multidimensional arrays that can be "ragged" (sub-arrays with different
|
|
2033
|
+
* lengths). jsonb_to_recordset can't reconstruct ragged multidimensional
|
|
2034
|
+
* arrays from JSON, so we need to drop these values.
|
|
2035
|
+
*/
|
|
2036
|
+
static safeStavalues(values) {
|
|
2037
|
+
if (!values || values.length === 0) return values;
|
|
2038
|
+
if (values.some((v) => Array.isArray(v))) {
|
|
2039
|
+
console.warn("Discarding ragged multidimensional stavalues array");
|
|
2040
|
+
return null;
|
|
2041
|
+
}
|
|
2042
|
+
return values;
|
|
2043
|
+
}
|
|
2044
|
+
async restoreStats17(tx) {
|
|
2045
|
+
const warnings = {
|
|
2046
|
+
tablesNotInExports: [],
|
|
2047
|
+
tablesNotInTest: [],
|
|
2048
|
+
tableNotAnalyzed: [],
|
|
2049
|
+
statsMissing: []
|
|
2050
|
+
};
|
|
2051
|
+
const processedTables = /* @__PURE__ */ new Set();
|
|
2052
|
+
let columnStatsUpdatePromise;
|
|
2053
|
+
const columnStatsValues = [];
|
|
2054
|
+
if (this.exportedMetadata) {
|
|
2055
|
+
for (const table of this.ownMetadata) {
|
|
2056
|
+
const targetTable = this.exportedMetadata.find((m) => m.tableName === table.tableName && m.schemaName === table.schemaName);
|
|
2057
|
+
if (!targetTable?.columns) continue;
|
|
2058
|
+
for (const column of targetTable.columns) {
|
|
2059
|
+
const { stats } = column;
|
|
2060
|
+
if (!stats) continue;
|
|
2061
|
+
columnStatsValues.push({
|
|
2062
|
+
schema_name: table.schemaName,
|
|
2063
|
+
table_name: table.tableName,
|
|
2064
|
+
column_name: column.columnName,
|
|
2065
|
+
stainherit: stats.stainherit ?? false,
|
|
2066
|
+
stanullfrac: stats.stanullfrac,
|
|
2067
|
+
stawidth: stats.stawidth,
|
|
2068
|
+
stadistinct: stats.stadistinct,
|
|
2069
|
+
stakind1: stats.stakind1,
|
|
2070
|
+
stakind2: stats.stakind2,
|
|
2071
|
+
stakind3: stats.stakind3,
|
|
2072
|
+
stakind4: stats.stakind4,
|
|
2073
|
+
stakind5: stats.stakind5,
|
|
2074
|
+
staop1: stats.staop1,
|
|
2075
|
+
staop2: stats.staop2,
|
|
2076
|
+
staop3: stats.staop3,
|
|
2077
|
+
staop4: stats.staop4,
|
|
2078
|
+
staop5: stats.staop5,
|
|
2079
|
+
stacoll1: stats.stacoll1,
|
|
2080
|
+
stacoll2: stats.stacoll2,
|
|
2081
|
+
stacoll3: stats.stacoll3,
|
|
2082
|
+
stacoll4: stats.stacoll4,
|
|
2083
|
+
stacoll5: stats.stacoll5,
|
|
2084
|
+
stanumbers1: stats.stanumbers1,
|
|
2085
|
+
stanumbers2: stats.stanumbers2,
|
|
2086
|
+
stanumbers3: stats.stanumbers3,
|
|
2087
|
+
stanumbers4: stats.stanumbers4,
|
|
2088
|
+
stanumbers5: stats.stanumbers5,
|
|
2089
|
+
stavalues1: Statistics.safeStavalues(stats.stavalues1),
|
|
2090
|
+
stavalues2: Statistics.safeStavalues(stats.stavalues2),
|
|
2091
|
+
stavalues3: Statistics.safeStavalues(stats.stavalues3),
|
|
2092
|
+
stavalues4: Statistics.safeStavalues(stats.stavalues4),
|
|
2093
|
+
stavalues5: Statistics.safeStavalues(stats.stavalues5),
|
|
2094
|
+
_value_type1: this.stavalueKind(Statistics.safeStavalues(stats.stavalues1)),
|
|
2095
|
+
_value_type2: this.stavalueKind(Statistics.safeStavalues(stats.stavalues2)),
|
|
2096
|
+
_value_type3: this.stavalueKind(Statistics.safeStavalues(stats.stavalues3)),
|
|
2097
|
+
_value_type4: this.stavalueKind(Statistics.safeStavalues(stats.stavalues4)),
|
|
2098
|
+
_value_type5: this.stavalueKind(Statistics.safeStavalues(stats.stavalues5))
|
|
2099
|
+
});
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
/**
|
|
2103
|
+
* Postgres has 5 different slots for storing statistics per column and a potentially unlimited
|
|
2104
|
+
* number of statistic types to choose from. Each code in `stakindN` can mean different things.
|
|
2105
|
+
* Some statistics are just numerical values such as `n_distinct` and `correlation`, meaning
|
|
2106
|
+
* they're only derived from `stanumbersN` and the value of `stanumbersN` is never read.
|
|
2107
|
+
* Others take advantage of the `stavaluesN` columns which use `anyarray` type to store
|
|
2108
|
+
* concrete values internally for things like histogram bounds.
|
|
2109
|
+
* Unfortunately we cannot change anyarrays without a C extension.
|
|
2110
|
+
*
|
|
2111
|
+
* (1) = most common values
|
|
2112
|
+
* (2) = scalar histogram
|
|
2113
|
+
* (3) = correlation <- can change
|
|
2114
|
+
* (4) = most common elements
|
|
2115
|
+
* (5) = distinct elem count histogram <- can change
|
|
2116
|
+
* (6) = length histogram (?) These don't appear in pg_stats
|
|
2117
|
+
* (7) = bounds histogram (?) These don't appear in pg_stats
|
|
2118
|
+
* (N) = potentially many more kinds of statistics. But postgres <=18 only uses these 7.
|
|
2119
|
+
*
|
|
2120
|
+
* What we're doing here is setting ANY statistic we cannot directly control
|
|
2121
|
+
* (anything that relies on stavaluesN) to 0 to make sure the planner isn't influenced by what
|
|
2122
|
+
* what the db collected from the test data.
|
|
2123
|
+
* Because we do our tests with `generic_plan` it seems it's already unlikely that the planner will be
|
|
2124
|
+
* using things like common values or histogram bounds to make the planning decisions we care about.
|
|
2125
|
+
* This is a just in case.
|
|
2126
|
+
*/
|
|
2127
|
+
const sql = dedent`
|
|
2128
|
+
WITH input AS (
|
|
2129
|
+
SELECT
|
|
2130
|
+
c.oid AS starelid,
|
|
2131
|
+
a.attnum AS staattnum,
|
|
2132
|
+
v.stainherit,
|
|
2133
|
+
v.stanullfrac,
|
|
2134
|
+
v.stawidth,
|
|
2135
|
+
v.stadistinct,
|
|
2136
|
+
v.stakind1,
|
|
2137
|
+
v.stakind2,
|
|
2138
|
+
v.stakind3,
|
|
2139
|
+
v.stakind4,
|
|
2140
|
+
v.stakind5,
|
|
2141
|
+
v.staop1,
|
|
2142
|
+
v.staop2,
|
|
2143
|
+
v.staop3,
|
|
2144
|
+
v.staop4,
|
|
2145
|
+
v.staop5,
|
|
2146
|
+
v.stacoll1,
|
|
2147
|
+
v.stacoll2,
|
|
2148
|
+
v.stacoll3,
|
|
2149
|
+
v.stacoll4,
|
|
2150
|
+
v.stacoll5,
|
|
2151
|
+
v.stanumbers1,
|
|
2152
|
+
v.stanumbers2,
|
|
2153
|
+
v.stanumbers3,
|
|
2154
|
+
v.stanumbers4,
|
|
2155
|
+
v.stanumbers5,
|
|
2156
|
+
v.stavalues1,
|
|
2157
|
+
v.stavalues2,
|
|
2158
|
+
v.stavalues3,
|
|
2159
|
+
v.stavalues4,
|
|
2160
|
+
v.stavalues5,
|
|
2161
|
+
_value_type1,
|
|
2162
|
+
_value_type2,
|
|
2163
|
+
_value_type3,
|
|
2164
|
+
_value_type4,
|
|
2165
|
+
_value_type5
|
|
2166
|
+
FROM jsonb_to_recordset($1::jsonb) AS v(
|
|
2167
|
+
schema_name text,
|
|
2168
|
+
table_name text,
|
|
2169
|
+
column_name text,
|
|
2170
|
+
stainherit boolean,
|
|
2171
|
+
stanullfrac real,
|
|
2172
|
+
stawidth integer,
|
|
2173
|
+
stadistinct real,
|
|
2174
|
+
stakind1 real,
|
|
2175
|
+
stakind2 real,
|
|
2176
|
+
stakind3 real,
|
|
2177
|
+
stakind4 real,
|
|
2178
|
+
stakind5 real,
|
|
2179
|
+
staop1 oid,
|
|
2180
|
+
staop2 oid,
|
|
2181
|
+
staop3 oid,
|
|
2182
|
+
staop4 oid,
|
|
2183
|
+
staop5 oid,
|
|
2184
|
+
stacoll1 oid,
|
|
2185
|
+
stacoll2 oid,
|
|
2186
|
+
stacoll3 oid,
|
|
2187
|
+
stacoll4 oid,
|
|
2188
|
+
stacoll5 oid,
|
|
2189
|
+
stanumbers1 real[],
|
|
2190
|
+
stanumbers2 real[],
|
|
2191
|
+
stanumbers3 real[],
|
|
2192
|
+
stanumbers4 real[],
|
|
2193
|
+
stanumbers5 real[],
|
|
2194
|
+
stavalues1 text[],
|
|
2195
|
+
stavalues2 text[],
|
|
2196
|
+
stavalues3 text[],
|
|
2197
|
+
stavalues4 text[],
|
|
2198
|
+
stavalues5 text[],
|
|
2199
|
+
_value_type1 text,
|
|
2200
|
+
_value_type2 text,
|
|
2201
|
+
_value_type3 text,
|
|
2202
|
+
_value_type4 text,
|
|
2203
|
+
_value_type5 text
|
|
2204
|
+
)
|
|
2205
|
+
JOIN pg_class c ON c.relname = v.table_name
|
|
2206
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace AND n.nspname = v.schema_name
|
|
2207
|
+
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attname = v.column_name
|
|
2208
|
+
),
|
|
2209
|
+
updated AS (
|
|
2210
|
+
UPDATE pg_statistic s
|
|
2211
|
+
SET
|
|
2212
|
+
stanullfrac = i.stanullfrac,
|
|
2213
|
+
stawidth = i.stawidth,
|
|
2214
|
+
stadistinct = i.stadistinct,
|
|
2215
|
+
stakind1 = i.stakind1,
|
|
2216
|
+
stakind2 = i.stakind2,
|
|
2217
|
+
stakind3 = i.stakind3,
|
|
2218
|
+
stakind4 = i.stakind4,
|
|
2219
|
+
stakind5 = i.stakind5,
|
|
2220
|
+
staop1 = i.staop1,
|
|
2221
|
+
staop2 = i.staop2,
|
|
2222
|
+
staop3 = i.staop3,
|
|
2223
|
+
staop4 = i.staop4,
|
|
2224
|
+
staop5 = i.staop5,
|
|
2225
|
+
stacoll1 = i.stacoll1,
|
|
2226
|
+
stacoll2 = i.stacoll2,
|
|
2227
|
+
stacoll3 = i.stacoll3,
|
|
2228
|
+
stacoll4 = i.stacoll4,
|
|
2229
|
+
stacoll5 = i.stacoll5,
|
|
2230
|
+
stanumbers1 = i.stanumbers1,
|
|
2231
|
+
stanumbers2 = i.stanumbers2,
|
|
2232
|
+
stanumbers3 = i.stanumbers3,
|
|
2233
|
+
stanumbers4 = i.stanumbers4,
|
|
2234
|
+
stanumbers5 = i.stanumbers5,
|
|
2235
|
+
stavalues1 = case
|
|
2236
|
+
when i.stavalues1 is null then null
|
|
2237
|
+
else array_in(i.stavalues1::text::cstring, i._value_type1::regtype::oid, -1)
|
|
2238
|
+
end,
|
|
2239
|
+
stavalues2 = case
|
|
2240
|
+
when i.stavalues2 is null then null
|
|
2241
|
+
else array_in(i.stavalues2::text::cstring, i._value_type2::regtype::oid, -1)
|
|
2242
|
+
end,
|
|
2243
|
+
stavalues3 = case
|
|
2244
|
+
when i.stavalues3 is null then null
|
|
2245
|
+
else array_in(i.stavalues3::text::cstring, i._value_type3::regtype::oid, -1)
|
|
2246
|
+
end,
|
|
2247
|
+
stavalues4 = case
|
|
2248
|
+
when i.stavalues4 is null then null
|
|
2249
|
+
else array_in(i.stavalues4::text::cstring, i._value_type4::regtype::oid, -1)
|
|
2250
|
+
end,
|
|
2251
|
+
stavalues5 = case
|
|
2252
|
+
when i.stavalues5 is null then null
|
|
2253
|
+
else array_in(i.stavalues5::text::cstring, i._value_type5::regtype::oid, -1)
|
|
2254
|
+
end
|
|
2255
|
+
-- stavalues1 = i.stavalues1,
|
|
2256
|
+
-- stavalues2 = i.stavalues2,
|
|
2257
|
+
-- stavalues3 = i.stavalues3,
|
|
2258
|
+
-- stavalues4 = i.stavalues4,
|
|
2259
|
+
-- stavalues5 = i.stavalues5
|
|
2260
|
+
FROM input i
|
|
2261
|
+
WHERE s.starelid = i.starelid AND s.staattnum = i.staattnum AND s.stainherit = i.stainherit
|
|
2262
|
+
RETURNING s.starelid, s.staattnum, s.stainherit, s.stakind1, s.stakind2, s.stakind3, s.stakind4, s.stakind5
|
|
2263
|
+
),
|
|
2264
|
+
inserted as (
|
|
2265
|
+
INSERT INTO pg_statistic (
|
|
2266
|
+
starelid, staattnum, stainherit,
|
|
2267
|
+
stanullfrac, stawidth, stadistinct,
|
|
2268
|
+
stakind1, stakind2, stakind3, stakind4, stakind5,
|
|
2269
|
+
staop1, staop2, staop3, staop4, staop5,
|
|
2270
|
+
stacoll1, stacoll2, stacoll3, stacoll4, stacoll5,
|
|
2271
|
+
stanumbers1, stanumbers2, stanumbers3, stanumbers4, stanumbers5,
|
|
2272
|
+
stavalues1, stavalues2, stavalues3, stavalues4, stavalues5
|
|
2273
|
+
)
|
|
2274
|
+
SELECT
|
|
2275
|
+
i.starelid, i.staattnum, i.stainherit,
|
|
2276
|
+
i.stanullfrac, i.stawidth, i.stadistinct,
|
|
2277
|
+
i.stakind1, i.stakind2, i.stakind3, i.stakind4, i.stakind5,
|
|
2278
|
+
i.staop1, i.staop2, i.staop3, i.staop4, i.staop5,
|
|
2279
|
+
i.stacoll1, i.stacoll2, i.stacoll3, i.stacoll4, i.stacoll5,
|
|
2280
|
+
i.stanumbers1, i.stanumbers2, i.stanumbers3, i.stanumbers4, i.stanumbers5,
|
|
2281
|
+
-- i.stavalues1, i.stavalues2, i.stavalues3, i.stavalues4, i.stavalues5,
|
|
2282
|
+
case
|
|
2283
|
+
when i.stavalues1 is null then null
|
|
2284
|
+
else array_in(i.stavalues1::text::cstring, i._value_type1::regtype::oid, -1)
|
|
2285
|
+
end,
|
|
2286
|
+
case
|
|
2287
|
+
when i.stavalues2 is null then null
|
|
2288
|
+
else array_in(i.stavalues2::text::cstring, i._value_type2::regtype::oid, -1)
|
|
2289
|
+
end,
|
|
2290
|
+
case
|
|
2291
|
+
when i.stavalues3 is null then null
|
|
2292
|
+
else array_in(i.stavalues3::text::cstring, i._value_type3::regtype::oid, -1)
|
|
2293
|
+
end,
|
|
2294
|
+
case
|
|
2295
|
+
when i.stavalues4 is null then null
|
|
2296
|
+
else array_in(i.stavalues4::text::cstring, i._value_type4::regtype::oid, -1)
|
|
2297
|
+
end,
|
|
2298
|
+
case
|
|
2299
|
+
when i.stavalues5 is null then null
|
|
2300
|
+
else array_in(i.stavalues5::text::cstring, i._value_type5::regtype::oid, -1)
|
|
2301
|
+
end
|
|
2302
|
+
-- i._value_type1, i._value_type2, i._value_type3, i._value_type4, i._value_type5
|
|
2303
|
+
FROM input i
|
|
2304
|
+
LEFT JOIN updated u
|
|
2305
|
+
ON i.starelid = u.starelid AND i.staattnum = u.staattnum AND i.stainherit = u.stainherit
|
|
2306
|
+
WHERE u.starelid IS NULL
|
|
2307
|
+
returning starelid, staattnum, stainherit, stakind1, stakind2, stakind3, stakind4, stakind5
|
|
2308
|
+
)
|
|
2309
|
+
select * from updated union all (select * from inserted); -- @qd_introspection`;
|
|
2310
|
+
columnStatsUpdatePromise = tx.exec(sql, [columnStatsValues]).catch((err) => {
|
|
2311
|
+
console.error("Something wrong wrong updating column stats");
|
|
2312
|
+
console.error(err);
|
|
2313
|
+
throw err;
|
|
2314
|
+
});
|
|
2315
|
+
}
|
|
2316
|
+
const reltuplesValues = [];
|
|
2317
|
+
for (const table of this.ownMetadata) {
|
|
2318
|
+
if (!table.columns) continue;
|
|
2319
|
+
processedTables.add(`${table.schemaName}.${table.tableName}`);
|
|
2320
|
+
let targetTable;
|
|
2321
|
+
if (this.exportedMetadata) targetTable = this.exportedMetadata.find((m) => m.tableName === table.tableName && m.schemaName === table.schemaName);
|
|
2322
|
+
let reltuples;
|
|
2323
|
+
let relpages;
|
|
2324
|
+
let relallvisible = 0;
|
|
2325
|
+
let relallfrozen;
|
|
2326
|
+
if (targetTable) {
|
|
2327
|
+
reltuples = targetTable.reltuples;
|
|
2328
|
+
relpages = targetTable.relpages;
|
|
2329
|
+
relallvisible = targetTable.relallvisible;
|
|
2330
|
+
relallfrozen = targetTable.relallfrozen;
|
|
2331
|
+
} else if (this.mode.kind === "fromAssumption") {
|
|
2332
|
+
reltuples = this.mode.reltuples;
|
|
2333
|
+
relpages = this.mode.relpages;
|
|
2334
|
+
} else {
|
|
2335
|
+
warnings.tablesNotInExports.push(`${table.schemaName}.${table.tableName}`);
|
|
2336
|
+
reltuples = DEFAULT_RELTUPLES;
|
|
2337
|
+
relpages = DEFAULT_RELPAGES;
|
|
2338
|
+
}
|
|
2339
|
+
reltuplesValues.push({
|
|
2340
|
+
relname: table.tableName,
|
|
2341
|
+
schema_name: table.schemaName,
|
|
2342
|
+
reltuples,
|
|
2343
|
+
relpages,
|
|
2344
|
+
relallfrozen,
|
|
2345
|
+
relallvisible
|
|
2346
|
+
});
|
|
2347
|
+
if (targetTable && targetTable.indexes) for (const index of targetTable.indexes) reltuplesValues.push({
|
|
2348
|
+
relname: index.indexName,
|
|
2349
|
+
schema_name: targetTable.schemaName,
|
|
2350
|
+
reltuples: index.reltuples,
|
|
2351
|
+
relpages: index.relpages,
|
|
2352
|
+
relallfrozen: index.relallfrozen,
|
|
2353
|
+
relallvisible: index.relallvisible
|
|
2354
|
+
});
|
|
2355
|
+
}
|
|
2356
|
+
const reltuplesQuery = dedent`
|
|
2357
|
+
update pg_class p
|
|
2358
|
+
set reltuples = v.reltuples,
|
|
2359
|
+
relpages = v.relpages,
|
|
2360
|
+
-- relallfrozen = case when v.relallfrozen is null then p.relallfrozen else v.relallfrozen end,
|
|
2361
|
+
relallvisible = case when v.relallvisible is null then p.relallvisible else v.relallvisible end
|
|
2362
|
+
from jsonb_to_recordset($1::jsonb)
|
|
2363
|
+
as v(reltuples real, relpages integer, relallfrozen integer, relallvisible integer, relname text, schema_name text)
|
|
2364
|
+
where p.relname = v.relname
|
|
2365
|
+
and p.relnamespace = (select oid from pg_namespace where nspname = v.schema_name)
|
|
2366
|
+
returning p.relname, p.relnamespace, p.reltuples, p.relpages;
|
|
2367
|
+
`;
|
|
2368
|
+
const reltuplesPromise = tx.exec(reltuplesQuery, [reltuplesValues]).catch((err) => {
|
|
2369
|
+
console.error("Something went wrong updating reltuples/relpages");
|
|
2370
|
+
console.error(err);
|
|
2371
|
+
return err;
|
|
2372
|
+
});
|
|
2373
|
+
if (this.exportedMetadata) for (const table of this.exportedMetadata) {
|
|
2374
|
+
const tableExists = processedTables.has(`${table.schemaName}.${table.tableName}`);
|
|
2375
|
+
if (tableExists && table.reltuples === -1) {
|
|
2376
|
+
console.warn(`Table ${table.tableName} has reltuples -1. Your production database is probably not analyzed properly`);
|
|
2377
|
+
warnings.tableNotAnalyzed.push(`${table.schemaName}.${table.tableName}`);
|
|
2378
|
+
}
|
|
2379
|
+
if (tableExists) continue;
|
|
2380
|
+
warnings.tablesNotInTest.push(`${table.schemaName}.${table.tableName}`);
|
|
2381
|
+
}
|
|
2382
|
+
const [statsUpdates, reltuplesUpdates] = await Promise.all([columnStatsUpdatePromise, reltuplesPromise]);
|
|
2383
|
+
if (!(statsUpdates ? statsUpdates.length === columnStatsValues.length : true)) console.error(`Did not update expected column stats`);
|
|
2384
|
+
if (reltuplesUpdates.length !== reltuplesValues.length) console.error(`Did not update expected reltuples/relpages`);
|
|
2385
|
+
return warnings;
|
|
2386
|
+
}
|
|
2387
|
+
static async dumpStats(db, postgresVersion, kind) {
|
|
2388
|
+
const fullDump = kind === "full";
|
|
2389
|
+
console.log(`dumping stats for postgres ${gray(postgresVersion)}`);
|
|
2390
|
+
return (await db.exec(`
|
|
2391
|
+
WITH table_columns AS (
|
|
2392
|
+
SELECT
|
|
2393
|
+
c.table_name,
|
|
2394
|
+
c.table_schema,
|
|
2395
|
+
cl.reltuples,
|
|
2396
|
+
cl.relpages,
|
|
2397
|
+
cl.relallvisible,
|
|
2398
|
+
-- cl.relallfrozen,
|
|
2399
|
+
n.nspname AS schema_name,
|
|
2400
|
+
json_agg(
|
|
2401
|
+
json_build_object(
|
|
2402
|
+
'columnName', c.column_name,
|
|
2403
|
+
'stats', (
|
|
2404
|
+
SELECT json_build_object(
|
|
2405
|
+
'starelid', s.starelid,
|
|
2406
|
+
'staattnum', s.staattnum,
|
|
2407
|
+
'stanullfrac', s.stanullfrac,
|
|
2408
|
+
'stawidth', s.stawidth,
|
|
2409
|
+
'stadistinct', s.stadistinct,
|
|
2410
|
+
'stakind1', s.stakind1, 'staop1', s.staop1, 'stacoll1', s.stacoll1, 'stanumbers1', s.stanumbers1,
|
|
2411
|
+
'stakind2', s.stakind2, 'staop2', s.staop2, 'stacoll2', s.stacoll2, 'stanumbers2', s.stanumbers2,
|
|
2412
|
+
'stakind3', s.stakind3, 'staop3', s.staop3, 'stacoll3', s.stacoll3, 'stanumbers3', s.stanumbers3,
|
|
2413
|
+
'stakind4', s.stakind4, 'staop4', s.staop4, 'stacoll4', s.stacoll4, 'stanumbers4', s.stanumbers4,
|
|
2414
|
+
'stakind5', s.stakind5, 'staop5', s.staop5, 'stacoll5', s.stacoll5, 'stanumbers5', s.stanumbers5,
|
|
2415
|
+
'stavalues1', CASE WHEN $1 THEN s.stavalues1 ELSE NULL END,
|
|
2416
|
+
'stavalues2', CASE WHEN $1 THEN s.stavalues2 ELSE NULL END,
|
|
2417
|
+
'stavalues3', CASE WHEN $1 THEN s.stavalues3 ELSE NULL END,
|
|
2418
|
+
'stavalues4', CASE WHEN $1 THEN s.stavalues4 ELSE NULL END,
|
|
2419
|
+
'stavalues5', CASE WHEN $1 THEN s.stavalues5 ELSE NULL END
|
|
2420
|
+
)
|
|
2421
|
+
FROM pg_statistic s
|
|
2422
|
+
WHERE s.starelid = a.attrelid AND s.staattnum = a.attnum
|
|
2423
|
+
)
|
|
2424
|
+
)
|
|
2425
|
+
ORDER BY c.ordinal_position
|
|
2426
|
+
) AS columns
|
|
2427
|
+
FROM information_schema.columns c
|
|
2428
|
+
JOIN pg_attribute a
|
|
2429
|
+
ON a.attrelid = (quote_ident(c.table_schema) || '.' || quote_ident(c.table_name))::regclass
|
|
2430
|
+
AND a.attname = c.column_name
|
|
2431
|
+
JOIN pg_class cl
|
|
2432
|
+
ON cl.oid = a.attrelid
|
|
2433
|
+
JOIN pg_namespace n
|
|
2434
|
+
ON n.oid = cl.relnamespace
|
|
2435
|
+
WHERE c.table_name NOT LIKE 'pg_%'
|
|
2436
|
+
AND n.nspname <> 'information_schema'
|
|
2437
|
+
AND c.table_name NOT IN ('pg_stat_statements', 'pg_stat_statements_info')
|
|
2438
|
+
GROUP BY c.table_name, c.table_schema, cl.reltuples, cl.relpages, cl.relallvisible, n.nspname
|
|
2439
|
+
),
|
|
2440
|
+
table_indexes AS (
|
|
2441
|
+
SELECT
|
|
2442
|
+
t.relname AS table_name,
|
|
2443
|
+
json_agg(
|
|
2444
|
+
json_build_object(
|
|
2445
|
+
'indexName', i.relname,
|
|
2446
|
+
'reltuples', i.reltuples,
|
|
2447
|
+
'relpages', i.relpages,
|
|
2448
|
+
'relallvisible', i.relallvisible
|
|
2449
|
+
-- 'relallfrozen', i.relallfrozen
|
|
2450
|
+
)
|
|
2451
|
+
) AS indexes
|
|
2452
|
+
FROM pg_class t
|
|
2453
|
+
JOIN pg_index ix ON ix.indrelid = t.oid
|
|
2454
|
+
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
2455
|
+
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
2456
|
+
WHERE t.relname NOT LIKE 'pg_%'
|
|
2457
|
+
AND n.nspname <> 'information_schema'
|
|
2458
|
+
GROUP BY t.relname
|
|
2459
|
+
)
|
|
2460
|
+
SELECT json_agg(
|
|
2461
|
+
json_build_object(
|
|
2462
|
+
'tableName', tc.table_name,
|
|
2463
|
+
'schemaName', tc.table_schema,
|
|
2464
|
+
'reltuples', tc.reltuples,
|
|
2465
|
+
'relpages', tc.relpages,
|
|
2466
|
+
'relallvisible', tc.relallvisible,
|
|
2467
|
+
-- 'relallfrozen', tc.relallfrozen,
|
|
2468
|
+
'columns', tc.columns,
|
|
2469
|
+
'indexes', COALESCE(ti.indexes, '[]'::json)
|
|
2470
|
+
)
|
|
2471
|
+
)
|
|
2472
|
+
FROM table_columns tc
|
|
2473
|
+
LEFT JOIN table_indexes ti
|
|
2474
|
+
ON ti.table_name = tc.table_name;
|
|
2475
|
+
`, [fullDump]))[0].json_agg;
|
|
2476
|
+
}
|
|
2477
|
+
/**
|
|
2478
|
+
* Returns all indexes in the database.
|
|
2479
|
+
* ONLY handles regular btree indexes
|
|
2480
|
+
*/
|
|
2481
|
+
async getExistingIndexes() {
|
|
2482
|
+
return await this.db.exec(`
|
|
2483
|
+
WITH partitioned_tables AS (
|
|
2484
|
+
SELECT
|
|
2485
|
+
inhparent::regclass AS parent_table,
|
|
2486
|
+
inhrelid::regclass AS partition_table
|
|
2487
|
+
FROM
|
|
2488
|
+
pg_inherits
|
|
2489
|
+
)
|
|
2490
|
+
SELECT
|
|
2491
|
+
n.nspname AS schema_name,
|
|
2492
|
+
COALESCE(pt.parent_table::text, t.relname) AS table_name,
|
|
2493
|
+
i.relname AS index_name,
|
|
2494
|
+
ix.indisprimary as is_primary,
|
|
2495
|
+
ix.indisunique as is_unique,
|
|
2496
|
+
am.amname AS index_type,
|
|
2497
|
+
array_agg(
|
|
2498
|
+
CASE
|
|
2499
|
+
-- Handle regular columns
|
|
2500
|
+
WHEN a.attname IS NOT NULL THEN
|
|
2501
|
+
json_build_object('name', a.attname, 'order',
|
|
2502
|
+
CASE
|
|
2503
|
+
WHEN (indoption[array_position(ix.indkey, a.attnum)] & 1) = 1 THEN 'DESC'
|
|
2504
|
+
ELSE 'ASC'
|
|
2505
|
+
END,
|
|
2506
|
+
'opclass', CASE WHEN opc.opcdefault THEN NULL ELSE opc.opcname END)
|
|
2507
|
+
-- Handle expressions
|
|
2508
|
+
ELSE
|
|
2509
|
+
json_build_object('name', pg_get_expr((ix.indexprs)::pg_node_tree, t.oid), 'order',
|
|
2510
|
+
CASE
|
|
2511
|
+
WHEN (indoption[array_position(ix.indkey, k.attnum)] & 1) = 1 THEN 'DESC'
|
|
2512
|
+
ELSE 'ASC'
|
|
2513
|
+
END,
|
|
2514
|
+
'opclass', CASE WHEN opc.opcdefault THEN NULL ELSE opc.opcname END)
|
|
2515
|
+
END
|
|
2516
|
+
ORDER BY array_position(ix.indkey, k.attnum)
|
|
2517
|
+
) AS index_columns
|
|
2518
|
+
FROM
|
|
2519
|
+
pg_class t
|
|
2520
|
+
LEFT JOIN partitioned_tables pt ON t.oid = pt.partition_table
|
|
2521
|
+
JOIN pg_index ix ON t.oid = ix.indrelid
|
|
2522
|
+
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
2523
|
+
JOIN pg_am am ON i.relam = am.oid
|
|
2524
|
+
LEFT JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY k(attnum, ordinality) ON true
|
|
2525
|
+
LEFT JOIN pg_attribute a ON a.attnum = k.attnum AND a.attrelid = t.oid
|
|
2526
|
+
LEFT JOIN pg_opclass opc ON opc.oid = ix.indclass[k.ordinality - 1]
|
|
2527
|
+
JOIN pg_namespace n ON t.relnamespace = n.oid
|
|
2528
|
+
WHERE
|
|
2529
|
+
n.nspname not like 'pg_%' and
|
|
2530
|
+
n.nspname <> 'information_schema'
|
|
2531
|
+
GROUP BY
|
|
2532
|
+
n.nspname, COALESCE(pt.parent_table::text, t.relname), i.relname, am.amname, ix.indisprimary, ix.indisunique
|
|
2533
|
+
ORDER BY
|
|
2534
|
+
COALESCE(pt.parent_table::text, t.relname), i.relname; -- @qd_introspection
|
|
2535
|
+
`);
|
|
2536
|
+
}
|
|
2537
|
+
};
|
|
2538
|
+
_defineProperty(Statistics, "defaultStatsMode", Object.freeze({
|
|
2539
|
+
kind: "fromAssumption",
|
|
2540
|
+
reltuples: DEFAULT_RELTUPLES,
|
|
2541
|
+
relpages: DEFAULT_RELPAGES
|
|
2542
|
+
}));
|
|
2543
|
+
|
|
2544
|
+
//#endregion
|
|
2545
|
+
//#region src/optimizer/pss-rewriter.ts
|
|
2546
|
+
/**
|
|
2547
|
+
* Rewriter for pg_stat_statements queries.
|
|
2548
|
+
* Not all queries found in pg_stat_statements can be
|
|
2549
|
+
* directly sent back to the database without first being rewritten.
|
|
2550
|
+
*/
|
|
2551
|
+
var PssRewriter = class {
|
|
2552
|
+
constructor() {
|
|
2553
|
+
_defineProperty(this, "problematicKeywords", [
|
|
2554
|
+
"interval",
|
|
2555
|
+
"timestamp",
|
|
2556
|
+
"geometry"
|
|
2557
|
+
]);
|
|
2558
|
+
}
|
|
2559
|
+
rewrite(query) {
|
|
2560
|
+
return this.rewriteKeywordWithParameter(query);
|
|
2561
|
+
}
|
|
2562
|
+
rewriteKeywordWithParameter(query) {
|
|
2563
|
+
return query.replace(/\b(\w+) (\$\d+)\b/gi, (match) => {
|
|
2564
|
+
const [keyword, parameter] = match.split(" ");
|
|
2565
|
+
if (!this.problematicKeywords.includes(keyword.toLowerCase())) return match;
|
|
2566
|
+
return `(${parameter}::${keyword.toLowerCase()})`;
|
|
2567
|
+
});
|
|
2568
|
+
}
|
|
2569
|
+
};
|
|
2570
|
+
|
|
2571
|
+
//#endregion
|
|
2572
|
+
export { Analyzer, ExportedStats, ExportedStatsColumns, ExportedStatsIndex, ExportedStatsStatistics, ExportedStatsV1, IndexOptimizer, PROCEED, PgIdentifier, PostgresQueryBuilder, PostgresVersion, PssRewriter, SKIP, Statistics, StatisticsMode, StatisticsSource, dropIndex, ignoredIdentifier, isIndexProbablyDroppable, isIndexSupported, parseMajorVersion, parseNudges, parseVersionNudges };
|
|
2573
|
+
//# sourceMappingURL=index.mjs.map
|