@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.js DELETED
@@ -1,2316 +0,0 @@
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
- if (is(node, "A_Expr")) {
143
- if (node.A_Expr.kind === "AEXPR_IN") {
144
- let list;
145
- if (node.A_Expr.lexpr && is(node.A_Expr.lexpr, "List")) {
146
- list = node.A_Expr.lexpr.List;
147
- } else if (node.A_Expr.rexpr && is(node.A_Expr.rexpr, "List")) {
148
- list = node.A_Expr.rexpr.List;
149
- }
150
- if (list?.items && list.items.length >= 10) {
151
- nudges.push({
152
- kind: "REPLACE_LARGE_IN_TUPLE_WITH_ANY_ARRAY",
153
- message: "`in (...)` queries with large tuples can often be replaced with `= ANY($1)` using a single parameter",
154
- severity: "INFO"
155
- });
156
- }
157
- }
158
- }
159
- return nudges;
160
- }
161
- function containsColumnRef(args) {
162
- for (const arg of args) {
163
- if (hasColumnRefInNode(arg)) {
164
- return true;
165
- }
166
- }
167
- return false;
168
- }
169
- function hasColumnRefInNode(node) {
170
- if (isANode(node) && is(node, "ColumnRef")) {
171
- return true;
172
- }
173
- if (typeof node !== "object" || node === null) {
174
- return false;
175
- }
176
- if (Array.isArray(node)) {
177
- return node.some((item) => hasColumnRefInNode(item));
178
- }
179
- if (isANode(node)) {
180
- const keys = Object.keys(node);
181
- return hasColumnRefInNode(node[keys[0]]);
182
- }
183
- for (const child of Object.values(node)) {
184
- if (hasColumnRefInNode(child)) {
185
- return true;
186
- }
187
- }
188
- return false;
189
- }
190
- function hasActualTablesInJoin(joinExpr) {
191
- if (joinExpr.JoinExpr.larg && is(joinExpr.JoinExpr.larg, "RangeVar")) {
192
- return true;
193
- }
194
- if (joinExpr.JoinExpr.larg && is(joinExpr.JoinExpr.larg, "JoinExpr")) {
195
- if (hasActualTablesInJoin(joinExpr.JoinExpr.larg)) {
196
- return true;
197
- }
198
- }
199
- if (joinExpr.JoinExpr.rarg && is(joinExpr.JoinExpr.rarg, "RangeVar")) {
200
- return true;
201
- }
202
- if (joinExpr.JoinExpr.rarg && is(joinExpr.JoinExpr.rarg, "JoinExpr")) {
203
- if (hasActualTablesInJoin(joinExpr.JoinExpr.rarg)) {
204
- return true;
205
- }
206
- }
207
- return false;
208
- }
209
- function isNullConstant(node) {
210
- if (!node || typeof node !== "object") {
211
- return false;
212
- }
213
- if (isANode(node) && is(node, "A_Const")) {
214
- return node.A_Const.isnull !== void 0;
215
- }
216
- return false;
217
- }
218
- function getStringConstantValue(node) {
219
- if (!node || typeof node !== "object") {
220
- return null;
221
- }
222
- if (isANode(node) && is(node, "A_Const") && node.A_Const.sval) {
223
- return node.A_Const.sval.sval || null;
224
- }
225
- return null;
226
- }
227
- function countBoolOrConditions(node) {
228
- if (node.BoolExpr.boolop !== "OR_EXPR" || !node.BoolExpr.args) {
229
- return 1;
230
- }
231
- let count = 0;
232
- for (const arg of node.BoolExpr.args) {
233
- if (isANode(arg) && is(arg, "BoolExpr") && arg.BoolExpr.boolop === "OR_EXPR") {
234
- count += countBoolOrConditions(arg);
235
- } else {
236
- count += 1;
237
- }
238
- }
239
- return count;
240
- }
241
-
242
- // src/sql/walker.ts
243
- var Walker = class _Walker {
244
- constructor(query) {
245
- this.query = query;
246
- __publicField(this, "tableMappings", /* @__PURE__ */ new Map());
247
- __publicField(this, "tempTables", /* @__PURE__ */ new Set());
248
- __publicField(this, "highlights", []);
249
- __publicField(this, "indexRepresentations", /* @__PURE__ */ new Set());
250
- __publicField(this, "indexesToCheck", []);
251
- __publicField(this, "highlightPositions", /* @__PURE__ */ new Set());
252
- // used for tallying the amount of times we see stuff so
253
- // we have a better idea of what to start off the algorithm with
254
- __publicField(this, "seenReferences", /* @__PURE__ */ new Map());
255
- __publicField(this, "shadowedAliases", []);
256
- __publicField(this, "nudges", []);
257
- }
258
- walk(root) {
259
- this.tableMappings = /* @__PURE__ */ new Map();
260
- this.tempTables = /* @__PURE__ */ new Set();
261
- this.highlights = [];
262
- this.indexRepresentations = /* @__PURE__ */ new Set();
263
- this.indexesToCheck = [];
264
- this.highlightPositions = /* @__PURE__ */ new Set();
265
- this.seenReferences = /* @__PURE__ */ new Map();
266
- this.shadowedAliases = [];
267
- this.nudges = [];
268
- _Walker.traverse(root, [], (node, stack) => {
269
- const nodeNudges = parseNudges(node, stack);
270
- this.nudges = [...this.nudges, ...nodeNudges];
271
- if (is2(node, "CommonTableExpr")) {
272
- if (node.CommonTableExpr.ctename) {
273
- this.tempTables.add(node.CommonTableExpr.ctename);
274
- }
275
- }
276
- if (is2(node, "RangeSubselect")) {
277
- if (node.RangeSubselect.alias?.aliasname) {
278
- this.tempTables.add(node.RangeSubselect.alias.aliasname);
279
- }
280
- }
281
- if (is2(node, "NullTest")) {
282
- if (node.NullTest.arg && node.NullTest.nulltesttype && is2(node.NullTest.arg, "ColumnRef")) {
283
- this.add(node.NullTest.arg, {
284
- where: { nulltest: node.NullTest.nulltesttype }
285
- });
286
- }
287
- }
288
- if (is2(node, "RangeVar") && node.RangeVar.relname) {
289
- const columnReference = {
290
- text: node.RangeVar.relname,
291
- start: node.RangeVar.location,
292
- quoted: false
293
- };
294
- if (node.RangeVar.schemaname) {
295
- columnReference.schema = node.RangeVar.schemaname;
296
- }
297
- this.tableMappings.set(node.RangeVar.relname, columnReference);
298
- if (node.RangeVar.alias?.aliasname) {
299
- const aliasName = node.RangeVar.alias.aliasname;
300
- const existingMapping = this.tableMappings.get(aliasName);
301
- const part = {
302
- text: node.RangeVar.relname,
303
- start: node.RangeVar.location,
304
- // what goes here? the text here doesn't _really_ exist.
305
- // so it can't be quoted or not quoted.
306
- // Does it even matter?
307
- quoted: true,
308
- alias: aliasName
309
- };
310
- if (node.RangeVar.schemaname) {
311
- part.schema = node.RangeVar.schemaname;
312
- }
313
- if (existingMapping) {
314
- const isSystemCatalog = node.RangeVar.relname?.startsWith("pg_") ?? false;
315
- if (!isSystemCatalog) {
316
- console.warn(
317
- `Ignoring alias ${aliasName} as it shadows an existing mapping for ${existingMapping.text}. We currently do not support alias shadowing.`
318
- );
319
- }
320
- this.shadowedAliases.push(part);
321
- return;
322
- }
323
- this.tableMappings.set(aliasName, part);
324
- }
325
- }
326
- if (is2(node, "SortBy")) {
327
- if (node.SortBy.node && is2(node.SortBy.node, "ColumnRef")) {
328
- this.add(node.SortBy.node, {
329
- sort: {
330
- dir: node.SortBy.sortby_dir ?? "SORTBY_DEFAULT",
331
- nulls: node.SortBy.sortby_nulls ?? "SORTBY_NULLS_DEFAULT"
332
- }
333
- });
334
- }
335
- }
336
- if (is2(node, "JoinExpr") && node.JoinExpr.quals) {
337
- if (is2(node.JoinExpr.quals, "A_Expr")) {
338
- if (node.JoinExpr.quals.A_Expr.lexpr && is2(node.JoinExpr.quals.A_Expr.lexpr, "ColumnRef")) {
339
- this.add(node.JoinExpr.quals.A_Expr.lexpr);
340
- }
341
- if (node.JoinExpr.quals.A_Expr.rexpr && is2(node.JoinExpr.quals.A_Expr.rexpr, "ColumnRef")) {
342
- this.add(node.JoinExpr.quals.A_Expr.rexpr);
343
- }
344
- }
345
- }
346
- if (is2(node, "A_Expr") && node.A_Expr.kind === "AEXPR_OP") {
347
- const opName = node.A_Expr.name?.[0] && is2(node.A_Expr.name[0], "String") && node.A_Expr.name[0].String.sval;
348
- if (opName && (opName === "@>" || opName === "?" || opName === "?|" || opName === "?&")) {
349
- const jsonbOperator = opName;
350
- if (node.A_Expr.lexpr && is2(node.A_Expr.lexpr, "ColumnRef")) {
351
- this.add(node.A_Expr.lexpr, { jsonbOperator });
352
- }
353
- if (node.A_Expr.rexpr && is2(node.A_Expr.rexpr, "ColumnRef")) {
354
- this.add(node.A_Expr.rexpr, { jsonbOperator });
355
- }
356
- }
357
- }
358
- if (is2(node, "ColumnRef")) {
359
- for (let i = 0; i < stack.length; i++) {
360
- const inReturningList = stack[i] === "returningList" && stack[i + 1] === "ResTarget" && stack[i + 2] === "val" && stack[i + 3] === "ColumnRef";
361
- if (inReturningList) {
362
- this.add(node, { ignored: true });
363
- return;
364
- }
365
- if (
366
- // stack[i] === "SelectStmt" &&
367
- stack[i + 1] === "targetList" && stack[i + 2] === "ResTarget" && stack[i + 3] === "val" && stack[i + 4] === "ColumnRef"
368
- ) {
369
- this.add(node, { ignored: true });
370
- return;
371
- }
372
- if (stack[i] === "FuncCall" && stack[i + 1] === "args") {
373
- this.add(node, { ignored: true });
374
- return;
375
- }
376
- }
377
- this.add(node);
378
- }
379
- });
380
- return {
381
- highlights: this.highlights,
382
- indexRepresentations: this.indexRepresentations,
383
- indexesToCheck: this.indexesToCheck,
384
- shadowedAliases: this.shadowedAliases,
385
- tempTables: this.tempTables,
386
- tableMappings: this.tableMappings,
387
- nudges: this.nudges
388
- };
389
- }
390
- add(node, options) {
391
- if (!node.ColumnRef.location) {
392
- console.error(`Node did not have a location. Skipping`, node);
393
- return;
394
- }
395
- if (!node.ColumnRef.fields) {
396
- console.error(node);
397
- throw new Error("Column reference must have fields");
398
- }
399
- let ignored = options?.ignored ?? false;
400
- let runningLength = node.ColumnRef.location;
401
- const parts = node.ColumnRef.fields.map(
402
- (field, i, length) => {
403
- if (!is2(field, "String") || !field.String.sval) {
404
- const out = deparseSync(field);
405
- ignored = true;
406
- return {
407
- quoted: out.startsWith('"'),
408
- text: out,
409
- start: runningLength
410
- };
411
- }
412
- const start = runningLength;
413
- const size = field.String.sval?.length ?? 0;
414
- let quoted = false;
415
- if (node.ColumnRef.location !== void 0) {
416
- const boundary = this.query[runningLength];
417
- if (boundary === '"') {
418
- quoted = true;
419
- }
420
- }
421
- const isLastIteration = i === length.length - 1;
422
- runningLength += size + (isLastIteration ? 0 : 1) + (quoted ? 2 : 0);
423
- return {
424
- text: field.String.sval,
425
- start,
426
- quoted
427
- };
428
- }
429
- );
430
- const end = runningLength;
431
- if (this.highlightPositions.has(node.ColumnRef.location)) {
432
- return;
433
- }
434
- this.highlightPositions.add(node.ColumnRef.location);
435
- const highlighted = `${this.query.slice(node.ColumnRef.location, end)}`;
436
- const seen = this.seenReferences.get(highlighted);
437
- if (!ignored) {
438
- this.seenReferences.set(highlighted, (seen ?? 0) + 1);
439
- }
440
- const ref = {
441
- frequency: seen ?? 1,
442
- representation: highlighted,
443
- parts,
444
- ignored: ignored ?? false,
445
- position: {
446
- start: node.ColumnRef.location,
447
- end
448
- }
449
- };
450
- if (options?.sort) {
451
- ref.sort = options.sort;
452
- }
453
- if (options?.where) {
454
- ref.where = options.where;
455
- }
456
- if (options?.jsonbOperator) {
457
- ref.jsonbOperator = options.jsonbOperator;
458
- }
459
- this.highlights.push(ref);
460
- }
461
- static traverse(node, stack, callback) {
462
- if (isANode2(node)) {
463
- callback(node, [...stack, getNodeKind(node)]);
464
- }
465
- if (typeof node !== "object" || node === null) {
466
- return;
467
- }
468
- if (Array.isArray(node)) {
469
- for (const item of node) {
470
- if (isANode2(item)) {
471
- _Walker.traverse(item, stack, callback);
472
- }
473
- }
474
- } else if (isANode2(node)) {
475
- const keys = Object.keys(node);
476
- _Walker.traverse(node[keys[0]], [...stack, getNodeKind(node)], callback);
477
- } else {
478
- for (const [key, child] of Object.entries(node)) {
479
- _Walker.traverse(child, [...stack, key], callback);
480
- }
481
- }
482
- }
483
- };
484
- function is2(node, kind) {
485
- return kind in node;
486
- }
487
- function getNodeKind(node) {
488
- const keys = Object.keys(node);
489
- return keys[0];
490
- }
491
- function isANode2(node) {
492
- if (typeof node !== "object" || node === null) {
493
- return false;
494
- }
495
- const keys = Object.keys(node);
496
- return keys.length === 1 && /^[A-Z]/.test(keys[0]);
497
- }
498
-
499
- // src/sql/analyzer.ts
500
- var ignoredIdentifier = "__qd_placeholder";
501
- var Analyzer = class {
502
- constructor(parser) {
503
- this.parser = parser;
504
- }
505
- async analyze(query, formattedQuery) {
506
- const ast = await this.parser(query);
507
- if (!ast.stmts) {
508
- throw new Error(
509
- "Query did not have any statements. This should probably never happen?"
510
- );
511
- }
512
- const stmt = ast.stmts[0].stmt;
513
- if (!stmt) {
514
- throw new Error(
515
- "Query did not have any statements. This should probably never happen?"
516
- );
517
- }
518
- const walker = new Walker(query);
519
- const {
520
- highlights,
521
- indexRepresentations,
522
- indexesToCheck,
523
- shadowedAliases,
524
- tempTables,
525
- tableMappings,
526
- nudges
527
- } = walker.walk(stmt);
528
- const sortedHighlights = highlights.sort(
529
- (a, b) => b.position.end - a.position.end
530
- );
531
- let currQuery = query;
532
- for (const highlight of sortedHighlights) {
533
- const parts = this.resolveTableAliases(highlight.parts, tableMappings);
534
- if (parts.length === 0) {
535
- console.error(highlight);
536
- throw new Error("Highlight must have at least one part");
537
- }
538
- let color;
539
- let skip = false;
540
- if (highlight.ignored) {
541
- color = (x) => dim(strikethrough(x));
542
- skip = true;
543
- } else if (parts.length === 2 && tempTables.has(parts[0].text) && // sometimes temp tables are aliased as existing tables
544
- // we don't want to ignore them if they are
545
- !tableMappings.has(parts[0].text)) {
546
- color = blue;
547
- skip = true;
548
- } else {
549
- color = bgMagentaBright;
550
- }
551
- const queryRepr = highlight.representation;
552
- const queryBeforeMatch = currQuery.slice(0, highlight.position.start);
553
- const queryAfterToken = currQuery.slice(highlight.position.end);
554
- currQuery = `${queryBeforeMatch}${color(queryRepr)}${this.colorizeKeywords(
555
- queryAfterToken,
556
- color
557
- )}`;
558
- if (indexRepresentations.has(queryRepr)) {
559
- skip = true;
560
- }
561
- if (!skip) {
562
- indexesToCheck.push(highlight);
563
- indexRepresentations.add(queryRepr);
564
- }
565
- }
566
- const referencedTables = [];
567
- for (const value of tableMappings.values()) {
568
- if (!value.alias) {
569
- referencedTables.push({
570
- schema: value.schema,
571
- table: value.text
572
- });
573
- }
574
- }
575
- const { tags, queryWithoutTags } = this.extractSqlcommenter(query);
576
- const formattedQueryWithoutTags = formattedQuery ? this.extractSqlcommenter(formattedQuery).queryWithoutTags : void 0;
577
- return {
578
- indexesToCheck,
579
- ansiHighlightedQuery: currQuery,
580
- referencedTables,
581
- shadowedAliases,
582
- tags,
583
- queryWithoutTags,
584
- formattedQueryWithoutTags,
585
- nudges
586
- };
587
- }
588
- deriveIndexes(tables, discovered, referencedTables) {
589
- const allIndexes = [];
590
- const seenIndexes = /* @__PURE__ */ new Set();
591
- function addIndex(index) {
592
- const key = `"${index.schema}":"${index.table}":"${index.column}"`;
593
- if (seenIndexes.has(key)) {
594
- return;
595
- }
596
- seenIndexes.add(key);
597
- allIndexes.push(index);
598
- }
599
- const matchingTables = this.filterReferences(referencedTables, tables);
600
- for (const colReference of discovered) {
601
- const partsCount = colReference.parts.length;
602
- const columnOnlyReference = partsCount === 1;
603
- const tableReference = partsCount === 2;
604
- const fullReference = partsCount === 3;
605
- if (columnOnlyReference) {
606
- const [column] = colReference.parts;
607
- const referencedColumn = this.normalize(column);
608
- for (const table of matchingTables) {
609
- if (!this.hasColumn(table, referencedColumn)) {
610
- continue;
611
- }
612
- const index = {
613
- schema: table.schemaName,
614
- table: table.tableName,
615
- column: referencedColumn
616
- };
617
- if (colReference.sort) {
618
- index.sort = colReference.sort;
619
- }
620
- if (colReference.where) {
621
- index.where = colReference.where;
622
- }
623
- if (colReference.jsonbOperator) {
624
- index.jsonbOperator = colReference.jsonbOperator;
625
- }
626
- addIndex(index);
627
- }
628
- } else if (tableReference) {
629
- const [table, column] = colReference.parts;
630
- const referencedTable = this.normalize(table);
631
- const referencedColumn = this.normalize(column);
632
- for (const matchingTable of matchingTables) {
633
- if (!this.hasColumn(matchingTable, referencedColumn)) {
634
- continue;
635
- }
636
- const index = {
637
- schema: matchingTable.schemaName,
638
- table: referencedTable,
639
- column: referencedColumn
640
- };
641
- if (colReference.sort) {
642
- index.sort = colReference.sort;
643
- }
644
- if (colReference.where) {
645
- index.where = colReference.where;
646
- }
647
- if (colReference.jsonbOperator) {
648
- index.jsonbOperator = colReference.jsonbOperator;
649
- }
650
- addIndex(index);
651
- }
652
- } else if (fullReference) {
653
- const [schema, table, column] = colReference.parts;
654
- const referencedSchema = this.normalize(schema);
655
- const referencedTable = this.normalize(table);
656
- const referencedColumn = this.normalize(column);
657
- const index = {
658
- schema: referencedSchema,
659
- table: referencedTable,
660
- column: referencedColumn
661
- };
662
- if (colReference.sort) {
663
- index.sort = colReference.sort;
664
- }
665
- if (colReference.where) {
666
- index.where = colReference.where;
667
- }
668
- if (colReference.jsonbOperator) {
669
- index.jsonbOperator = colReference.jsonbOperator;
670
- }
671
- addIndex(index);
672
- } else {
673
- console.error(
674
- "Column reference has too many parts. The query is malformed",
675
- colReference
676
- );
677
- continue;
678
- }
679
- }
680
- return allIndexes;
681
- }
682
- filterReferences(referencedTables, tables) {
683
- const matchingTables = [];
684
- for (const referencedTable of referencedTables) {
685
- const refs = tables.filter(({ tableName, schemaName }) => {
686
- let schemaMatches = true;
687
- if (referencedTable.schema) {
688
- schemaMatches = schemaName === referencedTable.schema;
689
- }
690
- return schemaMatches && tableName === referencedTable.table;
691
- });
692
- matchingTables.push(...refs);
693
- }
694
- return matchingTables;
695
- }
696
- hasColumn(table, columnName) {
697
- return table.columns?.some((column) => column.columnName === columnName) ?? false;
698
- }
699
- colorizeKeywords(query, color) {
700
- return query.replace(
701
- // eh? This kinda sucks
702
- /(^\s+)(asc|desc)?(\s+(nulls first|nulls last))?/i,
703
- (_, pre, dir, spaceNulls, nulls) => {
704
- return `${pre}${dir ? color(dir) : ""}${nulls ? spaceNulls.replace(nulls, color(nulls)) : ""}`;
705
- }
706
- ).replace(/(^\s+)(is (null|not null))/i, (_, pre, nulltest) => {
707
- return `${pre}${color(nulltest)}`;
708
- });
709
- }
710
- /**
711
- * Resolves aliases such as `a.b` to `x.b` if `a` is a known
712
- * alias to a table called x.
713
- *
714
- * Ignores all other combination of parts such as `a.b.c`
715
- */
716
- resolveTableAliases(parts, tableMappings) {
717
- if (parts.length !== 2) {
718
- return parts;
719
- }
720
- const tablePart = parts[0];
721
- const mapping = tableMappings.get(tablePart.text);
722
- if (mapping) {
723
- parts[0] = mapping;
724
- }
725
- return parts;
726
- }
727
- normalize(columnReference) {
728
- return columnReference.quoted ? columnReference.text : (
729
- // postgres automatically lowercases column names if not quoted
730
- columnReference.text.toLowerCase()
731
- );
732
- }
733
- extractSqlcommenter(query) {
734
- const trimmedQuery = query.trimEnd();
735
- const startPosition = trimmedQuery.lastIndexOf("/*");
736
- const endPosition = trimmedQuery.lastIndexOf("*/");
737
- if (startPosition === -1 || endPosition === -1) {
738
- return { tags: [], queryWithoutTags: trimmedQuery };
739
- }
740
- const queryWithoutTags = trimmedQuery.slice(0, startPosition);
741
- const tagString = trimmedQuery.slice(startPosition + 2, endPosition).trim();
742
- if (!tagString || typeof tagString !== "string") {
743
- return { tags: [], queryWithoutTags };
744
- }
745
- const tags = [];
746
- for (const match of tagString.split(",")) {
747
- const [key, value] = match.split("=");
748
- if (!key || !value) {
749
- if (tags.length > 0) {
750
- console.warn(
751
- `Invalid sqlcommenter tag: ${match} in comment: ${tagString}. Ignoring`
752
- );
753
- }
754
- continue;
755
- }
756
- try {
757
- let sliceStart = 0;
758
- if (value.startsWith("'")) {
759
- sliceStart = 1;
760
- }
761
- let sliceEnd = value.length;
762
- if (value.endsWith("'")) {
763
- sliceEnd -= 1;
764
- }
765
- const decoded = decodeURIComponent(value.slice(sliceStart, sliceEnd));
766
- tags.push({ key: key.trim(), value: decoded });
767
- } catch (err) {
768
- console.error(err);
769
- }
770
- }
771
- return { tags, queryWithoutTags };
772
- }
773
- };
774
-
775
- // src/sql/database.ts
776
- import { z } from "zod";
777
- var PostgresVersion = z.string().brand("PostgresVersion");
778
- async function dropIndex(tx, index) {
779
- try {
780
- await tx.exec(`
781
- savepoint idx_drop;
782
- drop index if exists ${index} cascade;
783
- `);
784
- return true;
785
- } catch (error) {
786
- await tx.exec(`rollback to idx_drop`);
787
- return false;
788
- }
789
- }
790
-
791
- // src/sql/indexes.ts
792
- function isIndexSupported(index) {
793
- return index.index_type === "btree" || index.index_type === "gin";
794
- }
795
- function isIndexProbablyDroppable(index) {
796
- return !index.is_primary && !index.is_unique;
797
- }
798
-
799
- // src/sql/builder.ts
800
- var PostgresQueryBuilder = class _PostgresQueryBuilder {
801
- constructor(query) {
802
- this.query = query;
803
- __publicField(this, "commands", {});
804
- __publicField(this, "isIntrospection", false);
805
- __publicField(this, "explainFlags", []);
806
- __publicField(this, "_preamble", 0);
807
- __publicField(this, "parameters", {});
808
- // substitution for `limit $1` -> `limit 5`
809
- __publicField(this, "limitSubstitution");
810
- }
811
- get preamble() {
812
- return this._preamble;
813
- }
814
- static createIndex(definition, name) {
815
- if (name) {
816
- return new _PostgresQueryBuilder(
817
- `create index "${name}" on ${definition};`
818
- );
819
- }
820
- return new _PostgresQueryBuilder(`create index on ${definition};`);
821
- }
822
- enable(command, value = true) {
823
- const commandString = `enable_${command}`;
824
- if (value) {
825
- this.commands[commandString] = "on";
826
- } else {
827
- this.commands[commandString] = "off";
828
- }
829
- return this;
830
- }
831
- withQuery(query) {
832
- this.query = query;
833
- return this;
834
- }
835
- introspect() {
836
- this.isIntrospection = true;
837
- return this;
838
- }
839
- explain(flags) {
840
- this.explainFlags = flags;
841
- return this;
842
- }
843
- parameterize(parameters) {
844
- Object.assign(this.parameters, parameters);
845
- return this;
846
- }
847
- replaceLimit(limit) {
848
- this.limitSubstitution = limit;
849
- return this;
850
- }
851
- build() {
852
- let commands = this.generateSetCommands();
853
- commands += this.generateExplain().query;
854
- if (this.isIntrospection) {
855
- commands += " -- @qd_introspection";
856
- }
857
- return commands;
858
- }
859
- /** Return the "set a=b" parts of the command in the query separate from the explain select ... part */
860
- buildParts() {
861
- const commands = this.generateSetCommands();
862
- const explain = this.generateExplain();
863
- this._preamble = explain.preamble;
864
- if (this.isIntrospection) {
865
- explain.query += " -- @qd_introspection";
866
- }
867
- return { commands, query: explain.query };
868
- }
869
- generateSetCommands() {
870
- let commands = "";
871
- for (const key in this.commands) {
872
- const value = this.commands[key];
873
- commands += `set local ${key}=${value};
874
- `;
875
- }
876
- return commands;
877
- }
878
- generateExplain() {
879
- let finalQuery = "";
880
- if (this.explainFlags.length > 0) {
881
- finalQuery += `explain (${this.explainFlags.join(", ")}) `;
882
- }
883
- const query = this.substituteQuery();
884
- const semicolon = query.endsWith(";") ? "" : ";";
885
- const preamble = finalQuery.length;
886
- finalQuery += `${query}${semicolon}`;
887
- return { query: finalQuery, preamble };
888
- }
889
- substituteQuery() {
890
- let query = this.query;
891
- if (this.limitSubstitution !== void 0) {
892
- query = query.replace(
893
- /limit\s+\$\d+/g,
894
- `limit ${this.limitSubstitution}`
895
- );
896
- }
897
- for (const [key, value] of Object.entries(this.parameters)) {
898
- query = query.replaceAll(`\\$${key}`, value.toString());
899
- }
900
- return query;
901
- }
902
- };
903
-
904
- // src/sql/pg-identifier.ts
905
- var _PgIdentifier = class _PgIdentifier {
906
- constructor(value, quoted) {
907
- this.value = value;
908
- this.quoted = quoted;
909
- }
910
- /**
911
- * Constructs an identifier from a single part (column or table name).
912
- * When quoting identifiers like `select table.col` use {@link fromParts} instead
913
- */
914
- static fromString(identifier) {
915
- const identifierRegex = /^[a-z_][a-zA-Z0-9_]*$/;
916
- const match = identifier.match(/^"(.+)"$/);
917
- if (match) {
918
- const value = match[1];
919
- const quoted2 = !identifierRegex.test(value) || this.reservedKeywords.has(value.toLowerCase());
920
- return new _PgIdentifier(value, quoted2);
921
- }
922
- const quoted = !identifierRegex.test(identifier) || this.reservedKeywords.has(identifier.toLowerCase());
923
- return new _PgIdentifier(identifier, quoted);
924
- }
925
- /**
926
- * Quotes parts of an identifier like `select schema.table.col`.
927
- * A separate function is necessary because postgres will treat
928
- * `select "HELLO.WORLD"` as a column name. It has to be like
929
- * `select "HELLO"."WORLD"` instead.
930
- */
931
- static fromParts(...identifiers) {
932
- return new _PgIdentifier(
933
- identifiers.map((identifier) => {
934
- if (typeof identifier === "string") {
935
- return _PgIdentifier.fromString(identifier);
936
- } else {
937
- return identifier;
938
- }
939
- }).join("."),
940
- false
941
- );
942
- }
943
- toString() {
944
- if (this.quoted) {
945
- return `"${this.value.replace(/"/g, '""')}"`;
946
- }
947
- return this.value;
948
- }
949
- toJSON() {
950
- return this.toString();
951
- }
952
- };
953
- // Every keyword that's not explicitly marked as
954
- // unreserved in src/include/parser/kwlist.h
955
- __publicField(_PgIdentifier, "reservedKeywords", /* @__PURE__ */ new Set([
956
- "all",
957
- "analyse",
958
- "analyze",
959
- "and",
960
- "any",
961
- "array",
962
- "as",
963
- "asc",
964
- "asymmetric",
965
- "authorization",
966
- "between",
967
- "bigint",
968
- "binary",
969
- "bit",
970
- "boolean",
971
- "both",
972
- "case",
973
- "cast",
974
- "char",
975
- "character",
976
- "check",
977
- "coalesce",
978
- "collate",
979
- "collation",
980
- "column",
981
- "concurrently",
982
- "constraint",
983
- "create",
984
- "cross",
985
- "current_catalog",
986
- "current_date",
987
- "current_role",
988
- "current_schema",
989
- "current_time",
990
- "current_timestamp",
991
- "current_user",
992
- "dec",
993
- "decimal",
994
- "default",
995
- "deferrable",
996
- "desc",
997
- "distinct",
998
- "do",
999
- "else",
1000
- "end",
1001
- "except",
1002
- "exists",
1003
- "extract",
1004
- "false",
1005
- "fetch",
1006
- "float",
1007
- "for",
1008
- "foreign",
1009
- "freeze",
1010
- "from",
1011
- "full",
1012
- "grant",
1013
- "greatest",
1014
- "group",
1015
- "grouping",
1016
- "having",
1017
- "ilike",
1018
- "in",
1019
- "initially",
1020
- "inner",
1021
- "inout",
1022
- "int",
1023
- "integer",
1024
- "intersect",
1025
- "interval",
1026
- "into",
1027
- "is",
1028
- "isnull",
1029
- "join",
1030
- "json",
1031
- "json_array",
1032
- "json_arrayagg",
1033
- "json_exists",
1034
- "json_object",
1035
- "json_objectagg",
1036
- "json_query",
1037
- "json_scalar",
1038
- "json_serialize",
1039
- "json_table",
1040
- "json_value",
1041
- "lateral",
1042
- "leading",
1043
- "least",
1044
- "left",
1045
- "like",
1046
- "limit",
1047
- "localtime",
1048
- "localtimestamp",
1049
- "merge_action",
1050
- "national",
1051
- "natural",
1052
- "nchar",
1053
- "none",
1054
- "normalize",
1055
- "not",
1056
- "notnull",
1057
- "null",
1058
- "nullif",
1059
- "numeric",
1060
- "offset",
1061
- "on",
1062
- "only",
1063
- "or",
1064
- "order",
1065
- "out",
1066
- "outer",
1067
- "overlaps",
1068
- "overlay",
1069
- "placing",
1070
- "position",
1071
- "precision",
1072
- "primary",
1073
- "real",
1074
- "references",
1075
- "returning",
1076
- "right",
1077
- "row",
1078
- "select",
1079
- "session_user",
1080
- "setof",
1081
- "similar",
1082
- "smallint",
1083
- "some",
1084
- "substring",
1085
- "symmetric",
1086
- "system_user",
1087
- "table",
1088
- "tablesample",
1089
- "then",
1090
- "time",
1091
- "timestamp",
1092
- "to",
1093
- "trailing",
1094
- "treat",
1095
- "trim",
1096
- "true",
1097
- "union",
1098
- "unique",
1099
- "user",
1100
- "using",
1101
- "values",
1102
- "varchar",
1103
- "variadic",
1104
- "verbose",
1105
- "when",
1106
- "where",
1107
- "window",
1108
- "with",
1109
- "xmlattributes",
1110
- "xmlconcat",
1111
- "xmlelement",
1112
- "xmlexists",
1113
- "xmlforest",
1114
- "xmlnamespaces",
1115
- "xmlparse",
1116
- "xmlpi",
1117
- "xmlroot",
1118
- "xmlserialize",
1119
- "xmltable"
1120
- ]));
1121
- var PgIdentifier = _PgIdentifier;
1122
-
1123
- // src/optimizer/genalgo.ts
1124
- import { blue as blue2, gray, green, magenta, red, yellow } from "colorette";
1125
-
1126
- // src/sql/permutations.ts
1127
- function permutationsWithDescendingLength(arr) {
1128
- const collected = [];
1129
- function collect(path, rest) {
1130
- for (let i = 0; i < rest.length; i++) {
1131
- const nextRest = [...rest.slice(0, i), ...rest.slice(i + 1)];
1132
- const nextPath = [...path, rest[i]];
1133
- collected.push(nextPath);
1134
- collect(nextPath, nextRest);
1135
- }
1136
- }
1137
- collect([], arr);
1138
- collected.sort((a, b) => b.length - a.length);
1139
- return collected;
1140
- }
1141
-
1142
- // src/optimizer/genalgo.ts
1143
- var _IndexOptimizer = class _IndexOptimizer {
1144
- constructor(db, statistics, existingIndexes, config = {}) {
1145
- this.db = db;
1146
- this.statistics = statistics;
1147
- this.existingIndexes = existingIndexes;
1148
- this.config = config;
1149
- }
1150
- async run(builder, indexes, beforeQuery) {
1151
- const baseExplain = await this.testQueryWithStats(builder, async (tx) => {
1152
- if (beforeQuery) {
1153
- await beforeQuery(tx);
1154
- }
1155
- });
1156
- const baseCost = Number(baseExplain.Plan["Total Cost"]);
1157
- if (baseCost === 0) {
1158
- return {
1159
- kind: "zero_cost_plan",
1160
- explainPlan: baseExplain.Plan
1161
- };
1162
- }
1163
- const toCreate = this.indexesToCreate(indexes);
1164
- const finalExplain = await this.testQueryWithStats(builder, async (tx) => {
1165
- if (beforeQuery) {
1166
- await beforeQuery(tx);
1167
- }
1168
- for (const permutation of toCreate) {
1169
- const createIndex = PostgresQueryBuilder.createIndex(
1170
- permutation.definition,
1171
- permutation.name
1172
- ).introspect().build();
1173
- await tx.exec(createIndex);
1174
- }
1175
- });
1176
- const finalCost = Number(finalExplain.Plan["Total Cost"]);
1177
- if (this.config.debug) {
1178
- console.dir(finalExplain, { depth: null });
1179
- }
1180
- const deltaPercentage = (baseCost - finalCost) / baseCost * 100;
1181
- if (finalCost < baseCost) {
1182
- console.log(
1183
- ` \u{1F389}\u{1F389}\u{1F389} ${green(`+${deltaPercentage.toFixed(2).padStart(5, "0")}%`)}`
1184
- );
1185
- } else if (finalCost > baseCost) {
1186
- console.log(
1187
- `${red(
1188
- `-${Math.abs(deltaPercentage).toFixed(2).padStart(5, "0")}%`
1189
- )} ${gray("If there's a better index, we haven't tried it")}`
1190
- );
1191
- }
1192
- const baseIndexes = this.findUsedIndexes(baseExplain.Plan);
1193
- const finalIndexes = this.findUsedIndexes(finalExplain.Plan);
1194
- const triedIndexes = new Map(
1195
- toCreate.map((index) => [index.name.toString(), index])
1196
- );
1197
- this.replaceUsedIndexesWithDefinition(finalExplain.Plan, triedIndexes);
1198
- return {
1199
- kind: "ok",
1200
- baseCost,
1201
- finalCost,
1202
- newIndexes: finalIndexes.newIndexes,
1203
- existingIndexes: baseIndexes.existingIndexes,
1204
- triedIndexes,
1205
- baseExplainPlan: baseExplain.Plan,
1206
- explainPlan: finalExplain.Plan
1207
- };
1208
- }
1209
- async runWithoutIndexes(builder) {
1210
- return await this.testQueryWithStats(builder, async (tx) => {
1211
- await this.dropExistingIndexes(tx);
1212
- });
1213
- }
1214
- /**
1215
- * Given the current indexes in the optimizer, transform them in some
1216
- * way to change which indexes will be assumed to exist when optimizing
1217
- *
1218
- * @example
1219
- * ```
1220
- * // resets indexes
1221
- * optimizer.transformIndexes(() => [])
1222
- *
1223
- * // adds new index
1224
- * optimizer.transformIndexes(indexes => [...indexes, newIndex])
1225
- * ```
1226
- */
1227
- transformIndexes(f) {
1228
- const newIndexes = f(this.existingIndexes);
1229
- this.existingIndexes = newIndexes;
1230
- return this;
1231
- }
1232
- /**
1233
- * Postgres has a limit of 63 characters for index names.
1234
- * So we use this to make sure we don't derive it from a list of columns that can
1235
- * overflow that limit.
1236
- */
1237
- indexName() {
1238
- const indexName = _IndexOptimizer.prefix + Math.random().toString(36).substring(2, 16);
1239
- return PgIdentifier.fromString(indexName);
1240
- }
1241
- // TODO: this doesn't belong in the optimizer
1242
- indexAlreadyExists(table, columns) {
1243
- return this.existingIndexes.find(
1244
- (index) => index.index_type === "btree" && index.table_name === table && index.index_columns.length === columns.length && index.index_columns.every((c, i) => {
1245
- if (columns[i].column !== c.name) {
1246
- return false;
1247
- }
1248
- if (columns[i].where) {
1249
- return false;
1250
- }
1251
- if (columns[i].sort) {
1252
- switch (columns[i].sort.dir) {
1253
- // Sorting is ASC by default in postgres
1254
- case "SORTBY_DEFAULT":
1255
- case "SORTBY_ASC":
1256
- if (c.order !== "ASC") {
1257
- return false;
1258
- }
1259
- break;
1260
- case "SORTBY_DESC":
1261
- if (c.order !== "DESC") {
1262
- return false;
1263
- }
1264
- break;
1265
- }
1266
- }
1267
- return true;
1268
- })
1269
- );
1270
- }
1271
- /**
1272
- * Derive the list of indexes [tableA(X, Y, Z), tableB(H, I, J)]
1273
- **/
1274
- indexesToCreate(rootCandidates) {
1275
- const btreeCandidates = rootCandidates.filter((c) => !c.jsonbOperator);
1276
- const ginCandidates = rootCandidates.filter((c) => c.jsonbOperator);
1277
- const nextStage = [];
1278
- const permutedIndexes = this.groupPotentialIndexColumnsByTable(btreeCandidates);
1279
- for (const permutation of permutedIndexes.values()) {
1280
- const { table: rawTable, schema: rawSchema, columns } = permutation;
1281
- const permutations = permutationsWithDescendingLength(columns);
1282
- for (const columns2 of permutations) {
1283
- const schema = PgIdentifier.fromString(rawSchema);
1284
- const table = PgIdentifier.fromString(rawTable);
1285
- const existingIndex = this.indexAlreadyExists(
1286
- table.toString(),
1287
- columns2
1288
- );
1289
- if (existingIndex) {
1290
- continue;
1291
- }
1292
- const indexName = this.indexName();
1293
- const definition = this.toDefinition({ table, schema, columns: columns2 }).raw;
1294
- nextStage.push({
1295
- name: indexName,
1296
- schema: schema.toString(),
1297
- table: table.toString(),
1298
- columns: columns2,
1299
- definition
1300
- });
1301
- }
1302
- }
1303
- const ginGroups = this.groupGinCandidatesByColumn(ginCandidates);
1304
- for (const group of ginGroups.values()) {
1305
- const { schema: rawSchema, table: rawTable, column, operators } = group;
1306
- const schema = PgIdentifier.fromString(rawSchema);
1307
- const table = PgIdentifier.fromString(rawTable);
1308
- const needsKeyExistence = operators.some(
1309
- (op) => op === "?" || op === "?|" || op === "?&"
1310
- );
1311
- const opclass = needsKeyExistence ? void 0 : "jsonb_path_ops";
1312
- const existingGin = this.ginIndexAlreadyExists(table.toString(), column);
1313
- if (existingGin) {
1314
- continue;
1315
- }
1316
- const indexName = this.indexName();
1317
- const candidate = {
1318
- schema: rawSchema,
1319
- table: rawTable,
1320
- column
1321
- };
1322
- const definition = this.toGinDefinition({
1323
- table,
1324
- schema,
1325
- column: PgIdentifier.fromString(column),
1326
- opclass
1327
- });
1328
- nextStage.push({
1329
- name: indexName,
1330
- schema: schema.toString(),
1331
- table: table.toString(),
1332
- columns: [candidate],
1333
- definition,
1334
- indexMethod: "gin",
1335
- opclass
1336
- });
1337
- }
1338
- return nextStage;
1339
- }
1340
- toDefinition({
1341
- schema,
1342
- table,
1343
- columns
1344
- }) {
1345
- const make = (col, order, where, keyword) => {
1346
- let fullyQualifiedTable;
1347
- if (schema.toString() === "public") {
1348
- fullyQualifiedTable = table;
1349
- } else {
1350
- fullyQualifiedTable = PgIdentifier.fromParts(schema, table);
1351
- }
1352
- const baseColumn = `${fullyQualifiedTable}(${columns.map((c) => {
1353
- const column = PgIdentifier.fromString(c.column);
1354
- const direction = c.sort && this.sortDirection(c.sort);
1355
- const nulls = c.sort && this.nullsOrder(c.sort);
1356
- let sort = col(column.toString());
1357
- if (direction) {
1358
- sort += ` ${order(direction)}`;
1359
- }
1360
- if (nulls) {
1361
- sort += ` ${order(nulls)}`;
1362
- }
1363
- return sort;
1364
- }).join(", ")})`;
1365
- return baseColumn;
1366
- };
1367
- const id = (a) => a;
1368
- const raw = make(id, id, id, id);
1369
- const colored = make(green, yellow, magenta, blue2);
1370
- return { raw, colored };
1371
- }
1372
- toGinDefinition({
1373
- schema,
1374
- table,
1375
- column,
1376
- opclass
1377
- }) {
1378
- let fullyQualifiedTable;
1379
- if (schema.toString() === "public") {
1380
- fullyQualifiedTable = table;
1381
- } else {
1382
- fullyQualifiedTable = PgIdentifier.fromParts(schema, table);
1383
- }
1384
- const opclassSuffix = opclass ? ` ${opclass}` : "";
1385
- return `${fullyQualifiedTable} using gin (${column}${opclassSuffix})`;
1386
- }
1387
- groupGinCandidatesByColumn(candidates) {
1388
- const groups = /* @__PURE__ */ new Map();
1389
- for (const c of candidates) {
1390
- if (!c.jsonbOperator) continue;
1391
- const key = `${c.schema}.${c.table}.${c.column}`;
1392
- const existing = groups.get(key);
1393
- if (existing) {
1394
- if (!existing.operators.includes(c.jsonbOperator)) {
1395
- existing.operators.push(c.jsonbOperator);
1396
- }
1397
- } else {
1398
- groups.set(key, {
1399
- schema: c.schema,
1400
- table: c.table,
1401
- column: c.column,
1402
- operators: [c.jsonbOperator]
1403
- });
1404
- }
1405
- }
1406
- return groups;
1407
- }
1408
- ginIndexAlreadyExists(table, column) {
1409
- return this.existingIndexes.find(
1410
- (index) => index.index_type === "gin" && index.table_name === table && index.index_columns.some((c) => c.name === column)
1411
- );
1412
- }
1413
- /**
1414
- * Drop indexes that can be dropped. Ignore the ones that can't
1415
- */
1416
- async dropExistingIndexes(tx) {
1417
- for (const index of this.existingIndexes) {
1418
- if (!isIndexProbablyDroppable(index)) {
1419
- continue;
1420
- }
1421
- const indexName = PgIdentifier.fromParts(
1422
- index.schema_name,
1423
- index.index_name
1424
- );
1425
- await dropIndex(tx, indexName);
1426
- }
1427
- }
1428
- whereClause(c, col, keyword) {
1429
- if (!c.where) {
1430
- return "";
1431
- }
1432
- if (c.where.nulltest === "IS_NULL") {
1433
- return `${col(`"${c.column}"`)} is ${keyword("null")}`;
1434
- }
1435
- if (c.where.nulltest === "IS_NOT_NULL") {
1436
- return `${col(`"${c.column}"`)} is not ${keyword("null")}`;
1437
- }
1438
- return "";
1439
- }
1440
- nullsOrder(s) {
1441
- if (!s.nulls) {
1442
- return "";
1443
- }
1444
- switch (s.nulls) {
1445
- case "SORTBY_NULLS_FIRST":
1446
- return "nulls first";
1447
- case "SORTBY_NULLS_LAST":
1448
- return "nulls last";
1449
- case "SORTBY_NULLS_DEFAULT":
1450
- default:
1451
- return "";
1452
- }
1453
- }
1454
- sortDirection(s) {
1455
- if (!s.dir) {
1456
- return "";
1457
- }
1458
- switch (s.dir) {
1459
- case "SORTBY_DESC":
1460
- return "desc";
1461
- case "SORTBY_ASC":
1462
- return "asc";
1463
- case "SORTBY_DEFAULT":
1464
- // god help us if we ever run into this
1465
- case "SORTBY_USING":
1466
- default:
1467
- return "";
1468
- }
1469
- }
1470
- async testQueryWithStats(builder, f, options) {
1471
- try {
1472
- await this.db.transaction(async (tx) => {
1473
- await f?.(tx);
1474
- await this.statistics.restoreStats(tx);
1475
- const flags = ["format json"];
1476
- if (options && !options.genericPlan) {
1477
- flags.push("analyze");
1478
- if (this.config.trace) {
1479
- flags.push("trace");
1480
- }
1481
- } else {
1482
- flags.push("generic_plan");
1483
- }
1484
- const { commands, query } = builder.explain(flags).buildParts();
1485
- await tx.exec(commands);
1486
- const result = await tx.exec(
1487
- query,
1488
- options?.params
1489
- );
1490
- const explain = result[0]["QUERY PLAN"][0];
1491
- throw new RollbackError(explain);
1492
- });
1493
- } catch (error) {
1494
- if (error instanceof RollbackError) {
1495
- return error.value;
1496
- }
1497
- throw error;
1498
- }
1499
- throw new Error("Unreachable");
1500
- }
1501
- groupPotentialIndexColumnsByTable(indexes) {
1502
- const tableColumns = /* @__PURE__ */ new Map();
1503
- for (const index of indexes) {
1504
- const existing = tableColumns.get(`${index.schema}.${index.table}`);
1505
- if (existing) {
1506
- existing.columns.push(index);
1507
- } else {
1508
- tableColumns.set(`${index.schema}.${index.table}`, {
1509
- table: index.table,
1510
- schema: index.schema,
1511
- columns: [index]
1512
- });
1513
- }
1514
- }
1515
- return tableColumns;
1516
- }
1517
- findUsedIndexes(explain) {
1518
- const newIndexes = /* @__PURE__ */ new Set();
1519
- const existingIndexes = /* @__PURE__ */ new Set();
1520
- const prefix = _IndexOptimizer.prefix;
1521
- walkExplain(explain, (stage) => {
1522
- const indexName = stage["Index Name"];
1523
- if (indexName) {
1524
- if (indexName.startsWith(prefix)) {
1525
- newIndexes.add(indexName);
1526
- } else if (indexName.includes(prefix)) {
1527
- const actualName = indexName.substring(indexName.indexOf(prefix));
1528
- newIndexes.add(actualName);
1529
- } else {
1530
- existingIndexes.add(indexName);
1531
- }
1532
- }
1533
- });
1534
- return {
1535
- newIndexes,
1536
- existingIndexes
1537
- };
1538
- }
1539
- replaceUsedIndexesWithDefinition(explain, triedIndexes) {
1540
- walkExplain(explain, (stage) => {
1541
- const indexName = stage["Index Name"];
1542
- if (typeof indexName === "string") {
1543
- const recommendation = triedIndexes.get(indexName);
1544
- if (recommendation) {
1545
- stage["Index Name"] = recommendation.definition;
1546
- }
1547
- }
1548
- });
1549
- }
1550
- };
1551
- __publicField(_IndexOptimizer, "prefix", "__qd_");
1552
- var IndexOptimizer = _IndexOptimizer;
1553
- function walkExplain(explain, f) {
1554
- function go(plan) {
1555
- f(plan);
1556
- if (plan.Plans) {
1557
- for (const p of plan.Plans) {
1558
- go(p);
1559
- }
1560
- }
1561
- }
1562
- go(explain);
1563
- }
1564
- var RollbackError = class {
1565
- constructor(value) {
1566
- this.value = value;
1567
- }
1568
- };
1569
- var PROCEED = Symbol("PROCEED");
1570
- var SKIP = Symbol("SKIP");
1571
-
1572
- // src/optimizer/statistics.ts
1573
- import { gray as gray2 } from "colorette";
1574
- import dedent from "dedent";
1575
- import { z as z2 } from "zod";
1576
- var StatisticsSource = z2.union([
1577
- z2.object({
1578
- kind: z2.literal("path"),
1579
- path: z2.string().min(1)
1580
- }),
1581
- z2.object({
1582
- kind: z2.literal("inline")
1583
- })
1584
- ]);
1585
- var ExportedStatsStatistics = z2.object({
1586
- stawidth: z2.number(),
1587
- stainherit: z2.boolean().default(false),
1588
- // 0 representing unknown
1589
- stadistinct: z2.number(),
1590
- // this has no "nullable" state
1591
- stanullfrac: z2.number(),
1592
- stakind1: z2.number().min(0),
1593
- stakind2: z2.number().min(0),
1594
- stakind3: z2.number().min(0),
1595
- stakind4: z2.number().min(0),
1596
- stakind5: z2.number().min(0),
1597
- staop1: z2.string(),
1598
- staop2: z2.string(),
1599
- staop3: z2.string(),
1600
- staop4: z2.string(),
1601
- staop5: z2.string(),
1602
- stacoll1: z2.string(),
1603
- stacoll2: z2.string(),
1604
- stacoll3: z2.string(),
1605
- stacoll4: z2.string(),
1606
- stacoll5: z2.string(),
1607
- stanumbers1: z2.array(z2.number()).nullable(),
1608
- stanumbers2: z2.array(z2.number()).nullable(),
1609
- stanumbers3: z2.array(z2.number()).nullable(),
1610
- stanumbers4: z2.array(z2.number()).nullable(),
1611
- stanumbers5: z2.array(z2.number()).nullable(),
1612
- // theoretically... this could only be strings and numbers
1613
- // but we don't have a crystal ball
1614
- stavalues1: z2.array(z2.any()).nullable(),
1615
- stavalues2: z2.array(z2.any()).nullable(),
1616
- stavalues3: z2.array(z2.any()).nullable(),
1617
- stavalues4: z2.array(z2.any()).nullable(),
1618
- stavalues5: z2.array(z2.any()).nullable()
1619
- });
1620
- var ExportedStatsColumns = z2.object({
1621
- columnName: z2.string(),
1622
- stats: ExportedStatsStatistics.nullable()
1623
- });
1624
- var ExportedStatsIndex = z2.object({
1625
- indexName: z2.string(),
1626
- relpages: z2.number(),
1627
- reltuples: z2.number(),
1628
- relallvisible: z2.number(),
1629
- relallfrozen: z2.number().optional()
1630
- });
1631
- var ExportedStatsV1 = z2.object({
1632
- tableName: z2.string(),
1633
- schemaName: z2.string(),
1634
- // can be negative
1635
- relpages: z2.number(),
1636
- // can be negative
1637
- reltuples: z2.number(),
1638
- relallvisible: z2.number(),
1639
- // only postgres 18+
1640
- relallfrozen: z2.number().optional(),
1641
- columns: z2.array(ExportedStatsColumns).nullable(),
1642
- indexes: z2.array(ExportedStatsIndex)
1643
- });
1644
- var ExportedStats = z2.union([ExportedStatsV1]);
1645
- var StatisticsMode = z2.discriminatedUnion("kind", [
1646
- z2.object({
1647
- kind: z2.literal("fromAssumption"),
1648
- reltuples: z2.number().min(0),
1649
- relpages: z2.number().min(0)
1650
- }),
1651
- z2.object({
1652
- kind: z2.literal("fromStatisticsExport"),
1653
- stats: z2.array(ExportedStats),
1654
- source: StatisticsSource
1655
- })
1656
- ]);
1657
- var DEFAULT_RELTUPLES = 1e4;
1658
- var DEFAULT_RELPAGES = 1;
1659
- var _Statistics = class _Statistics {
1660
- constructor(db, postgresVersion, ownMetadata, statsMode) {
1661
- this.db = db;
1662
- this.postgresVersion = postgresVersion;
1663
- this.ownMetadata = ownMetadata;
1664
- __publicField(this, "mode");
1665
- __publicField(this, "exportedMetadata");
1666
- if (statsMode) {
1667
- this.mode = statsMode;
1668
- if (statsMode.kind === "fromStatisticsExport") {
1669
- this.exportedMetadata = statsMode.stats;
1670
- }
1671
- } else {
1672
- this.mode = _Statistics.defaultStatsMode;
1673
- }
1674
- }
1675
- static statsModeFromAssumption({
1676
- reltuples,
1677
- relpages
1678
- }) {
1679
- return {
1680
- kind: "fromAssumption",
1681
- reltuples,
1682
- relpages
1683
- };
1684
- }
1685
- /**
1686
- * Create a statistic mode from stats exported from another database
1687
- **/
1688
- static statsModeFromExport(stats) {
1689
- return {
1690
- kind: "fromStatisticsExport",
1691
- source: { kind: "inline" },
1692
- stats
1693
- };
1694
- }
1695
- static async fromPostgres(db, statsMode) {
1696
- const version = await db.serverNum();
1697
- const ownStats = await _Statistics.dumpStats(db, version, "full");
1698
- return new _Statistics(db, version, ownStats, statsMode);
1699
- }
1700
- restoreStats(tx) {
1701
- return this.restoreStats17(tx);
1702
- }
1703
- approximateTotalRows() {
1704
- if (!this.exportedMetadata) {
1705
- return 0;
1706
- }
1707
- let totalRows = 0;
1708
- for (const table of this.exportedMetadata) {
1709
- totalRows += table.reltuples;
1710
- }
1711
- return totalRows;
1712
- }
1713
- /**
1714
- * We have to cast stavaluesN to the correct type
1715
- * This derives that type for us so it can be used in `array_in`
1716
- */
1717
- stavalueKind(values) {
1718
- if (!values || values.length === 0) {
1719
- return null;
1720
- }
1721
- const [elem] = values;
1722
- if (typeof elem === "number") {
1723
- return "real";
1724
- } else if (typeof elem === "boolean") {
1725
- return "boolean";
1726
- }
1727
- return "text";
1728
- }
1729
- /**
1730
- * PostgreSQL's anyarray columns in pg_statistic can hold arrays of arrays
1731
- * for columns with array types (e.g. text[], int4[]). These create
1732
- * multidimensional arrays that can be "ragged" (sub-arrays with different
1733
- * lengths). jsonb_to_recordset can't reconstruct ragged multidimensional
1734
- * arrays from JSON, so we need to drop these values.
1735
- */
1736
- static safeStavalues(values) {
1737
- if (!values || values.length === 0) return values;
1738
- if (values.some((v) => Array.isArray(v))) {
1739
- console.warn("Discarding ragged multidimensional stavalues array");
1740
- return null;
1741
- }
1742
- return values;
1743
- }
1744
- async restoreStats17(tx) {
1745
- const warnings = {
1746
- tablesNotInExports: [],
1747
- tablesNotInTest: [],
1748
- tableNotAnalyzed: [],
1749
- statsMissing: []
1750
- };
1751
- const processedTables = /* @__PURE__ */ new Set();
1752
- let columnStatsUpdatePromise;
1753
- const columnStatsValues = [];
1754
- if (this.exportedMetadata) {
1755
- for (const table of this.ownMetadata) {
1756
- const targetTable = this.exportedMetadata.find(
1757
- (m) => m.tableName === table.tableName && m.schemaName === table.schemaName
1758
- );
1759
- if (!targetTable?.columns) {
1760
- continue;
1761
- }
1762
- for (const column of targetTable.columns) {
1763
- const { stats } = column;
1764
- if (!stats) {
1765
- continue;
1766
- }
1767
- columnStatsValues.push({
1768
- schema_name: table.schemaName,
1769
- table_name: table.tableName,
1770
- column_name: column.columnName,
1771
- stainherit: stats.stainherit ?? false,
1772
- stanullfrac: stats.stanullfrac,
1773
- stawidth: stats.stawidth,
1774
- stadistinct: stats.stadistinct,
1775
- stakind1: stats.stakind1,
1776
- stakind2: stats.stakind2,
1777
- stakind3: stats.stakind3,
1778
- stakind4: stats.stakind4,
1779
- stakind5: stats.stakind5,
1780
- staop1: stats.staop1,
1781
- staop2: stats.staop2,
1782
- staop3: stats.staop3,
1783
- staop4: stats.staop4,
1784
- staop5: stats.staop5,
1785
- stacoll1: stats.stacoll1,
1786
- stacoll2: stats.stacoll2,
1787
- stacoll3: stats.stacoll3,
1788
- stacoll4: stats.stacoll4,
1789
- stacoll5: stats.stacoll5,
1790
- stanumbers1: stats.stanumbers1,
1791
- stanumbers2: stats.stanumbers2,
1792
- stanumbers3: stats.stanumbers3,
1793
- stanumbers4: stats.stanumbers4,
1794
- stanumbers5: stats.stanumbers5,
1795
- stavalues1: _Statistics.safeStavalues(stats.stavalues1),
1796
- stavalues2: _Statistics.safeStavalues(stats.stavalues2),
1797
- stavalues3: _Statistics.safeStavalues(stats.stavalues3),
1798
- stavalues4: _Statistics.safeStavalues(stats.stavalues4),
1799
- stavalues5: _Statistics.safeStavalues(stats.stavalues5),
1800
- _value_type1: this.stavalueKind(
1801
- _Statistics.safeStavalues(stats.stavalues1)
1802
- ),
1803
- _value_type2: this.stavalueKind(
1804
- _Statistics.safeStavalues(stats.stavalues2)
1805
- ),
1806
- _value_type3: this.stavalueKind(
1807
- _Statistics.safeStavalues(stats.stavalues3)
1808
- ),
1809
- _value_type4: this.stavalueKind(
1810
- _Statistics.safeStavalues(stats.stavalues4)
1811
- ),
1812
- _value_type5: this.stavalueKind(
1813
- _Statistics.safeStavalues(stats.stavalues5)
1814
- )
1815
- });
1816
- }
1817
- }
1818
- const sql = dedent`
1819
- WITH input AS (
1820
- SELECT
1821
- c.oid AS starelid,
1822
- a.attnum AS staattnum,
1823
- v.stainherit,
1824
- v.stanullfrac,
1825
- v.stawidth,
1826
- v.stadistinct,
1827
- v.stakind1,
1828
- v.stakind2,
1829
- v.stakind3,
1830
- v.stakind4,
1831
- v.stakind5,
1832
- v.staop1,
1833
- v.staop2,
1834
- v.staop3,
1835
- v.staop4,
1836
- v.staop5,
1837
- v.stacoll1,
1838
- v.stacoll2,
1839
- v.stacoll3,
1840
- v.stacoll4,
1841
- v.stacoll5,
1842
- v.stanumbers1,
1843
- v.stanumbers2,
1844
- v.stanumbers3,
1845
- v.stanumbers4,
1846
- v.stanumbers5,
1847
- v.stavalues1,
1848
- v.stavalues2,
1849
- v.stavalues3,
1850
- v.stavalues4,
1851
- v.stavalues5,
1852
- _value_type1,
1853
- _value_type2,
1854
- _value_type3,
1855
- _value_type4,
1856
- _value_type5
1857
- FROM jsonb_to_recordset($1::jsonb) AS v(
1858
- schema_name text,
1859
- table_name text,
1860
- column_name text,
1861
- stainherit boolean,
1862
- stanullfrac real,
1863
- stawidth integer,
1864
- stadistinct real,
1865
- stakind1 real,
1866
- stakind2 real,
1867
- stakind3 real,
1868
- stakind4 real,
1869
- stakind5 real,
1870
- staop1 oid,
1871
- staop2 oid,
1872
- staop3 oid,
1873
- staop4 oid,
1874
- staop5 oid,
1875
- stacoll1 oid,
1876
- stacoll2 oid,
1877
- stacoll3 oid,
1878
- stacoll4 oid,
1879
- stacoll5 oid,
1880
- stanumbers1 real[],
1881
- stanumbers2 real[],
1882
- stanumbers3 real[],
1883
- stanumbers4 real[],
1884
- stanumbers5 real[],
1885
- stavalues1 text[],
1886
- stavalues2 text[],
1887
- stavalues3 text[],
1888
- stavalues4 text[],
1889
- stavalues5 text[],
1890
- _value_type1 text,
1891
- _value_type2 text,
1892
- _value_type3 text,
1893
- _value_type4 text,
1894
- _value_type5 text
1895
- )
1896
- JOIN pg_class c ON c.relname = v.table_name
1897
- JOIN pg_namespace n ON n.oid = c.relnamespace AND n.nspname = v.schema_name
1898
- JOIN pg_attribute a ON a.attrelid = c.oid AND a.attname = v.column_name
1899
- ),
1900
- updated AS (
1901
- UPDATE pg_statistic s
1902
- SET
1903
- stanullfrac = i.stanullfrac,
1904
- stawidth = i.stawidth,
1905
- stadistinct = i.stadistinct,
1906
- stakind1 = i.stakind1,
1907
- stakind2 = i.stakind2,
1908
- stakind3 = i.stakind3,
1909
- stakind4 = i.stakind4,
1910
- stakind5 = i.stakind5,
1911
- staop1 = i.staop1,
1912
- staop2 = i.staop2,
1913
- staop3 = i.staop3,
1914
- staop4 = i.staop4,
1915
- staop5 = i.staop5,
1916
- stacoll1 = i.stacoll1,
1917
- stacoll2 = i.stacoll2,
1918
- stacoll3 = i.stacoll3,
1919
- stacoll4 = i.stacoll4,
1920
- stacoll5 = i.stacoll5,
1921
- stanumbers1 = i.stanumbers1,
1922
- stanumbers2 = i.stanumbers2,
1923
- stanumbers3 = i.stanumbers3,
1924
- stanumbers4 = i.stanumbers4,
1925
- stanumbers5 = i.stanumbers5,
1926
- stavalues1 = case
1927
- when i.stavalues1 is null then null
1928
- else array_in(i.stavalues1::text::cstring, i._value_type1::regtype::oid, -1)
1929
- end,
1930
- stavalues2 = case
1931
- when i.stavalues2 is null then null
1932
- else array_in(i.stavalues2::text::cstring, i._value_type2::regtype::oid, -1)
1933
- end,
1934
- stavalues3 = case
1935
- when i.stavalues3 is null then null
1936
- else array_in(i.stavalues3::text::cstring, i._value_type3::regtype::oid, -1)
1937
- end,
1938
- stavalues4 = case
1939
- when i.stavalues4 is null then null
1940
- else array_in(i.stavalues4::text::cstring, i._value_type4::regtype::oid, -1)
1941
- end,
1942
- stavalues5 = case
1943
- when i.stavalues5 is null then null
1944
- else array_in(i.stavalues5::text::cstring, i._value_type5::regtype::oid, -1)
1945
- end
1946
- -- stavalues1 = i.stavalues1,
1947
- -- stavalues2 = i.stavalues2,
1948
- -- stavalues3 = i.stavalues3,
1949
- -- stavalues4 = i.stavalues4,
1950
- -- stavalues5 = i.stavalues5
1951
- FROM input i
1952
- WHERE s.starelid = i.starelid AND s.staattnum = i.staattnum AND s.stainherit = i.stainherit
1953
- RETURNING s.starelid, s.staattnum, s.stainherit, s.stakind1, s.stakind2, s.stakind3, s.stakind4, s.stakind5
1954
- ),
1955
- inserted as (
1956
- INSERT INTO pg_statistic (
1957
- starelid, staattnum, stainherit,
1958
- stanullfrac, stawidth, stadistinct,
1959
- stakind1, stakind2, stakind3, stakind4, stakind5,
1960
- staop1, staop2, staop3, staop4, staop5,
1961
- stacoll1, stacoll2, stacoll3, stacoll4, stacoll5,
1962
- stanumbers1, stanumbers2, stanumbers3, stanumbers4, stanumbers5,
1963
- stavalues1, stavalues2, stavalues3, stavalues4, stavalues5
1964
- )
1965
- SELECT
1966
- i.starelid, i.staattnum, i.stainherit,
1967
- i.stanullfrac, i.stawidth, i.stadistinct,
1968
- i.stakind1, i.stakind2, i.stakind3, i.stakind4, i.stakind5,
1969
- i.staop1, i.staop2, i.staop3, i.staop4, i.staop5,
1970
- i.stacoll1, i.stacoll2, i.stacoll3, i.stacoll4, i.stacoll5,
1971
- i.stanumbers1, i.stanumbers2, i.stanumbers3, i.stanumbers4, i.stanumbers5,
1972
- -- i.stavalues1, i.stavalues2, i.stavalues3, i.stavalues4, i.stavalues5,
1973
- case
1974
- when i.stavalues1 is null then null
1975
- else array_in(i.stavalues1::text::cstring, i._value_type1::regtype::oid, -1)
1976
- end,
1977
- case
1978
- when i.stavalues2 is null then null
1979
- else array_in(i.stavalues2::text::cstring, i._value_type2::regtype::oid, -1)
1980
- end,
1981
- case
1982
- when i.stavalues3 is null then null
1983
- else array_in(i.stavalues3::text::cstring, i._value_type3::regtype::oid, -1)
1984
- end,
1985
- case
1986
- when i.stavalues4 is null then null
1987
- else array_in(i.stavalues4::text::cstring, i._value_type4::regtype::oid, -1)
1988
- end,
1989
- case
1990
- when i.stavalues5 is null then null
1991
- else array_in(i.stavalues5::text::cstring, i._value_type5::regtype::oid, -1)
1992
- end
1993
- -- i._value_type1, i._value_type2, i._value_type3, i._value_type4, i._value_type5
1994
- FROM input i
1995
- LEFT JOIN updated u
1996
- ON i.starelid = u.starelid AND i.staattnum = u.staattnum AND i.stainherit = u.stainherit
1997
- WHERE u.starelid IS NULL
1998
- returning starelid, staattnum, stainherit, stakind1, stakind2, stakind3, stakind4, stakind5
1999
- )
2000
- select * from updated union all (select * from inserted); -- @qd_introspection`;
2001
- columnStatsUpdatePromise = tx.exec(sql, [columnStatsValues]).catch((err) => {
2002
- console.error("Something wrong wrong updating column stats");
2003
- console.error(err);
2004
- throw err;
2005
- });
2006
- }
2007
- const reltuplesValues = [];
2008
- for (const table of this.ownMetadata) {
2009
- if (!table.columns) {
2010
- continue;
2011
- }
2012
- processedTables.add(`${table.schemaName}.${table.tableName}`);
2013
- let targetTable;
2014
- if (this.exportedMetadata) {
2015
- targetTable = this.exportedMetadata.find(
2016
- (m) => m.tableName === table.tableName && m.schemaName === table.schemaName
2017
- );
2018
- }
2019
- let reltuples;
2020
- let relpages;
2021
- let relallvisible = 0;
2022
- let relallfrozen;
2023
- if (targetTable) {
2024
- reltuples = targetTable.reltuples;
2025
- relpages = targetTable.relpages;
2026
- relallvisible = targetTable.relallvisible;
2027
- relallfrozen = targetTable.relallfrozen;
2028
- } else if (this.mode.kind === "fromAssumption") {
2029
- reltuples = this.mode.reltuples;
2030
- relpages = this.mode.relpages;
2031
- } else {
2032
- warnings.tablesNotInExports.push(
2033
- `${table.schemaName}.${table.tableName}`
2034
- );
2035
- reltuples = DEFAULT_RELTUPLES;
2036
- relpages = DEFAULT_RELPAGES;
2037
- }
2038
- reltuplesValues.push({
2039
- relname: table.tableName,
2040
- schema_name: table.schemaName,
2041
- reltuples,
2042
- relpages,
2043
- relallfrozen,
2044
- relallvisible
2045
- });
2046
- if (targetTable && targetTable.indexes) {
2047
- for (const index of targetTable.indexes) {
2048
- reltuplesValues.push({
2049
- relname: index.indexName,
2050
- schema_name: targetTable.schemaName,
2051
- reltuples: index.reltuples,
2052
- relpages: index.relpages,
2053
- relallfrozen: index.relallfrozen,
2054
- relallvisible: index.relallvisible
2055
- });
2056
- }
2057
- }
2058
- }
2059
- const reltuplesQuery = dedent`
2060
- update pg_class p
2061
- set reltuples = v.reltuples,
2062
- relpages = v.relpages,
2063
- -- relallfrozen = case when v.relallfrozen is null then p.relallfrozen else v.relallfrozen end,
2064
- relallvisible = case when v.relallvisible is null then p.relallvisible else v.relallvisible end
2065
- from jsonb_to_recordset($1::jsonb)
2066
- as v(reltuples real, relpages integer, relallfrozen integer, relallvisible integer, relname text, schema_name text)
2067
- where p.relname = v.relname
2068
- and p.relnamespace = (select oid from pg_namespace where nspname = v.schema_name)
2069
- returning p.relname, p.relnamespace, p.reltuples, p.relpages;
2070
- `;
2071
- const reltuplesPromise = tx.exec(reltuplesQuery, [reltuplesValues]).catch((err) => {
2072
- console.error("Something went wrong updating reltuples/relpages");
2073
- console.error(err);
2074
- return err;
2075
- });
2076
- if (this.exportedMetadata) {
2077
- for (const table of this.exportedMetadata) {
2078
- const tableExists = processedTables.has(
2079
- `${table.schemaName}.${table.tableName}`
2080
- );
2081
- if (tableExists && table.reltuples === -1) {
2082
- console.warn(
2083
- `Table ${table.tableName} has reltuples -1. Your production database is probably not analyzed properly`
2084
- );
2085
- warnings.tableNotAnalyzed.push(
2086
- `${table.schemaName}.${table.tableName}`
2087
- );
2088
- }
2089
- if (tableExists) {
2090
- continue;
2091
- }
2092
- warnings.tablesNotInTest.push(`${table.schemaName}.${table.tableName}`);
2093
- }
2094
- }
2095
- const [statsUpdates, reltuplesUpdates] = await Promise.all([
2096
- columnStatsUpdatePromise,
2097
- reltuplesPromise
2098
- ]);
2099
- const updatedColumnsProperly = statsUpdates ? statsUpdates.length === columnStatsValues.length : true;
2100
- if (!updatedColumnsProperly) {
2101
- console.error(`Did not update expected column stats`);
2102
- }
2103
- if (reltuplesUpdates.length !== reltuplesValues.length) {
2104
- console.error(`Did not update expected reltuples/relpages`);
2105
- }
2106
- return warnings;
2107
- }
2108
- static async dumpStats(db, postgresVersion, kind) {
2109
- const fullDump = kind === "full";
2110
- console.log(`dumping stats for postgres ${gray2(postgresVersion)}`);
2111
- const stats = await db.exec(
2112
- `
2113
- WITH table_columns AS (
2114
- SELECT
2115
- c.table_name,
2116
- c.table_schema,
2117
- cl.reltuples,
2118
- cl.relpages,
2119
- cl.relallvisible,
2120
- -- cl.relallfrozen,
2121
- n.nspname AS schema_name,
2122
- json_agg(
2123
- json_build_object(
2124
- 'columnName', c.column_name,
2125
- 'stats', (
2126
- SELECT json_build_object(
2127
- 'starelid', s.starelid,
2128
- 'staattnum', s.staattnum,
2129
- 'stanullfrac', s.stanullfrac,
2130
- 'stawidth', s.stawidth,
2131
- 'stadistinct', s.stadistinct,
2132
- 'stakind1', s.stakind1, 'staop1', s.staop1, 'stacoll1', s.stacoll1, 'stanumbers1', s.stanumbers1,
2133
- 'stakind2', s.stakind2, 'staop2', s.staop2, 'stacoll2', s.stacoll2, 'stanumbers2', s.stanumbers2,
2134
- 'stakind3', s.stakind3, 'staop3', s.staop3, 'stacoll3', s.stacoll3, 'stanumbers3', s.stanumbers3,
2135
- 'stakind4', s.stakind4, 'staop4', s.staop4, 'stacoll4', s.stacoll4, 'stanumbers4', s.stanumbers4,
2136
- 'stakind5', s.stakind5, 'staop5', s.staop5, 'stacoll5', s.stacoll5, 'stanumbers5', s.stanumbers5,
2137
- 'stavalues1', CASE WHEN $1 THEN s.stavalues1 ELSE NULL END,
2138
- 'stavalues2', CASE WHEN $1 THEN s.stavalues2 ELSE NULL END,
2139
- 'stavalues3', CASE WHEN $1 THEN s.stavalues3 ELSE NULL END,
2140
- 'stavalues4', CASE WHEN $1 THEN s.stavalues4 ELSE NULL END,
2141
- 'stavalues5', CASE WHEN $1 THEN s.stavalues5 ELSE NULL END
2142
- )
2143
- FROM pg_statistic s
2144
- WHERE s.starelid = a.attrelid AND s.staattnum = a.attnum
2145
- )
2146
- )
2147
- ORDER BY c.ordinal_position
2148
- ) AS columns
2149
- FROM information_schema.columns c
2150
- JOIN pg_attribute a
2151
- ON a.attrelid = (quote_ident(c.table_schema) || '.' || quote_ident(c.table_name))::regclass
2152
- AND a.attname = c.column_name
2153
- JOIN pg_class cl
2154
- ON cl.oid = a.attrelid
2155
- JOIN pg_namespace n
2156
- ON n.oid = cl.relnamespace
2157
- WHERE c.table_name NOT LIKE 'pg_%'
2158
- AND n.nspname <> 'information_schema'
2159
- AND c.table_name NOT IN ('pg_stat_statements', 'pg_stat_statements_info')
2160
- GROUP BY c.table_name, c.table_schema, cl.reltuples, cl.relpages, cl.relallvisible, n.nspname
2161
- ),
2162
- table_indexes AS (
2163
- SELECT
2164
- t.relname AS table_name,
2165
- json_agg(
2166
- json_build_object(
2167
- 'indexName', i.relname,
2168
- 'reltuples', i.reltuples,
2169
- 'relpages', i.relpages,
2170
- 'relallvisible', i.relallvisible
2171
- -- 'relallfrozen', i.relallfrozen
2172
- )
2173
- ) AS indexes
2174
- FROM pg_class t
2175
- JOIN pg_index ix ON ix.indrelid = t.oid
2176
- JOIN pg_class i ON i.oid = ix.indexrelid
2177
- JOIN pg_namespace n ON n.oid = t.relnamespace
2178
- WHERE t.relname NOT LIKE 'pg_%'
2179
- AND n.nspname <> 'information_schema'
2180
- GROUP BY t.relname
2181
- )
2182
- SELECT json_agg(
2183
- json_build_object(
2184
- 'tableName', tc.table_name,
2185
- 'schemaName', tc.table_schema,
2186
- 'reltuples', tc.reltuples,
2187
- 'relpages', tc.relpages,
2188
- 'relallvisible', tc.relallvisible,
2189
- -- 'relallfrozen', tc.relallfrozen,
2190
- 'columns', tc.columns,
2191
- 'indexes', COALESCE(ti.indexes, '[]'::json)
2192
- )
2193
- )
2194
- FROM table_columns tc
2195
- LEFT JOIN table_indexes ti
2196
- ON ti.table_name = tc.table_name;
2197
- `,
2198
- [fullDump]
2199
- );
2200
- return stats[0].json_agg;
2201
- }
2202
- /**
2203
- * Returns all indexes in the database.
2204
- * ONLY handles regular btree indexes
2205
- */
2206
- async getExistingIndexes() {
2207
- const indexes = await this.db.exec(`
2208
- WITH partitioned_tables AS (
2209
- SELECT
2210
- inhparent::regclass AS parent_table,
2211
- inhrelid::regclass AS partition_table
2212
- FROM
2213
- pg_inherits
2214
- )
2215
- SELECT
2216
- n.nspname AS schema_name,
2217
- COALESCE(pt.parent_table::text, t.relname) AS table_name,
2218
- i.relname AS index_name,
2219
- ix.indisprimary as is_primary,
2220
- ix.indisunique as is_unique,
2221
- am.amname AS index_type,
2222
- array_agg(
2223
- CASE
2224
- -- Handle regular columns
2225
- WHEN a.attname IS NOT NULL THEN
2226
- json_build_object('name', a.attname, 'order',
2227
- CASE
2228
- WHEN (indoption[array_position(ix.indkey, a.attnum)] & 1) = 1 THEN 'DESC'
2229
- ELSE 'ASC'
2230
- END,
2231
- 'opclass', CASE WHEN opc.opcdefault THEN NULL ELSE opc.opcname END)
2232
- -- Handle expressions
2233
- ELSE
2234
- json_build_object('name', pg_get_expr((ix.indexprs)::pg_node_tree, t.oid), 'order',
2235
- CASE
2236
- WHEN (indoption[array_position(ix.indkey, k.attnum)] & 1) = 1 THEN 'DESC'
2237
- ELSE 'ASC'
2238
- END,
2239
- 'opclass', CASE WHEN opc.opcdefault THEN NULL ELSE opc.opcname END)
2240
- END
2241
- ORDER BY array_position(ix.indkey, k.attnum)
2242
- ) AS index_columns
2243
- FROM
2244
- pg_class t
2245
- LEFT JOIN partitioned_tables pt ON t.oid = pt.partition_table
2246
- JOIN pg_index ix ON t.oid = ix.indrelid
2247
- JOIN pg_class i ON i.oid = ix.indexrelid
2248
- JOIN pg_am am ON i.relam = am.oid
2249
- LEFT JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY k(attnum, ordinality) ON true
2250
- LEFT JOIN pg_attribute a ON a.attnum = k.attnum AND a.attrelid = t.oid
2251
- LEFT JOIN pg_opclass opc ON opc.oid = ix.indclass[k.ordinality - 1]
2252
- JOIN pg_namespace n ON t.relnamespace = n.oid
2253
- WHERE
2254
- n.nspname not like 'pg_%' and
2255
- n.nspname <> 'information_schema'
2256
- GROUP BY
2257
- n.nspname, COALESCE(pt.parent_table::text, t.relname), i.relname, am.amname, ix.indisprimary, ix.indisunique
2258
- ORDER BY
2259
- COALESCE(pt.parent_table::text, t.relname), i.relname; -- @qd_introspection
2260
- `);
2261
- return indexes;
2262
- }
2263
- };
2264
- // preventing accidental internal mutations
2265
- __publicField(_Statistics, "defaultStatsMode", Object.freeze({
2266
- kind: "fromAssumption",
2267
- reltuples: DEFAULT_RELTUPLES,
2268
- relpages: DEFAULT_RELPAGES
2269
- }));
2270
- var Statistics = _Statistics;
2271
-
2272
- // src/optimizer/pss-rewriter.ts
2273
- var PssRewriter = class {
2274
- constructor() {
2275
- __publicField(this, "problematicKeywords", ["interval", "timestamp", "geometry"]);
2276
- }
2277
- rewrite(query) {
2278
- return this.rewriteKeywordWithParameter(query);
2279
- }
2280
- rewriteKeywordWithParameter(query) {
2281
- return query.replace(/\b(\w+) (\$\d+)\b/gi, (match) => {
2282
- const [keyword, parameter] = match.split(" ");
2283
- const isProblematicKeyword = this.problematicKeywords.includes(
2284
- keyword.toLowerCase()
2285
- );
2286
- if (!isProblematicKeyword) {
2287
- return match;
2288
- }
2289
- return `(${parameter}::${keyword.toLowerCase()})`;
2290
- });
2291
- }
2292
- };
2293
- export {
2294
- Analyzer,
2295
- ExportedStats,
2296
- ExportedStatsColumns,
2297
- ExportedStatsIndex,
2298
- ExportedStatsStatistics,
2299
- ExportedStatsV1,
2300
- IndexOptimizer,
2301
- PROCEED,
2302
- PgIdentifier,
2303
- PostgresQueryBuilder,
2304
- PostgresVersion,
2305
- PssRewriter,
2306
- SKIP,
2307
- Statistics,
2308
- StatisticsMode,
2309
- StatisticsSource,
2310
- dropIndex,
2311
- ignoredIdentifier,
2312
- isIndexProbablyDroppable,
2313
- isIndexSupported,
2314
- parseNudges
2315
- };
2316
- //# sourceMappingURL=index.js.map