-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathindex.go
364 lines (336 loc) · 9.82 KB
/
index.go
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the CockroachDB Software License
// included in the /LICENSE file.
package catformat
import (
"context"
"fmt"
"strconv"
"github.com/cockroachdb/cockroach/pkg/geo/geoindex"
"github.com/cockroachdb/cockroach/pkg/geo/geopb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemaexpr"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/idxtype"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/errors"
)
// IndexDisplayMode influences how an index should be formatted for pretty print
// in IndexForDisplay function.
type IndexDisplayMode int
const (
// IndexDisplayShowCreate indicates index definition to be printed as a CREATE
// INDEX statement.
IndexDisplayShowCreate IndexDisplayMode = iota
// IndexDisplayDefOnly indicates index definition to be printed as INDEX
// definition format within a CREATE TABLE statement.
IndexDisplayDefOnly
)
// IndexForDisplay formats an index descriptor as a SQL string. It converts user
// defined types in partial index predicate expressions to a human-readable
// form.
//
// If tableName is anonymous then no table name is included in the formatted
// string. For example:
//
// INDEX i (a) WHERE b > 0
//
// If tableName is not anonymous, then "ON" and the name is included:
//
// INDEX i ON t (a) WHERE b > 0
func IndexForDisplay(
ctx context.Context,
table catalog.TableDescriptor,
tableName *tree.TableName,
index catalog.Index,
partition string,
formatFlags tree.FmtFlags,
evalCtx *eval.Context,
semaCtx *tree.SemaContext,
sessionData *sessiondata.SessionData,
displayMode IndexDisplayMode,
) (string, error) {
return indexForDisplay(
ctx,
table,
tableName,
index.IndexDesc(),
index.Primary(),
partition,
formatFlags,
evalCtx,
semaCtx,
sessionData,
displayMode,
)
}
func indexForDisplay(
ctx context.Context,
table catalog.TableDescriptor,
tableName *tree.TableName,
index *descpb.IndexDescriptor,
isPrimary bool,
partition string,
formatFlags tree.FmtFlags,
evalCtx *eval.Context,
semaCtx *tree.SemaContext,
sessionData *sessiondata.SessionData,
displayMode IndexDisplayMode,
) (string, error) {
// Please also update CreateIndex's "Format" method in
// pkg/sql/sem/tree/create.go if there's any update to index definition
// components.
if displayMode == IndexDisplayShowCreate && *tableName == descpb.AnonymousTable {
return "", errors.New("tableName must be set for IndexDisplayShowCreate mode")
}
f := tree.NewFmtCtx(formatFlags)
if displayMode == IndexDisplayShowCreate {
f.WriteString("CREATE ")
}
if index.Unique {
f.WriteString("UNIQUE ")
}
if !f.HasFlags(tree.FmtPGCatalog) {
switch index.Type {
case idxtype.INVERTED:
f.WriteString("INVERTED ")
case idxtype.VECTOR:
f.WriteString("VECTOR ")
}
}
f.WriteString("INDEX ")
f.FormatNameP(&index.Name)
if *tableName != descpb.AnonymousTable {
f.WriteString(" ON ")
f.FormatNode(tableName)
}
if f.HasFlags(tree.FmtPGCatalog) {
f.WriteString(" USING")
switch index.Type {
case idxtype.INVERTED:
f.WriteString(" gin")
case idxtype.VECTOR:
f.WriteString(" cspann")
default:
f.WriteString(" btree")
}
}
f.WriteString(" (")
if err := FormatIndexElements(ctx, table, index, f, evalCtx, semaCtx, sessionData); err != nil {
return "", err
}
f.WriteByte(')')
if index.IsSharded() {
if f.HasFlags(tree.FmtPGCatalog) {
fmt.Fprintf(f, " USING HASH WITH (bucket_count=%v)",
index.Sharded.ShardBuckets)
} else {
f.WriteString(" USING HASH")
}
}
if !isPrimary && len(index.StoreColumnNames) > 0 {
f.WriteString(" STORING (")
for i := range index.StoreColumnNames {
if i > 0 {
f.WriteString(", ")
}
f.FormatNameP(&index.StoreColumnNames[i])
}
f.WriteByte(')')
}
f.WriteString(partition)
if !f.HasFlags(tree.FmtPGCatalog) {
if err := formatStorageConfigs(table, index, f); err != nil {
return "", err
}
}
if index.IsPartial() {
predFmtFlag := tree.FmtParsable
if f.HasFlags(tree.FmtPGCatalog) {
predFmtFlag = tree.FmtPGCatalog
} else {
if f.HasFlags(tree.FmtMarkRedactionNode) {
predFmtFlag |= tree.FmtMarkRedactionNode
}
if f.HasFlags(tree.FmtOmitNameRedaction) {
predFmtFlag |= tree.FmtOmitNameRedaction
}
}
pred, err := schemaexpr.FormatExprForDisplay(ctx, table, index.Predicate, evalCtx, semaCtx, sessionData, predFmtFlag)
if err != nil {
return "", err
}
f.WriteString(" WHERE ")
if f.HasFlags(tree.FmtPGCatalog) {
f.WriteString("(")
f.WriteString(pred)
f.WriteString(")")
} else {
f.WriteString(pred)
}
}
if idxInvisibility := index.Invisibility; idxInvisibility != 0.0 {
if idxInvisibility == 1.0 {
f.WriteString(" NOT VISIBLE")
} else {
f.WriteString(" VISIBILITY ")
f.WriteString(fmt.Sprintf("%.2f", 1-index.Invisibility))
}
}
return f.CloseAndGetString(), nil
}
// FormatIndexElements formats the key columns an index. If the column is an
// inaccessible computed column, the computed column expression is formatted.
// Otherwise, the column name is formatted. Each column is separated by commas
// and includes the direction of the index if the index is not an inverted
// index.
func FormatIndexElements(
ctx context.Context,
table catalog.TableDescriptor,
index *descpb.IndexDescriptor,
f *tree.FmtCtx,
evalCtx *eval.Context,
semaCtx *tree.SemaContext,
sessionData *sessiondata.SessionData,
) error {
elemFmtFlag := tree.FmtParsable
if f.HasFlags(tree.FmtPGCatalog) {
elemFmtFlag = tree.FmtPGCatalog
} else {
if f.HasFlags(tree.FmtMarkRedactionNode) {
elemFmtFlag |= tree.FmtMarkRedactionNode
}
if f.HasFlags(tree.FmtOmitNameRedaction) {
elemFmtFlag |= tree.FmtOmitNameRedaction
}
}
startIdx := index.ExplicitColumnStartIdx()
for i, n := startIdx, len(index.KeyColumnIDs); i < n; i++ {
col, err := catalog.MustFindColumnByID(table, index.KeyColumnIDs[i])
if err != nil {
return err
}
if i > startIdx {
f.WriteString(", ")
}
if col.IsExpressionIndexColumn() {
expr, err := schemaexpr.FormatExprForExpressionIndexDisplay(
ctx, table, col.GetComputeExpr(), evalCtx, semaCtx, sessionData, elemFmtFlag,
)
if err != nil {
return err
}
f.WriteString(expr)
} else {
f.FormatNameP(&index.KeyColumnNames[i])
}
// TODO(drewk): we might need to print something like "vector_l2_ops" for
// vector indexes.
if index.Type == idxtype.INVERTED &&
col.GetID() == index.InvertedColumnID() && len(index.InvertedColumnKinds) > 0 {
switch index.InvertedColumnKinds[0] {
case catpb.InvertedIndexColumnKind_TRIGRAM:
f.WriteString(" gin_trgm_ops")
}
}
// The last column of an inverted or vector index cannot have a DESC
// direction. Since the default direction is ASC, we omit the direction
// entirely for inverted/vector index columns.
if i < n-1 || index.Type.AllowExplicitDirection() {
f.WriteByte(' ')
f.WriteString(index.KeyColumnDirections[i].String())
}
}
return nil
}
// formatStorageConfigs writes the index's storage configurations to the given
// format context.
func formatStorageConfigs(
table catalog.TableDescriptor, index *descpb.IndexDescriptor, f *tree.FmtCtx,
) error {
numCustomSettings := 0
if index.GeoConfig.S2Geometry != nil || index.GeoConfig.S2Geography != nil {
var s2Config *geopb.S2Config
if index.GeoConfig.S2Geometry != nil {
s2Config = index.GeoConfig.S2Geometry.S2Config
}
if index.GeoConfig.S2Geography != nil {
s2Config = index.GeoConfig.S2Geography.S2Config
}
defaultS2Config := geoindex.DefaultS2Config()
if *s2Config != *defaultS2Config {
for _, check := range []struct {
key string
val int32
defaultVal int32
}{
{`s2_max_level`, s2Config.MaxLevel, defaultS2Config.MaxLevel},
{`s2_level_mod`, s2Config.LevelMod, defaultS2Config.LevelMod},
{`s2_max_cells`, s2Config.MaxCells, defaultS2Config.MaxCells},
} {
if check.val != check.defaultVal {
if numCustomSettings > 0 {
f.WriteString(", ")
} else {
f.WriteString(" WITH (")
}
numCustomSettings++
f.WriteString(check.key)
f.WriteString("=")
f.WriteString(strconv.Itoa(int(check.val)))
}
}
}
if index.GeoConfig.S2Geometry != nil {
col, err := catalog.MustFindColumnByID(table, index.InvertedColumnID())
if err != nil {
return errors.Wrapf(err, "expected column %q to exist in table", index.InvertedColumnName())
}
defaultConfig, err := geoindex.GeometryIndexConfigForSRID(col.GetType().GeoSRIDOrZero())
if err != nil {
return errors.Wrapf(err, "expected SRID definition for %d", col.GetType().GeoSRIDOrZero())
}
cfg := index.GeoConfig.S2Geometry
for _, check := range []struct {
key string
val float64
defaultVal float64
}{
{`geometry_min_x`, cfg.MinX, defaultConfig.S2Geometry.MinX},
{`geometry_max_x`, cfg.MaxX, defaultConfig.S2Geometry.MaxX},
{`geometry_min_y`, cfg.MinY, defaultConfig.S2Geometry.MinY},
{`geometry_max_y`, cfg.MaxY, defaultConfig.S2Geometry.MaxY},
} {
if check.val != check.defaultVal {
if numCustomSettings > 0 {
f.WriteString(", ")
} else {
f.WriteString(" WITH (")
}
numCustomSettings++
f.WriteString(check.key)
f.WriteString("=")
f.WriteString(strconv.FormatFloat(check.val, 'f', -1, 64))
}
}
}
}
if index.IsSharded() {
if numCustomSettings > 0 {
f.WriteString(", ")
} else {
f.WriteString(" WITH (")
}
f.WriteString(`bucket_count=`)
f.WriteString(strconv.FormatInt(int64(index.Sharded.ShardBuckets), 10))
numCustomSettings++
}
if numCustomSettings > 0 {
f.WriteString(")")
}
return nil
}