-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
descriptor.go
359 lines (317 loc) · 12.9 KB
/
descriptor.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
// Copyright 2020 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 catalog
import (
"context"
"github.com/cockroachdb/cockroach/pkg/geo/geoindex"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"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/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/redact"
)
// IndexOpts configures the behavior of TableDescriptor.ForEachIndex.
type IndexOpts struct {
// NonPhysicalPrimaryIndex should be included.
NonPhysicalPrimaryIndex bool
// DropMutations should be included.
DropMutations bool
// AddMutations should be included.
AddMutations bool
}
// Descriptor is an interface to be shared by individual descriptor
// types.
type Descriptor interface {
tree.NameResolutionResult
GetID() descpb.ID
GetName() string
GetParentID() descpb.ID
GetParentSchemaID() descpb.ID
// IsUncommittedVersion returns true if this descriptor represent a version
// which is not the currently committed version. Implementations may return
// false negatives here in cases where a descriptor may have crossed a
// serialization boundary. In particular, this can occur during execution on
// remote nodes as well as during some scenarios in schema changes.
IsUncommittedVersion() bool
// Metadata for descriptor leasing.
GetVersion() descpb.DescriptorVersion
GetModificationTime() hlc.Timestamp
GetDrainingNames() []descpb.NameInfo
GetPrivileges() *descpb.PrivilegeDescriptor
TypeName() string
GetAuditMode() descpb.TableDescriptor_AuditMode
Public() bool
Adding() bool
Dropped() bool
Offline() bool
GetOfflineReason() string
// DescriptorProto prepares this descriptor for serialization.
DescriptorProto() *descpb.Descriptor
}
// DatabaseDescriptor will eventually be called dbdesc.Descriptor.
// It is implemented by Immutable.
type DatabaseDescriptor interface {
Descriptor
// Note: Prior to user-defined schemas, databases were the schema meta for
// objects.
//
// TODO(ajwerner): Remove this in the 20.2 cycle as part of user-defined
// schemas.
tree.SchemaMeta
DatabaseDesc() *descpb.DatabaseDescriptor
Regions() (descpb.Regions, error)
IsMultiRegion() bool
PrimaryRegion() (descpb.Region, error)
Validate() error
}
// SchemaDescriptor will eventually be called schemadesc.Descriptor.
// It is implemented by Immutable.
type SchemaDescriptor interface {
Descriptor
SchemaDesc() *descpb.SchemaDescriptor
}
// TableDescriptor is an interface around the table descriptor types.
type TableDescriptor interface {
Descriptor
TableDesc() *descpb.TableDescriptor
GetState() descpb.DescriptorState
GetSequenceOpts() *descpb.TableDescriptor_SequenceOpts
GetViewQuery() string
GetLease() *descpb.TableDescriptor_SchemaChangeLease
GetDropTime() int64
GetFormatVersion() descpb.FormatVersion
GetPrimaryIndexID() descpb.IndexID
GetPrimaryIndex() *descpb.IndexDescriptor // deprecated
PrimaryIndexSpan(codec keys.SQLCodec) roachpb.Span
IndexSpan(codec keys.SQLCodec, id descpb.IndexID) roachpb.Span
GetIndexMutationCapabilities(id descpb.IndexID) (isMutation, isWriteOnly bool)
KeysPerRow(id descpb.IndexID) (int, error)
PrimaryIndexInterface() Index
AllIndexes() []Index
ActiveIndexes() []Index
NonDropIndexes() []Index
PartialIndexes() []Index
PublicNonPrimaryIndexes() []Index
WritableNonPrimaryIndexes() []Index
DeletableNonPrimaryIndexes() []Index
DeleteOnlyNonPrimaryIndexes() []Index
ForEachIndex(opts IndexOpts, f func(idx Index) error) error
ForEachActiveIndex(f func(idx Index) error) error
ForEachNonDropIndex(f func(idx Index) error) error
ForEachPartialIndex(f func(idx Index) error) error
ForEachPublicNonPrimaryIndex(f func(idx Index) error) error
ForEachWritableNonPrimaryIndex(f func(idx Index) error) error
ForEachDeletableNonPrimaryIndex(f func(idx Index) error) error
ForEachDeleteOnlyNonPrimaryIndex(f func(idx Index) error) error
FindIndex(opts IndexOpts, test func(idx Index) bool) Index
FindActiveIndex(test func(idx Index) bool) Index
FindNonDropIndex(test func(idx Index) bool) Index
FindPartialIndex(test func(idx Index) bool) Index
FindPublicNonPrimaryIndex(test func(idx Index) bool) Index
FindWritableNonPrimaryIndex(test func(idx Index) bool) Index
FindDeletableNonPrimaryIndex(test func(idx Index) bool) Index
FindDeleteOnlyNonPrimaryIndex(test func(idx Index) bool) Index
FindIndexWithID(id descpb.IndexID) (Index, error)
FindIndexWithName(name string) (Index, error)
HasPrimaryKey() bool
PrimaryKeyString() string
GetPublicColumns() []descpb.ColumnDescriptor
ForeachPublicColumn(f func(col *descpb.ColumnDescriptor) error) error
ForeachNonDropColumn(f func(col *descpb.ColumnDescriptor) error) error
NamesForColumnIDs(ids descpb.ColumnIDs) ([]string, error)
FindColumnByName(name tree.Name) (*descpb.ColumnDescriptor, bool, error)
FindActiveColumnByID(id descpb.ColumnID) (*descpb.ColumnDescriptor, error)
FindColumnByID(id descpb.ColumnID) (*descpb.ColumnDescriptor, error)
ColumnIdxMap() TableColMap
GetColumnAtIdx(idx int) *descpb.ColumnDescriptor
AllNonDropColumns() []descpb.ColumnDescriptor
VisibleColumns() []descpb.ColumnDescriptor
ColumnsWithMutations(includeMutations bool) []descpb.ColumnDescriptor
ColumnIdxMapWithMutations(includeMutations bool) TableColMap
DeletableColumns() []descpb.ColumnDescriptor
MutationColumns() []descpb.ColumnDescriptor
ContainsUserDefinedTypes() bool
GetColumnOrdinalsWithUserDefinedTypes() []int
UserDefinedTypeColsHaveSameVersion(otherDesc TableDescriptor) bool
GetFamilies() []descpb.ColumnFamilyDescriptor
NumFamilies() int
FindFamilyByID(id descpb.FamilyID) (*descpb.ColumnFamilyDescriptor, error)
ForeachFamily(f func(family *descpb.ColumnFamilyDescriptor) error) error
IsTable() bool
IsView() bool
IsSequence() bool
IsTemporary() bool
IsVirtualTable() bool
IsPhysicalTable() bool
IsInterleaved() bool
MaterializedView() bool
GetMutationJobs() []descpb.TableDescriptor_MutationJob
GetReplacementOf() descpb.TableDescriptor_Replacement
GetAllReferencedTypeIDs(
getType func(descpb.ID) (TypeDescriptor, error),
) (descpb.IDs, error)
Validate(ctx context.Context, txn DescGetter) error
ForeachDependedOnBy(f func(dep *descpb.TableDescriptor_Reference) error) error
GetDependsOn() []descpb.ID
GetConstraintInfoWithLookup(fn TableLookupFn) (map[string]descpb.ConstraintDetail, error)
ForeachOutboundFK(f func(fk *descpb.ForeignKeyConstraint) error) error
GetChecks() []*descpb.TableDescriptor_CheckConstraint
AllActiveAndInactiveChecks() []*descpb.TableDescriptor_CheckConstraint
ActiveChecks() []descpb.TableDescriptor_CheckConstraint
AllActiveAndInactiveUniqueWithoutIndexConstraints() []*descpb.UniqueWithoutIndexConstraint
ForeachInboundFK(f func(fk *descpb.ForeignKeyConstraint) error) error
FindActiveColumnByName(s string) (*descpb.ColumnDescriptor, error)
WritableColumns() []descpb.ColumnDescriptor
}
// Index is an interface around the index descriptor types.
type Index interface {
IndexDesc() *descpb.IndexDescriptor
IndexDescDeepCopy() descpb.IndexDescriptor
Ordinal() int
Primary() bool
Public() bool
WriteAndDeleteOnly() bool
DeleteOnly() bool
Adding() bool
Dropped() bool
GetID() descpb.IndexID
GetName() string
IsInterleaved() bool
IsPartial() bool
IsUnique() bool
IsDisabled() bool
IsSharded() bool
IsCreatedExplicitly() bool
GetPredicate() string
GetType() descpb.IndexDescriptor_Type
IsValidOriginIndex(originColIDs descpb.ColumnIDs) bool
IsValidReferencedIndex(referencedColIDs descpb.ColumnIDs) bool
GetGeoConfig() geoindex.Config
GetSharded() descpb.ShardedDescriptor
GetShardColumnName() string
GetVersion() descpb.IndexDescriptorVersion
GetEncodingType() descpb.IndexDescriptorEncodingType
GetPartitioning() descpb.PartitioningDescriptor
FindPartitionByName(name string) descpb.PartitioningDescriptor
PartitionNames() []string
NumInterleaveAncestors() int
GetInterleaveAncestor(ancestorOrdinal int) descpb.InterleaveDescriptor_Ancestor
NumInterleavedBy() int
GetInterleavedBy(interleavedByOrdinal int) descpb.ForeignKeyReference
NumColumns() int
GetColumnID(columnOrdinal int) descpb.ColumnID
GetColumnName(columnOrdinal int) string
GetColumnDirection(columnOrdinal int) descpb.IndexDescriptor_Direction
ContainsColumnID(colID descpb.ColumnID) bool
InvertedColumnID() descpb.ColumnID
InvertedColumnName() string
ForEachColumnID(func(id descpb.ColumnID) error) error
NumStoredColumns() int
GetStoredColumnID(storedColumnOrdinal int) descpb.ColumnID
GetStoredColumnName(storedColumnOrdinal int) string
HasOldStoredColumns() bool
NumExtraColumns() int
GetExtraColumnID(extraColumnOrdinal int) descpb.ColumnID
NumCompositeColumns() int
GetCompositeColumnID(compositeColumnOrdinal int) descpb.ColumnID
}
// TypeDescriptor will eventually be called typedesc.Descriptor.
// It is implemented by (Imm|M)utableTypeDescriptor.
type TypeDescriptor interface {
Descriptor
TypeDesc() *descpb.TypeDescriptor
HydrateTypeInfoWithName(ctx context.Context, typ *types.T, name *tree.TypeName, res TypeDescriptorResolver) error
MakeTypesT(ctx context.Context, name *tree.TypeName, res TypeDescriptorResolver) (*types.T, error)
HasPendingSchemaChanges() bool
GetIDClosure() map[descpb.ID]struct{}
PrimaryRegion() (descpb.Region, error)
Validate(ctx context.Context, dg DescGetter) error
}
// TypeDescriptorResolver is an interface used during hydration of type
// metadata in types.T's. It is similar to tree.TypeReferenceResolver, except
// that it has the power to return TypeDescriptor, rather than only a
// types.T. Implementers of tree.TypeReferenceResolver should implement this
// interface as well.
type TypeDescriptorResolver interface {
// GetTypeDescriptor returns the type descriptor for the input ID.
GetTypeDescriptor(ctx context.Context, id descpb.ID) (tree.TypeName, TypeDescriptor, error)
}
// FilterDescriptorState inspects the state of a given descriptor and returns an
// error if the state is anything but public. The error describes the state of
// the descriptor.
func FilterDescriptorState(desc Descriptor, flags tree.CommonLookupFlags) error {
switch {
case desc.Dropped() && !flags.IncludeDropped:
return NewInactiveDescriptorError(ErrDescriptorDropped)
case desc.Offline() && !flags.IncludeOffline:
err := errors.Errorf("%s %q is offline", desc.TypeName(), desc.GetName())
if desc.GetOfflineReason() != "" {
err = errors.Errorf("%s %q is offline: %s", desc.TypeName(), desc.GetName(), desc.GetOfflineReason())
}
return NewInactiveDescriptorError(err)
case desc.Adding():
// Only table descriptors can be in the adding state.
return pgerror.WithCandidateCode(newAddingTableError(desc.(TableDescriptor)),
pgcode.ObjectNotInPrerequisiteState)
default:
return nil
}
}
// TableLookupFn is used to resolve a table from an ID, particularly when
// getting constraint info.
type TableLookupFn func(descpb.ID) (TableDescriptor, error)
// Descriptors is a sortable list of Descriptors.
type Descriptors []Descriptor
func (d Descriptors) Len() int { return len(d) }
func (d Descriptors) Less(i, j int) bool { return d[i].GetID() < d[j].GetID() }
func (d Descriptors) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
// FormatSafeDescriptorProperties is a shared helper function for writing
// un-redacted, common parts of a descriptor. It writes <prop>: value separated
// by commas to w. These key-value pairs would be valid YAML if wrapped in
// curly braces.
func FormatSafeDescriptorProperties(w *redact.StringBuilder, desc Descriptor) {
w.Printf("ID: %d, Version: %d", desc.GetID(), desc.GetVersion())
if desc.IsUncommittedVersion() {
w.Printf(", IsUncommitted: true")
}
w.Printf(", ModificationTime: %q", desc.GetModificationTime())
if parentID := desc.GetParentID(); parentID != 0 {
w.Printf(", ParentID: %d", parentID)
}
if parentSchemaID := desc.GetParentSchemaID(); parentSchemaID != 0 {
w.Printf(", ParentSchemaID: %d", parentSchemaID)
}
{
var state descpb.DescriptorState
switch {
case desc.Public():
state = descpb.DescriptorState_PUBLIC
case desc.Dropped():
state = descpb.DescriptorState_DROP
case desc.Adding():
state = descpb.DescriptorState_ADD
case desc.Offline():
state = descpb.DescriptorState_OFFLINE
}
w.Printf(", State: %v", state)
if offlineReason := desc.GetOfflineReason(); state == descpb.DescriptorState_OFFLINE &&
offlineReason != "" {
w.Printf(", OfflineReason: %q", redact.Safe(offlineReason))
}
}
if drainingNames := desc.GetDrainingNames(); len(drainingNames) > 0 {
w.Printf(", NumDrainingNames: %d", len(drainingNames))
}
}