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