-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
schemaInsightsApi.ts
195 lines (179 loc) · 6.08 KB
/
schemaInsightsApi.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// Copyright 2022 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
import { executeSql, SqlExecutionRequest, SqlTxnResult } from "./sqlApi";
import {
InsightRecommendation,
InsightType,
recommendDropUnusedIndex,
} from "../insights";
import { HexStringToInt64String } from "../util";
// Export for db-console import from clusterUiApi.
export type { InsightRecommendation } from "../insights";
export type ClusterIndexUsageStatistic = {
table_id: number;
index_id: number;
last_read?: string;
created_at?: string;
index_name: string;
table_name: string;
database_id: number;
database_name: string;
unused_threshold: string;
};
type CreateIndexRecommendationsResponse = {
fingerprint_id: string;
db: string;
query: string;
querysummary: string;
implicittxn: boolean;
index_recommendations: string[];
};
type SchemaInsightResponse =
| ClusterIndexUsageStatistic
| CreateIndexRecommendationsResponse;
type SchemaInsightQuery<RowType> = {
name: InsightType;
query: string;
toSchemaInsight: (response: SqlTxnResult<RowType>) => InsightRecommendation[];
};
function clusterIndexUsageStatsToSchemaInsight(
txn_result: SqlTxnResult<ClusterIndexUsageStatistic>,
): InsightRecommendation[] {
const results: Record<string, InsightRecommendation> = {};
txn_result.rows.forEach(row => {
const result = recommendDropUnusedIndex(row);
if (result.recommend) {
const key = row.table_id.toString() + row.index_id.toString();
if (!results[key]) {
results[key] = {
type: "DROP_INDEX",
database: row.database_name,
query: `DROP INDEX ${row.table_name}@${row.index_name};`,
indexDetails: {
table: row.table_name,
indexID: row.index_id,
indexName: row.index_name,
lastUsed: result.reason,
},
};
}
}
});
return Object.values(results);
}
function createIndexRecommendationsToSchemaInsight(
txn_result: SqlTxnResult<CreateIndexRecommendationsResponse>,
): InsightRecommendation[] {
const results: InsightRecommendation[] = [];
txn_result.rows.forEach(row => {
row.index_recommendations.forEach(rec => {
const recSplit = rec.split(" : ");
const recType = recSplit[0];
const recQuery = recSplit[1];
let idxType: InsightType;
switch (recType) {
case "creation":
idxType = "CREATE_INDEX";
break;
case "replacement":
idxType = "REPLACE_INDEX";
break;
case "drop":
idxType = "DROP_INDEX";
break;
}
results.push({
type: idxType,
database: row.db,
execution: {
statement: row.query,
summary: row.querysummary,
fingerprintID: HexStringToInt64String(row.fingerprint_id),
implicit: row.implicittxn,
},
query: recQuery,
});
});
});
return results;
}
const dropUnusedIndexQuery: SchemaInsightQuery<ClusterIndexUsageStatistic> = {
name: "DROP_INDEX",
query: `SELECT
us.table_id,
us.index_id,
us.last_read,
ti.created_at,
ti.index_name,
t.name as table_name,
t.parent_id as database_id,
t.database_name,
(SELECT value FROM crdb_internal.cluster_settings WHERE variable = 'sql.index_recommendation.drop_unused_duration') AS unused_threshold
FROM "".crdb_internal.index_usage_statistics AS us
JOIN "".crdb_internal.table_indexes as ti ON us.index_id = ti.index_id AND us.table_id = ti.descriptor_id
JOIN "".crdb_internal.tables as t ON t.table_id = ti.descriptor_id and t.name = ti.descriptor_name
WHERE t.database_name != 'system' AND ti.index_type != 'primary';`,
toSchemaInsight: clusterIndexUsageStatsToSchemaInsight,
};
const createIndexRecommendationsQuery: SchemaInsightQuery<CreateIndexRecommendationsResponse> =
{
name: "CREATE_INDEX",
query: `SELECT
encode(fingerprint_id, 'hex') AS fingerprint_id,
metadata ->> 'db' AS db,
metadata ->> 'query' AS query,
metadata ->> 'querySummary' as querySummary,
metadata ->> 'implicitTxn' AS implicitTxn,
index_recommendations
FROM (
SELECT
fingerprint_id,
statistics -> 'statistics' ->> 'lastExecAt' as lastExecAt,
metadata,
index_recommendations,
row_number() over(
PARTITION BY
fingerprint_id
ORDER BY statistics -> 'statistics' ->> 'lastExecAt' DESC
) AS rank
FROM crdb_internal.statement_statistics)
WHERE rank=1 AND array_length(index_recommendations,1) > 0;`,
toSchemaInsight: createIndexRecommendationsToSchemaInsight,
};
const schemaInsightQueries: SchemaInsightQuery<SchemaInsightResponse>[] = [
dropUnusedIndexQuery,
createIndexRecommendationsQuery,
];
// getSchemaInsights makes requests over the SQL API and transforms the corresponding
// SQL responses into schema insights.
export function getSchemaInsights(): Promise<InsightRecommendation[]> {
const request: SqlExecutionRequest = {
statements: schemaInsightQueries.map(insightQuery => ({
sql: insightQuery.query,
})),
execute: true,
};
return executeSql<SchemaInsightResponse>(request).then(result => {
const results: InsightRecommendation[] = [];
if (result.execution.txn_results.length === 0) {
// No data.
return results;
}
result.execution.txn_results.map(txn_result => {
// Note: txn_result.statement values begin at 1, not 0.
const insightQuery: SchemaInsightQuery<SchemaInsightResponse> =
schemaInsightQueries[txn_result.statement - 1];
if (txn_result.rows) {
results.push(...insightQuery.toSchemaInsight(txn_result));
}
});
return results;
});
}