@query-doctor/core 0.3.0 → 0.4.1-rc.1

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