-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathutils.go
350 lines (315 loc) · 9.51 KB
/
utils.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
// Copyright 2019 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.
package cat
import (
"bytes"
"context"
"fmt"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/treeprinter"
"github.com/cockroachdb/errors"
)
// ExpandDataSourceGlob is a utility function that expands a tree.TablePattern
// into a list of object names.
func ExpandDataSourceGlob(
ctx context.Context, catalog Catalog, flags Flags, pattern tree.TablePattern,
) ([]DataSourceName, error) {
switch p := pattern.(type) {
case *tree.TableName:
_, name, err := catalog.ResolveDataSource(ctx, flags, p)
if err != nil {
return nil, err
}
return []DataSourceName{name}, nil
case *tree.AllTablesSelector:
schema, _, err := catalog.ResolveSchema(ctx, flags, &p.ObjectNamePrefix)
if err != nil {
return nil, err
}
return schema.GetDataSourceNames(ctx)
default:
return nil, errors.Errorf("invalid TablePattern type %T", p)
}
}
// ResolveTableIndex resolves a TableIndexName.
func ResolveTableIndex(
ctx context.Context, catalog Catalog, flags Flags, name *tree.TableIndexName,
) (Index, DataSourceName, error) {
if name.Table.ObjectName != "" {
ds, tn, err := catalog.ResolveDataSource(ctx, flags, &name.Table)
if err != nil {
return nil, DataSourceName{}, err
}
table, ok := ds.(Table)
if !ok {
return nil, DataSourceName{}, pgerror.Newf(
pgcode.WrongObjectType, "%q is not a table", name.Table.ObjectName,
)
}
if name.Index == "" {
// Return primary index.
return table.Index(0), tn, nil
}
for i := 0; i < table.IndexCount(); i++ {
if idx := table.Index(i); idx.Name() == tree.Name(name.Index) {
return idx, tn, nil
}
}
return nil, DataSourceName{}, pgerror.Newf(
pgcode.UndefinedObject, "index %q does not exist", name.Index,
)
}
// We have to search for a table that has an index with the given name.
schema, _, err := catalog.ResolveSchema(ctx, flags, &name.Table.ObjectNamePrefix)
if err != nil {
return nil, DataSourceName{}, err
}
dsNames, err := schema.GetDataSourceNames(ctx)
if err != nil {
return nil, DataSourceName{}, err
}
var found Index
var foundTabName DataSourceName
for i := range dsNames {
ds, tn, err := catalog.ResolveDataSource(ctx, flags, &dsNames[i])
if err != nil {
return nil, DataSourceName{}, err
}
table, ok := ds.(Table)
if !ok {
// Not a table, ignore.
continue
}
for i := 0; i < table.IndexCount(); i++ {
if idx := table.Index(i); idx.Name() == tree.Name(name.Index) {
if found != nil {
return nil, DataSourceName{}, pgerror.Newf(pgcode.AmbiguousParameter,
"index name %q is ambiguous (found in %s and %s)",
name.Index, tn.String(), foundTabName.String())
}
found = idx
foundTabName = tn
break
}
}
}
if found == nil {
return nil, DataSourceName{}, pgerror.Newf(
pgcode.UndefinedObject, "index %q does not exist", name.Index,
)
}
return found, foundTabName, nil
}
// ConvertColumnIDsToOrdinals converts a list of ColumnIDs (such as from a
// tree.TableRef), to a list of ordinal positions of non-mutation columns within
// the given table. See tree.Table for more information on column ordinals.
func ConvertColumnIDsToOrdinals(tab Table, columns []tree.ColumnID) (ordinals []int) {
ordinals = make([]int, len(columns))
for i, c := range columns {
ord := 0
cnt := tab.AllColumnCount()
for ord < cnt {
if !IsMutationColumn(tab, ord) && tab.Column(ord).ColID() == StableID(c) {
break
}
ord++
}
if ord >= cnt {
panic(pgerror.Newf(pgcode.UndefinedColumn,
"column [%d] does not exist", c))
}
ordinals[i] = ord
}
return ordinals
}
// FindTableColumnByName returns the ordinal of the non-mutation column having
// the given name, if one exists in the given table. Otherwise, it returns -1.
func FindTableColumnByName(tab Table, name tree.Name) int {
for ord, n := 0, tab.AllColumnCount(); ord < n; ord++ {
if !IsMutationColumn(tab, ord) && tab.Column(ord).ColName() == name {
return ord
}
}
return -1
}
// FormatTable nicely formats a catalog table using a treeprinter for debugging
// and testing.
func FormatTable(cat Catalog, tab Table, tp treeprinter.Node) {
child := tp.Childf("TABLE %s", tab.Name())
if tab.IsVirtualTable() {
child.Child("virtual table")
}
var buf bytes.Buffer
for i := 0; i < tab.AllColumnCount(); i++ {
buf.Reset()
formatColumn(tab.Column(i), IsMutationColumn(tab, i), &buf)
child.Child(buf.String())
}
// If we only have one primary family (the default), don't print it.
if tab.FamilyCount() > 1 || tab.Family(0).Name() != "primary" {
for i := 0; i < tab.FamilyCount(); i++ {
buf.Reset()
formatFamily(tab.Family(i), &buf)
child.Child(buf.String())
}
}
for i := 0; i < tab.CheckCount(); i++ {
child.Childf("CHECK (%s)", tab.Check(i).Constraint)
}
for i := 0; i < tab.DeletableIndexCount(); i++ {
formatCatalogIndex(tab, i, child)
}
for i := 0; i < tab.OutboundForeignKeyCount(); i++ {
formatCatalogFKRef(cat, false /* inbound */, tab.OutboundForeignKey(i), child)
}
for i := 0; i < tab.InboundForeignKeyCount(); i++ {
formatCatalogFKRef(cat, true /* inbound */, tab.InboundForeignKey(i), child)
}
// TODO(radu): show stats.
}
// formatCatalogIndex nicely formats a catalog index using a treeprinter for
// debugging and testing.
func formatCatalogIndex(tab Table, ord int, tp treeprinter.Node) {
idx := tab.Index(ord)
inverted := ""
if idx.IsInverted() {
inverted = "INVERTED "
}
mutation := ""
if IsMutationIndex(tab, ord) {
mutation = " (mutation)"
}
child := tp.Childf("%sINDEX %s%s", inverted, idx.Name(), mutation)
var buf bytes.Buffer
colCount := idx.ColumnCount()
if ord == PrimaryIndex {
// Omit the "stored" columns from the primary index.
colCount = idx.KeyColumnCount()
}
for i := 0; i < colCount; i++ {
buf.Reset()
idxCol := idx.Column(i)
formatColumn(idxCol.Column, false /* isMutationCol */, &buf)
if idxCol.Descending {
fmt.Fprintf(&buf, " desc")
}
if i >= idx.LaxKeyColumnCount() {
fmt.Fprintf(&buf, " (storing)")
}
child.Child(buf.String())
}
FormatZone(idx.Zone(), child)
partPrefixes := idx.PartitionByListPrefixes()
if len(partPrefixes) != 0 {
c := child.Child("partition by list prefixes")
for i := range partPrefixes {
c.Child(partPrefixes[i].String())
}
}
if n := idx.InterleaveAncestorCount(); n > 0 {
c := child.Child("interleave ancestors")
for i := 0; i < n; i++ {
table, index, numKeyCols := idx.InterleaveAncestor(i)
c.Childf(
"table=%d index=%d (%d key column%s)",
table, index, numKeyCols, util.Pluralize(int64(numKeyCols)),
)
}
}
if n := idx.InterleavedByCount(); n > 0 {
c := child.Child("interleaved by")
for i := 0; i < n; i++ {
table, index := idx.InterleavedBy(i)
c.Childf("table=%d index=%d", table, index)
}
}
}
// formatColPrefix returns a string representation of a list of columns. The
// columns are provided through a function.
func formatCols(tab Table, numCols int, colOrdinal func(tab Table, i int) int) string {
var buf bytes.Buffer
buf.WriteByte('(')
for i := 0; i < numCols; i++ {
if i > 0 {
buf.WriteString(", ")
}
colName := tab.Column(colOrdinal(tab, i)).ColName()
buf.WriteString(colName.String())
}
buf.WriteByte(')')
return buf.String()
}
// formatCatalogFKRef nicely formats a catalog foreign key reference using a
// treeprinter for debugging and testing.
func formatCatalogFKRef(
catalog Catalog, inbound bool, fkRef ForeignKeyConstraint, tp treeprinter.Node,
) {
originDS, _, err := catalog.ResolveDataSourceByID(context.TODO(), Flags{}, fkRef.OriginTableID())
if err != nil {
panic(err)
}
refDS, _, err := catalog.ResolveDataSourceByID(context.TODO(), Flags{}, fkRef.ReferencedTableID())
if err != nil {
panic(err)
}
title := "CONSTRAINT"
if inbound {
title = "REFERENCED BY " + title
}
var extra bytes.Buffer
if fkRef.MatchMethod() != tree.MatchSimple {
fmt.Fprintf(&extra, " %s", fkRef.MatchMethod())
}
if action := fkRef.DeleteReferenceAction(); action != tree.NoAction {
fmt.Fprintf(&extra, " ON DELETE %s", action.String())
}
tp.Childf(
"%s %s FOREIGN KEY %v %s REFERENCES %v %s%s",
title,
fkRef.Name(),
originDS.Name(),
formatCols(originDS.(Table), fkRef.ColumnCount(), fkRef.OriginColumnOrdinal),
refDS.Name(),
formatCols(refDS.(Table), fkRef.ColumnCount(), fkRef.ReferencedColumnOrdinal),
extra.String(),
)
}
func formatColumn(col Column, isMutationCol bool, buf *bytes.Buffer) {
fmt.Fprintf(buf, "%s %s", col.ColName(), col.DatumType())
if !col.IsNullable() {
fmt.Fprintf(buf, " not null")
}
if col.IsComputed() {
fmt.Fprintf(buf, " as (%s) stored", col.ComputedExprStr())
}
if col.HasDefault() {
fmt.Fprintf(buf, " default (%s)", col.DefaultExprStr())
}
if col.IsHidden() {
fmt.Fprintf(buf, " [hidden]")
}
if isMutationCol {
fmt.Fprintf(buf, " [mutation]")
}
}
func formatFamily(family Family, buf *bytes.Buffer) {
fmt.Fprintf(buf, "FAMILY %s (", family.Name())
for i, n := 0, family.ColumnCount(); i < n; i++ {
if i != 0 {
buf.WriteString(", ")
}
col := family.Column(i)
buf.WriteString(string(col.ColName()))
}
buf.WriteString(")")
}