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