@query-doctor/core 0.8.0 → 0.8.1-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 -2550
  11. package/dist/index.d.cts +11 -776
  12. package/dist/index.d.mts +11 -776
  13. package/dist/index.mjs +11 -2506
  14. package/dist/optimizer/genalgo.cjs +352 -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 +349 -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 +311 -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 +310 -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,2507 +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
- /**
835
- * Analyzes a query and returns a list of column references that
836
- * should be indexed.
837
- *
838
- * This should be instantiated once per analyzed query.
839
- */
840
- var Analyzer = class {
841
- constructor(parser) {
842
- this.parser = parser;
843
- }
844
- async analyze(query, formattedQuery) {
845
- const ast = await this.parser(query);
846
- if (!ast.stmts) throw new Error("Query did not have any statements. This should probably never happen?");
847
- const stmt = ast.stmts[0].stmt;
848
- if (!stmt) throw new Error("Query did not have any statements. This should probably never happen?");
849
- const { highlights, indexRepresentations, indexesToCheck, shadowedAliases, tempTables, tableMappings, nudges } = new Walker(query).walk(stmt);
850
- const sortedHighlights = highlights.sort((a, b) => b.position.end - a.position.end);
851
- let currQuery = query;
852
- for (const highlight of sortedHighlights) {
853
- const parts = this.resolveTableAliases(highlight.parts, tableMappings);
854
- if (parts.length === 0) {
855
- console.error(highlight);
856
- throw new Error("Highlight must have at least one part");
857
- }
858
- let color;
859
- let skip = false;
860
- if (highlight.ignored) {
861
- color = (x) => dim(strikethrough(x));
862
- skip = true;
863
- } else if (parts.length === 2 && tempTables.has(parts[0].text) && !tableMappings.has(parts[0].text)) {
864
- color = blue;
865
- skip = true;
866
- } else color = bgMagentaBright;
867
- const queryRepr = highlight.representation;
868
- const queryBeforeMatch = currQuery.slice(0, highlight.position.start);
869
- const queryAfterToken = currQuery.slice(highlight.position.end);
870
- currQuery = `${queryBeforeMatch}${color(queryRepr)}${this.colorizeKeywords(queryAfterToken, color)}`;
871
- const reprKey = highlight.jsonbExtraction ? `${queryRepr}::${highlight.jsonbExtraction}` : queryRepr;
872
- if (indexRepresentations.has(reprKey)) skip = true;
873
- if (!skip) {
874
- indexesToCheck.push(highlight);
875
- indexRepresentations.add(reprKey);
876
- }
877
- }
878
- const referencedTables = [];
879
- for (const value of tableMappings.values()) if (!value.alias) referencedTables.push({
880
- schema: value.schema,
881
- table: value.text
882
- });
883
- const { tags, queryWithoutTags } = this.extractSqlcommenter(query);
884
- const formattedQueryWithoutTags = formattedQuery ? this.extractSqlcommenter(formattedQuery).queryWithoutTags : void 0;
885
- return {
886
- indexesToCheck,
887
- ansiHighlightedQuery: currQuery,
888
- referencedTables,
889
- shadowedAliases,
890
- tags,
891
- queryWithoutTags,
892
- formattedQueryWithoutTags,
893
- nudges
894
- };
895
- }
896
- deriveIndexes(tables, discovered, referencedTables) {
897
- /**
898
- * There are 3 different kinds of parts a col reference can have
899
- * {a} = just a column within context. Find out the table
900
- * {a, b} = a column reference with a table reference. There's still ambiguity here
901
- * with what the schema could be in case there are 2 tables with the same name in different schemas.
902
- * {a, b, c} = a column reference with a table reference and a schema reference.
903
- * This is the best case scenario.
904
- */
905
- const allIndexes = [];
906
- const seenIndexes = /* @__PURE__ */ new Set();
907
- function addIndex(index) {
908
- const extractionSuffix = index.jsonbExtraction ? `:"${index.jsonbExtraction}"` : "";
909
- const key = `"${index.schema}":"${index.table}":"${index.column}"${extractionSuffix}`;
910
- if (seenIndexes.has(key)) return;
911
- seenIndexes.add(key);
912
- allIndexes.push(index);
913
- }
914
- const matchingTables = this.filterReferences(referencedTables, tables);
915
- for (const colReference of discovered) {
916
- const partsCount = colReference.parts.length;
917
- const columnOnlyReference = partsCount === 1;
918
- const tableReference = partsCount === 2;
919
- const fullReference = partsCount === 3;
920
- if (columnOnlyReference) {
921
- const [column] = colReference.parts;
922
- const referencedColumn = this.normalize(column);
923
- for (const table of matchingTables) {
924
- if (!this.hasColumn(table, referencedColumn)) continue;
925
- const index = {
926
- schema: table.schemaName,
927
- table: table.tableName,
928
- column: referencedColumn
929
- };
930
- if (colReference.sort) index.sort = colReference.sort;
931
- if (colReference.where) index.where = colReference.where;
932
- if (colReference.jsonbOperator) index.jsonbOperator = colReference.jsonbOperator;
933
- if (colReference.jsonbExtraction) index.jsonbExtraction = colReference.jsonbExtraction;
934
- addIndex(index);
935
- }
936
- } else if (tableReference) {
937
- const [table, column] = colReference.parts;
938
- const referencedTable = this.normalize(table);
939
- const referencedColumn = this.normalize(column);
940
- for (const matchingTable of matchingTables) {
941
- if (!this.hasColumn(matchingTable, referencedColumn)) continue;
942
- const index = {
943
- schema: matchingTable.schemaName,
944
- table: referencedTable,
945
- column: referencedColumn
946
- };
947
- if (colReference.sort) index.sort = colReference.sort;
948
- if (colReference.where) index.where = colReference.where;
949
- if (colReference.jsonbOperator) index.jsonbOperator = colReference.jsonbOperator;
950
- if (colReference.jsonbExtraction) index.jsonbExtraction = colReference.jsonbExtraction;
951
- addIndex(index);
952
- }
953
- } else if (fullReference) {
954
- const [schema, table, column] = colReference.parts;
955
- const index = {
956
- schema: this.normalize(schema),
957
- table: this.normalize(table),
958
- column: this.normalize(column)
959
- };
960
- if (colReference.sort) index.sort = colReference.sort;
961
- if (colReference.where) index.where = colReference.where;
962
- if (colReference.jsonbOperator) index.jsonbOperator = colReference.jsonbOperator;
963
- if (colReference.jsonbExtraction) index.jsonbExtraction = colReference.jsonbExtraction;
964
- addIndex(index);
965
- } else {
966
- console.error("Column reference has too many parts. The query is malformed", colReference);
967
- continue;
968
- }
969
- }
970
- return allIndexes;
971
- }
972
- filterReferences(referencedTables, tables) {
973
- const matchingTables = [];
974
- for (const referencedTable of referencedTables) {
975
- const refs = tables.filter(({ tableName, schemaName }) => {
976
- let schemaMatches = true;
977
- if (referencedTable.schema) schemaMatches = schemaName === referencedTable.schema;
978
- return schemaMatches && tableName === referencedTable.table;
979
- });
980
- matchingTables.push(...refs);
981
- }
982
- return matchingTables;
983
- }
984
- hasColumn(table, columnName) {
985
- return table.columns?.some((column) => column.columnName === columnName) ?? false;
986
- }
987
- colorizeKeywords(query, color) {
988
- return query.replace(/(^\s+)(asc|desc)?(\s+(nulls first|nulls last))?/i, (_, pre, dir, spaceNulls, nulls) => {
989
- return `${pre}${dir ? color(dir) : ""}${nulls ? spaceNulls.replace(nulls, color(nulls)) : ""}`;
990
- }).replace(/(^\s+)(is (null|not null))/i, (_, pre, nulltest) => {
991
- return `${pre}${color(nulltest)}`;
992
- });
993
- }
994
- /**
995
- * Resolves aliases such as `a.b` to `x.b` if `a` is a known
996
- * alias to a table called x.
997
- *
998
- * Ignores all other combination of parts such as `a.b.c`
999
- */
1000
- resolveTableAliases(parts, tableMappings) {
1001
- if (parts.length !== 2) return parts;
1002
- const tablePart = parts[0];
1003
- const mapping = tableMappings.get(tablePart.text);
1004
- if (mapping) parts[0] = mapping;
1005
- return parts;
1006
- }
1007
- normalize(columnReference) {
1008
- return columnReference.quoted ? columnReference.text : columnReference.text.toLowerCase();
1009
- }
1010
- extractSqlcommenter(query) {
1011
- const trimmedQuery = query.trimEnd();
1012
- const startPosition = trimmedQuery.lastIndexOf("/*");
1013
- const endPosition = trimmedQuery.lastIndexOf("*/");
1014
- if (startPosition === -1 || endPosition === -1) return {
1015
- tags: [],
1016
- queryWithoutTags: trimmedQuery
1017
- };
1018
- const afterComment = trimmedQuery.slice(endPosition + 2).trim();
1019
- if (afterComment && afterComment !== ";") return {
1020
- tags: [],
1021
- queryWithoutTags: trimmedQuery
1022
- };
1023
- const queryWithoutTags = trimmedQuery.slice(0, startPosition);
1024
- const tagString = trimmedQuery.slice(startPosition + 2, endPosition).trim();
1025
- if (!tagString || typeof tagString !== "string") return {
1026
- tags: [],
1027
- queryWithoutTags
1028
- };
1029
- const tags = [];
1030
- for (const match of tagString.split(",")) {
1031
- const [key, value] = match.split("=");
1032
- if (!key || !value) {
1033
- if (tags.length > 0) console.warn(`Invalid sqlcommenter tag: ${match} in comment: ${tagString}. Ignoring`);
1034
- continue;
1035
- }
1036
- try {
1037
- let sliceStart = 0;
1038
- if (value.startsWith("'")) sliceStart = 1;
1039
- let sliceEnd = value.length;
1040
- if (value.endsWith("'")) sliceEnd -= 1;
1041
- const decoded = decodeURIComponent(value.slice(sliceStart, sliceEnd));
1042
- tags.push({
1043
- key: key.trim(),
1044
- value: decoded
1045
- });
1046
- } catch (err) {
1047
- console.error(err);
1048
- }
1049
- }
1050
- return {
1051
- tags,
1052
- queryWithoutTags
1053
- };
1054
- }
1055
- };
1056
- //#endregion
1057
- //#region src/sql/database.ts
1058
- const PostgresVersion = z.string().brand("PostgresVersion");
1059
- /** Zod schema for PostgresExplainStage — validates common fields, passes through variant-specific ones. */
1060
- const PostgresExplainStageSchema = z.lazy(() => z.object({
1061
- "Node Type": z.string(),
1062
- "Total Cost": z.number(),
1063
- "Plan Width": z.number(),
1064
- "Node Id": z.number().optional(),
1065
- Plans: z.array(PostgresExplainStageSchema).optional()
1066
- }).passthrough());
1067
- /**
1068
- * Drops a disabled index. Rollsback if it fails for any reason
1069
- * @returns Did dropping the index succeed?
1070
- */
1071
- async function dropIndex(tx, index) {
1072
- try {
1073
- await tx.exec(`
1074
- savepoint idx_drop;
1075
- drop index if exists ${index} cascade;
1076
- `);
1077
- return true;
1078
- } catch {
1079
- await tx.exec(`rollback to idx_drop`);
1080
- return false;
1081
- }
1082
- }
1083
- //#endregion
1084
- //#region src/sql/indexes.ts
1085
- function isIndexSupported(index) {
1086
- return index.index_type === "btree" || index.index_type === "gin";
1087
- }
1088
- /**
1089
- * Doesn't necessarily decide whether the index can be dropped but can be
1090
- * used to not even try dropping indexes that _definitely_ cannot be dropped
1091
- */
1092
- function isIndexProbablyDroppable(index) {
1093
- return !index.is_primary && !index.is_unique;
1094
- }
1095
- //#endregion
1096
- //#region src/sql/builder.ts
1097
- var PostgresQueryBuilder = class PostgresQueryBuilder {
1098
- constructor(query) {
1099
- this.query = query;
1100
- _defineProperty(this, "commands", {});
1101
- _defineProperty(this, "isIntrospection", false);
1102
- _defineProperty(this, "explainFlags", []);
1103
- _defineProperty(this, "_preamble", 0);
1104
- _defineProperty(this, "parameters", {});
1105
- _defineProperty(this, "limitSubstitution", void 0);
1106
- }
1107
- get preamble() {
1108
- return this._preamble;
1109
- }
1110
- static createIndex(definition, name) {
1111
- if (name) return new PostgresQueryBuilder(`create index "${name}" on ${definition};`);
1112
- return new PostgresQueryBuilder(`create index on ${definition};`);
1113
- }
1114
- enable(command, value = true) {
1115
- const commandString = `enable_${command}`;
1116
- if (value) this.commands[commandString] = "on";
1117
- else this.commands[commandString] = "off";
1118
- return this;
1119
- }
1120
- withQuery(query) {
1121
- this.query = query;
1122
- return this;
1123
- }
1124
- introspect() {
1125
- this.isIntrospection = true;
1126
- return this;
1127
- }
1128
- explain(flags) {
1129
- this.explainFlags = flags;
1130
- return this;
1131
- }
1132
- parameterize(parameters) {
1133
- Object.assign(this.parameters, parameters);
1134
- return this;
1135
- }
1136
- replaceLimit(limit) {
1137
- this.limitSubstitution = limit;
1138
- return this;
1139
- }
1140
- build() {
1141
- let commands = this.generateSetCommands();
1142
- commands += this.generateExplain().query;
1143
- if (this.isIntrospection) commands += " -- @qd_introspection";
1144
- return commands;
1145
- }
1146
- /** Return the "set a=b" parts of the command in the query separate from the explain select ... part */
1147
- buildParts() {
1148
- const commands = this.generateSetCommands();
1149
- const explain = this.generateExplain();
1150
- this._preamble = explain.preamble;
1151
- if (this.isIntrospection) explain.query += " -- @qd_introspection";
1152
- return {
1153
- commands,
1154
- query: explain.query
1155
- };
1156
- }
1157
- generateSetCommands() {
1158
- let commands = "";
1159
- for (const key in this.commands) {
1160
- const value = this.commands[key];
1161
- commands += `set local ${key}=${value};\n`;
1162
- }
1163
- return commands;
1164
- }
1165
- generateExplain() {
1166
- let finalQuery = "";
1167
- if (this.explainFlags.length > 0) finalQuery += `explain (${this.explainFlags.join(", ")}) `;
1168
- const query = this.substituteQuery();
1169
- const semicolon = query.endsWith(";") ? "" : ";";
1170
- const preamble = finalQuery.length;
1171
- finalQuery += `${query}${semicolon}`;
1172
- return {
1173
- query: finalQuery,
1174
- preamble
1175
- };
1176
- }
1177
- substituteQuery() {
1178
- let query = this.query;
1179
- if (this.limitSubstitution !== void 0) query = query.replace(/limit\s+\$\d+/g, `limit ${this.limitSubstitution}`);
1180
- for (const [key, value] of Object.entries(this.parameters)) query = query.replaceAll(`\\$${key}`, value.toString());
1181
- return query;
1182
- }
1183
- };
1184
- //#endregion
1185
- //#region src/sql/pg-identifier.ts
1186
- /**
1187
- * Represents an identifier in postgres that is subject
1188
- * to quoting rules. The {@link toString} rule behaves
1189
- * exactly like calling `select quote_ident($1)` in postgres
1190
- */
1191
- var PgIdentifier = class PgIdentifier {
1192
- constructor(value, quoted) {
1193
- this.value = value;
1194
- this.quoted = quoted;
1195
- }
1196
- /**
1197
- * Constructs an identifier from a single part (column or table name).
1198
- * When quoting identifiers like `select table.col` use {@link fromParts} instead
1199
- */
1200
- static fromString(identifier) {
1201
- const identifierRegex = /^[a-z_][a-z0-9_]*$/;
1202
- const match = identifier.match(/^"(.+)"$/);
1203
- if (match) {
1204
- const value = match[1];
1205
- return new PgIdentifier(value, !identifierRegex.test(value) || this.reservedKeywords.has(value.toLowerCase()));
1206
- }
1207
- return new PgIdentifier(identifier, !identifierRegex.test(identifier) || this.reservedKeywords.has(identifier.toLowerCase()));
1208
- }
1209
- /**
1210
- * Quotes parts of an identifier like `select schema.table.col`.
1211
- * A separate function is necessary because postgres will treat
1212
- * `select "HELLO.WORLD"` as a column name. It has to be like
1213
- * `select "HELLO"."WORLD"` instead.
1214
- */
1215
- static fromParts(...identifiers) {
1216
- return new PgIdentifier(identifiers.map((identifier) => {
1217
- if (typeof identifier === "string") return PgIdentifier.fromString(identifier);
1218
- else return identifier;
1219
- }).join("."), false);
1220
- }
1221
- toString() {
1222
- if (this.quoted) return `"${this.value.replace(/"/g, "\"\"")}"`;
1223
- return this.value;
1224
- }
1225
- toJSON() {
1226
- return this.toString();
1227
- }
1228
- };
1229
- _defineProperty(PgIdentifier, "reservedKeywords", new Set([
1230
- "all",
1231
- "analyse",
1232
- "analyze",
1233
- "and",
1234
- "any",
1235
- "array",
1236
- "as",
1237
- "asc",
1238
- "asymmetric",
1239
- "authorization",
1240
- "between",
1241
- "bigint",
1242
- "binary",
1243
- "bit",
1244
- "boolean",
1245
- "both",
1246
- "case",
1247
- "cast",
1248
- "char",
1249
- "character",
1250
- "check",
1251
- "coalesce",
1252
- "collate",
1253
- "collation",
1254
- "column",
1255
- "concurrently",
1256
- "constraint",
1257
- "create",
1258
- "cross",
1259
- "current_catalog",
1260
- "current_date",
1261
- "current_role",
1262
- "current_schema",
1263
- "current_time",
1264
- "current_timestamp",
1265
- "current_user",
1266
- "dec",
1267
- "decimal",
1268
- "default",
1269
- "deferrable",
1270
- "desc",
1271
- "distinct",
1272
- "do",
1273
- "else",
1274
- "end",
1275
- "except",
1276
- "exists",
1277
- "extract",
1278
- "false",
1279
- "fetch",
1280
- "float",
1281
- "for",
1282
- "foreign",
1283
- "freeze",
1284
- "from",
1285
- "full",
1286
- "grant",
1287
- "greatest",
1288
- "group",
1289
- "grouping",
1290
- "having",
1291
- "ilike",
1292
- "in",
1293
- "initially",
1294
- "inner",
1295
- "inout",
1296
- "int",
1297
- "integer",
1298
- "intersect",
1299
- "interval",
1300
- "into",
1301
- "is",
1302
- "isnull",
1303
- "join",
1304
- "json",
1305
- "json_array",
1306
- "json_arrayagg",
1307
- "json_exists",
1308
- "json_object",
1309
- "json_objectagg",
1310
- "json_query",
1311
- "json_scalar",
1312
- "json_serialize",
1313
- "json_table",
1314
- "json_value",
1315
- "lateral",
1316
- "leading",
1317
- "least",
1318
- "left",
1319
- "like",
1320
- "limit",
1321
- "localtime",
1322
- "localtimestamp",
1323
- "merge_action",
1324
- "national",
1325
- "natural",
1326
- "nchar",
1327
- "none",
1328
- "normalize",
1329
- "not",
1330
- "notnull",
1331
- "null",
1332
- "nullif",
1333
- "numeric",
1334
- "offset",
1335
- "on",
1336
- "only",
1337
- "or",
1338
- "order",
1339
- "out",
1340
- "outer",
1341
- "overlaps",
1342
- "overlay",
1343
- "placing",
1344
- "position",
1345
- "precision",
1346
- "primary",
1347
- "real",
1348
- "references",
1349
- "returning",
1350
- "right",
1351
- "row",
1352
- "select",
1353
- "session_user",
1354
- "setof",
1355
- "similar",
1356
- "smallint",
1357
- "some",
1358
- "substring",
1359
- "symmetric",
1360
- "system_user",
1361
- "table",
1362
- "tablesample",
1363
- "then",
1364
- "time",
1365
- "timestamp",
1366
- "to",
1367
- "trailing",
1368
- "treat",
1369
- "trim",
1370
- "true",
1371
- "union",
1372
- "unique",
1373
- "user",
1374
- "using",
1375
- "values",
1376
- "varchar",
1377
- "variadic",
1378
- "verbose",
1379
- "when",
1380
- "where",
1381
- "window",
1382
- "with",
1383
- "xmlattributes",
1384
- "xmlconcat",
1385
- "xmlelement",
1386
- "xmlexists",
1387
- "xmlforest",
1388
- "xmlnamespaces",
1389
- "xmlparse",
1390
- "xmlpi",
1391
- "xmlroot",
1392
- "xmlserialize",
1393
- "xmltable"
1394
- ]));
1395
- //#endregion
1396
- //#region src/sql/permutations.ts
1397
- /**
1398
- * Create permutations of the array while sorting it from
1399
- * largest permutation to smallest.
1400
- *
1401
- * This is important when generating index permutations as
1402
- * postgres happens to prefer indexes with the latest
1403
- * creation date when the cost of using 2 are the same
1404
- **/
1405
- function permutationsWithDescendingLength(arr) {
1406
- const collected = [];
1407
- function collect(path, rest) {
1408
- for (let i = 0; i < rest.length; i++) {
1409
- const nextRest = [...rest.slice(0, i), ...rest.slice(i + 1)];
1410
- const nextPath = [...path, rest[i]];
1411
- collected.push(nextPath);
1412
- collect(nextPath, nextRest);
1413
- }
1414
- }
1415
- collect([], arr);
1416
- collected.sort((a, b) => b.length - a.length);
1417
- return collected;
1418
- }
1419
- //#endregion
1420
- //#region src/optimizer/genalgo.ts
1421
- var IndexOptimizer = class IndexOptimizer {
1422
- constructor(db, statistics, existingIndexes, config = {}) {
1423
- this.db = db;
1424
- this.statistics = statistics;
1425
- this.existingIndexes = existingIndexes;
1426
- this.config = config;
1427
- }
1428
- async run(builder, indexes, beforeQuery) {
1429
- const baseExplain = await this.testQueryWithStats(builder, async (tx) => {
1430
- if (beforeQuery) await beforeQuery(tx);
1431
- });
1432
- const baseCost = Number(baseExplain.Plan["Total Cost"]);
1433
- if (baseCost === 0) return {
1434
- kind: "zero_cost_plan",
1435
- explainPlan: baseExplain.Plan
1436
- };
1437
- const toCreate = this.indexesToCreate(indexes);
1438
- const finalExplain = await this.testQueryWithStats(builder, async (tx) => {
1439
- if (beforeQuery) await beforeQuery(tx);
1440
- for (const permutation of toCreate) {
1441
- const createIndex = PostgresQueryBuilder.createIndex(permutation.definition, permutation.name).introspect().build();
1442
- await tx.exec(createIndex);
1443
- }
1444
- });
1445
- const finalCost = Number(finalExplain.Plan["Total Cost"]);
1446
- if (this.config.debug) console.dir(finalExplain, { depth: null });
1447
- const deltaPercentage = (baseCost - finalCost) / baseCost * 100;
1448
- if (finalCost < baseCost) console.log(` 🎉🎉🎉 ${green(`+${deltaPercentage.toFixed(2).padStart(5, "0")}%`)}`);
1449
- 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")}`);
1450
- const baseIndexes = this.findUsedIndexes(baseExplain.Plan);
1451
- const finalIndexes = this.findUsedIndexes(finalExplain.Plan);
1452
- const triedIndexes = new Map(toCreate.map((index) => [index.name.toString(), index]));
1453
- this.replaceUsedIndexesWithDefinition(finalExplain.Plan, triedIndexes);
1454
- return {
1455
- kind: "ok",
1456
- baseCost,
1457
- finalCost,
1458
- newIndexes: finalIndexes.newIndexes,
1459
- existingIndexes: baseIndexes.existingIndexes,
1460
- triedIndexes,
1461
- baseExplainPlan: baseExplain.Plan,
1462
- explainPlan: finalExplain.Plan
1463
- };
1464
- }
1465
- async runWithoutIndexes(builder) {
1466
- return await this.testQueryWithStats(builder, async (tx) => {
1467
- await this.dropExistingIndexes(tx);
1468
- });
1469
- }
1470
- /**
1471
- * Given the current indexes in the optimizer, transform them in some
1472
- * way to change which indexes will be assumed to exist when optimizing
1473
- *
1474
- * @example
1475
- * ```
1476
- * // resets indexes
1477
- * optimizer.transformIndexes(() => [])
1478
- *
1479
- * // adds new index
1480
- * optimizer.transformIndexes(indexes => [...indexes, newIndex])
1481
- * ```
1482
- */
1483
- transformIndexes(f) {
1484
- this.existingIndexes = f(this.existingIndexes);
1485
- return this;
1486
- }
1487
- /**
1488
- * Postgres has a limit of 63 characters for index names.
1489
- * So we use this to make sure we don't derive it from a list of columns that can
1490
- * overflow that limit.
1491
- */
1492
- indexName() {
1493
- const indexName = IndexOptimizer.prefix + Math.random().toString(36).substring(2, 16);
1494
- return PgIdentifier.fromString(indexName);
1495
- }
1496
- indexAlreadyExists(table, columns) {
1497
- 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) => {
1498
- if (columns[i].column !== c.name) return false;
1499
- if (columns[i].where) return false;
1500
- if (columns[i].sort) switch (columns[i].sort.dir) {
1501
- case "SORTBY_DEFAULT":
1502
- case "SORTBY_ASC":
1503
- if (c.order !== "ASC") return false;
1504
- break;
1505
- case "SORTBY_DESC":
1506
- if (c.order !== "DESC") return false;
1507
- break;
1508
- }
1509
- return true;
1510
- }));
1511
- }
1512
- /**
1513
- * Derive the list of indexes [tableA(X, Y, Z), tableB(H, I, J)]
1514
- **/
1515
- indexesToCreate(rootCandidates) {
1516
- const expressionCandidates = rootCandidates.filter((c) => c.jsonbExtraction);
1517
- const btreeCandidates = rootCandidates.filter((c) => !c.jsonbOperator && !c.jsonbExtraction);
1518
- const ginCandidates = rootCandidates.filter((c) => c.jsonbOperator);
1519
- const nextStage = [];
1520
- const permutedIndexes = this.groupPotentialIndexColumnsByTable(btreeCandidates);
1521
- for (const permutation of permutedIndexes.values()) {
1522
- const { table: rawTable, schema: rawSchema, columns } = permutation;
1523
- const permutations = permutationsWithDescendingLength(columns);
1524
- for (const columns of permutations) {
1525
- const schema = PgIdentifier.fromString(rawSchema);
1526
- const table = PgIdentifier.fromString(rawTable);
1527
- if (this.indexAlreadyExists(table.toString(), columns)) continue;
1528
- const indexName = this.indexName();
1529
- const definition = this.toDefinition({
1530
- table,
1531
- schema,
1532
- columns
1533
- }).raw;
1534
- nextStage.push({
1535
- name: indexName,
1536
- schema: schema.toString(),
1537
- table: table.toString(),
1538
- columns,
1539
- definition
1540
- });
1541
- }
1542
- }
1543
- const ginGroups = this.groupGinCandidatesByColumn(ginCandidates);
1544
- for (const group of ginGroups.values()) {
1545
- const { schema: rawSchema, table: rawTable, column, operators } = group;
1546
- const schema = PgIdentifier.fromString(rawSchema);
1547
- const table = PgIdentifier.fromString(rawTable);
1548
- const opclass = operators.some((op) => op !== "@>") ? void 0 : "jsonb_path_ops";
1549
- if (this.ginIndexAlreadyExists(table.toString(), column)) continue;
1550
- const indexName = this.indexName();
1551
- const candidate = {
1552
- schema: rawSchema,
1553
- table: rawTable,
1554
- column
1555
- };
1556
- const definition = this.toGinDefinition({
1557
- table,
1558
- schema,
1559
- column: PgIdentifier.fromString(column),
1560
- opclass
1561
- });
1562
- nextStage.push({
1563
- name: indexName,
1564
- schema: schema.toString(),
1565
- table: table.toString(),
1566
- columns: [candidate],
1567
- definition,
1568
- indexMethod: "gin",
1569
- opclass
1570
- });
1571
- }
1572
- const seenExpressions = /* @__PURE__ */ new Set();
1573
- for (const candidate of expressionCandidates) {
1574
- const expression = candidate.jsonbExtraction;
1575
- const key = `${candidate.schema}.${candidate.table}.${expression}`;
1576
- if (seenExpressions.has(key)) continue;
1577
- seenExpressions.add(key);
1578
- const schema = PgIdentifier.fromString(candidate.schema);
1579
- const table = PgIdentifier.fromString(candidate.table);
1580
- const indexName = this.indexName();
1581
- const definition = this.toExpressionDefinition({
1582
- table,
1583
- schema,
1584
- expression
1585
- });
1586
- nextStage.push({
1587
- name: indexName,
1588
- schema: schema.toString(),
1589
- table: table.toString(),
1590
- columns: [candidate],
1591
- definition
1592
- });
1593
- }
1594
- return nextStage;
1595
- }
1596
- toDefinition({ schema, table, columns }) {
1597
- const make = (col, order, _where, _keyword) => {
1598
- let fullyQualifiedTable;
1599
- if (schema.toString() === "public") fullyQualifiedTable = table;
1600
- else fullyQualifiedTable = PgIdentifier.fromParts(schema, table);
1601
- return `${fullyQualifiedTable}(${columns.map((c) => {
1602
- const column = PgIdentifier.fromString(c.column);
1603
- const direction = c.sort && this.sortDirection(c.sort);
1604
- const nulls = c.sort && this.nullsOrder(c.sort);
1605
- let sort = col(column.toString());
1606
- if (direction) sort += ` ${order(direction)}`;
1607
- if (nulls) sort += ` ${order(nulls)}`;
1608
- return sort;
1609
- }).join(", ")})`;
1610
- };
1611
- const id = (a) => a;
1612
- return {
1613
- raw: make(id, id, id, id),
1614
- colored: make(green, yellow, magenta, blue)
1615
- };
1616
- }
1617
- toGinDefinition({ schema, table, column, opclass }) {
1618
- let fullyQualifiedTable;
1619
- if (schema.toString() === "public") fullyQualifiedTable = table;
1620
- else fullyQualifiedTable = PgIdentifier.fromParts(schema, table);
1621
- const opclassSuffix = opclass ? ` ${opclass}` : "";
1622
- return `${fullyQualifiedTable} using gin (${column}${opclassSuffix})`;
1623
- }
1624
- toExpressionDefinition({ schema, table, expression }) {
1625
- let fullyQualifiedTable;
1626
- if (schema.toString() === "public") fullyQualifiedTable = table;
1627
- else fullyQualifiedTable = PgIdentifier.fromParts(schema, table);
1628
- return `${fullyQualifiedTable}((${expression}))`;
1629
- }
1630
- groupGinCandidatesByColumn(candidates) {
1631
- const groups = /* @__PURE__ */ new Map();
1632
- for (const c of candidates) {
1633
- if (!c.jsonbOperator) continue;
1634
- const key = `${c.schema}.${c.table}.${c.column}`;
1635
- const existing = groups.get(key);
1636
- if (existing) {
1637
- if (!existing.operators.includes(c.jsonbOperator)) existing.operators.push(c.jsonbOperator);
1638
- } else groups.set(key, {
1639
- schema: c.schema,
1640
- table: c.table,
1641
- column: c.column,
1642
- operators: [c.jsonbOperator]
1643
- });
1644
- }
1645
- return groups;
1646
- }
1647
- ginIndexAlreadyExists(table, column) {
1648
- return this.existingIndexes.find((index) => index.index_type === "gin" && index.table_name === table && index.index_columns.some((c) => c.name === column));
1649
- }
1650
- /**
1651
- * Drop indexes that can be dropped. Ignore the ones that can't
1652
- */
1653
- async dropExistingIndexes(tx) {
1654
- for (const index of this.existingIndexes) {
1655
- if (!isIndexProbablyDroppable(index)) continue;
1656
- await dropIndex(tx, PgIdentifier.fromParts(index.schema_name, index.index_name));
1657
- }
1658
- }
1659
- whereClause(c, col, keyword) {
1660
- if (!c.where) return "";
1661
- if (c.where.nulltest === "IS_NULL") return `${col(`"${c.column}"`)} is ${keyword("null")}`;
1662
- if (c.where.nulltest === "IS_NOT_NULL") return `${col(`"${c.column}"`)} is not ${keyword("null")}`;
1663
- return "";
1664
- }
1665
- nullsOrder(s) {
1666
- if (!s.nulls) return "";
1667
- switch (s.nulls) {
1668
- case "SORTBY_NULLS_FIRST": return "nulls first";
1669
- case "SORTBY_NULLS_LAST": return "nulls last";
1670
- default: return "";
1671
- }
1672
- }
1673
- sortDirection(s) {
1674
- if (!s.dir) return "";
1675
- switch (s.dir) {
1676
- case "SORTBY_DESC": return "desc";
1677
- case "SORTBY_ASC": return "asc";
1678
- default: return "";
1679
- }
1680
- }
1681
- async testQueryWithStats(builder, f, options) {
1682
- try {
1683
- await this.db.transaction(async (tx) => {
1684
- await f?.(tx);
1685
- await this.statistics.restoreStats(tx);
1686
- const flags = ["format json"];
1687
- if (options && !options.genericPlan) {
1688
- flags.push("analyze");
1689
- if (this.config.trace) flags.push("trace");
1690
- } else flags.push("generic_plan");
1691
- const { commands, query } = builder.introspect().explain(flags).buildParts();
1692
- await tx.exec(commands);
1693
- const explain = (await tx.exec(query, options?.params))[0]["QUERY PLAN"][0];
1694
- throw new RollbackError(explain);
1695
- });
1696
- } catch (error) {
1697
- if (error instanceof RollbackError) return error.value;
1698
- throw error;
1699
- }
1700
- throw new Error("Unreachable");
1701
- }
1702
- groupPotentialIndexColumnsByTable(indexes) {
1703
- const tableColumns = /* @__PURE__ */ new Map();
1704
- for (const index of indexes) {
1705
- const existing = tableColumns.get(`${index.schema}.${index.table}`);
1706
- if (existing) existing.columns.push(index);
1707
- else tableColumns.set(`${index.schema}.${index.table}`, {
1708
- table: index.table,
1709
- schema: index.schema,
1710
- columns: [index]
1711
- });
1712
- }
1713
- return tableColumns;
1714
- }
1715
- findUsedIndexes(explain) {
1716
- const newIndexes = /* @__PURE__ */ new Set();
1717
- const existingIndexes = /* @__PURE__ */ new Set();
1718
- const prefix = IndexOptimizer.prefix;
1719
- walkExplain(explain, (stage) => {
1720
- const indexName = stage["Index Name"];
1721
- if (indexName) if (indexName.startsWith(prefix)) newIndexes.add(indexName);
1722
- else if (indexName.includes(prefix)) {
1723
- const actualName = indexName.substring(indexName.indexOf(prefix));
1724
- newIndexes.add(actualName);
1725
- } else existingIndexes.add(indexName);
1726
- });
1727
- return {
1728
- newIndexes,
1729
- existingIndexes
1730
- };
1731
- }
1732
- replaceUsedIndexesWithDefinition(explain, triedIndexes) {
1733
- walkExplain(explain, (stage) => {
1734
- const indexName = stage["Index Name"];
1735
- if (typeof indexName === "string") {
1736
- const recommendation = triedIndexes.get(indexName);
1737
- if (recommendation) stage["Index Name"] = recommendation.definition;
1738
- }
1739
- });
1740
- }
1741
- };
1742
- _defineProperty(IndexOptimizer, "prefix", "__qd_");
1743
- function walkExplain(explain, f) {
1744
- function go(plan) {
1745
- f(plan);
1746
- if (plan.Plans) for (const p of plan.Plans) go(p);
1747
- }
1748
- go(explain);
1749
- }
1750
- var RollbackError = class {
1751
- constructor(value) {
1752
- this.value = value;
1753
- }
1754
- };
1755
- const PROCEED = Symbol("PROCEED");
1756
- const SKIP = Symbol("SKIP");
1757
- //#endregion
1758
- //#region src/optimizer/statistics.ts
1759
- const StatisticsSource = z.union([z.object({
1760
- kind: z.literal("path"),
1761
- path: z.string().min(1)
1762
- }), z.object({ kind: z.literal("inline") })]);
1763
- const ExportedStatsStatistics = z.object({
1764
- stawidth: z.number(),
1765
- stainherit: z.boolean().default(false),
1766
- stadistinct: z.number(),
1767
- stanullfrac: z.number(),
1768
- stakind1: z.number().min(0),
1769
- stakind2: z.number().min(0),
1770
- stakind3: z.number().min(0),
1771
- stakind4: z.number().min(0),
1772
- stakind5: z.number().min(0),
1773
- staop1: z.string(),
1774
- staop2: z.string(),
1775
- staop3: z.string(),
1776
- staop4: z.string(),
1777
- staop5: z.string(),
1778
- stacoll1: z.string(),
1779
- stacoll2: z.string(),
1780
- stacoll3: z.string(),
1781
- stacoll4: z.string(),
1782
- stacoll5: z.string(),
1783
- stanumbers1: z.array(z.number()).nullable(),
1784
- stanumbers2: z.array(z.number()).nullable(),
1785
- stanumbers3: z.array(z.number()).nullable(),
1786
- stanumbers4: z.array(z.number()).nullable(),
1787
- stanumbers5: z.array(z.number()).nullable(),
1788
- stavalues1: z.array(z.any()).nullable(),
1789
- stavalues2: z.array(z.any()).nullable(),
1790
- stavalues3: z.array(z.any()).nullable(),
1791
- stavalues4: z.array(z.any()).nullable(),
1792
- stavalues5: z.array(z.any()).nullable()
1793
- });
1794
- const ExportedStatsColumns = z.object({
1795
- columnName: z.string(),
1796
- attlen: z.number().nullable(),
1797
- stats: ExportedStatsStatistics.nullable()
1798
- });
1799
- const ExportedStatsIndex = z.object({
1800
- indexName: z.string(),
1801
- amname: z.string().default("btree"),
1802
- relpages: z.number(),
1803
- reltuples: z.number(),
1804
- relallvisible: z.number(),
1805
- relallfrozen: z.number().optional(),
1806
- fillfactor: z.number().default(90),
1807
- columns: z.array(z.object({ attlen: z.number().nullable() })).default([])
1808
- });
1809
- const ExportedStatsV1 = z.object({
1810
- tableName: z.string(),
1811
- schemaName: z.string(),
1812
- relpages: z.number(),
1813
- reltuples: z.number(),
1814
- relallvisible: z.number(),
1815
- relallfrozen: z.number().optional(),
1816
- columns: z.array(ExportedStatsColumns).default([]),
1817
- indexes: z.array(ExportedStatsIndex)
1818
- });
1819
- const ExportedStats = z.union([ExportedStatsV1]);
1820
- const StatisticsMode = z.discriminatedUnion("kind", [z.object({
1821
- kind: z.literal("fromAssumption"),
1822
- reltuples: z.number().min(0)
1823
- }), z.object({
1824
- kind: z.literal("fromStatisticsExport"),
1825
- stats: z.array(ExportedStats),
1826
- source: StatisticsSource
1827
- })]);
1828
- const DEFAULT_RELTUPLES = 1e4;
1829
- const DEFAULT_RELPAGES = 1;
1830
- const DEFAULT_PAGE_SIZE = 2 ** 13;
1831
- function estimateStawidth(col) {
1832
- return col.attlen ?? 32;
1833
- }
1834
- function estimateRelpages(reltuples, columns) {
1835
- const rowWidth = columns.reduce((sum, col) => sum + estimateStawidth(col), 0) + 27;
1836
- return Math.ceil(reltuples * rowWidth / DEFAULT_PAGE_SIZE);
1837
- }
1838
- function estimateIndexRelpages(reltuples, columns, fillfactor, amname, tableRelpages) {
1839
- if (amname === "gin") return Math.ceil(tableRelpages * .3);
1840
- const keyWidth = columns.reduce((sum, col) => sum + estimateStawidth(col) + 16, 0);
1841
- return Math.ceil(reltuples * keyWidth / DEFAULT_PAGE_SIZE / fillfactor);
1842
- }
1843
- var Statistics = class Statistics {
1844
- constructor(db, postgresVersion, ownMetadata, statsMode) {
1845
- this.db = db;
1846
- this.postgresVersion = postgresVersion;
1847
- this.ownMetadata = ownMetadata;
1848
- _defineProperty(this, "mode", void 0);
1849
- _defineProperty(this, "exportedMetadata", void 0);
1850
- if (statsMode) {
1851
- this.mode = statsMode;
1852
- if (statsMode.kind === "fromStatisticsExport") this.exportedMetadata = statsMode.stats;
1853
- } else this.mode = Statistics.defaultStatsMode;
1854
- }
1855
- static statsModeFromAssumption({ reltuples }) {
1856
- return {
1857
- kind: "fromAssumption",
1858
- reltuples
1859
- };
1860
- }
1861
- /**
1862
- * Create a statistic mode from stats exported from another database
1863
- **/
1864
- static statsModeFromExport(stats) {
1865
- return {
1866
- kind: "fromStatisticsExport",
1867
- source: { kind: "inline" },
1868
- stats
1869
- };
1870
- }
1871
- static async fromPostgres(db, statsMode) {
1872
- const version = await db.serverNum();
1873
- return new Statistics(db, version, await Statistics.dumpStats(db, version, "full"), statsMode);
1874
- }
1875
- restoreStats(tx) {
1876
- return this.restoreStats17(tx);
1877
- }
1878
- approximateTotalRows() {
1879
- if (!this.exportedMetadata) return 0;
1880
- let totalRows = 0;
1881
- for (const table of this.exportedMetadata) totalRows += table.reltuples;
1882
- return totalRows;
1883
- }
1884
- /**
1885
- * We have to cast stavaluesN to the correct type
1886
- * This derives that type for us so it can be used in `array_in`
1887
- */
1888
- stavalueKind(values) {
1889
- if (!values || values.length === 0) return null;
1890
- const [elem] = values;
1891
- if (typeof elem === "number") return "real";
1892
- else if (typeof elem === "boolean") return "boolean";
1893
- return "text";
1894
- }
1895
- /**
1896
- * PostgreSQL's anyarray columns in pg_statistic can hold arrays of arrays
1897
- * for columns with array types (e.g. text[], int4[]). These create
1898
- * multidimensional arrays that can be "ragged" (sub-arrays with different
1899
- * lengths). jsonb_to_recordset can't reconstruct ragged multidimensional
1900
- * arrays from JSON, so we need to drop these values.
1901
- */
1902
- static safeStavalues(values) {
1903
- if (!values || values.length === 0) return values;
1904
- if (values.some((v) => Array.isArray(v))) {
1905
- console.warn("Discarding ragged multidimensional stavalues array");
1906
- return null;
1907
- }
1908
- return values;
1909
- }
1910
- async restoreStats17(tx) {
1911
- const warnings = {
1912
- tablesNotInExports: [],
1913
- tablesNotInTest: [],
1914
- tableNotAnalyzed: [],
1915
- statsMissing: []
1916
- };
1917
- const processedTables = /* @__PURE__ */ new Set();
1918
- let columnStatsUpdatePromise;
1919
- const columnStatsValues = [];
1920
- for (const table of this.ownMetadata) {
1921
- const target = (this.exportedMetadata?.find((m) => m.tableName === table.tableName && m.schemaName === table.schemaName))?.columns ?? table.columns;
1922
- for (const column of target) {
1923
- const { stats } = column;
1924
- if (!stats || this.mode.kind === "fromAssumption") {
1925
- const stawidth = stats?.stawidth || estimateStawidth(column);
1926
- columnStatsValues.push({
1927
- schema_name: table.schemaName,
1928
- table_name: table.tableName,
1929
- column_name: column.columnName,
1930
- stainherit: false,
1931
- stanullfrac: .04,
1932
- stawidth,
1933
- stadistinct: -.9,
1934
- stakind1: 0,
1935
- stakind2: 0,
1936
- stakind3: 3,
1937
- stakind4: 0,
1938
- stakind5: 0,
1939
- stacoll1: "0",
1940
- stacoll2: "0",
1941
- stacoll3: "0",
1942
- stacoll4: "0",
1943
- stacoll5: "0",
1944
- staop1: "0",
1945
- staop2: "0",
1946
- staop3: "0",
1947
- staop4: "0",
1948
- staop5: "0",
1949
- stanumbers1: null,
1950
- stanumbers2: null,
1951
- stanumbers3: [.9],
1952
- stanumbers4: null,
1953
- stanumbers5: null,
1954
- stavalues1: null,
1955
- stavalues2: null,
1956
- stavalues3: null,
1957
- stavalues4: null,
1958
- stavalues5: null,
1959
- _value_type1: "real",
1960
- _value_type2: "real",
1961
- _value_type3: "real",
1962
- _value_type4: "real",
1963
- _value_type5: "real"
1964
- });
1965
- continue;
1966
- }
1967
- columnStatsValues.push({
1968
- schema_name: table.schemaName,
1969
- table_name: table.tableName,
1970
- column_name: column.columnName,
1971
- stainherit: stats.stainherit ?? false,
1972
- stanullfrac: stats.stanullfrac,
1973
- stawidth: stats.stawidth,
1974
- stadistinct: stats.stadistinct,
1975
- stakind1: stats.stakind1,
1976
- stakind2: stats.stakind2,
1977
- stakind3: stats.stakind3,
1978
- stakind4: stats.stakind4,
1979
- stakind5: stats.stakind5,
1980
- staop1: stats.staop1,
1981
- staop2: stats.staop2,
1982
- staop3: stats.staop3,
1983
- staop4: stats.staop4,
1984
- staop5: stats.staop5,
1985
- stacoll1: stats.stacoll1,
1986
- stacoll2: stats.stacoll2,
1987
- stacoll3: stats.stacoll3,
1988
- stacoll4: stats.stacoll4,
1989
- stacoll5: stats.stacoll5,
1990
- stanumbers1: stats.stanumbers1,
1991
- stanumbers2: stats.stanumbers2,
1992
- stanumbers3: stats.stanumbers3,
1993
- stanumbers4: stats.stanumbers4,
1994
- stanumbers5: stats.stanumbers5,
1995
- stavalues1: Statistics.safeStavalues(stats.stavalues1),
1996
- stavalues2: Statistics.safeStavalues(stats.stavalues2),
1997
- stavalues3: Statistics.safeStavalues(stats.stavalues3),
1998
- stavalues4: Statistics.safeStavalues(stats.stavalues4),
1999
- stavalues5: Statistics.safeStavalues(stats.stavalues5),
2000
- _value_type1: this.stavalueKind(Statistics.safeStavalues(stats.stavalues1)),
2001
- _value_type2: this.stavalueKind(Statistics.safeStavalues(stats.stavalues2)),
2002
- _value_type3: this.stavalueKind(Statistics.safeStavalues(stats.stavalues3)),
2003
- _value_type4: this.stavalueKind(Statistics.safeStavalues(stats.stavalues4)),
2004
- _value_type5: this.stavalueKind(Statistics.safeStavalues(stats.stavalues5))
2005
- });
2006
- }
2007
- }
2008
- /**
2009
- * Postgres has 5 different slots for storing statistics per column and a potentially unlimited
2010
- * number of statistic types to choose from. Each code in `stakindN` can mean different things.
2011
- * Some statistics are just numerical values such as `n_distinct` and `correlation`, meaning
2012
- * they're only derived from `stanumbersN` and the value of `stanumbersN` is never read.
2013
- * Others take advantage of the `stavaluesN` columns which use `anyarray` type to store
2014
- * concrete values internally for things like histogram bounds.
2015
- * Unfortunately we cannot change anyarrays without a C extension.
2016
- *
2017
- * (1) = most common values
2018
- * (2) = scalar histogram
2019
- * (3) = correlation <- can change
2020
- * (4) = most common elements
2021
- * (5) = distinct elem count histogram <- can change
2022
- * (6) = length histogram (?) These don't appear in pg_stats
2023
- * (7) = bounds histogram (?) These don't appear in pg_stats
2024
- * (N) = potentially many more kinds of statistics. But postgres <=18 only uses these 7.
2025
- *
2026
- * What we're doing here is setting ANY statistic we cannot directly control
2027
- * (anything that relies on stavaluesN) to 0 to make sure the planner isn't influenced by what
2028
- * what the db collected from the test data.
2029
- * Because we do our tests with `generic_plan` it seems it's already unlikely that the planner will be
2030
- * using things like common values or histogram bounds to make the planning decisions we care about.
2031
- * This is a just in case.
2032
- */
2033
- const sql = dedent`
2034
- WITH input AS (
2035
- SELECT
2036
- c.oid AS starelid,
2037
- a.attnum AS staattnum,
2038
- v.stainherit,
2039
- v.stanullfrac,
2040
- v.stawidth,
2041
- v.stadistinct,
2042
- v.stakind1,
2043
- v.stakind2,
2044
- v.stakind3,
2045
- v.stakind4,
2046
- v.stakind5,
2047
- v.staop1,
2048
- v.staop2,
2049
- v.staop3,
2050
- v.staop4,
2051
- v.staop5,
2052
- v.stacoll1,
2053
- v.stacoll2,
2054
- v.stacoll3,
2055
- v.stacoll4,
2056
- v.stacoll5,
2057
- v.stanumbers1,
2058
- v.stanumbers2,
2059
- v.stanumbers3,
2060
- v.stanumbers4,
2061
- v.stanumbers5,
2062
- v.stavalues1,
2063
- v.stavalues2,
2064
- v.stavalues3,
2065
- v.stavalues4,
2066
- v.stavalues5,
2067
- _value_type1,
2068
- _value_type2,
2069
- _value_type3,
2070
- _value_type4,
2071
- _value_type5
2072
- FROM jsonb_to_recordset($1::jsonb) AS v(
2073
- schema_name text,
2074
- table_name text,
2075
- column_name text,
2076
- stainherit boolean,
2077
- stanullfrac real,
2078
- stawidth integer,
2079
- stadistinct real,
2080
- stakind1 real,
2081
- stakind2 real,
2082
- stakind3 real,
2083
- stakind4 real,
2084
- stakind5 real,
2085
- staop1 oid,
2086
- staop2 oid,
2087
- staop3 oid,
2088
- staop4 oid,
2089
- staop5 oid,
2090
- stacoll1 oid,
2091
- stacoll2 oid,
2092
- stacoll3 oid,
2093
- stacoll4 oid,
2094
- stacoll5 oid,
2095
- stanumbers1 real[],
2096
- stanumbers2 real[],
2097
- stanumbers3 real[],
2098
- stanumbers4 real[],
2099
- stanumbers5 real[],
2100
- stavalues1 text[],
2101
- stavalues2 text[],
2102
- stavalues3 text[],
2103
- stavalues4 text[],
2104
- stavalues5 text[],
2105
- _value_type1 text,
2106
- _value_type2 text,
2107
- _value_type3 text,
2108
- _value_type4 text,
2109
- _value_type5 text
2110
- )
2111
- JOIN pg_class c ON c.relname = v.table_name
2112
- JOIN pg_namespace n ON n.oid = c.relnamespace AND n.nspname = v.schema_name
2113
- JOIN pg_attribute a ON a.attrelid = c.oid AND a.attname = v.column_name
2114
- ),
2115
- updated AS (
2116
- UPDATE pg_statistic s
2117
- SET
2118
- stanullfrac = i.stanullfrac,
2119
- stawidth = i.stawidth,
2120
- stadistinct = i.stadistinct,
2121
- stakind1 = i.stakind1,
2122
- stakind2 = i.stakind2,
2123
- stakind3 = i.stakind3,
2124
- stakind4 = i.stakind4,
2125
- stakind5 = i.stakind5,
2126
- staop1 = i.staop1,
2127
- staop2 = i.staop2,
2128
- staop3 = i.staop3,
2129
- staop4 = i.staop4,
2130
- staop5 = i.staop5,
2131
- stacoll1 = i.stacoll1,
2132
- stacoll2 = i.stacoll2,
2133
- stacoll3 = i.stacoll3,
2134
- stacoll4 = i.stacoll4,
2135
- stacoll5 = i.stacoll5,
2136
- stanumbers1 = i.stanumbers1,
2137
- stanumbers2 = i.stanumbers2,
2138
- stanumbers3 = i.stanumbers3,
2139
- stanumbers4 = i.stanumbers4,
2140
- stanumbers5 = i.stanumbers5,
2141
- stavalues1 = case
2142
- when i.stavalues1 is null then null
2143
- else array_in(i.stavalues1::text::cstring, i._value_type1::regtype::oid, -1)
2144
- end,
2145
- stavalues2 = case
2146
- when i.stavalues2 is null then null
2147
- else array_in(i.stavalues2::text::cstring, i._value_type2::regtype::oid, -1)
2148
- end,
2149
- stavalues3 = case
2150
- when i.stavalues3 is null then null
2151
- else array_in(i.stavalues3::text::cstring, i._value_type3::regtype::oid, -1)
2152
- end,
2153
- stavalues4 = case
2154
- when i.stavalues4 is null then null
2155
- else array_in(i.stavalues4::text::cstring, i._value_type4::regtype::oid, -1)
2156
- end,
2157
- stavalues5 = case
2158
- when i.stavalues5 is null then null
2159
- else array_in(i.stavalues5::text::cstring, i._value_type5::regtype::oid, -1)
2160
- end
2161
- -- stavalues1 = i.stavalues1,
2162
- -- stavalues2 = i.stavalues2,
2163
- -- stavalues3 = i.stavalues3,
2164
- -- stavalues4 = i.stavalues4,
2165
- -- stavalues5 = i.stavalues5
2166
- FROM input i
2167
- WHERE s.starelid = i.starelid AND s.staattnum = i.staattnum AND s.stainherit = i.stainherit
2168
- RETURNING s.starelid, s.staattnum, s.stainherit, s.stakind1, s.stakind2, s.stakind3, s.stakind4, s.stakind5
2169
- ),
2170
- inserted as (
2171
- INSERT INTO pg_statistic (
2172
- starelid, staattnum, stainherit,
2173
- stanullfrac, stawidth, stadistinct,
2174
- stakind1, stakind2, stakind3, stakind4, stakind5,
2175
- staop1, staop2, staop3, staop4, staop5,
2176
- stacoll1, stacoll2, stacoll3, stacoll4, stacoll5,
2177
- stanumbers1, stanumbers2, stanumbers3, stanumbers4, stanumbers5,
2178
- stavalues1, stavalues2, stavalues3, stavalues4, stavalues5
2179
- )
2180
- SELECT
2181
- i.starelid, i.staattnum, i.stainherit,
2182
- i.stanullfrac, i.stawidth, i.stadistinct,
2183
- i.stakind1, i.stakind2, i.stakind3, i.stakind4, i.stakind5,
2184
- i.staop1, i.staop2, i.staop3, i.staop4, i.staop5,
2185
- i.stacoll1, i.stacoll2, i.stacoll3, i.stacoll4, i.stacoll5,
2186
- i.stanumbers1, i.stanumbers2, i.stanumbers3, i.stanumbers4, i.stanumbers5,
2187
- -- i.stavalues1, i.stavalues2, i.stavalues3, i.stavalues4, i.stavalues5,
2188
- case
2189
- when i.stavalues1 is null then null
2190
- else array_in(i.stavalues1::text::cstring, i._value_type1::regtype::oid, -1)
2191
- end,
2192
- case
2193
- when i.stavalues2 is null then null
2194
- else array_in(i.stavalues2::text::cstring, i._value_type2::regtype::oid, -1)
2195
- end,
2196
- case
2197
- when i.stavalues3 is null then null
2198
- else array_in(i.stavalues3::text::cstring, i._value_type3::regtype::oid, -1)
2199
- end,
2200
- case
2201
- when i.stavalues4 is null then null
2202
- else array_in(i.stavalues4::text::cstring, i._value_type4::regtype::oid, -1)
2203
- end,
2204
- case
2205
- when i.stavalues5 is null then null
2206
- else array_in(i.stavalues5::text::cstring, i._value_type5::regtype::oid, -1)
2207
- end
2208
- -- i._value_type1, i._value_type2, i._value_type3, i._value_type4, i._value_type5
2209
- FROM input i
2210
- LEFT JOIN updated u
2211
- ON i.starelid = u.starelid AND i.staattnum = u.staattnum AND i.stainherit = u.stainherit
2212
- WHERE u.starelid IS NULL
2213
- returning starelid, staattnum, stainherit, stakind1, stakind2, stakind3, stakind4, stakind5
2214
- )
2215
- select * from updated union all (select * from inserted); -- @qd_introspection`;
2216
- columnStatsUpdatePromise = tx.exec(sql, [columnStatsValues]).catch((err) => {
2217
- console.error("Something wrong wrong updating column stats");
2218
- console.error(err);
2219
- throw err;
2220
- });
2221
- const reltuplesValues = [];
2222
- for (const table of this.ownMetadata) {
2223
- processedTables.add(`${table.schemaName}.${table.tableName}`);
2224
- let targetTable;
2225
- if (this.exportedMetadata) targetTable = this.exportedMetadata.find((m) => m.tableName === table.tableName && m.schemaName === table.schemaName);
2226
- else targetTable = table;
2227
- let reltuples;
2228
- let relpages;
2229
- let relallvisible = 0;
2230
- let relallfrozen;
2231
- if (this.mode.kind === "fromAssumption") {
2232
- reltuples = this.mode.reltuples;
2233
- relpages = estimateRelpages(reltuples, table.columns);
2234
- } else if (targetTable) {
2235
- reltuples = targetTable.reltuples;
2236
- relpages = targetTable.relpages;
2237
- relallvisible = targetTable.relallvisible;
2238
- relallfrozen = targetTable.relallfrozen;
2239
- } else {
2240
- warnings.tablesNotInExports.push(`${table.schemaName}.${table.tableName}`);
2241
- reltuples = DEFAULT_RELTUPLES;
2242
- relpages = DEFAULT_RELPAGES;
2243
- }
2244
- reltuplesValues.push({
2245
- relname: table.tableName,
2246
- schema_name: table.schemaName,
2247
- reltuples,
2248
- relpages,
2249
- relallfrozen,
2250
- relallvisible
2251
- });
2252
- if (this.mode.kind === "fromAssumption") for (const index of table.indexes) {
2253
- const indexRelpages = estimateIndexRelpages(this.mode.reltuples, index.columns, index.fillfactor / 100, index.amname, relpages);
2254
- reltuplesValues.push({
2255
- relname: index.indexName,
2256
- schema_name: table.schemaName,
2257
- reltuples: this.mode.reltuples,
2258
- relpages: indexRelpages,
2259
- relallfrozen: 0,
2260
- relallvisible: indexRelpages
2261
- });
2262
- }
2263
- else if (targetTable) for (const index of targetTable.indexes) reltuplesValues.push({
2264
- relname: index.indexName,
2265
- schema_name: targetTable.schemaName,
2266
- reltuples: index.reltuples,
2267
- relpages: index.relpages,
2268
- relallfrozen: index.relallfrozen,
2269
- relallvisible: index.relallvisible
2270
- });
2271
- }
2272
- const reltuplesQuery = dedent`
2273
- update pg_class p
2274
- set reltuples = v.reltuples,
2275
- relpages = v.relpages,
2276
- -- relallfrozen = case when v.relallfrozen is null then p.relallfrozen else v.relallfrozen end,
2277
- relallvisible = case when v.relallvisible is null then p.relallvisible else v.relallvisible end
2278
- from jsonb_to_recordset($1::jsonb)
2279
- as v(reltuples real, relpages integer, relallfrozen integer, relallvisible integer, relname text, schema_name text)
2280
- where p.relname = v.relname
2281
- and p.relnamespace = (select oid from pg_namespace where nspname = v.schema_name)
2282
- returning p.relname, p.relnamespace, p.reltuples, p.relpages;
2283
- `;
2284
- const reltuplesPromise = tx.exec(reltuplesQuery, [reltuplesValues]).catch((err) => {
2285
- console.error("Something went wrong updating reltuples/relpages");
2286
- console.error(err);
2287
- return err;
2288
- });
2289
- if (this.exportedMetadata) for (const table of this.exportedMetadata) {
2290
- const tableExists = processedTables.has(`${table.schemaName}.${table.tableName}`);
2291
- if (tableExists && table.reltuples === -1) {
2292
- console.warn(`Table ${table.tableName} has reltuples -1. Your production database is probably not analyzed properly`);
2293
- warnings.tableNotAnalyzed.push(`${table.schemaName}.${table.tableName}`);
2294
- }
2295
- if (tableExists) continue;
2296
- warnings.tablesNotInTest.push(`${table.schemaName}.${table.tableName}`);
2297
- }
2298
- const [statsUpdates, reltuplesUpdates] = await Promise.all([columnStatsUpdatePromise, reltuplesPromise]);
2299
- if (!(statsUpdates ? statsUpdates.length === columnStatsValues.length : true)) console.error(`Did not update expected column stats`);
2300
- if (reltuplesUpdates.length !== reltuplesValues.length) console.error(`Did not update expected reltuples/relpages`);
2301
- return warnings;
2302
- }
2303
- static async dumpStats(db, postgresVersion, kind) {
2304
- const fullDump = kind === "full";
2305
- console.log(`dumping stats for postgres ${gray(postgresVersion)}`);
2306
- const stats = await db.exec(`
2307
- WITH table_columns AS (
2308
- SELECT
2309
- cl.relname,
2310
- n.nspname,
2311
- cl.reltuples,
2312
- cl.relpages,
2313
- cl.relallvisible,
2314
- -- cl.relallfrozen,
2315
- json_agg(
2316
- json_build_object(
2317
- 'columnName', a.attname,
2318
- 'attlen', CASE WHEN a.attlen > 0 THEN a.attlen ELSE NULL END,
2319
- 'stats', (
2320
- SELECT json_build_object(
2321
- 'starelid', s.starelid,
2322
- 'staattnum', s.staattnum,
2323
- 'stanullfrac', s.stanullfrac,
2324
- 'stawidth', s.stawidth,
2325
- 'stadistinct', s.stadistinct,
2326
- 'stakind1', s.stakind1, 'staop1', s.staop1, 'stacoll1', s.stacoll1, 'stanumbers1', s.stanumbers1,
2327
- 'stakind2', s.stakind2, 'staop2', s.staop2, 'stacoll2', s.stacoll2, 'stanumbers2', s.stanumbers2,
2328
- 'stakind3', s.stakind3, 'staop3', s.staop3, 'stacoll3', s.stacoll3, 'stanumbers3', s.stanumbers3,
2329
- 'stakind4', s.stakind4, 'staop4', s.staop4, 'stacoll4', s.stacoll4, 'stanumbers4', s.stanumbers4,
2330
- 'stakind5', s.stakind5, 'staop5', s.staop5, 'stacoll5', s.stacoll5, 'stanumbers5', s.stanumbers5,
2331
- 'stavalues1', CASE WHEN $1 THEN s.stavalues1 ELSE NULL END,
2332
- 'stavalues2', CASE WHEN $1 THEN s.stavalues2 ELSE NULL END,
2333
- 'stavalues3', CASE WHEN $1 THEN s.stavalues3 ELSE NULL END,
2334
- 'stavalues4', CASE WHEN $1 THEN s.stavalues4 ELSE NULL END,
2335
- 'stavalues5', CASE WHEN $1 THEN s.stavalues5 ELSE NULL END
2336
- )
2337
- FROM pg_statistic s
2338
- WHERE s.starelid = a.attrelid AND s.staattnum = a.attnum
2339
- )
2340
- )
2341
- ORDER BY a.attnum
2342
- ) AS columns
2343
- FROM pg_class cl
2344
- JOIN pg_namespace n ON n.oid = cl.relnamespace
2345
- JOIN pg_attribute a ON a.attrelid = cl.oid AND a.attnum > 0 AND NOT a.attisdropped
2346
- WHERE cl.relkind = 'r'
2347
- AND n.nspname NOT IN ('pg_catalog', 'information_schema', 'tiger', 'tiger_data', 'topology')
2348
- AND cl.relname NOT IN ('pg_stat_statements', 'pg_stat_statements_info')
2349
- GROUP BY cl.relname, n.nspname, cl.reltuples, cl.relpages, cl.relallvisible
2350
- ),
2351
- table_indexes AS (
2352
- SELECT
2353
- t.relname AS table_name,
2354
- json_agg(
2355
- json_build_object(
2356
- 'indexName', i.relname,
2357
- 'amname', am.amname,
2358
- 'reltuples', i.reltuples,
2359
- 'relpages', i.relpages,
2360
- 'relallvisible', i.relallvisible,
2361
- -- 'relallfrozen', i.relallfrozen,
2362
- 'fillfactor', COALESCE(
2363
- (
2364
- SELECT (regexp_match(opt, 'fillfactor=(\\d+)'))[1]::integer
2365
- FROM unnest(i.reloptions) AS opt
2366
- WHERE opt LIKE 'fillfactor=%'
2367
- LIMIT 1
2368
- ),
2369
- 90
2370
- ),
2371
- 'columns', COALESCE(
2372
- (
2373
- SELECT json_agg(json_build_object(
2374
- 'attlen', CASE WHEN a.attlen > 0 THEN a.attlen ELSE NULL END
2375
- ) ORDER BY col_pos.ord)
2376
- FROM unnest(ix.indkey) WITH ORDINALITY AS col_pos(attnum, ord)
2377
- JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = col_pos.attnum
2378
- WHERE col_pos.attnum > 0
2379
- ),
2380
- '[]'::json
2381
- )
2382
- )
2383
- ) AS indexes
2384
- FROM pg_class t
2385
- JOIN pg_index ix ON ix.indrelid = t.oid
2386
- JOIN pg_class i ON i.oid = ix.indexrelid
2387
- JOIN pg_am am ON am.oid = i.relam
2388
- JOIN pg_namespace n ON n.oid = t.relnamespace
2389
- WHERE t.relname NOT LIKE 'pg_%'
2390
- AND n.nspname <> 'information_schema'
2391
- AND n.nspname NOT IN ('tiger', 'tiger_data', 'topology')
2392
- GROUP BY t.relname
2393
- )
2394
- SELECT json_agg(
2395
- json_build_object(
2396
- 'tableName', tc.relname,
2397
- 'schemaName', tc.nspname,
2398
- 'reltuples', tc.reltuples,
2399
- 'relpages', tc.relpages,
2400
- 'relallvisible', tc.relallvisible,
2401
- -- 'relallfrozen', tc.relallfrozen,
2402
- 'columns', COALESCE(tc.columns, '[]'::json),
2403
- 'indexes', COALESCE(ti.indexes, '[]'::json)
2404
- )
2405
- )
2406
- FROM table_columns tc
2407
- LEFT JOIN table_indexes ti
2408
- ON ti.table_name = tc.relname;
2409
- `, [fullDump]);
2410
- return z.array(ExportedStats).parse(stats[0].json_agg);
2411
- }
2412
- /**
2413
- * Returns all indexes in the database.
2414
- * ONLY handles regular btree indexes
2415
- */
2416
- async getExistingIndexes() {
2417
- return await this.db.exec(`
2418
- WITH partitioned_tables AS (
2419
- SELECT
2420
- inhparent::regclass AS parent_table,
2421
- inhrelid::regclass AS partition_table
2422
- FROM
2423
- pg_inherits
2424
- )
2425
- SELECT
2426
- n.nspname AS schema_name,
2427
- COALESCE(pt.parent_table::text, t.relname) AS table_name,
2428
- i.relname AS index_name,
2429
- ix.indisprimary as is_primary,
2430
- ix.indisunique as is_unique,
2431
- am.amname AS index_type,
2432
- array_agg(
2433
- CASE
2434
- -- Handle regular columns
2435
- WHEN a.attname IS NOT NULL THEN
2436
- json_build_object('name', a.attname, 'order',
2437
- CASE
2438
- WHEN (indoption[array_position(ix.indkey, a.attnum)] & 1) = 1 THEN 'DESC'
2439
- ELSE 'ASC'
2440
- END,
2441
- 'opclass', CASE WHEN opc.opcdefault THEN NULL ELSE opc.opcname END)
2442
- -- Handle expressions
2443
- ELSE
2444
- json_build_object('name', pg_get_expr((ix.indexprs)::pg_node_tree, t.oid), 'order',
2445
- CASE
2446
- WHEN (indoption[array_position(ix.indkey, k.attnum)] & 1) = 1 THEN 'DESC'
2447
- ELSE 'ASC'
2448
- END,
2449
- 'opclass', CASE WHEN opc.opcdefault THEN NULL ELSE opc.opcname END)
2450
- END
2451
- ORDER BY array_position(ix.indkey, k.attnum)
2452
- ) AS index_columns
2453
- FROM
2454
- pg_class t
2455
- LEFT JOIN partitioned_tables pt ON t.oid = pt.partition_table
2456
- JOIN pg_index ix ON t.oid = ix.indrelid
2457
- JOIN pg_class i ON i.oid = ix.indexrelid
2458
- JOIN pg_am am ON i.relam = am.oid
2459
- LEFT JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY k(attnum, ordinality) ON true
2460
- LEFT JOIN pg_attribute a ON a.attnum = k.attnum AND a.attrelid = t.oid
2461
- LEFT JOIN pg_opclass opc ON opc.oid = ix.indclass[k.ordinality - 1]
2462
- JOIN pg_namespace n ON t.relnamespace = n.oid
2463
- WHERE
2464
- n.nspname not like 'pg_%' and
2465
- n.nspname <> 'information_schema'
2466
- GROUP BY
2467
- n.nspname, COALESCE(pt.parent_table::text, t.relname), i.relname, am.amname, ix.indisprimary, ix.indisunique
2468
- ORDER BY
2469
- COALESCE(pt.parent_table::text, t.relname), i.relname; -- @qd_introspection
2470
- `);
2471
- }
2472
- };
2473
- _defineProperty(Statistics, "defaultStatsMode", Object.freeze({
2474
- kind: "fromAssumption",
2475
- reltuples: DEFAULT_RELTUPLES,
2476
- relpages: DEFAULT_RELPAGES
2477
- }));
2478
- //#endregion
2479
- //#region src/optimizer/pss-rewriter.ts
2480
- /**
2481
- * Rewriter for pg_stat_statements queries.
2482
- * Not all queries found in pg_stat_statements can be
2483
- * directly sent back to the database without first being rewritten.
2484
- */
2485
- var PssRewriter = class {
2486
- constructor() {
2487
- _defineProperty(this, "problematicKeywords", [
2488
- "interval",
2489
- "timestamp",
2490
- "geometry"
2491
- ]);
2492
- }
2493
- rewrite(query) {
2494
- return this.rewriteKeywordWithParameter(query);
2495
- }
2496
- rewriteKeywordWithParameter(query) {
2497
- return query.replace(/\b(\w+) (\$\d+)\b/gi, (match) => {
2498
- const [keyword, parameter] = match.split(" ");
2499
- if (!this.problematicKeywords.includes(keyword.toLowerCase())) return match;
2500
- return `(${parameter}::${keyword.toLowerCase()})`;
2501
- });
2502
- }
2503
- };
2504
- //#endregion
2505
- export { Analyzer, ExportedStats, ExportedStatsColumns, ExportedStatsIndex, ExportedStatsStatistics, ExportedStatsV1, IndexOptimizer, PROCEED, PgIdentifier, PostgresExplainStageSchema, PostgresQueryBuilder, PostgresVersion, PssRewriter, SKIP, Statistics, StatisticsMode, StatisticsSource, dropIndex, ignoredIdentifier, isIndexProbablyDroppable, isIndexSupported, parseNudges };
2506
-
2507
- //# sourceMappingURL=index.mjs.map
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";
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 };