@query-doctor/core 0.0.3
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/.eslintrc.cjs +4 -0
- package/dist/index.cjs +1833 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1787 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +24297 -0
- package/dist/index.mjs.map +1 -0
- package/dist/optimizer/genalgo.d.ts +82 -0
- package/dist/optimizer/genalgo.d.ts.map +1 -0
- package/dist/optimizer/statistics.d.ts +373 -0
- package/dist/optimizer/statistics.d.ts.map +1 -0
- package/dist/sql/analyzer.d.ts +97 -0
- package/dist/sql/analyzer.d.ts.map +1 -0
- package/dist/sql/analyzer_test.d.ts +2 -0
- package/dist/sql/analyzer_test.d.ts.map +1 -0
- package/dist/sql/builder.d.ts +24 -0
- package/dist/sql/builder.d.ts.map +1 -0
- package/dist/sql/database.d.ts +31 -0
- package/dist/sql/database.d.ts.map +1 -0
- package/dist/sql/nudges.d.ts +15 -0
- package/dist/sql/nudges.d.ts.map +1 -0
- package/dist/sql/permutations_test.d.ts +2 -0
- package/dist/sql/permutations_test.d.ts.map +1 -0
- package/dist/sql/schema_dump.d.ts +132 -0
- package/dist/sql/schema_dump.d.ts.map +1 -0
- package/dist/sql/trace.d.ts +1 -0
- package/dist/sql/trace.d.ts.map +1 -0
- package/dist/sql/walker.d.ts +44 -0
- package/dist/sql/walker.d.ts.map +1 -0
- package/package.json +37 -0
- package/tsconfig.json +12 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1787 @@
|
|
|
1
|
+
'use client'
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
4
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
5
|
+
|
|
6
|
+
// src/sql/analyzer.ts
|
|
7
|
+
import {
|
|
8
|
+
bgMagentaBright,
|
|
9
|
+
blue,
|
|
10
|
+
dim,
|
|
11
|
+
strikethrough
|
|
12
|
+
} from "colorette";
|
|
13
|
+
|
|
14
|
+
// src/sql/walker.ts
|
|
15
|
+
import { deparseSync } from "pgsql-deparser";
|
|
16
|
+
|
|
17
|
+
// src/sql/nudges.ts
|
|
18
|
+
function is(node, kind) {
|
|
19
|
+
return kind in node;
|
|
20
|
+
}
|
|
21
|
+
function isANode(node) {
|
|
22
|
+
if (typeof node !== "object" || node === null) {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
const keys = Object.keys(node);
|
|
26
|
+
return keys.length === 1 && /^[A-Z]/.test(keys[0]);
|
|
27
|
+
}
|
|
28
|
+
function parseNudges(node, stack) {
|
|
29
|
+
const nudges = [];
|
|
30
|
+
if (is(node, "A_Star")) {
|
|
31
|
+
nudges.push({
|
|
32
|
+
kind: "AVOID_SELECT_STAR",
|
|
33
|
+
severity: "INFO",
|
|
34
|
+
message: "Avoid using SELECT *"
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
if (is(node, "FuncCall")) {
|
|
38
|
+
const inWhereClause = stack.some((item) => item === "whereClause");
|
|
39
|
+
if (inWhereClause && node.FuncCall.args) {
|
|
40
|
+
const hasColumnRef = containsColumnRef(node.FuncCall.args);
|
|
41
|
+
if (hasColumnRef) {
|
|
42
|
+
nudges.push({
|
|
43
|
+
kind: "AVOID_FUNCTIONS_ON_COLUMNS_IN_WHERE",
|
|
44
|
+
severity: "WARNING",
|
|
45
|
+
message: "Avoid using functions on columns in WHERE clause"
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (is(node, "SelectStmt")) {
|
|
51
|
+
const isSubquery = stack.some(
|
|
52
|
+
(item) => item === "RangeSubselect" || item === "SubLink" || item === "CommonTableExpr"
|
|
53
|
+
);
|
|
54
|
+
if (!isSubquery) {
|
|
55
|
+
const hasFromClause = node.SelectStmt.fromClause && node.SelectStmt.fromClause.length > 0;
|
|
56
|
+
if (hasFromClause) {
|
|
57
|
+
const hasActualTables = node.SelectStmt.fromClause.some((fromItem) => {
|
|
58
|
+
return is(fromItem, "RangeVar") || is(fromItem, "JoinExpr") && hasActualTablesInJoin(fromItem);
|
|
59
|
+
});
|
|
60
|
+
if (hasActualTables) {
|
|
61
|
+
if (!node.SelectStmt.whereClause) {
|
|
62
|
+
nudges.push({
|
|
63
|
+
kind: "MISSING_WHERE_CLAUSE",
|
|
64
|
+
severity: "INFO",
|
|
65
|
+
message: "Missing WHERE clause"
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
if (!node.SelectStmt.limitCount) {
|
|
69
|
+
nudges.push({
|
|
70
|
+
kind: "MISSING_LIMIT_CLAUSE",
|
|
71
|
+
severity: "INFO",
|
|
72
|
+
message: "Missing LIMIT clause"
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (is(node, "A_Expr")) {
|
|
80
|
+
const isEqualityOp = node.A_Expr.kind === "AEXPR_OP" && node.A_Expr.name && node.A_Expr.name.length > 0 && is(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 === "<>");
|
|
81
|
+
if (isEqualityOp) {
|
|
82
|
+
const leftIsNull = isNullConstant(node.A_Expr.lexpr);
|
|
83
|
+
const rightIsNull = isNullConstant(node.A_Expr.rexpr);
|
|
84
|
+
if (leftIsNull || rightIsNull) {
|
|
85
|
+
nudges.push({
|
|
86
|
+
kind: "USE_IS_NULL_NOT_EQUALS",
|
|
87
|
+
severity: "WARNING",
|
|
88
|
+
message: "Use IS NULL instead of = or != or <> for NULL comparisons"
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const isLikeOp = node.A_Expr.kind === "AEXPR_LIKE" || node.A_Expr.kind === "AEXPR_ILIKE";
|
|
93
|
+
if (isLikeOp && node.A_Expr.rexpr) {
|
|
94
|
+
const patternString = getStringConstantValue(node.A_Expr.rexpr);
|
|
95
|
+
if (patternString && patternString.startsWith("%")) {
|
|
96
|
+
nudges.push({
|
|
97
|
+
kind: "AVOID_LEADING_WILDCARD_LIKE",
|
|
98
|
+
severity: "WARNING",
|
|
99
|
+
message: "Avoid using LIKE with leading wildcards"
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (is(node, "SelectStmt") && node.SelectStmt.distinctClause) {
|
|
105
|
+
nudges.push({
|
|
106
|
+
kind: "AVOID_DISTINCT_WITHOUT_REASON",
|
|
107
|
+
severity: "WARNING",
|
|
108
|
+
message: "Avoid using DISTINCT without a reason"
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
if (is(node, "JoinExpr")) {
|
|
112
|
+
if (!node.JoinExpr.quals) {
|
|
113
|
+
nudges.push({
|
|
114
|
+
kind: "MISSING_JOIN_CONDITION",
|
|
115
|
+
severity: "WARNING",
|
|
116
|
+
message: "Missing JOIN condition"
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (is(node, "SelectStmt") && node.SelectStmt.fromClause && node.SelectStmt.fromClause.length > 1) {
|
|
121
|
+
const tableCount = node.SelectStmt.fromClause.filter(
|
|
122
|
+
(item) => is(item, "RangeVar")
|
|
123
|
+
).length;
|
|
124
|
+
if (tableCount > 1) {
|
|
125
|
+
nudges.push({
|
|
126
|
+
kind: "MISSING_JOIN_CONDITION",
|
|
127
|
+
severity: "WARNING",
|
|
128
|
+
message: "Missing JOIN condition"
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (is(node, "BoolExpr") && node.BoolExpr.boolop === "OR_EXPR") {
|
|
133
|
+
const orCount = countBoolOrConditions(node);
|
|
134
|
+
if (orCount >= 3) {
|
|
135
|
+
nudges.push({
|
|
136
|
+
kind: "CONSIDER_IN_INSTEAD_OF_MANY_ORS",
|
|
137
|
+
severity: "WARNING",
|
|
138
|
+
message: "Consider using IN instead of many ORs"
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return nudges;
|
|
143
|
+
}
|
|
144
|
+
function containsColumnRef(args) {
|
|
145
|
+
for (const arg of args) {
|
|
146
|
+
if (hasColumnRefInNode(arg)) {
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
function hasColumnRefInNode(node) {
|
|
153
|
+
if (isANode(node) && is(node, "ColumnRef")) {
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
156
|
+
if (typeof node !== "object" || node === null) {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
if (Array.isArray(node)) {
|
|
160
|
+
return node.some((item) => hasColumnRefInNode(item));
|
|
161
|
+
}
|
|
162
|
+
if (isANode(node)) {
|
|
163
|
+
const keys = Object.keys(node);
|
|
164
|
+
return hasColumnRefInNode(node[keys[0]]);
|
|
165
|
+
}
|
|
166
|
+
for (const child of Object.values(node)) {
|
|
167
|
+
if (hasColumnRefInNode(child)) {
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
function hasActualTablesInJoin(joinExpr) {
|
|
174
|
+
if (joinExpr.JoinExpr.larg && is(joinExpr.JoinExpr.larg, "RangeVar")) {
|
|
175
|
+
return true;
|
|
176
|
+
}
|
|
177
|
+
if (joinExpr.JoinExpr.larg && is(joinExpr.JoinExpr.larg, "JoinExpr")) {
|
|
178
|
+
if (hasActualTablesInJoin(joinExpr.JoinExpr.larg)) {
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (joinExpr.JoinExpr.rarg && is(joinExpr.JoinExpr.rarg, "RangeVar")) {
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
if (joinExpr.JoinExpr.rarg && is(joinExpr.JoinExpr.rarg, "JoinExpr")) {
|
|
186
|
+
if (hasActualTablesInJoin(joinExpr.JoinExpr.rarg)) {
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
function isNullConstant(node) {
|
|
193
|
+
if (!node || typeof node !== "object") {
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
if (isANode(node) && is(node, "A_Const")) {
|
|
197
|
+
return node.A_Const.isnull !== void 0;
|
|
198
|
+
}
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
function getStringConstantValue(node) {
|
|
202
|
+
if (!node || typeof node !== "object") {
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
if (isANode(node) && is(node, "A_Const") && node.A_Const.sval) {
|
|
206
|
+
return node.A_Const.sval.sval || null;
|
|
207
|
+
}
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
function countBoolOrConditions(node) {
|
|
211
|
+
if (node.BoolExpr.boolop !== "OR_EXPR" || !node.BoolExpr.args) {
|
|
212
|
+
return 1;
|
|
213
|
+
}
|
|
214
|
+
let count = 0;
|
|
215
|
+
for (const arg of node.BoolExpr.args) {
|
|
216
|
+
if (isANode(arg) && is(arg, "BoolExpr") && arg.BoolExpr.boolop === "OR_EXPR") {
|
|
217
|
+
count += countBoolOrConditions(arg);
|
|
218
|
+
} else {
|
|
219
|
+
count += 1;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return count;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// src/sql/walker.ts
|
|
226
|
+
var Walker = class _Walker {
|
|
227
|
+
constructor(query) {
|
|
228
|
+
this.query = query;
|
|
229
|
+
__publicField(this, "tableMappings", /* @__PURE__ */ new Map());
|
|
230
|
+
__publicField(this, "tempTables", /* @__PURE__ */ new Set());
|
|
231
|
+
__publicField(this, "highlights", []);
|
|
232
|
+
__publicField(this, "indexRepresentations", /* @__PURE__ */ new Set());
|
|
233
|
+
__publicField(this, "indexesToCheck", []);
|
|
234
|
+
__publicField(this, "highlightPositions", /* @__PURE__ */ new Set());
|
|
235
|
+
// used for tallying the amount of times we see stuff so
|
|
236
|
+
// we have a better idea of what to start off the algorithm with
|
|
237
|
+
__publicField(this, "seenReferences", /* @__PURE__ */ new Map());
|
|
238
|
+
__publicField(this, "shadowedAliases", []);
|
|
239
|
+
__publicField(this, "nudges", []);
|
|
240
|
+
}
|
|
241
|
+
walk(root) {
|
|
242
|
+
this.tableMappings = /* @__PURE__ */ new Map();
|
|
243
|
+
this.tempTables = /* @__PURE__ */ new Set();
|
|
244
|
+
this.highlights = [];
|
|
245
|
+
this.indexRepresentations = /* @__PURE__ */ new Set();
|
|
246
|
+
this.indexesToCheck = [];
|
|
247
|
+
this.highlightPositions = /* @__PURE__ */ new Set();
|
|
248
|
+
this.seenReferences = /* @__PURE__ */ new Map();
|
|
249
|
+
this.shadowedAliases = [];
|
|
250
|
+
this.nudges = [];
|
|
251
|
+
_Walker.traverse(root, [], (node, stack) => {
|
|
252
|
+
const nodeNudges = parseNudges(node, stack);
|
|
253
|
+
this.nudges = [...this.nudges, ...nodeNudges];
|
|
254
|
+
if (is2(node, "CommonTableExpr")) {
|
|
255
|
+
if (node.CommonTableExpr.ctename) {
|
|
256
|
+
this.tempTables.add(node.CommonTableExpr.ctename);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
if (is2(node, "RangeSubselect")) {
|
|
260
|
+
if (node.RangeSubselect.alias?.aliasname) {
|
|
261
|
+
this.tempTables.add(node.RangeSubselect.alias.aliasname);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (is2(node, "NullTest")) {
|
|
265
|
+
if (node.NullTest.arg && node.NullTest.nulltesttype && is2(node.NullTest.arg, "ColumnRef")) {
|
|
266
|
+
this.add(node.NullTest.arg, {
|
|
267
|
+
where: { nulltest: node.NullTest.nulltesttype }
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (is2(node, "RangeVar") && node.RangeVar.relname) {
|
|
272
|
+
this.tableMappings.set(node.RangeVar.relname, {
|
|
273
|
+
text: node.RangeVar.relname,
|
|
274
|
+
start: node.RangeVar.location,
|
|
275
|
+
quoted: false
|
|
276
|
+
});
|
|
277
|
+
if (node.RangeVar.alias?.aliasname) {
|
|
278
|
+
const aliasName = node.RangeVar.alias.aliasname;
|
|
279
|
+
const existingMapping = this.tableMappings.get(aliasName);
|
|
280
|
+
const part = {
|
|
281
|
+
text: node.RangeVar.relname,
|
|
282
|
+
start: node.RangeVar.location,
|
|
283
|
+
// what goes here? the text here doesn't _really_ exist.
|
|
284
|
+
// so it can't be quoted or not quoted.
|
|
285
|
+
// Does it even matter?
|
|
286
|
+
quoted: true,
|
|
287
|
+
alias: aliasName
|
|
288
|
+
};
|
|
289
|
+
if (existingMapping) {
|
|
290
|
+
console.warn(
|
|
291
|
+
`Ignoring alias ${aliasName} as it shadows an existing mapping. We currently do not support alias shadowing.`
|
|
292
|
+
);
|
|
293
|
+
this.shadowedAliases.push(part);
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
this.tableMappings.set(aliasName, part);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
if (is2(node, "SortBy")) {
|
|
300
|
+
if (node.SortBy.node && is2(node.SortBy.node, "ColumnRef")) {
|
|
301
|
+
this.add(node.SortBy.node, {
|
|
302
|
+
sort: {
|
|
303
|
+
dir: node.SortBy.sortby_dir ?? "SORTBY_DEFAULT",
|
|
304
|
+
nulls: node.SortBy.sortby_nulls ?? "SORTBY_NULLS_DEFAULT"
|
|
305
|
+
}
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
if (is2(node, "JoinExpr") && node.JoinExpr.quals) {
|
|
310
|
+
if (is2(node.JoinExpr.quals, "A_Expr")) {
|
|
311
|
+
if (node.JoinExpr.quals.A_Expr.lexpr && is2(node.JoinExpr.quals.A_Expr.lexpr, "ColumnRef")) {
|
|
312
|
+
this.add(node.JoinExpr.quals.A_Expr.lexpr);
|
|
313
|
+
}
|
|
314
|
+
if (node.JoinExpr.quals.A_Expr.rexpr && is2(node.JoinExpr.quals.A_Expr.rexpr, "ColumnRef")) {
|
|
315
|
+
this.add(node.JoinExpr.quals.A_Expr.rexpr);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
if (is2(node, "ColumnRef")) {
|
|
320
|
+
for (let i = 0; i < stack.length; i++) {
|
|
321
|
+
const inReturningList = stack[i] === "returningList" && stack[i + 1] === "ResTarget" && stack[i + 2] === "val" && stack[i + 3] === "ColumnRef";
|
|
322
|
+
if (inReturningList) {
|
|
323
|
+
this.add(node, { ignored: true });
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
if (
|
|
327
|
+
// stack[i] === "SelectStmt" &&
|
|
328
|
+
stack[i + 1] === "targetList" && stack[i + 2] === "ResTarget" && stack[i + 3] === "val" && stack[i + 4] === "ColumnRef"
|
|
329
|
+
) {
|
|
330
|
+
this.add(node, { ignored: true });
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
if (stack[i] === "FuncCall" && stack[i + 1] === "args") {
|
|
334
|
+
this.add(node, { ignored: true });
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
this.add(node);
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
return {
|
|
342
|
+
highlights: this.highlights,
|
|
343
|
+
indexRepresentations: this.indexRepresentations,
|
|
344
|
+
indexesToCheck: this.indexesToCheck,
|
|
345
|
+
shadowedAliases: this.shadowedAliases,
|
|
346
|
+
tempTables: this.tempTables,
|
|
347
|
+
tableMappings: this.tableMappings,
|
|
348
|
+
nudges: this.nudges
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
add(node, options) {
|
|
352
|
+
if (!node.ColumnRef.location) {
|
|
353
|
+
console.error(`Node did not have a location. Skipping`, node);
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
if (!node.ColumnRef.fields) {
|
|
357
|
+
console.error(node);
|
|
358
|
+
throw new Error("Column reference must have fields");
|
|
359
|
+
}
|
|
360
|
+
let ignored = options?.ignored ?? false;
|
|
361
|
+
let runningLength = node.ColumnRef.location;
|
|
362
|
+
const parts = node.ColumnRef.fields.map(
|
|
363
|
+
(field, i, length) => {
|
|
364
|
+
if (!is2(field, "String") || !field.String.sval) {
|
|
365
|
+
const out = deparseSync(field);
|
|
366
|
+
ignored = true;
|
|
367
|
+
return {
|
|
368
|
+
quoted: out.startsWith('"'),
|
|
369
|
+
text: out,
|
|
370
|
+
start: runningLength
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
const start = runningLength;
|
|
374
|
+
const size = field.String.sval?.length ?? 0;
|
|
375
|
+
let quoted = false;
|
|
376
|
+
if (node.ColumnRef.location !== void 0) {
|
|
377
|
+
const boundary = this.query[runningLength];
|
|
378
|
+
if (boundary === '"') {
|
|
379
|
+
quoted = true;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
const isLastIteration = i === length.length - 1;
|
|
383
|
+
runningLength += size + (isLastIteration ? 0 : 1) + (quoted ? 2 : 0);
|
|
384
|
+
return {
|
|
385
|
+
text: field.String.sval,
|
|
386
|
+
start,
|
|
387
|
+
quoted
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
);
|
|
391
|
+
const end = runningLength;
|
|
392
|
+
if (this.highlightPositions.has(node.ColumnRef.location)) {
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
this.highlightPositions.add(node.ColumnRef.location);
|
|
396
|
+
const highlighted = `${this.query.slice(node.ColumnRef.location, end)}`;
|
|
397
|
+
const seen = this.seenReferences.get(highlighted);
|
|
398
|
+
if (!ignored) {
|
|
399
|
+
this.seenReferences.set(highlighted, (seen ?? 0) + 1);
|
|
400
|
+
}
|
|
401
|
+
const ref = {
|
|
402
|
+
frequency: seen ?? 1,
|
|
403
|
+
representation: highlighted,
|
|
404
|
+
parts,
|
|
405
|
+
ignored: ignored ?? false,
|
|
406
|
+
position: {
|
|
407
|
+
start: node.ColumnRef.location,
|
|
408
|
+
end
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
if (options?.sort) {
|
|
412
|
+
ref.sort = options.sort;
|
|
413
|
+
}
|
|
414
|
+
if (options?.where) {
|
|
415
|
+
ref.where = options.where;
|
|
416
|
+
}
|
|
417
|
+
this.highlights.push(ref);
|
|
418
|
+
}
|
|
419
|
+
static traverse(node, stack, callback) {
|
|
420
|
+
if (isANode2(node)) {
|
|
421
|
+
callback(node, [...stack, getNodeKind(node)]);
|
|
422
|
+
}
|
|
423
|
+
if (typeof node !== "object" || node === null) {
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
if (Array.isArray(node)) {
|
|
427
|
+
for (const item of node) {
|
|
428
|
+
if (isANode2(item)) {
|
|
429
|
+
_Walker.traverse(item, stack, callback);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
} else if (isANode2(node)) {
|
|
433
|
+
const keys = Object.keys(node);
|
|
434
|
+
_Walker.traverse(node[keys[0]], [...stack, getNodeKind(node)], callback);
|
|
435
|
+
} else {
|
|
436
|
+
for (const [key, child] of Object.entries(node)) {
|
|
437
|
+
_Walker.traverse(child, [...stack, key], callback);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
function is2(node, kind) {
|
|
443
|
+
return kind in node;
|
|
444
|
+
}
|
|
445
|
+
function getNodeKind(node) {
|
|
446
|
+
const keys = Object.keys(node);
|
|
447
|
+
return keys[0];
|
|
448
|
+
}
|
|
449
|
+
function isANode2(node) {
|
|
450
|
+
if (typeof node !== "object" || node === null) {
|
|
451
|
+
return false;
|
|
452
|
+
}
|
|
453
|
+
const keys = Object.keys(node);
|
|
454
|
+
return keys.length === 1 && /^[A-Z]/.test(keys[0]);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// src/sql/analyzer.ts
|
|
458
|
+
var ignoredIdentifier = "__qd_placeholder";
|
|
459
|
+
var Analyzer = class {
|
|
460
|
+
constructor(parser) {
|
|
461
|
+
this.parser = parser;
|
|
462
|
+
}
|
|
463
|
+
async analyze(query, formattedQuery) {
|
|
464
|
+
const ast = await this.parser(query);
|
|
465
|
+
if (!ast.stmts) {
|
|
466
|
+
throw new Error(
|
|
467
|
+
"Query did not have any statements. This should probably never happen?"
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
const stmt = ast.stmts[0].stmt;
|
|
471
|
+
if (!stmt) {
|
|
472
|
+
throw new Error(
|
|
473
|
+
"Query did not have any statements. This should probably never happen?"
|
|
474
|
+
);
|
|
475
|
+
}
|
|
476
|
+
const walker = new Walker(query);
|
|
477
|
+
const {
|
|
478
|
+
highlights,
|
|
479
|
+
indexRepresentations,
|
|
480
|
+
indexesToCheck,
|
|
481
|
+
shadowedAliases,
|
|
482
|
+
tempTables,
|
|
483
|
+
tableMappings,
|
|
484
|
+
nudges
|
|
485
|
+
} = walker.walk(stmt);
|
|
486
|
+
const sortedHighlights = highlights.sort(
|
|
487
|
+
(a, b) => b.position.end - a.position.end
|
|
488
|
+
);
|
|
489
|
+
let currQuery = query;
|
|
490
|
+
for (const highlight of sortedHighlights) {
|
|
491
|
+
const parts = this.resolveTableAliases(highlight.parts, tableMappings);
|
|
492
|
+
if (parts.length === 0) {
|
|
493
|
+
console.error(highlight);
|
|
494
|
+
throw new Error("Highlight must have at least one part");
|
|
495
|
+
}
|
|
496
|
+
let color;
|
|
497
|
+
let skip = false;
|
|
498
|
+
if (highlight.ignored) {
|
|
499
|
+
color = (x) => dim(strikethrough(x));
|
|
500
|
+
skip = true;
|
|
501
|
+
} else if (parts.length === 2 && tempTables.has(parts[0].text) && // sometimes temp tables are aliased as existing tables
|
|
502
|
+
// we don't want to ignore them if they are
|
|
503
|
+
!tableMappings.has(parts[0].text)) {
|
|
504
|
+
color = blue;
|
|
505
|
+
skip = true;
|
|
506
|
+
} else {
|
|
507
|
+
color = bgMagentaBright;
|
|
508
|
+
}
|
|
509
|
+
const queryRepr = highlight.representation;
|
|
510
|
+
const queryBeforeMatch = currQuery.slice(0, highlight.position.start);
|
|
511
|
+
const queryAfterToken = currQuery.slice(highlight.position.end);
|
|
512
|
+
currQuery = `${queryBeforeMatch}${color(queryRepr)}${this.colorizeKeywords(
|
|
513
|
+
queryAfterToken,
|
|
514
|
+
color
|
|
515
|
+
)}`;
|
|
516
|
+
if (indexRepresentations.has(queryRepr)) {
|
|
517
|
+
skip = true;
|
|
518
|
+
}
|
|
519
|
+
if (!skip) {
|
|
520
|
+
indexesToCheck.push(highlight);
|
|
521
|
+
indexRepresentations.add(queryRepr);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
const referencedTables = [];
|
|
525
|
+
for (const value of tableMappings.values()) {
|
|
526
|
+
if (!value.alias) {
|
|
527
|
+
referencedTables.push(value.text);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
const { tags, queryWithoutTags } = this.extractSqlcommenter(query);
|
|
531
|
+
const formattedQueryWithoutTags = formattedQuery ? this.extractSqlcommenter(formattedQuery).queryWithoutTags : void 0;
|
|
532
|
+
return {
|
|
533
|
+
indexesToCheck,
|
|
534
|
+
ansiHighlightedQuery: currQuery,
|
|
535
|
+
referencedTables,
|
|
536
|
+
shadowedAliases,
|
|
537
|
+
tags,
|
|
538
|
+
queryWithoutTags,
|
|
539
|
+
formattedQueryWithoutTags,
|
|
540
|
+
nudges
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
deriveIndexes(tables, discovered) {
|
|
544
|
+
const allIndexes = [];
|
|
545
|
+
const seenIndexes = /* @__PURE__ */ new Set();
|
|
546
|
+
function addIndex(index) {
|
|
547
|
+
const key = `"${index.schema}":"${index.table}":"${index.column}"`;
|
|
548
|
+
if (seenIndexes.has(key)) {
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
seenIndexes.add(key);
|
|
552
|
+
allIndexes.push(index);
|
|
553
|
+
}
|
|
554
|
+
for (const colReference of discovered) {
|
|
555
|
+
const partsCount = colReference.parts.length;
|
|
556
|
+
const columnOnlyReference = partsCount === 1;
|
|
557
|
+
const tableReference = partsCount === 2;
|
|
558
|
+
const fullReference = partsCount === 3;
|
|
559
|
+
if (columnOnlyReference) {
|
|
560
|
+
const [column] = colReference.parts;
|
|
561
|
+
const referencedColumn = this.normalize(column);
|
|
562
|
+
const matchingTables = tables.filter((table) => {
|
|
563
|
+
return table.columns?.some((column2) => {
|
|
564
|
+
return column2.columnName === referencedColumn;
|
|
565
|
+
}) ?? false;
|
|
566
|
+
});
|
|
567
|
+
for (const table of matchingTables) {
|
|
568
|
+
const index = {
|
|
569
|
+
schema: table.schemaName,
|
|
570
|
+
table: table.tableName,
|
|
571
|
+
column: referencedColumn
|
|
572
|
+
};
|
|
573
|
+
if (colReference.sort) {
|
|
574
|
+
index.sort = colReference.sort;
|
|
575
|
+
}
|
|
576
|
+
if (colReference.where) {
|
|
577
|
+
index.where = colReference.where;
|
|
578
|
+
}
|
|
579
|
+
addIndex(index);
|
|
580
|
+
}
|
|
581
|
+
} else if (tableReference) {
|
|
582
|
+
const [table, column] = colReference.parts;
|
|
583
|
+
const referencedTable = this.normalize(table);
|
|
584
|
+
const referencedColumn = this.normalize(column);
|
|
585
|
+
const matchingTable = tables.find((table2) => {
|
|
586
|
+
const hasMatchingColumn = table2.columns?.some((column2) => {
|
|
587
|
+
return column2.columnName === referencedColumn;
|
|
588
|
+
}) ?? false;
|
|
589
|
+
return table2.tableName === referencedTable && hasMatchingColumn;
|
|
590
|
+
});
|
|
591
|
+
if (matchingTable) {
|
|
592
|
+
const index = {
|
|
593
|
+
schema: matchingTable.schemaName,
|
|
594
|
+
table: referencedTable,
|
|
595
|
+
column: referencedColumn
|
|
596
|
+
};
|
|
597
|
+
if (colReference.sort) {
|
|
598
|
+
index.sort = colReference.sort;
|
|
599
|
+
}
|
|
600
|
+
if (colReference.where) {
|
|
601
|
+
index.where = colReference.where;
|
|
602
|
+
}
|
|
603
|
+
addIndex(index);
|
|
604
|
+
}
|
|
605
|
+
} else if (fullReference) {
|
|
606
|
+
const [schema, table, column] = colReference.parts;
|
|
607
|
+
const referencedSchema = this.normalize(schema);
|
|
608
|
+
const referencedTable = this.normalize(table);
|
|
609
|
+
const referencedColumn = this.normalize(column);
|
|
610
|
+
const index = {
|
|
611
|
+
schema: referencedSchema,
|
|
612
|
+
table: referencedTable,
|
|
613
|
+
column: referencedColumn
|
|
614
|
+
};
|
|
615
|
+
if (colReference.sort) {
|
|
616
|
+
index.sort = colReference.sort;
|
|
617
|
+
}
|
|
618
|
+
if (colReference.where) {
|
|
619
|
+
index.where = colReference.where;
|
|
620
|
+
}
|
|
621
|
+
addIndex(index);
|
|
622
|
+
} else {
|
|
623
|
+
console.error(
|
|
624
|
+
"Column reference has too many parts. The query is malformed",
|
|
625
|
+
colReference
|
|
626
|
+
);
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
return allIndexes;
|
|
631
|
+
}
|
|
632
|
+
colorizeKeywords(query, color) {
|
|
633
|
+
return query.replace(
|
|
634
|
+
// eh? This kinda sucks
|
|
635
|
+
/(^\s+)(asc|desc)?(\s+(nulls first|nulls last))?/i,
|
|
636
|
+
(_, pre, dir, spaceNulls, nulls) => {
|
|
637
|
+
return `${pre}${dir ? color(dir) : ""}${nulls ? spaceNulls.replace(nulls, color(nulls)) : ""}`;
|
|
638
|
+
}
|
|
639
|
+
).replace(/(^\s+)(is (null|not null))/i, (_, pre, nulltest) => {
|
|
640
|
+
return `${pre}${color(nulltest)}`;
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* Resolves aliases such as `a.b` to `x.b` if `a` is a known
|
|
645
|
+
* alias to a table called x.
|
|
646
|
+
*
|
|
647
|
+
* Ignores all other combination of parts such as `a.b.c`
|
|
648
|
+
*/
|
|
649
|
+
resolveTableAliases(parts, tableMappings) {
|
|
650
|
+
if (parts.length !== 2) {
|
|
651
|
+
return parts;
|
|
652
|
+
}
|
|
653
|
+
const tablePart = parts[0];
|
|
654
|
+
const mapping = tableMappings.get(tablePart.text);
|
|
655
|
+
if (mapping) {
|
|
656
|
+
parts[0] = mapping;
|
|
657
|
+
}
|
|
658
|
+
return parts;
|
|
659
|
+
}
|
|
660
|
+
normalize(columnReference) {
|
|
661
|
+
return columnReference.quoted ? columnReference.text : (
|
|
662
|
+
// postgres automatically lowercases column names if not quoted
|
|
663
|
+
columnReference.text.toLowerCase()
|
|
664
|
+
);
|
|
665
|
+
}
|
|
666
|
+
extractSqlcommenter(query) {
|
|
667
|
+
const trimmedQuery = query.trimEnd();
|
|
668
|
+
const startPosition = trimmedQuery.lastIndexOf("/*");
|
|
669
|
+
const endPosition = trimmedQuery.lastIndexOf("*/");
|
|
670
|
+
if (startPosition === -1 || endPosition === -1) {
|
|
671
|
+
return { tags: [], queryWithoutTags: trimmedQuery };
|
|
672
|
+
}
|
|
673
|
+
const queryWithoutTags = trimmedQuery.slice(0, startPosition);
|
|
674
|
+
const tagString = trimmedQuery.slice(startPosition + 2, endPosition);
|
|
675
|
+
if (!tagString || typeof tagString !== "string") {
|
|
676
|
+
return { tags: [], queryWithoutTags };
|
|
677
|
+
}
|
|
678
|
+
const tags = [];
|
|
679
|
+
for (const match of tagString.split(",")) {
|
|
680
|
+
const [key, value] = match.split("=");
|
|
681
|
+
if (!key || !value) {
|
|
682
|
+
console.warn(`Invalid sqlcommenter tag: ${match}. Ignoring`);
|
|
683
|
+
continue;
|
|
684
|
+
}
|
|
685
|
+
try {
|
|
686
|
+
let sliceStart = 0;
|
|
687
|
+
if (value.startsWith("'")) {
|
|
688
|
+
sliceStart = 1;
|
|
689
|
+
}
|
|
690
|
+
let sliceEnd = value.length;
|
|
691
|
+
if (value.endsWith("'")) {
|
|
692
|
+
sliceEnd -= 1;
|
|
693
|
+
}
|
|
694
|
+
const decoded = decodeURIComponent(value.slice(sliceStart, sliceEnd));
|
|
695
|
+
tags.push({ key: key.trim(), value: decoded });
|
|
696
|
+
} catch (err) {
|
|
697
|
+
console.error(err);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
return { tags, queryWithoutTags };
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
|
|
704
|
+
// src/sql/database.ts
|
|
705
|
+
import { z } from "zod";
|
|
706
|
+
var PostgresVersion = z.string().brand("PostgresVersion");
|
|
707
|
+
|
|
708
|
+
// src/optimizer/genalgo.ts
|
|
709
|
+
import { blue as blue2, gray, green, magenta, red, yellow } from "colorette";
|
|
710
|
+
|
|
711
|
+
// src/sql/builder.ts
|
|
712
|
+
var PostgresQueryBuilder = class _PostgresQueryBuilder {
|
|
713
|
+
constructor(query) {
|
|
714
|
+
this.query = query;
|
|
715
|
+
__publicField(this, "commands", {});
|
|
716
|
+
__publicField(this, "isIntrospection", false);
|
|
717
|
+
__publicField(this, "explainFlags", []);
|
|
718
|
+
__publicField(this, "_preamble", 0);
|
|
719
|
+
}
|
|
720
|
+
get preamble() {
|
|
721
|
+
return this._preamble;
|
|
722
|
+
}
|
|
723
|
+
static createIndex(definition, name) {
|
|
724
|
+
if (name) {
|
|
725
|
+
return new _PostgresQueryBuilder(
|
|
726
|
+
`create index "${name}" on ${definition};`
|
|
727
|
+
);
|
|
728
|
+
}
|
|
729
|
+
return new _PostgresQueryBuilder(`create index on ${definition};`);
|
|
730
|
+
}
|
|
731
|
+
enable(command, value = true) {
|
|
732
|
+
const commandString = `enable_${command}`;
|
|
733
|
+
if (value) {
|
|
734
|
+
this.commands[commandString] = "on";
|
|
735
|
+
} else {
|
|
736
|
+
this.commands[commandString] = "off";
|
|
737
|
+
}
|
|
738
|
+
return this;
|
|
739
|
+
}
|
|
740
|
+
withQuery(query) {
|
|
741
|
+
this.query = query;
|
|
742
|
+
return this;
|
|
743
|
+
}
|
|
744
|
+
introspect() {
|
|
745
|
+
this.isIntrospection = true;
|
|
746
|
+
return this;
|
|
747
|
+
}
|
|
748
|
+
explain(flags) {
|
|
749
|
+
this.explainFlags = flags;
|
|
750
|
+
return this;
|
|
751
|
+
}
|
|
752
|
+
build() {
|
|
753
|
+
let commands = this.generateSetCommands();
|
|
754
|
+
commands += this.generateExplain().query;
|
|
755
|
+
if (this.isIntrospection) {
|
|
756
|
+
commands += " -- @qd_introspection";
|
|
757
|
+
}
|
|
758
|
+
return commands;
|
|
759
|
+
}
|
|
760
|
+
/** Return the "set a=b" parts of the command in the query separate from the explain select ... part */
|
|
761
|
+
buildParts() {
|
|
762
|
+
const commands = this.generateSetCommands();
|
|
763
|
+
const explain = this.generateExplain();
|
|
764
|
+
this._preamble = explain.preamble;
|
|
765
|
+
if (this.isIntrospection) {
|
|
766
|
+
explain.query += " -- @qd_introspection";
|
|
767
|
+
}
|
|
768
|
+
return { commands, query: explain.query };
|
|
769
|
+
}
|
|
770
|
+
generateSetCommands() {
|
|
771
|
+
let commands = "";
|
|
772
|
+
for (const key in this.commands) {
|
|
773
|
+
const value = this.commands[key];
|
|
774
|
+
commands += `set local ${key}=${value};
|
|
775
|
+
`;
|
|
776
|
+
}
|
|
777
|
+
return commands;
|
|
778
|
+
}
|
|
779
|
+
generateExplain() {
|
|
780
|
+
let query = "";
|
|
781
|
+
if (this.explainFlags.length > 0) {
|
|
782
|
+
query += `explain (${this.explainFlags.join(", ")}) `;
|
|
783
|
+
}
|
|
784
|
+
const semicolon = this.query.endsWith(";") ? "" : ";";
|
|
785
|
+
const preamble = query.length;
|
|
786
|
+
query += `${this.query}${semicolon}`;
|
|
787
|
+
return { query, preamble };
|
|
788
|
+
}
|
|
789
|
+
};
|
|
790
|
+
|
|
791
|
+
// src/optimizer/genalgo.ts
|
|
792
|
+
var _IndexOptimizer = class _IndexOptimizer {
|
|
793
|
+
constructor(db, statistics, existingIndexes, config = {}) {
|
|
794
|
+
this.db = db;
|
|
795
|
+
this.statistics = statistics;
|
|
796
|
+
this.existingIndexes = existingIndexes;
|
|
797
|
+
this.config = config;
|
|
798
|
+
}
|
|
799
|
+
async run(builder, indexes) {
|
|
800
|
+
const baseExplain = await this.runWithoutIndexes(builder);
|
|
801
|
+
const baseCost = Number(baseExplain.Plan["Total Cost"]);
|
|
802
|
+
if (baseCost === 0) {
|
|
803
|
+
return {
|
|
804
|
+
kind: "zero_cost_plan",
|
|
805
|
+
explainPlan: baseExplain
|
|
806
|
+
};
|
|
807
|
+
}
|
|
808
|
+
console.log("Base cost with current indexes", baseCost);
|
|
809
|
+
const permutedIndexes = this.tableColumnIndexCandidates(indexes);
|
|
810
|
+
const nextStage = [];
|
|
811
|
+
const triedIndexes = /* @__PURE__ */ new Map();
|
|
812
|
+
for (const { table, schema, columns } of permutedIndexes.values()) {
|
|
813
|
+
const permutations = permuteWithFeedback(columns);
|
|
814
|
+
let iter = permutations.next(PROCEED);
|
|
815
|
+
const previousCost = baseCost;
|
|
816
|
+
while (!iter.done) {
|
|
817
|
+
const columns2 = iter.value;
|
|
818
|
+
const existingIndex = this.indexAlreadyExists(table, columns2);
|
|
819
|
+
if (existingIndex) {
|
|
820
|
+
console.log(` <${gray("skip")}> ${gray(existingIndex.index_name)}`);
|
|
821
|
+
iter = permutations.next(PROCEED);
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
let indexDefinition = "?";
|
|
825
|
+
const indexName = this.indexName();
|
|
826
|
+
const { raw, colored } = this.toDefinition({
|
|
827
|
+
columns: columns2,
|
|
828
|
+
schema,
|
|
829
|
+
table
|
|
830
|
+
});
|
|
831
|
+
const shortenedSchema = schema === "public" ? "" : `"${schema}".`;
|
|
832
|
+
const indexDefinitionClean = `${shortenedSchema}"${table}"(${columns2.map((c) => `"${c.column}"`).join(", ")})`;
|
|
833
|
+
indexDefinition = colored;
|
|
834
|
+
const query = PostgresQueryBuilder.createIndex(
|
|
835
|
+
raw,
|
|
836
|
+
indexName
|
|
837
|
+
).introspect();
|
|
838
|
+
triedIndexes.set(indexName, {
|
|
839
|
+
schema,
|
|
840
|
+
table,
|
|
841
|
+
columns: columns2,
|
|
842
|
+
definition: indexDefinitionClean
|
|
843
|
+
});
|
|
844
|
+
const explain = await this.testQueryWithStats(builder, async (sql) => {
|
|
845
|
+
await sql.exec(query.build());
|
|
846
|
+
});
|
|
847
|
+
const explainCost = Number(explain.Plan["Total Cost"]);
|
|
848
|
+
const costDeltaPercentage = (previousCost - explainCost) / previousCost * 100;
|
|
849
|
+
if (previousCost > explainCost) {
|
|
850
|
+
console.log(
|
|
851
|
+
`${green(
|
|
852
|
+
`+${costDeltaPercentage.toFixed(2).padStart(5, "0")}%`
|
|
853
|
+
)} ${indexDefinition} `
|
|
854
|
+
);
|
|
855
|
+
iter = permutations.next(PROCEED);
|
|
856
|
+
} else {
|
|
857
|
+
console.log(
|
|
858
|
+
`${previousCost === explainCost ? ` ${gray("00.00%")}` : `${red(
|
|
859
|
+
`-${Math.abs(costDeltaPercentage).toFixed(2).padStart(5, "0")}%`
|
|
860
|
+
)}`} ${indexDefinition}`
|
|
861
|
+
);
|
|
862
|
+
iter = permutations.next(PROCEED);
|
|
863
|
+
}
|
|
864
|
+
nextStage.push({
|
|
865
|
+
name: indexName,
|
|
866
|
+
schema,
|
|
867
|
+
table,
|
|
868
|
+
columns: columns2
|
|
869
|
+
});
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
const finalExplain = await this.testQueryWithStats(builder, async (sql) => {
|
|
873
|
+
for (const permutation of nextStage) {
|
|
874
|
+
const indexName = permutation.name;
|
|
875
|
+
await sql.exec(
|
|
876
|
+
`create index "${indexName}" on ${this.toDefinition(permutation).raw}; -- @qd_introspection`
|
|
877
|
+
);
|
|
878
|
+
}
|
|
879
|
+
});
|
|
880
|
+
const finalCost = Number(finalExplain.Plan["Total Cost"]);
|
|
881
|
+
if (this.config.debug) {
|
|
882
|
+
console.dir(finalExplain, { depth: null });
|
|
883
|
+
}
|
|
884
|
+
const deltaPercentage = (baseCost - finalCost) / baseCost * 100;
|
|
885
|
+
if (finalCost < baseCost) {
|
|
886
|
+
console.log(
|
|
887
|
+
` \u{1F389}\u{1F389}\u{1F389} ${green(`+${deltaPercentage.toFixed(2).padStart(5, "0")}%`)}`
|
|
888
|
+
);
|
|
889
|
+
} else if (finalCost > baseCost) {
|
|
890
|
+
console.log(
|
|
891
|
+
`${red(
|
|
892
|
+
`-${Math.abs(deltaPercentage).toFixed(2).padStart(5, "0")}%`
|
|
893
|
+
)} ${gray("If there's a better index, we haven't tried it")}`
|
|
894
|
+
);
|
|
895
|
+
}
|
|
896
|
+
const { newIndexes, existingIndexes: existingIndexesUsedByQuery } = this.findUsedIndexes(finalExplain.Plan);
|
|
897
|
+
return {
|
|
898
|
+
kind: "ok",
|
|
899
|
+
baseCost,
|
|
900
|
+
finalCost,
|
|
901
|
+
newIndexes,
|
|
902
|
+
existingIndexes: existingIndexesUsedByQuery,
|
|
903
|
+
triedIndexes,
|
|
904
|
+
baseExplainPlan: baseExplain,
|
|
905
|
+
explainPlan: finalExplain
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
async runWithoutIndexes(builder) {
|
|
909
|
+
return await this.testQueryWithStats(builder, async (tx) => {
|
|
910
|
+
await this.dropExistingIndexes(tx);
|
|
911
|
+
});
|
|
912
|
+
}
|
|
913
|
+
/**
|
|
914
|
+
* Postgres has a limit of 63 characters for index names.
|
|
915
|
+
* So we use this to make sure we don't derive it from a list of columns that can
|
|
916
|
+
* overflow that limit.
|
|
917
|
+
*/
|
|
918
|
+
indexName() {
|
|
919
|
+
return _IndexOptimizer.prefix + Math.random().toString(36).substring(2, 16);
|
|
920
|
+
}
|
|
921
|
+
// TODO: this doesn't belong in the optimizer
|
|
922
|
+
indexAlreadyExists(table, columns) {
|
|
923
|
+
return this.existingIndexes.find(
|
|
924
|
+
(index) => index.index_type === "btree" && index.table_name === table && index.index_columns.length === columns.length && index.index_columns.every((c, i) => columns[i].column === c.name)
|
|
925
|
+
);
|
|
926
|
+
}
|
|
927
|
+
toDefinition(permuted) {
|
|
928
|
+
const make = (col, order, where, keyword) => {
|
|
929
|
+
const baseColumn = `"${permuted.schema}"."${permuted.table}"(${permuted.columns.map((c) => {
|
|
930
|
+
const direction = c.sort && this.sortDirection(c.sort);
|
|
931
|
+
const nulls = c.sort && this.nullsOrder(c.sort);
|
|
932
|
+
let sort = col(`"${c.column}"`);
|
|
933
|
+
if (direction) {
|
|
934
|
+
sort += ` ${order(direction)}`;
|
|
935
|
+
}
|
|
936
|
+
if (nulls) {
|
|
937
|
+
sort += ` ${order(nulls)}`;
|
|
938
|
+
}
|
|
939
|
+
return sort;
|
|
940
|
+
}).join(", ")})`;
|
|
941
|
+
return baseColumn;
|
|
942
|
+
};
|
|
943
|
+
const id = (a) => a;
|
|
944
|
+
const raw = make(id, id, id, id);
|
|
945
|
+
const colored = make(green, yellow, magenta, blue2);
|
|
946
|
+
return { raw, colored };
|
|
947
|
+
}
|
|
948
|
+
/**
|
|
949
|
+
* Drop indexes that can be dropped (non-primary keys)
|
|
950
|
+
*/
|
|
951
|
+
async dropExistingIndexes(tx) {
|
|
952
|
+
for (const index of this.existingIndexes) {
|
|
953
|
+
if (index.is_primary) {
|
|
954
|
+
continue;
|
|
955
|
+
}
|
|
956
|
+
await tx.exec(
|
|
957
|
+
`drop index if exists ${index.schema_name}.${index.index_name} cascade`
|
|
958
|
+
);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
whereClause(c, col, keyword) {
|
|
962
|
+
if (!c.where) {
|
|
963
|
+
return "";
|
|
964
|
+
}
|
|
965
|
+
if (c.where.nulltest === "IS_NULL") {
|
|
966
|
+
return `${col(`"${c.column}"`)} is ${keyword("null")}`;
|
|
967
|
+
}
|
|
968
|
+
if (c.where.nulltest === "IS_NOT_NULL") {
|
|
969
|
+
return `${col(`"${c.column}"`)} is not ${keyword("null")}`;
|
|
970
|
+
}
|
|
971
|
+
return "";
|
|
972
|
+
}
|
|
973
|
+
nullsOrder(s) {
|
|
974
|
+
if (!s.nulls) {
|
|
975
|
+
return "";
|
|
976
|
+
}
|
|
977
|
+
switch (s.nulls) {
|
|
978
|
+
case "SORTBY_NULLS_FIRST":
|
|
979
|
+
return "nulls first";
|
|
980
|
+
case "SORTBY_NULLS_LAST":
|
|
981
|
+
return "nulls last";
|
|
982
|
+
case "SORTBY_NULLS_DEFAULT":
|
|
983
|
+
default:
|
|
984
|
+
return "";
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
sortDirection(s) {
|
|
988
|
+
if (!s.dir) {
|
|
989
|
+
return "";
|
|
990
|
+
}
|
|
991
|
+
switch (s.dir) {
|
|
992
|
+
case "SORTBY_DESC":
|
|
993
|
+
return "desc";
|
|
994
|
+
case "SORTBY_ASC":
|
|
995
|
+
return "asc";
|
|
996
|
+
case "SORTBY_DEFAULT":
|
|
997
|
+
// god help us if we ever run into this
|
|
998
|
+
case "SORTBY_USING":
|
|
999
|
+
default:
|
|
1000
|
+
return "";
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
async testQueryWithStats(builder, f, options) {
|
|
1004
|
+
try {
|
|
1005
|
+
await this.db.transaction(async (tx) => {
|
|
1006
|
+
await f?.(tx);
|
|
1007
|
+
await this.statistics.restoreStats(tx);
|
|
1008
|
+
const flags = ["format json", "trace"];
|
|
1009
|
+
if (options && !options.genericPlan) {
|
|
1010
|
+
flags.push("analyze");
|
|
1011
|
+
} else {
|
|
1012
|
+
flags.push("generic_plan");
|
|
1013
|
+
}
|
|
1014
|
+
const { commands, query } = builder.explain(flags).buildParts();
|
|
1015
|
+
await tx.exec(commands);
|
|
1016
|
+
const result = await tx.exec(
|
|
1017
|
+
query,
|
|
1018
|
+
options?.params
|
|
1019
|
+
);
|
|
1020
|
+
const explain = result[0]["QUERY PLAN"][0];
|
|
1021
|
+
throw new RollbackError(explain);
|
|
1022
|
+
});
|
|
1023
|
+
} catch (error) {
|
|
1024
|
+
if (error instanceof RollbackError) {
|
|
1025
|
+
return error.value;
|
|
1026
|
+
}
|
|
1027
|
+
throw error;
|
|
1028
|
+
}
|
|
1029
|
+
throw new Error("Unreachable");
|
|
1030
|
+
}
|
|
1031
|
+
tableColumnIndexCandidates(indexes) {
|
|
1032
|
+
const tableColumns = /* @__PURE__ */ new Map();
|
|
1033
|
+
for (const index of indexes) {
|
|
1034
|
+
const existing = tableColumns.get(`${index.schema}.${index.table}`);
|
|
1035
|
+
if (existing) {
|
|
1036
|
+
existing.columns.push(index);
|
|
1037
|
+
} else {
|
|
1038
|
+
tableColumns.set(`${index.schema}.${index.table}`, {
|
|
1039
|
+
table: index.table,
|
|
1040
|
+
schema: index.schema,
|
|
1041
|
+
columns: [index]
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
return tableColumns;
|
|
1046
|
+
}
|
|
1047
|
+
findUsedIndexes(explain) {
|
|
1048
|
+
const newIndexes = /* @__PURE__ */ new Set();
|
|
1049
|
+
const existingIndexes = /* @__PURE__ */ new Set();
|
|
1050
|
+
function go(plan) {
|
|
1051
|
+
const indexName = plan["Index Name"];
|
|
1052
|
+
if (indexName) {
|
|
1053
|
+
if (indexName.startsWith(_IndexOptimizer.prefix)) {
|
|
1054
|
+
newIndexes.add(indexName);
|
|
1055
|
+
} else {
|
|
1056
|
+
existingIndexes.add(indexName);
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
if (plan.Plans) {
|
|
1060
|
+
for (const p of plan.Plans) {
|
|
1061
|
+
go(p);
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
go(explain);
|
|
1066
|
+
return {
|
|
1067
|
+
newIndexes,
|
|
1068
|
+
existingIndexes
|
|
1069
|
+
};
|
|
1070
|
+
}
|
|
1071
|
+
};
|
|
1072
|
+
__publicField(_IndexOptimizer, "prefix", "__qd_");
|
|
1073
|
+
var IndexOptimizer = _IndexOptimizer;
|
|
1074
|
+
var RollbackError = class {
|
|
1075
|
+
constructor(value) {
|
|
1076
|
+
this.value = value;
|
|
1077
|
+
}
|
|
1078
|
+
};
|
|
1079
|
+
var PROCEED = Symbol("PROCEED");
|
|
1080
|
+
var SKIP = Symbol("SKIP");
|
|
1081
|
+
function* permuteWithFeedback(arr) {
|
|
1082
|
+
function* helper(path, rest) {
|
|
1083
|
+
let i = 0;
|
|
1084
|
+
while (i < rest.length) {
|
|
1085
|
+
const nextPath = [...path, rest[i]];
|
|
1086
|
+
const nextRest = [...rest.slice(0, i), ...rest.slice(i + 1)];
|
|
1087
|
+
const input = yield nextPath;
|
|
1088
|
+
if (input === PROCEED) {
|
|
1089
|
+
yield* helper(nextPath, nextRest);
|
|
1090
|
+
}
|
|
1091
|
+
i++;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
yield* helper([], arr);
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
// src/optimizer/statistics.ts
|
|
1098
|
+
import { gray as gray2 } from "colorette";
|
|
1099
|
+
import dedent from "dedent";
|
|
1100
|
+
import { z as z2 } from "zod";
|
|
1101
|
+
var StatisticsSource = z2.union([
|
|
1102
|
+
z2.object({
|
|
1103
|
+
kind: z2.literal("path"),
|
|
1104
|
+
path: z2.string().min(1)
|
|
1105
|
+
}),
|
|
1106
|
+
z2.object({
|
|
1107
|
+
kind: z2.literal("inline")
|
|
1108
|
+
})
|
|
1109
|
+
]);
|
|
1110
|
+
var ExportedStatsStatistics = z2.object({
|
|
1111
|
+
stawidth: z2.number(),
|
|
1112
|
+
stainherit: z2.boolean().default(false),
|
|
1113
|
+
// 0 representing unknown
|
|
1114
|
+
stadistinct: z2.number(),
|
|
1115
|
+
// this has no "nullable" state
|
|
1116
|
+
stanullfrac: z2.number(),
|
|
1117
|
+
stakind1: z2.number().min(0),
|
|
1118
|
+
stakind2: z2.number().min(0),
|
|
1119
|
+
stakind3: z2.number().min(0),
|
|
1120
|
+
stakind4: z2.number().min(0),
|
|
1121
|
+
stakind5: z2.number().min(0),
|
|
1122
|
+
staop1: z2.string(),
|
|
1123
|
+
staop2: z2.string(),
|
|
1124
|
+
staop3: z2.string(),
|
|
1125
|
+
staop4: z2.string(),
|
|
1126
|
+
staop5: z2.string(),
|
|
1127
|
+
stacoll1: z2.string(),
|
|
1128
|
+
stacoll2: z2.string(),
|
|
1129
|
+
stacoll3: z2.string(),
|
|
1130
|
+
stacoll4: z2.string(),
|
|
1131
|
+
stacoll5: z2.string(),
|
|
1132
|
+
stanumbers1: z2.array(z2.number()).nullable(),
|
|
1133
|
+
stanumbers2: z2.array(z2.number()).nullable(),
|
|
1134
|
+
stanumbers3: z2.array(z2.number()).nullable(),
|
|
1135
|
+
stanumbers4: z2.array(z2.number()).nullable(),
|
|
1136
|
+
stanumbers5: z2.array(z2.number()).nullable(),
|
|
1137
|
+
// theoretically... this could only be strings and numbers
|
|
1138
|
+
// but we don't have a crystal ball
|
|
1139
|
+
stavalues1: z2.array(z2.any()).nullable(),
|
|
1140
|
+
stavalues2: z2.array(z2.any()).nullable(),
|
|
1141
|
+
stavalues3: z2.array(z2.any()).nullable(),
|
|
1142
|
+
stavalues4: z2.array(z2.any()).nullable(),
|
|
1143
|
+
stavalues5: z2.array(z2.any()).nullable()
|
|
1144
|
+
});
|
|
1145
|
+
var ExportedStatsColumns = z2.object({
|
|
1146
|
+
columnName: z2.string(),
|
|
1147
|
+
stats: ExportedStatsStatistics.nullable(),
|
|
1148
|
+
dataType: z2.string(),
|
|
1149
|
+
isNullable: z2.boolean(),
|
|
1150
|
+
numericScale: z2.number().nullable(),
|
|
1151
|
+
columnDefault: z2.string().nullable(),
|
|
1152
|
+
numericPrecision: z2.number().nullable(),
|
|
1153
|
+
characterMaximumLength: z2.number().nullable()
|
|
1154
|
+
});
|
|
1155
|
+
var ExportedStatsIndex = z2.object({
|
|
1156
|
+
indexName: z2.string(),
|
|
1157
|
+
relpages: z2.number(),
|
|
1158
|
+
reltuples: z2.number(),
|
|
1159
|
+
relallvisible: z2.number(),
|
|
1160
|
+
relallfrozen: z2.number().optional()
|
|
1161
|
+
});
|
|
1162
|
+
var ExportedStatsV1 = z2.object({
|
|
1163
|
+
tableName: z2.string(),
|
|
1164
|
+
schemaName: z2.string(),
|
|
1165
|
+
// can be negative
|
|
1166
|
+
relpages: z2.number(),
|
|
1167
|
+
// can be negative
|
|
1168
|
+
reltuples: z2.number(),
|
|
1169
|
+
relallvisible: z2.number(),
|
|
1170
|
+
// only postgres 18+
|
|
1171
|
+
relallfrozen: z2.number().optional(),
|
|
1172
|
+
columns: z2.array(ExportedStatsColumns).nullable(),
|
|
1173
|
+
indexes: z2.array(ExportedStatsIndex)
|
|
1174
|
+
});
|
|
1175
|
+
var ExportedStats = z2.union([ExportedStatsV1]);
|
|
1176
|
+
var StatisticsMode = z2.discriminatedUnion("kind", [
|
|
1177
|
+
z2.object({
|
|
1178
|
+
kind: z2.literal("fromAssumption"),
|
|
1179
|
+
reltuples: z2.number().min(0),
|
|
1180
|
+
relpages: z2.number().min(0)
|
|
1181
|
+
}),
|
|
1182
|
+
z2.object({
|
|
1183
|
+
kind: z2.literal("fromStatisticsExport"),
|
|
1184
|
+
stats: z2.array(ExportedStats),
|
|
1185
|
+
source: StatisticsSource
|
|
1186
|
+
})
|
|
1187
|
+
]);
|
|
1188
|
+
var DEFAULT_RELTUPLES = 1e4;
|
|
1189
|
+
var DEFAULT_RELPAGES = 1;
|
|
1190
|
+
var _Statistics = class _Statistics {
|
|
1191
|
+
constructor(db, postgresVersion, ownMetadata, statsMode) {
|
|
1192
|
+
this.db = db;
|
|
1193
|
+
this.postgresVersion = postgresVersion;
|
|
1194
|
+
this.ownMetadata = ownMetadata;
|
|
1195
|
+
__publicField(this, "mode");
|
|
1196
|
+
__publicField(this, "exportedMetadata");
|
|
1197
|
+
if (statsMode) {
|
|
1198
|
+
this.mode = statsMode;
|
|
1199
|
+
if (statsMode.kind === "fromStatisticsExport") {
|
|
1200
|
+
this.exportedMetadata = statsMode.stats;
|
|
1201
|
+
}
|
|
1202
|
+
} else {
|
|
1203
|
+
this.mode = _Statistics.defaultStatsMode;
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
static statsModeFromAssumption({
|
|
1207
|
+
reltuples,
|
|
1208
|
+
relpages
|
|
1209
|
+
}) {
|
|
1210
|
+
return {
|
|
1211
|
+
kind: "fromAssumption",
|
|
1212
|
+
reltuples,
|
|
1213
|
+
relpages
|
|
1214
|
+
};
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* Create a statistic mode from stats exported from another database
|
|
1218
|
+
**/
|
|
1219
|
+
static statsModeFromExport(stats) {
|
|
1220
|
+
return {
|
|
1221
|
+
kind: "fromStatisticsExport",
|
|
1222
|
+
source: { kind: "inline" },
|
|
1223
|
+
stats
|
|
1224
|
+
};
|
|
1225
|
+
}
|
|
1226
|
+
static async fromPostgres(db, statsMode) {
|
|
1227
|
+
const version = await db.serverNum();
|
|
1228
|
+
const ownStats = await _Statistics.dumpStats(db, version, "full");
|
|
1229
|
+
return new _Statistics(db, version, ownStats, statsMode);
|
|
1230
|
+
}
|
|
1231
|
+
restoreStats(tx) {
|
|
1232
|
+
return this.restoreStats17(tx);
|
|
1233
|
+
}
|
|
1234
|
+
/**
|
|
1235
|
+
* We have to cast stavaluesN to the correct type
|
|
1236
|
+
* This derives that type for us so it can be used in `array_in`
|
|
1237
|
+
*/
|
|
1238
|
+
stavalueKind(values) {
|
|
1239
|
+
if (!values || values.length === 0) {
|
|
1240
|
+
return null;
|
|
1241
|
+
}
|
|
1242
|
+
const [elem] = values;
|
|
1243
|
+
if (typeof elem === "number") {
|
|
1244
|
+
return "real";
|
|
1245
|
+
} else if (typeof elem === "boolean") {
|
|
1246
|
+
return "boolean";
|
|
1247
|
+
}
|
|
1248
|
+
return "text";
|
|
1249
|
+
}
|
|
1250
|
+
async restoreStats17(tx) {
|
|
1251
|
+
const warnings = {
|
|
1252
|
+
tablesNotInExports: [],
|
|
1253
|
+
tablesNotInTest: [],
|
|
1254
|
+
tableNotAnalyzed: [],
|
|
1255
|
+
statsMissing: []
|
|
1256
|
+
};
|
|
1257
|
+
const processedTables = /* @__PURE__ */ new Set();
|
|
1258
|
+
let columnStatsUpdatePromise;
|
|
1259
|
+
const columnStatsValues = [];
|
|
1260
|
+
if (this.exportedMetadata) {
|
|
1261
|
+
for (const table of this.ownMetadata) {
|
|
1262
|
+
const targetTable = this.exportedMetadata.find(
|
|
1263
|
+
(m) => m.tableName === table.tableName && m.schemaName === table.schemaName
|
|
1264
|
+
);
|
|
1265
|
+
if (!targetTable?.columns) {
|
|
1266
|
+
continue;
|
|
1267
|
+
}
|
|
1268
|
+
for (const column of targetTable.columns) {
|
|
1269
|
+
const { stats } = column;
|
|
1270
|
+
if (!stats) {
|
|
1271
|
+
continue;
|
|
1272
|
+
}
|
|
1273
|
+
columnStatsValues.push({
|
|
1274
|
+
schema_name: table.schemaName,
|
|
1275
|
+
table_name: table.tableName,
|
|
1276
|
+
column_name: column.columnName,
|
|
1277
|
+
stainherit: stats.stainherit ?? false,
|
|
1278
|
+
stanullfrac: stats.stanullfrac,
|
|
1279
|
+
stawidth: stats.stawidth,
|
|
1280
|
+
stadistinct: stats.stadistinct,
|
|
1281
|
+
stakind1: stats.stakind1,
|
|
1282
|
+
stakind2: stats.stakind2,
|
|
1283
|
+
stakind3: stats.stakind3,
|
|
1284
|
+
stakind4: stats.stakind4,
|
|
1285
|
+
stakind5: stats.stakind5,
|
|
1286
|
+
staop1: stats.staop1,
|
|
1287
|
+
staop2: stats.staop2,
|
|
1288
|
+
staop3: stats.staop3,
|
|
1289
|
+
staop4: stats.staop4,
|
|
1290
|
+
staop5: stats.staop5,
|
|
1291
|
+
stacoll1: stats.stacoll1,
|
|
1292
|
+
stacoll2: stats.stacoll2,
|
|
1293
|
+
stacoll3: stats.stacoll3,
|
|
1294
|
+
stacoll4: stats.stacoll4,
|
|
1295
|
+
stacoll5: stats.stacoll5,
|
|
1296
|
+
stanumbers1: stats.stanumbers1,
|
|
1297
|
+
stanumbers2: stats.stanumbers2,
|
|
1298
|
+
stanumbers3: stats.stanumbers3,
|
|
1299
|
+
stanumbers4: stats.stanumbers4,
|
|
1300
|
+
stanumbers5: stats.stanumbers5,
|
|
1301
|
+
stavalues1: stats.stavalues1,
|
|
1302
|
+
stavalues2: stats.stavalues2,
|
|
1303
|
+
stavalues3: stats.stavalues3,
|
|
1304
|
+
stavalues4: stats.stavalues4,
|
|
1305
|
+
stavalues5: stats.stavalues5,
|
|
1306
|
+
_value_type1: this.stavalueKind(stats.stavalues1),
|
|
1307
|
+
_value_type2: this.stavalueKind(stats.stavalues2),
|
|
1308
|
+
_value_type3: this.stavalueKind(stats.stavalues3),
|
|
1309
|
+
_value_type4: this.stavalueKind(stats.stavalues4),
|
|
1310
|
+
_value_type5: this.stavalueKind(stats.stavalues5)
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
const sql = dedent`
|
|
1315
|
+
WITH input AS (
|
|
1316
|
+
SELECT
|
|
1317
|
+
c.oid AS starelid,
|
|
1318
|
+
a.attnum AS staattnum,
|
|
1319
|
+
v.stainherit,
|
|
1320
|
+
v.stanullfrac,
|
|
1321
|
+
v.stawidth,
|
|
1322
|
+
v.stadistinct,
|
|
1323
|
+
v.stakind1,
|
|
1324
|
+
v.stakind2,
|
|
1325
|
+
v.stakind3,
|
|
1326
|
+
v.stakind4,
|
|
1327
|
+
v.stakind5,
|
|
1328
|
+
v.staop1,
|
|
1329
|
+
v.staop2,
|
|
1330
|
+
v.staop3,
|
|
1331
|
+
v.staop4,
|
|
1332
|
+
v.staop5,
|
|
1333
|
+
v.stacoll1,
|
|
1334
|
+
v.stacoll2,
|
|
1335
|
+
v.stacoll3,
|
|
1336
|
+
v.stacoll4,
|
|
1337
|
+
v.stacoll5,
|
|
1338
|
+
v.stanumbers1,
|
|
1339
|
+
v.stanumbers2,
|
|
1340
|
+
v.stanumbers3,
|
|
1341
|
+
v.stanumbers4,
|
|
1342
|
+
v.stanumbers5,
|
|
1343
|
+
v.stavalues1,
|
|
1344
|
+
v.stavalues2,
|
|
1345
|
+
v.stavalues3,
|
|
1346
|
+
v.stavalues4,
|
|
1347
|
+
v.stavalues5,
|
|
1348
|
+
_value_type1,
|
|
1349
|
+
_value_type2,
|
|
1350
|
+
_value_type3,
|
|
1351
|
+
_value_type4,
|
|
1352
|
+
_value_type5
|
|
1353
|
+
FROM jsonb_to_recordset($1::jsonb) AS v(
|
|
1354
|
+
schema_name text,
|
|
1355
|
+
table_name text,
|
|
1356
|
+
column_name text,
|
|
1357
|
+
stainherit boolean,
|
|
1358
|
+
stanullfrac real,
|
|
1359
|
+
stawidth integer,
|
|
1360
|
+
stadistinct real,
|
|
1361
|
+
stakind1 real,
|
|
1362
|
+
stakind2 real,
|
|
1363
|
+
stakind3 real,
|
|
1364
|
+
stakind4 real,
|
|
1365
|
+
stakind5 real,
|
|
1366
|
+
staop1 oid,
|
|
1367
|
+
staop2 oid,
|
|
1368
|
+
staop3 oid,
|
|
1369
|
+
staop4 oid,
|
|
1370
|
+
staop5 oid,
|
|
1371
|
+
stacoll1 oid,
|
|
1372
|
+
stacoll2 oid,
|
|
1373
|
+
stacoll3 oid,
|
|
1374
|
+
stacoll4 oid,
|
|
1375
|
+
stacoll5 oid,
|
|
1376
|
+
stanumbers1 real[],
|
|
1377
|
+
stanumbers2 real[],
|
|
1378
|
+
stanumbers3 real[],
|
|
1379
|
+
stanumbers4 real[],
|
|
1380
|
+
stanumbers5 real[],
|
|
1381
|
+
stavalues1 text[],
|
|
1382
|
+
stavalues2 text[],
|
|
1383
|
+
stavalues3 text[],
|
|
1384
|
+
stavalues4 text[],
|
|
1385
|
+
stavalues5 text[],
|
|
1386
|
+
_value_type1 text,
|
|
1387
|
+
_value_type2 text,
|
|
1388
|
+
_value_type3 text,
|
|
1389
|
+
_value_type4 text,
|
|
1390
|
+
_value_type5 text
|
|
1391
|
+
)
|
|
1392
|
+
JOIN pg_class c ON c.relname = v.table_name
|
|
1393
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace AND n.nspname = v.schema_name
|
|
1394
|
+
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attname = v.column_name
|
|
1395
|
+
),
|
|
1396
|
+
updated AS (
|
|
1397
|
+
UPDATE pg_statistic s
|
|
1398
|
+
SET
|
|
1399
|
+
stanullfrac = i.stanullfrac,
|
|
1400
|
+
stawidth = i.stawidth,
|
|
1401
|
+
stadistinct = i.stadistinct,
|
|
1402
|
+
stakind1 = i.stakind1,
|
|
1403
|
+
stakind2 = i.stakind2,
|
|
1404
|
+
stakind3 = i.stakind3,
|
|
1405
|
+
stakind4 = i.stakind4,
|
|
1406
|
+
stakind5 = i.stakind5,
|
|
1407
|
+
staop1 = i.staop1,
|
|
1408
|
+
staop2 = i.staop2,
|
|
1409
|
+
staop3 = i.staop3,
|
|
1410
|
+
staop4 = i.staop4,
|
|
1411
|
+
staop5 = i.staop5,
|
|
1412
|
+
stacoll1 = i.stacoll1,
|
|
1413
|
+
stacoll2 = i.stacoll2,
|
|
1414
|
+
stacoll3 = i.stacoll3,
|
|
1415
|
+
stacoll4 = i.stacoll4,
|
|
1416
|
+
stacoll5 = i.stacoll5,
|
|
1417
|
+
stanumbers1 = i.stanumbers1,
|
|
1418
|
+
stanumbers2 = i.stanumbers2,
|
|
1419
|
+
stanumbers3 = i.stanumbers3,
|
|
1420
|
+
stanumbers4 = i.stanumbers4,
|
|
1421
|
+
stanumbers5 = i.stanumbers5,
|
|
1422
|
+
stavalues1 = case
|
|
1423
|
+
when i.stavalues1 is null then null
|
|
1424
|
+
else array_in(i.stavalues1::text::cstring, i._value_type1::regtype::oid, -1)
|
|
1425
|
+
end,
|
|
1426
|
+
stavalues2 = case
|
|
1427
|
+
when i.stavalues2 is null then null
|
|
1428
|
+
else array_in(i.stavalues2::text::cstring, i._value_type2::regtype::oid, -1)
|
|
1429
|
+
end,
|
|
1430
|
+
stavalues3 = case
|
|
1431
|
+
when i.stavalues3 is null then null
|
|
1432
|
+
else array_in(i.stavalues3::text::cstring, i._value_type3::regtype::oid, -1)
|
|
1433
|
+
end,
|
|
1434
|
+
stavalues4 = case
|
|
1435
|
+
when i.stavalues4 is null then null
|
|
1436
|
+
else array_in(i.stavalues4::text::cstring, i._value_type4::regtype::oid, -1)
|
|
1437
|
+
end,
|
|
1438
|
+
stavalues5 = case
|
|
1439
|
+
when i.stavalues5 is null then null
|
|
1440
|
+
else array_in(i.stavalues5::text::cstring, i._value_type5::regtype::oid, -1)
|
|
1441
|
+
end
|
|
1442
|
+
-- stavalues1 = i.stavalues1,
|
|
1443
|
+
-- stavalues2 = i.stavalues2,
|
|
1444
|
+
-- stavalues3 = i.stavalues3,
|
|
1445
|
+
-- stavalues4 = i.stavalues4,
|
|
1446
|
+
-- stavalues5 = i.stavalues5
|
|
1447
|
+
FROM input i
|
|
1448
|
+
WHERE s.starelid = i.starelid AND s.staattnum = i.staattnum AND s.stainherit = i.stainherit
|
|
1449
|
+
RETURNING s.starelid, s.staattnum, s.stainherit, s.stakind1, s.stakind2, s.stakind3, s.stakind4, s.stakind5
|
|
1450
|
+
),
|
|
1451
|
+
inserted as (
|
|
1452
|
+
INSERT INTO pg_statistic (
|
|
1453
|
+
starelid, staattnum, stainherit,
|
|
1454
|
+
stanullfrac, stawidth, stadistinct,
|
|
1455
|
+
stakind1, stakind2, stakind3, stakind4, stakind5,
|
|
1456
|
+
staop1, staop2, staop3, staop4, staop5,
|
|
1457
|
+
stacoll1, stacoll2, stacoll3, stacoll4, stacoll5,
|
|
1458
|
+
stanumbers1, stanumbers2, stanumbers3, stanumbers4, stanumbers5,
|
|
1459
|
+
stavalues1, stavalues2, stavalues3, stavalues4, stavalues5
|
|
1460
|
+
)
|
|
1461
|
+
SELECT
|
|
1462
|
+
i.starelid, i.staattnum, i.stainherit,
|
|
1463
|
+
i.stanullfrac, i.stawidth, i.stadistinct,
|
|
1464
|
+
i.stakind1, i.stakind2, i.stakind3, i.stakind4, i.stakind5,
|
|
1465
|
+
i.staop1, i.staop2, i.staop3, i.staop4, i.staop5,
|
|
1466
|
+
i.stacoll1, i.stacoll2, i.stacoll3, i.stacoll4, i.stacoll5,
|
|
1467
|
+
i.stanumbers1, i.stanumbers2, i.stanumbers3, i.stanumbers4, i.stanumbers5,
|
|
1468
|
+
-- i.stavalues1, i.stavalues2, i.stavalues3, i.stavalues4, i.stavalues5,
|
|
1469
|
+
case
|
|
1470
|
+
when i.stavalues1 is null then null
|
|
1471
|
+
else array_in(i.stavalues1::text::cstring, i._value_type1::regtype::oid, -1)
|
|
1472
|
+
end,
|
|
1473
|
+
case
|
|
1474
|
+
when i.stavalues2 is null then null
|
|
1475
|
+
else array_in(i.stavalues2::text::cstring, i._value_type2::regtype::oid, -1)
|
|
1476
|
+
end,
|
|
1477
|
+
case
|
|
1478
|
+
when i.stavalues3 is null then null
|
|
1479
|
+
else array_in(i.stavalues3::text::cstring, i._value_type3::regtype::oid, -1)
|
|
1480
|
+
end,
|
|
1481
|
+
case
|
|
1482
|
+
when i.stavalues4 is null then null
|
|
1483
|
+
else array_in(i.stavalues4::text::cstring, i._value_type4::regtype::oid, -1)
|
|
1484
|
+
end,
|
|
1485
|
+
case
|
|
1486
|
+
when i.stavalues5 is null then null
|
|
1487
|
+
else array_in(i.stavalues5::text::cstring, i._value_type5::regtype::oid, -1)
|
|
1488
|
+
end
|
|
1489
|
+
-- i._value_type1, i._value_type2, i._value_type3, i._value_type4, i._value_type5
|
|
1490
|
+
FROM input i
|
|
1491
|
+
LEFT JOIN updated u
|
|
1492
|
+
ON i.starelid = u.starelid AND i.staattnum = u.staattnum AND i.stainherit = u.stainherit
|
|
1493
|
+
WHERE u.starelid IS NULL
|
|
1494
|
+
returning starelid, staattnum, stainherit, stakind1, stakind2, stakind3, stakind4, stakind5
|
|
1495
|
+
)
|
|
1496
|
+
select * from updated union all (select * from inserted); -- @qd_introspection`;
|
|
1497
|
+
columnStatsUpdatePromise = tx.exec(sql, [columnStatsValues]).catch((err) => {
|
|
1498
|
+
console.error("Something wrong wrong updating column stats");
|
|
1499
|
+
console.error(err);
|
|
1500
|
+
throw err;
|
|
1501
|
+
});
|
|
1502
|
+
}
|
|
1503
|
+
const reltuplesValues = [];
|
|
1504
|
+
for (const table of this.ownMetadata) {
|
|
1505
|
+
if (!table.columns) {
|
|
1506
|
+
continue;
|
|
1507
|
+
}
|
|
1508
|
+
processedTables.add(`${table.schemaName}.${table.tableName}`);
|
|
1509
|
+
let targetTable;
|
|
1510
|
+
if (this.exportedMetadata) {
|
|
1511
|
+
targetTable = this.exportedMetadata.find(
|
|
1512
|
+
(m) => m.tableName === table.tableName && m.schemaName === table.schemaName
|
|
1513
|
+
);
|
|
1514
|
+
}
|
|
1515
|
+
let reltuples;
|
|
1516
|
+
let relpages;
|
|
1517
|
+
let relallvisible = 0;
|
|
1518
|
+
let relallfrozen;
|
|
1519
|
+
if (targetTable) {
|
|
1520
|
+
reltuples = targetTable.reltuples;
|
|
1521
|
+
relpages = targetTable.relpages;
|
|
1522
|
+
relallvisible = targetTable.relallvisible;
|
|
1523
|
+
relallfrozen = targetTable.relallfrozen;
|
|
1524
|
+
} else if (this.mode.kind === "fromAssumption") {
|
|
1525
|
+
reltuples = this.mode.reltuples;
|
|
1526
|
+
relpages = this.mode.relpages;
|
|
1527
|
+
} else {
|
|
1528
|
+
warnings.tablesNotInExports.push(
|
|
1529
|
+
`${table.schemaName}.${table.tableName}`
|
|
1530
|
+
);
|
|
1531
|
+
reltuples = DEFAULT_RELTUPLES;
|
|
1532
|
+
relpages = DEFAULT_RELPAGES;
|
|
1533
|
+
}
|
|
1534
|
+
reltuplesValues.push({
|
|
1535
|
+
relname: table.tableName,
|
|
1536
|
+
schema_name: table.schemaName,
|
|
1537
|
+
reltuples,
|
|
1538
|
+
relpages,
|
|
1539
|
+
relallfrozen,
|
|
1540
|
+
relallvisible
|
|
1541
|
+
});
|
|
1542
|
+
if (targetTable && targetTable.indexes) {
|
|
1543
|
+
for (const index of targetTable.indexes) {
|
|
1544
|
+
reltuplesValues.push({
|
|
1545
|
+
relname: index.indexName,
|
|
1546
|
+
schema_name: targetTable.schemaName,
|
|
1547
|
+
reltuples: index.reltuples,
|
|
1548
|
+
relpages: index.relpages,
|
|
1549
|
+
relallfrozen: index.relallfrozen,
|
|
1550
|
+
relallvisible: index.relallvisible
|
|
1551
|
+
});
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
const reltuplesQuery = dedent`
|
|
1556
|
+
update pg_class p
|
|
1557
|
+
set reltuples = v.reltuples,
|
|
1558
|
+
relpages = v.relpages,
|
|
1559
|
+
-- relallfrozen = case when v.relallfrozen is null then p.relallfrozen else v.relallfrozen end,
|
|
1560
|
+
relallvisible = case when v.relallvisible is null then p.relallvisible else v.relallvisible end
|
|
1561
|
+
from jsonb_to_recordset($1::jsonb)
|
|
1562
|
+
as v(reltuples real, relpages integer, relallfrozen integer, relallvisible integer, relname text, schema_name text)
|
|
1563
|
+
where p.relname = v.relname
|
|
1564
|
+
and p.relnamespace = (select oid from pg_namespace where nspname = v.schema_name)
|
|
1565
|
+
returning p.relname, p.relnamespace, p.reltuples, p.relpages;
|
|
1566
|
+
`;
|
|
1567
|
+
const reltuplesPromise = tx.exec(reltuplesQuery, [reltuplesValues]).catch((err) => {
|
|
1568
|
+
console.error("Something went wrong updating reltuples/relpages");
|
|
1569
|
+
console.error(err);
|
|
1570
|
+
return err;
|
|
1571
|
+
});
|
|
1572
|
+
if (this.exportedMetadata) {
|
|
1573
|
+
for (const table of this.exportedMetadata) {
|
|
1574
|
+
const tableExists = processedTables.has(
|
|
1575
|
+
`${table.schemaName}.${table.tableName}`
|
|
1576
|
+
);
|
|
1577
|
+
if (tableExists && table.reltuples === -1) {
|
|
1578
|
+
console.warn(
|
|
1579
|
+
`Table ${table.tableName} has reltuples -1. Your production database is probably not analyzed properly`
|
|
1580
|
+
);
|
|
1581
|
+
warnings.tableNotAnalyzed.push(
|
|
1582
|
+
`${table.schemaName}.${table.tableName}`
|
|
1583
|
+
);
|
|
1584
|
+
}
|
|
1585
|
+
if (tableExists) {
|
|
1586
|
+
continue;
|
|
1587
|
+
}
|
|
1588
|
+
warnings.tablesNotInTest.push(`${table.schemaName}.${table.tableName}`);
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
const [statsUpdates, reltuplesUpdates] = await Promise.all([
|
|
1592
|
+
columnStatsUpdatePromise,
|
|
1593
|
+
reltuplesPromise
|
|
1594
|
+
]);
|
|
1595
|
+
const updatedColumnsProperly = statsUpdates ? statsUpdates.length === columnStatsValues.length : true;
|
|
1596
|
+
if (!updatedColumnsProperly) {
|
|
1597
|
+
console.error(`Did not update expected column stats`);
|
|
1598
|
+
}
|
|
1599
|
+
if (reltuplesUpdates.length !== reltuplesValues.length) {
|
|
1600
|
+
console.error(`Did not update expected reltuples/relpages`);
|
|
1601
|
+
}
|
|
1602
|
+
return warnings;
|
|
1603
|
+
}
|
|
1604
|
+
static async dumpStats(db, postgresVersion, kind) {
|
|
1605
|
+
const fullDump = kind === "full";
|
|
1606
|
+
console.log(`dumping stats for postgres ${gray2(postgresVersion)}`);
|
|
1607
|
+
const stats = await db.exec(
|
|
1608
|
+
`
|
|
1609
|
+
WITH table_columns AS (
|
|
1610
|
+
SELECT
|
|
1611
|
+
c.table_name,
|
|
1612
|
+
c.table_schema,
|
|
1613
|
+
cl.reltuples,
|
|
1614
|
+
cl.relpages,
|
|
1615
|
+
cl.relallvisible,
|
|
1616
|
+
-- cl.relallfrozen,
|
|
1617
|
+
n.nspname AS schema_name,
|
|
1618
|
+
json_agg(
|
|
1619
|
+
json_build_object(
|
|
1620
|
+
'columnName', c.column_name,
|
|
1621
|
+
'dataType', c.data_type,
|
|
1622
|
+
'isNullable', (c.is_nullable = 'YES')::boolean,
|
|
1623
|
+
'characterMaximumLength', c.character_maximum_length,
|
|
1624
|
+
'numericPrecision', c.numeric_precision,
|
|
1625
|
+
'numericScale', c.numeric_scale,
|
|
1626
|
+
'columnDefault', c.column_default,
|
|
1627
|
+
'stats', (
|
|
1628
|
+
SELECT json_build_object(
|
|
1629
|
+
'starelid', s.starelid,
|
|
1630
|
+
'staattnum', s.staattnum,
|
|
1631
|
+
'stanullfrac', s.stanullfrac,
|
|
1632
|
+
'stawidth', s.stawidth,
|
|
1633
|
+
'stadistinct', s.stadistinct,
|
|
1634
|
+
'stakind1', s.stakind1, 'staop1', s.staop1, 'stacoll1', s.stacoll1, 'stanumbers1', s.stanumbers1,
|
|
1635
|
+
'stakind2', s.stakind2, 'staop2', s.staop2, 'stacoll2', s.stacoll2, 'stanumbers2', s.stanumbers2,
|
|
1636
|
+
'stakind3', s.stakind3, 'staop3', s.staop3, 'stacoll3', s.stacoll3, 'stanumbers3', s.stanumbers3,
|
|
1637
|
+
'stakind4', s.stakind4, 'staop4', s.staop4, 'stacoll4', s.stacoll4, 'stanumbers4', s.stanumbers4,
|
|
1638
|
+
'stakind5', s.stakind5, 'staop5', s.staop5, 'stacoll5', s.stacoll5, 'stanumbers5', s.stanumbers5,
|
|
1639
|
+
'stavalues1', CASE WHEN $1 THEN s.stavalues1 ELSE NULL END,
|
|
1640
|
+
'stavalues2', CASE WHEN $1 THEN s.stavalues2 ELSE NULL END,
|
|
1641
|
+
'stavalues3', CASE WHEN $1 THEN s.stavalues3 ELSE NULL END,
|
|
1642
|
+
'stavalues4', CASE WHEN $1 THEN s.stavalues4 ELSE NULL END,
|
|
1643
|
+
'stavalues5', CASE WHEN $1 THEN s.stavalues5 ELSE NULL END
|
|
1644
|
+
)
|
|
1645
|
+
FROM pg_statistic s
|
|
1646
|
+
WHERE s.starelid = a.attrelid AND s.staattnum = a.attnum
|
|
1647
|
+
)
|
|
1648
|
+
)
|
|
1649
|
+
ORDER BY c.ordinal_position
|
|
1650
|
+
) AS columns
|
|
1651
|
+
FROM information_schema.columns c
|
|
1652
|
+
JOIN pg_attribute a
|
|
1653
|
+
ON a.attrelid = (quote_ident(c.table_schema) || '.' || quote_ident(c.table_name))::regclass
|
|
1654
|
+
AND a.attname = c.column_name
|
|
1655
|
+
JOIN pg_class cl
|
|
1656
|
+
ON cl.oid = a.attrelid
|
|
1657
|
+
JOIN pg_namespace n
|
|
1658
|
+
ON n.oid = cl.relnamespace
|
|
1659
|
+
WHERE c.table_name NOT LIKE 'pg_%'
|
|
1660
|
+
AND n.nspname <> 'information_schema'
|
|
1661
|
+
AND c.table_name NOT IN ('pg_stat_statements', 'pg_stat_statements_info')
|
|
1662
|
+
GROUP BY c.table_name, c.table_schema, cl.reltuples, cl.relpages, cl.relallvisible, n.nspname
|
|
1663
|
+
),
|
|
1664
|
+
table_indexes AS (
|
|
1665
|
+
SELECT
|
|
1666
|
+
t.relname AS table_name,
|
|
1667
|
+
json_agg(
|
|
1668
|
+
json_build_object(
|
|
1669
|
+
'indexName', i.relname,
|
|
1670
|
+
'reltuples', i.reltuples,
|
|
1671
|
+
'relpages', i.relpages,
|
|
1672
|
+
'relallvisible', i.relallvisible
|
|
1673
|
+
-- 'relallfrozen', i.relallfrozen
|
|
1674
|
+
)
|
|
1675
|
+
) AS indexes
|
|
1676
|
+
FROM pg_class t
|
|
1677
|
+
JOIN pg_index ix ON ix.indrelid = t.oid
|
|
1678
|
+
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
1679
|
+
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
1680
|
+
WHERE t.relname NOT LIKE 'pg_%'
|
|
1681
|
+
AND n.nspname <> 'information_schema'
|
|
1682
|
+
GROUP BY t.relname
|
|
1683
|
+
)
|
|
1684
|
+
SELECT json_agg(
|
|
1685
|
+
json_build_object(
|
|
1686
|
+
'tableName', tc.table_name,
|
|
1687
|
+
'schemaName', tc.table_schema,
|
|
1688
|
+
'reltuples', tc.reltuples,
|
|
1689
|
+
'relpages', tc.relpages,
|
|
1690
|
+
'relallvisible', tc.relallvisible,
|
|
1691
|
+
-- 'relallfrozen', tc.relallfrozen,
|
|
1692
|
+
'columns', tc.columns,
|
|
1693
|
+
'indexes', COALESCE(ti.indexes, '[]'::json)
|
|
1694
|
+
)
|
|
1695
|
+
)
|
|
1696
|
+
FROM table_columns tc
|
|
1697
|
+
LEFT JOIN table_indexes ti
|
|
1698
|
+
ON ti.table_name = tc.table_name;
|
|
1699
|
+
`,
|
|
1700
|
+
[fullDump]
|
|
1701
|
+
);
|
|
1702
|
+
return stats[0].json_agg;
|
|
1703
|
+
}
|
|
1704
|
+
/**
|
|
1705
|
+
* Returns all indexes in the database.
|
|
1706
|
+
* ONLY handles regular btree indexes
|
|
1707
|
+
*/
|
|
1708
|
+
async getExistingIndexes() {
|
|
1709
|
+
const indexes = await this.db.exec(`
|
|
1710
|
+
WITH partitioned_tables AS (
|
|
1711
|
+
SELECT
|
|
1712
|
+
inhparent::regclass AS parent_table,
|
|
1713
|
+
inhrelid::regclass AS partition_table
|
|
1714
|
+
FROM
|
|
1715
|
+
pg_inherits
|
|
1716
|
+
)
|
|
1717
|
+
SELECT
|
|
1718
|
+
n.nspname AS schema_name,
|
|
1719
|
+
COALESCE(pt.parent_table::text, t.relname) AS table_name,
|
|
1720
|
+
i.relname AS index_name,
|
|
1721
|
+
ix.indisprimary as is_primary,
|
|
1722
|
+
am.amname AS index_type,
|
|
1723
|
+
array_agg(
|
|
1724
|
+
CASE
|
|
1725
|
+
-- Handle regular columns
|
|
1726
|
+
WHEN a.attname IS NOT NULL THEN
|
|
1727
|
+
json_build_object('name', a.attname, 'order',
|
|
1728
|
+
CASE
|
|
1729
|
+
WHEN (indoption[array_position(ix.indkey, a.attnum)] & 1) = 1 THEN 'DESC'
|
|
1730
|
+
ELSE 'ASC'
|
|
1731
|
+
END)
|
|
1732
|
+
-- Handle expressions
|
|
1733
|
+
ELSE
|
|
1734
|
+
json_build_object('name', pg_get_expr((ix.indexprs)::pg_node_tree, t.oid), 'order',
|
|
1735
|
+
CASE
|
|
1736
|
+
WHEN (indoption[array_position(ix.indkey, k.attnum)] & 1) = 1 THEN 'DESC'
|
|
1737
|
+
ELSE 'ASC'
|
|
1738
|
+
END)
|
|
1739
|
+
END
|
|
1740
|
+
ORDER BY array_position(ix.indkey, k.attnum)
|
|
1741
|
+
) AS index_columns
|
|
1742
|
+
FROM
|
|
1743
|
+
pg_class t
|
|
1744
|
+
LEFT JOIN partitioned_tables pt ON t.oid = pt.partition_table
|
|
1745
|
+
JOIN pg_index ix ON t.oid = ix.indrelid
|
|
1746
|
+
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
1747
|
+
JOIN pg_am am ON i.relam = am.oid
|
|
1748
|
+
LEFT JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY k(attnum, ordinality) ON true
|
|
1749
|
+
LEFT JOIN pg_attribute a ON a.attnum = k.attnum AND a.attrelid = t.oid
|
|
1750
|
+
JOIN pg_namespace n ON t.relnamespace = n.oid
|
|
1751
|
+
WHERE
|
|
1752
|
+
n.nspname = 'public'
|
|
1753
|
+
GROUP BY
|
|
1754
|
+
n.nspname, COALESCE(pt.parent_table::text, t.relname), i.relname, am.amname, ix.indisprimary
|
|
1755
|
+
ORDER BY
|
|
1756
|
+
COALESCE(pt.parent_table::text, t.relname), i.relname; -- @qd_introspection
|
|
1757
|
+
`);
|
|
1758
|
+
return indexes;
|
|
1759
|
+
}
|
|
1760
|
+
};
|
|
1761
|
+
// preventing accidental internal mutations
|
|
1762
|
+
__publicField(_Statistics, "defaultStatsMode", Object.freeze({
|
|
1763
|
+
kind: "fromAssumption",
|
|
1764
|
+
reltuples: DEFAULT_RELTUPLES,
|
|
1765
|
+
relpages: DEFAULT_RELPAGES
|
|
1766
|
+
}));
|
|
1767
|
+
var Statistics = _Statistics;
|
|
1768
|
+
export {
|
|
1769
|
+
Analyzer,
|
|
1770
|
+
ExportedStats,
|
|
1771
|
+
ExportedStatsColumns,
|
|
1772
|
+
ExportedStatsIndex,
|
|
1773
|
+
ExportedStatsStatistics,
|
|
1774
|
+
ExportedStatsV1,
|
|
1775
|
+
IndexOptimizer,
|
|
1776
|
+
PROCEED,
|
|
1777
|
+
PostgresQueryBuilder,
|
|
1778
|
+
PostgresVersion,
|
|
1779
|
+
SKIP,
|
|
1780
|
+
Statistics,
|
|
1781
|
+
StatisticsMode,
|
|
1782
|
+
StatisticsSource,
|
|
1783
|
+
ignoredIdentifier,
|
|
1784
|
+
parseNudges,
|
|
1785
|
+
permuteWithFeedback
|
|
1786
|
+
};
|
|
1787
|
+
//# sourceMappingURL=index.js.map
|