-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathcollection.go
1333 lines (1222 loc) · 46.1 KB
/
collection.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the CockroachDB Software License
// included in the /LICENSE file.
// Package descs provides abstractions for dealing with sets of descriptors.
// It is utilized during schema changes and by catalog.Accessor implementations.
package descs
import (
"context"
"strings"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/bootstrap"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkeys"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/hydrateddesccache"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/internal/catkv"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/internal/validate"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/lease"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/nstree"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemadesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/systemschema"
"github.com/cockroachdb/cockroach/pkg/sql/isql"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catid"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlliveness"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/iterutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/errors"
)
// Collection is a collection of descriptors held by a single session that
// serves SQL requests, or a background job using descriptors. The
// collection is cleared using ReleaseAll() which is called at the
// end of each transaction on the session, or on hitting conditions such
// as errors, or retries that result in transaction timestamp changes.
//
// TODO(ajwerner): Remove the txn argument from the Collection by more tightly
// binding a collection to a *kv.Txn.
type Collection struct {
// settings dictate whether we validate descriptors on write.
settings *cluster.Settings
// version used for validation
version clusterversion.ClusterVersion
// virtualSchemas optionally holds the virtual schemas.
virtual virtualDescriptors
// A collection of descriptors valid for the timestamp. They are released once
// the transaction using them is complete.
leased leasedDescriptors
// A collection of descriptors with changes not yet committed.
// These descriptors have been modified by the uncommitted transaction
// affiliated with this Collection and should be written to storage
// upon commit.
//
// This layer allows a transaction to see its own modifications while
// bypassing the descriptor lease mechanism. The lease mechanism will have its
// own transaction to read the descriptor and will hang waiting for the
// uncommitted changes to the descriptor if this transaction is PRIORITY HIGH.
//
// These descriptors are local to this Collection and their state is thus
// not visible to other transactions.
uncommitted uncommittedDescriptors
uncommittedComments uncommittedComments
uncommittedZoneConfigs uncommittedZoneConfigs
// A cached implementation of catkv.CatalogReader used for accessing stored
// descriptors, namespace entries, comments and zone configs. The cache
// accumulates every descriptor and other catalog data ever read from KV
// in the transaction affiliated with this Collection.
cr catkv.CatalogReader
// shadowedNames is the set of name keys which should not be looked up in
// storage. Maintaining this set is necessary to properly handle the renaming
// of descriptors, especially when attempting to reuse an old name: without
// this set the check that verifies that the target name is not already in
// use would systematically fail.
shadowedNames map[descpb.NameInfo]struct{}
// validationLevels is the highest-known level of validation that the
// descriptor with the corresponding ID has reached. This is used to avoid
// redundant validation checks which can be quite expensive.
validationLevels map[descpb.ID]catalog.ValidationLevel
// syntheticDescriptors contains in-memory descriptors which override all
// other matching descriptors during immutable descriptor resolution (by name
// or by ID), but should not be written to disk. These support internal
// queries which need to use a special modified descriptor (e.g. validating
// non-public schema elements during a schema change).
synthetic syntheticDescriptors
// temporarySchemaProvider is used to access temporary schema descriptors.
temporarySchemaProvider TemporarySchemaProvider
// validationModeProvider is used to access the session var which determines
// the descriptor validation mode: 'on', 'off' or 'read_only'.
validationModeProvider DescriptorValidationModeProvider
// hydrated is node-level cache of table descriptors which utilize
// user-defined types.
hydrated *hydrateddesccache.Cache
// skipValidationOnWrite should only be set to true during forced descriptor
// repairs.
skipValidationOnWrite bool
// readerCatalogSetup indicates that replicated descriptors can be modified
// by this collection.
readerCatalogSetup bool
// deletedDescs that will not need to wait for new lease versions.
deletedDescs catalog.DescriptorIDSet
// maxTimestampBoundDeadlineHolder contains the maximum timestamp to read
// schemas at. This is only set during the retries of bounded_staleness when
// nearest_only=True, in which we want a schema read that should be no older
// than MaxTimestampBound.
maxTimestampBoundDeadlineHolder maxTimestampBoundDeadlineHolder
// Session is a sqlliveness.Session which may be optionally set.
// It must be set in the multi-tenant environment for ephemeral
// SQL pods. It should not be set otherwise.
sqlLivenessSession sqlliveness.Session
}
// FromTxn is a convenience function to extract a descs.Collection which is
// being interface-smuggled through an isql.Txn. It may return nil.
func FromTxn(txn isql.Txn) *Collection {
if g, ok := txn.(Txn); ok {
return g.Descriptors()
}
return nil
}
// GetDeletedDescs returns the deleted descriptors of the collection.
func (tc *Collection) GetDeletedDescs() catalog.DescriptorIDSet {
return tc.deletedDescs
}
// MaybeUpdateDeadline updates the deadline in a given transaction
// based on the leased descriptors in this collection. This update is
// only done when a deadline exists.
func (tc *Collection) MaybeUpdateDeadline(ctx context.Context, txn *kv.Txn) (err error) {
return tc.leased.maybeUpdateDeadline(ctx, txn, tc.sqlLivenessSession)
}
// SetMaxTimestampBound sets the maximum timestamp to read schemas at.
func (tc *Collection) SetMaxTimestampBound(maxTimestampBound hlc.Timestamp) {
tc.maxTimestampBoundDeadlineHolder.maxTimestampBound = maxTimestampBound
}
// ResetMaxTimestampBound resets the maximum timestamp to read schemas at.
func (tc *Collection) ResetMaxTimestampBound() {
tc.maxTimestampBoundDeadlineHolder.maxTimestampBound = hlc.Timestamp{}
}
// GetMaxTimestampBound returns the maximum timestamp to read schemas at.
func (tc *Collection) GetMaxTimestampBound() hlc.Timestamp {
return tc.maxTimestampBoundDeadlineHolder.maxTimestampBound
}
// SkipValidationOnWrite avoids validating stored descriptors prior to
// a transaction commit.
func (tc *Collection) SkipValidationOnWrite() {
tc.skipValidationOnWrite = true
}
// SetReaderCatalogSetup indicates this collection is being used to
// modify reader catalogs.
func (tc *Collection) SetReaderCatalogSetup() {
tc.readerCatalogSetup = true
}
// ReleaseSpecifiedLeases releases the leases for the descriptors with ids in
// the passed slice. Errors are logged but ignored.
func (tc *Collection) ReleaseSpecifiedLeases(ctx context.Context, descs []lease.IDVersion) {
tc.leased.release(ctx, descs)
}
// ReleaseLeases releases all leases. Errors are logged but ignored.
func (tc *Collection) ReleaseLeases(ctx context.Context) {
tc.leased.releaseAll(ctx)
// Clear the associated sqlliveness.session
tc.sqlLivenessSession = nil
}
// ReleaseAll releases all state currently held by the Collection.
// ReleaseAll calls ReleaseLeases.
func (tc *Collection) ReleaseAll(ctx context.Context) {
tc.ReleaseLeases(ctx)
tc.ResetUncommitted(ctx)
tc.cr.Reset(ctx)
tc.skipValidationOnWrite = false
}
// HasUncommittedTables returns true if the Collection contains uncommitted
// tables.
func (tc *Collection) HasUncommittedTables() (has bool) {
_ = tc.uncommitted.iterateUncommittedByID(func(desc catalog.Descriptor) error {
if _, has = desc.(catalog.TableDescriptor); has {
return iterutil.StopIteration()
}
return nil
})
return has
}
// HasUncommittedDescriptors returns true if the collection contains any
// uncommitted descriptors.
func (tc *Collection) HasUncommittedDescriptors() bool {
return tc.uncommitted.uncommitted.Len() > 0
}
// HasUncommittedTypes returns true if the Collection contains uncommitted
// types.
func (tc *Collection) HasUncommittedTypes() (has bool) {
_ = tc.uncommitted.iterateUncommittedByID(func(desc catalog.Descriptor) error {
if _, has = desc.(catalog.TypeDescriptor); has {
return iterutil.StopIteration()
}
return nil
})
return has
}
// AddUncommittedDescriptor adds an uncommitted descriptor modified in the
// transaction to the Collection. The descriptor must either be a new descriptor
// or carry the original version or carry the subsequent version to the original
// version.
//
// Subsequent attempts to resolve this descriptor mutably, either by name or ID
// will return this exact object. Subsequent attempts to resolve this descriptor
// immutably will return a copy of the descriptor in the current state. A deep
// copy is performed in this call. This descriptor is evicted from the name
// index of the stored descriptors layer in order for this layer to properly
// shadow it.
//
// An uncommitted descriptor cannot coexist with a synthetic descriptor with the
// same ID or the same name.
func (tc *Collection) AddUncommittedDescriptor(
ctx context.Context, desc catalog.MutableDescriptor,
) (err error) {
if !desc.IsUncommittedVersion() {
return nil
}
defer func() {
if err != nil {
err = errors.NewAssertionErrorWithWrappedErrf(err, "adding uncommitted %s %q (%d) version %d",
desc.DescriptorType(), desc.GetName(), desc.GetID(), desc.GetVersion())
}
}()
if tc.synthetic.getSyntheticByID(desc.GetID()) != nil {
return errors.AssertionFailedf(
"cannot add uncommitted %s %q (%d) when a synthetic descriptor with the same ID exists",
desc.DescriptorType(), desc.GetName(), desc.GetID())
}
if tc.synthetic.getSyntheticByName(desc.GetParentID(), desc.GetParentSchemaID(), desc.GetName()) != nil {
return errors.AssertionFailedf(
"cannot add uncommitted %s %q (%d) when a synthetic descriptor with the same name exists",
desc.DescriptorType(), desc.GetName(), desc.GetID())
}
tc.markAsShadowedName(desc.GetID())
return tc.uncommitted.upsert(ctx, desc)
}
// WriteDescToBatch calls MaybeIncrementVersion, adds the descriptor to the
// collection as an uncommitted descriptor, and writes it into b.
func (tc *Collection) WriteDescToBatch(
ctx context.Context, kvTrace bool, desc catalog.MutableDescriptor, b *kv.Batch,
) error {
if desc.GetID() == descpb.InvalidID {
return errors.AssertionFailedf("cannot write descriptor with an empty ID: %v", desc)
}
desc.MaybeIncrementVersion()
// Replicated PCR descriptors cannot be modified unless the collection
// is setup for updating them.
if !tc.readerCatalogSetup && desc.GetReplicatedPCRVersion() != 0 {
return pgerror.Newf(pgcode.ReadOnlySQLTransaction,
"replicated %s %s (%d) cannot be mutated",
desc.GetObjectTypeString(),
desc.GetName(),
desc.GetID())
}
if !tc.skipValidationOnWrite && tc.validationModeProvider.ValidateDescriptorsOnWrite() {
if err := validate.Self(tc.version, desc); err != nil {
return err
}
}
// Retrieve the expected bytes of `desc` in storage.
// If this is the first time we write to `desc` in the transaction, its
// expected bytes will be retrieved when we read it into this desc.Collection,
// and carried over in it.
// If, however, this is not the first time we write to `desc` in the transaction,
// which means it has existed in `tc.uncommitted`, we will retrieve the expected
// bytes from there.
var expected []byte
if exist := tc.uncommitted.getUncommittedByID(desc.GetID()); exist != nil {
expected = exist.GetRawBytesInStorage()
} else {
expected = desc.GetRawBytesInStorage()
}
if err := tc.AddUncommittedDescriptor(ctx, desc); err != nil {
return err
}
descKey := catalogkeys.MakeDescMetadataKey(tc.codec(), desc.GetID())
proto := desc.DescriptorProto()
if kvTrace {
log.VEventf(ctx, 2, "CPut %s -> %s", descKey, proto)
}
b.CPut(descKey, proto, expected)
return nil
}
// DeleteDescToBatch adds a delete from system.descriptor to the batch.
func (tc *Collection) DeleteDescToBatch(
ctx context.Context, kvTrace bool, id descpb.ID, b *kv.Batch,
) error {
if id == descpb.InvalidID {
return errors.AssertionFailedf("cannot delete descriptor with an empty ID: %v", id)
}
descKey := catalogkeys.MakeDescMetadataKey(tc.codec(), id)
if kvTrace {
log.VEventf(ctx, 2, "Del %s", descKey)
}
b.Del(descKey)
tc.NotifyOfDeletedDescriptor(id)
return nil
}
// InsertNamespaceEntryToBatch adds an insertion into system.namespace to the
// batch.
func (tc *Collection) InsertNamespaceEntryToBatch(
ctx context.Context, kvTrace bool, e catalog.NameEntry, b *kv.Batch,
) error {
if ns := tc.cr.Cache().LookupNamespaceEntry(e); ns != nil {
tc.markAsShadowedName(ns.GetID())
}
tc.markAsShadowedName(e.GetID())
if e.GetName() == "" || e.GetID() == descpb.InvalidID {
return errors.AssertionFailedf(
"cannot insert namespace entry (%d, %d, %q) -> %d with an empty name or ID",
e.GetParentID(), e.GetParentSchemaID(), e.GetName(), e.GetID(),
)
}
nameKey := catalogkeys.EncodeNameKey(tc.codec(), e)
if kvTrace {
log.VEventf(ctx, 2, "CPut %s -> %d", nameKey, e.GetID())
}
b.CPut(nameKey, e.GetID(), nil /* expValue */)
return nil
}
// UpsertNamespaceEntryToBatch adds an upsert into system.namespace to the
// batch.
func (tc *Collection) UpsertNamespaceEntryToBatch(
ctx context.Context, kvTrace bool, e catalog.NameEntry, b *kv.Batch,
) error {
if ns := tc.cr.Cache().LookupNamespaceEntry(e); ns != nil {
tc.markAsShadowedName(ns.GetID())
}
tc.markAsShadowedName(e.GetID())
if e.GetName() == "" || e.GetID() == descpb.InvalidID {
return errors.AssertionFailedf(
"cannot upsert namespace entry (%d, %d, %q) -> %d with an empty name or ID",
e.GetParentID(), e.GetParentSchemaID(), e.GetName(), e.GetID(),
)
}
nameKey := catalogkeys.EncodeNameKey(tc.codec(), e)
if kvTrace {
log.VEventf(ctx, 2, "Put %s -> %d", nameKey, e.GetID())
}
b.Put(nameKey, e.GetID())
return nil
}
// DeleteNamespaceEntryToBatch adds a deletion from system.namespace to the
// batch.
func (tc *Collection) DeleteNamespaceEntryToBatch(
ctx context.Context, kvTrace bool, k catalog.NameKey, b *kv.Batch,
) error {
if ns := tc.cr.Cache().LookupNamespaceEntry(k); ns != nil {
tc.markAsShadowedName(ns.GetID())
}
nameKey := catalogkeys.EncodeNameKey(tc.codec(), k)
if kvTrace {
log.VEventf(ctx, 2, "Del %s", nameKey)
}
b.Del(nameKey)
return nil
}
func (tc *Collection) markAsShadowedName(id descpb.ID) {
desc := tc.cr.Cache().LookupDescriptor(id)
if desc == nil {
return
}
if tc.shadowedNames == nil {
tc.shadowedNames = make(map[descpb.NameInfo]struct{})
}
tc.shadowedNames[descpb.NameInfo{
ParentID: desc.GetParentID(),
ParentSchemaID: desc.GetParentSchemaID(),
Name: desc.GetName(),
}] = struct{}{}
}
func (tc *Collection) isShadowedName(nameKey catalog.NameKey) bool {
var k descpb.NameInfo
switch t := nameKey.(type) {
case descpb.NameInfo:
k = t
case *descpb.NameInfo:
k = *t
default:
k = descpb.NameInfo{
ParentID: nameKey.GetParentID(),
ParentSchemaID: nameKey.GetParentSchemaID(),
Name: nameKey.GetName(),
}
}
_, ok := tc.shadowedNames[k]
return ok
}
// WriteCommentToBatch adds the comment changes to uncommitted layer and writes
// to the kv batch.
func (tc *Collection) WriteCommentToBatch(
ctx context.Context, kvTrace bool, b *kv.Batch, key catalogkeys.CommentKey, cmt string,
) error {
cmtWriter := bootstrap.MakeKVWriter(tc.codec(), systemschema.CommentsTable)
values := []tree.Datum{
tree.NewDInt(tree.DInt(key.CommentType)),
tree.NewDInt(tree.DInt(key.ObjectID)),
tree.NewDInt(tree.DInt(key.SubID)),
tree.NewDString(cmt),
}
var expValues []tree.Datum
if oldCmt, found := tc.GetComment(key); found {
expValues = []tree.Datum{
tree.NewDInt(tree.DInt(key.CommentType)),
tree.NewDInt(tree.DInt(key.ObjectID)),
tree.NewDInt(tree.DInt(key.SubID)),
tree.NewDString(oldCmt),
}
}
var err error
if expValues == nil {
err = cmtWriter.Insert(ctx, b, kvTrace, values...)
} else {
err = cmtWriter.Update(ctx, b, kvTrace, values, expValues)
}
if err != nil {
return err
}
tc.AddUncommittedComment(key, cmt)
return nil
}
// DeleteCommentInBatch deletes a comment with the given (objID, subID, cmtType) key in
// the same batch and marks it as deleted
func (tc *Collection) DeleteCommentInBatch(
ctx context.Context, kvTrace bool, b *kv.Batch, key catalogkeys.CommentKey,
) error {
cmtWriter := bootstrap.MakeKVWriter(tc.codec(), systemschema.CommentsTable)
values := []tree.Datum{
tree.NewDInt(tree.DInt(key.CommentType)),
tree.NewDInt(tree.DInt(key.ObjectID)),
tree.NewDInt(tree.DInt(key.SubID)),
// kv delete only care about keys, so it's fine to just use an empty string
// for comment here since it's not part of any index.
tree.NewDString(""),
}
if err := cmtWriter.Delete(ctx, b, kvTrace, values...); err != nil {
return err
}
tc.MarkUncommittedCommentDeleted(key)
return nil
}
// DeleteTableComments deletes all comment on a table.
func (tc *Collection) DeleteTableComments(
ctx context.Context, kvTrace bool, b *kv.Batch, tblID descpb.ID,
) error {
for _, t := range catalogkeys.AllTableCommentTypes {
cmtKeyPrefix := catalogkeys.MakeObjectCommentsMetadataPrefix(tc.codec(), t, tblID)
b.DelRange(cmtKeyPrefix, cmtKeyPrefix.PrefixEnd(), false /* returnKeys */)
if kvTrace {
log.VEventf(ctx, 2, "DelRange %s", cmtKeyPrefix)
}
}
tc.MarkUncommittedCommentDeletedForTable(tblID)
return nil
}
// WriteZoneConfigToBatch adds the new zoneconfig to uncommitted layer and
// writes to the kv batch.
func (tc *Collection) WriteZoneConfigToBatch(
ctx context.Context, kvTrace bool, b *kv.Batch, descID descpb.ID, zc catalog.ZoneConfig,
) error {
zcWriter := bootstrap.MakeKVWriter(tc.codec(), systemschema.ZonesTable, 0 /* SkippedColumnFamilyIDs*/)
var val roachpb.Value
if err := val.SetProto(zc.ZoneConfigProto()); err != nil {
return err
}
valBytes, err := val.GetBytes()
if err != nil {
return err
}
values := []tree.Datum{
tree.NewDInt(tree.DInt(descID)),
tree.NewDBytes(tree.DBytes(valBytes)),
}
var expValues []tree.Datum
if zc.GetRawBytesInStorage() != nil {
expValues = []tree.Datum{
tree.NewDInt(tree.DInt(descID)),
tree.NewDBytes(tree.DBytes(zc.GetRawBytesInStorage())),
}
}
if expValues == nil {
err = zcWriter.Insert(ctx, b, kvTrace, values...)
} else {
err = zcWriter.Update(ctx, b, kvTrace, values, expValues)
}
if err != nil {
return err
}
return tc.AddUncommittedZoneConfig(descID, zc.ZoneConfigProto())
}
// DeleteZoneConfigInBatch deletes zone config of the table.
func (tc *Collection) DeleteZoneConfigInBatch(
ctx context.Context, kvTrace bool, b *kv.Batch, descID descpb.ID,
) error {
// Check if it's actually deleting something.
zcWriter := bootstrap.MakeKVWriter(tc.codec(), systemschema.ZonesTable)
values := []tree.Datum{
tree.NewDInt(tree.DInt(descID)),
tree.NewDBytes(""),
}
if err := zcWriter.Delete(ctx, b, kvTrace, values...); err != nil {
return err
}
tc.MarkUncommittedZoneConfigDeleted(descID)
return nil
}
// WriteDesc constructs a new Batch, calls WriteDescToBatch and runs it.
func (tc *Collection) WriteDesc(
ctx context.Context, kvTrace bool, desc catalog.MutableDescriptor, txn *kv.Txn,
) error {
b := txn.NewBatch()
if err := tc.WriteDescToBatch(ctx, kvTrace, desc, b); err != nil {
return err
}
return txn.Run(ctx, b)
}
// LookupDatabaseID returns the descriptor ID assigned to a database name.
func (tc *Collection) LookupDatabaseID(
ctx context.Context, txn *kv.Txn, dbName string,
) (descpb.ID, error) {
return tc.lookupDescriptorID(ctx, txn, descpb.NameInfo{Name: dbName})
}
// LookupSchemaID returns the descriptor ID assigned to a schema name.
func (tc *Collection) LookupSchemaID(
ctx context.Context, txn *kv.Txn, dbID descpb.ID, schemaName string,
) (descpb.ID, error) {
key := descpb.NameInfo{ParentID: dbID, Name: schemaName}
return tc.lookupDescriptorID(ctx, txn, key)
}
// LookupObjectID returns the descriptor ID assigned to an object name.
func (tc *Collection) LookupObjectID(
ctx context.Context, txn *kv.Txn, dbID descpb.ID, schemaID descpb.ID, objectName string,
) (descpb.ID, error) {
key := descpb.NameInfo{ParentID: dbID, ParentSchemaID: schemaID, Name: objectName}
return tc.lookupDescriptorID(ctx, txn, key)
}
// lookupDescriptorID returns the descriptor ID assigned to an object name.
func (tc *Collection) lookupDescriptorID(
ctx context.Context, txn *kv.Txn, key descpb.NameInfo,
) (descpb.ID, error) {
// First look up in-memory descriptors in collection,
// except for leased descriptors.
objInMemory, err := func() (catalog.Descriptor, error) {
flags := defaultUnleasedFlags()
flags.layerFilters.withoutStorage = true
flags.descFilters.withoutDropped = true
var db catalog.DatabaseDescriptor
var sc catalog.SchemaDescriptor
expectedType := catalog.Database
if key.ParentID != descpb.InvalidID {
var parentDescs [2]catalog.Descriptor
var err error
if key.ParentSchemaID != descpb.InvalidID {
err = getDescriptorsByID(ctx, tc, txn, flags, parentDescs[:], key.ParentID, key.ParentSchemaID)
} else {
err = getDescriptorsByID(ctx, tc, txn, flags, parentDescs[:1], key.ParentID)
}
if err != nil {
return nil, err
}
db, err = catalog.AsDatabaseDescriptor(parentDescs[0])
if err != nil {
return nil, err
}
expectedType = catalog.Schema
if key.ParentSchemaID != descpb.InvalidID {
expectedType = catalog.Any
sc, err = catalog.AsSchemaDescriptor(parentDescs[1])
if err != nil {
return nil, err
}
}
}
return getDescriptorByName(ctx, txn, tc, db, sc, key.Name, flags, expectedType)
}()
if err != nil && !errors.Is(err, catalog.ErrDescriptorNotFound) {
return descpb.InvalidID, err
}
if objInMemory != nil {
return objInMemory.GetID(), nil
}
// Look up ID in storage if nothing was found in memory.
if tc.isShadowedName(key) {
return descpb.InvalidID, nil
}
read, err := tc.cr.GetByNames(ctx, txn, []descpb.NameInfo{key})
if err != nil {
return descpb.InvalidID, err
}
if e := read.LookupNamespaceEntry(&key); e != nil {
return e.GetID(), nil
}
return descpb.InvalidID, nil
}
// GetOriginalPreviousIDVersionsForUncommitted returns all the IDVersion
// pairs for descriptors that have undergone a schema change.
// Returns an empty slice for no schema changes.
//
// The version returned for each schema change is clusterVersion - 1, because
// that's the one that will be used when checking for table descriptor
// two-version invariance.
func (tc *Collection) GetOriginalPreviousIDVersionsForUncommitted() (
withNewVersions []lease.IDVersion,
err error,
) {
err = tc.uncommitted.iterateUncommittedByID(func(uncommitted catalog.Descriptor) error {
original := tc.uncommitted.getOriginalByID(uncommitted.GetID())
// Ignore new descriptors.
if original == nil {
return nil
}
// Sanity checks. If AddUncommittedDescriptor is implemented and used
// correctly then these should never fail.
if original.GetVersion() == 0 {
return errors.AssertionFailedf(
"expected original version of uncommitted %s %q (%d) to be non-zero",
uncommitted.DescriptorType(), uncommitted.GetName(), uncommitted.GetID())
}
if expected, actual := uncommitted.GetVersion()-1, original.GetVersion(); expected != actual {
return errors.AssertionFailedf(
"expected original version of uncommitted %s %q (%d) to be %d, instead is %d",
uncommitted.DescriptorType(), uncommitted.GetName(), uncommitted.GetID(), expected, actual)
}
prev := lease.NewIDVersionPrev(original.GetName(), original.GetID(), original.GetVersion())
withNewVersions = append(withNewVersions, prev)
return nil
})
return withNewVersions, err
}
// GetUncommittedTables returns all the tables updated or created in the
// transaction.
func (tc *Collection) GetUncommittedTables() (tables []catalog.TableDescriptor) {
_ = tc.uncommitted.iterateUncommittedByID(func(desc catalog.Descriptor) error {
if table, ok := desc.(catalog.TableDescriptor); ok {
tables = append(tables, table)
}
return nil
})
return tables
}
// GetUncommittedDatabases returns all the databases updated or created in the
// transaction.
func (tc *Collection) GetUncommittedDatabases() (databases []catalog.DatabaseDescriptor) {
_ = tc.uncommitted.iterateUncommittedByID(func(desc catalog.Descriptor) error {
if database, ok := desc.(catalog.DatabaseDescriptor); ok {
databases = append(databases, database)
}
return nil
})
return databases
}
func newMutableSyntheticDescriptorAssertionError(id descpb.ID) error {
return errors.AssertionFailedf("attempted mutable access of synthetic descriptor %d", id)
}
// GetAll returns all descriptors, namespace entries, comments and
// zone configs visible by the transaction.
func (tc *Collection) GetAll(ctx context.Context, txn *kv.Txn) (nstree.Catalog, error) {
stored, err := tc.cr.ScanAll(ctx, txn)
if err != nil {
return nstree.Catalog{}, err
}
ret, err := tc.aggregateAllLayers(ctx, txn, stored)
if err != nil {
return nstree.Catalog{}, err
}
return ret.Catalog, nil
}
// GetDescriptorsInSpans returns all descriptors within a given span.
func (tc *Collection) GetDescriptorsInSpans(
ctx context.Context, txn *kv.Txn, spans []roachpb.Span,
) (nstree.Catalog, error) {
return tc.cr.ScanDescriptorsInSpans(ctx, txn, spans)
}
// GetAllComments gets all comments for all descriptors in the given database.
// This method never returns the underlying catalog, since it will be incomplete and only
// contain comments.
// If the dbContext is nil, we return the database-level comments.
func (tc *Collection) GetAllComments(
ctx context.Context, txn *kv.Txn, db catalog.DatabaseDescriptor,
) (nstree.CommentCatalog, error) {
kvComments, err := tc.cr.ScanAllComments(ctx, txn, db)
if err != nil {
return nil, err
}
comments, err := tc.aggregateAllLayers(ctx, txn, kvComments)
if err != nil {
return nil, err
}
return comments, nil
}
// GetAllFromStorageUnvalidated delegates to an uncached catkv.CatalogReader's
// ScanAll method. Nothing is cached, validated or hydrated. This is to be used
// sparingly and only in situations which warrant it, where an unmediated view
// of the stored catalog is explicitly desired for observability.
func (tc *Collection) GetAllFromStorageUnvalidated(
ctx context.Context, txn *kv.Txn,
) (nstree.Catalog, error) {
return catkv.NewUncachedCatalogReader(tc.codec()).ScanAll(ctx, txn)
}
// GetAllDatabases is like GetAll but filtered to non-dropped databases.
func (tc *Collection) GetAllDatabases(ctx context.Context, txn *kv.Txn) (nstree.Catalog, error) {
stored, err := tc.cr.ScanNamespaceForDatabases(ctx, txn)
if err != nil {
return nstree.Catalog{}, err
}
ret, err := tc.aggregateAllLayers(ctx, txn, stored)
if err != nil {
return nstree.Catalog{}, err
}
var dbIDs catalog.DescriptorIDSet
_ = ret.ForEachDescriptor(func(desc catalog.Descriptor) error {
if desc.DescriptorType() != catalog.Database {
return nil
}
dbIDs.Add(desc.GetID())
return nil
})
return ret.FilterByIDs(dbIDs.Ordered()), nil
}
// GetAllSchemasInDatabase is like GetAll but filtered to the schemas with
// the specified parent database. Includes virtual schemas.
func (tc *Collection) GetAllSchemasInDatabase(
ctx context.Context, txn *kv.Txn, db catalog.DatabaseDescriptor,
) (nstree.Catalog, error) {
stored, err := tc.cr.ScanNamespaceForDatabaseSchemas(ctx, txn, db)
if err != nil {
return nstree.Catalog{}, err
}
var ret nstree.MutableCatalog
if db.HasPublicSchemaWithDescriptor() {
ret, err = tc.aggregateAllLayers(ctx, txn, stored)
} else {
ret, err = tc.aggregateAllLayers(ctx, txn, stored, schemadesc.GetPublicSchema())
}
if err != nil {
return nstree.Catalog{}, err
}
var schemaIDs catalog.DescriptorIDSet
_ = ret.ForEachDescriptor(func(desc catalog.Descriptor) error {
sc, ok := desc.(catalog.SchemaDescriptor)
if !ok {
return nil
}
switch sc.SchemaKind() {
case catalog.SchemaTemporary, catalog.SchemaUserDefined:
if sc.GetParentID() != db.GetID() {
return nil
}
}
schemaIDs.Add(desc.GetID())
return nil
})
return ret.FilterByIDs(schemaIDs.Ordered()), nil
}
// GetAllObjectsInSchema is like GetAll but filtered to the objects with
// the specified parent schema. Includes virtual objects. Does not include
// dropped objects.
func (tc *Collection) GetAllObjectsInSchema(
ctx context.Context, txn *kv.Txn, db catalog.DatabaseDescriptor, sc catalog.SchemaDescriptor,
) (nstree.Catalog, error) {
var ret nstree.MutableCatalog
if sc.SchemaKind() == catalog.SchemaVirtual {
tc.virtual.addAllToCatalog(ret)
} else {
stored, err := tc.cr.ScanNamespaceForSchemaObjects(ctx, txn, db, sc)
if err != nil {
return nstree.Catalog{}, err
}
ret, err = tc.aggregateAllLayers(ctx, txn, stored, sc)
if err != nil {
return nstree.Catalog{}, err
}
}
var objectIDs catalog.DescriptorIDSet
_ = ret.ForEachDescriptor(func(desc catalog.Descriptor) error {
if desc.GetParentSchemaID() == sc.GetID() {
objectIDs.Add(desc.GetID())
}
return nil
})
return ret.FilterByIDs(objectIDs.Ordered()), nil
}
// GetAllInDatabase is like the union of GetAllSchemasInDatabase and
// GetAllObjectsInSchema applied to each of those schemas.
// Includes virtual objects. Does not include dropped objects.
func (tc *Collection) GetAllInDatabase(
ctx context.Context, txn *kv.Txn, db catalog.DatabaseDescriptor,
) (nstree.Catalog, error) {
stored, err := tc.cr.ScanNamespaceForDatabaseSchemasAndObjects(ctx, txn, db)
if err != nil {
return nstree.Catalog{}, err
}
schemas, err := tc.GetAllSchemasInDatabase(ctx, txn, db)
if err != nil {
return nstree.Catalog{}, err
}
var schemasSlice []catalog.SchemaDescriptor
if err := schemas.ForEachDescriptor(func(desc catalog.Descriptor) error {
sc, err := catalog.AsSchemaDescriptor(desc)
schemasSlice = append(schemasSlice, sc)
return err
}); err != nil {
return nstree.Catalog{}, err
}
ret, err := tc.aggregateAllLayers(ctx, txn, stored, schemasSlice...)
if err != nil {
return nstree.Catalog{}, err
}
var inDatabaseIDs catalog.DescriptorIDSet
if err := ret.ForEachDescriptor(func(desc catalog.Descriptor) error {
if desc.DescriptorType() == catalog.Schema {
if dbID := desc.GetParentID(); dbID != descpb.InvalidID && dbID != db.GetID() {
return nil
}
} else {
if schemas.LookupDescriptor(desc.GetParentSchemaID()) == nil {
return nil
}
}
inDatabaseIDs.Add(desc.GetID())
return nil
}); err != nil {
return nstree.Catalog{}, err
}
return ret.FilterByIDs(inDatabaseIDs.Ordered()), nil
}
// GetAllTablesInDatabase is like GetAllInDatabase but filtered to tables.
// Includes virtual objects. Does not include dropped objects.
func (tc *Collection) GetAllTablesInDatabase(
ctx context.Context, txn *kv.Txn, db catalog.DatabaseDescriptor,
) (nstree.Catalog, error) {
stored, err := tc.cr.ScanNamespaceForDatabaseSchemasAndObjects(ctx, txn, db)
if err != nil {
return nstree.Catalog{}, err
}
var ret nstree.MutableCatalog
if db.HasPublicSchemaWithDescriptor() {
ret, err = tc.aggregateAllLayers(ctx, txn, stored)
} else {
ret, err = tc.aggregateAllLayers(ctx, txn, stored, schemadesc.GetPublicSchema())
}
if err != nil {
return nstree.Catalog{}, err
}
var inDatabaseIDs catalog.DescriptorIDSet
_ = ret.ForEachDescriptor(func(desc catalog.Descriptor) error {
if desc.DescriptorType() != catalog.Table {
return nil
}
if dbID := desc.GetParentID(); dbID != descpb.InvalidID && dbID != db.GetID() {
return nil
}
inDatabaseIDs.Add(desc.GetID())
return nil
})
return ret.FilterByIDs(inDatabaseIDs.Ordered()), nil
}
// aggregateAllLayers is the helper function used by GetAll* methods which
// takes care to stack all of the Collection's layer appropriately and ensures
// that the returned descriptors are properly hydrated and validated.
func (tc *Collection) aggregateAllLayers(
ctx context.Context, txn *kv.Txn, stored nstree.Catalog, schemas ...catalog.SchemaDescriptor,
) (ret nstree.MutableCatalog, _ error) {
// Descriptors need to be re-read to ensure proper validation hydration etc.
// We collect their IDs for this purpose and we'll re-add them later.
var descIDs catalog.DescriptorIDSet
// Start with the known function descriptor IDs.
for _, sc := range schemas {
if sc.SchemaKind() == catalog.SchemaPublic {
// This is needed at least for the temp system db during restores.
descIDs.Add(sc.GetID())
}
_ = sc.ForEachFunctionSignature(func(sig descpb.SchemaDescriptor_FunctionSignature) error {
descIDs.Add(sig.ID)
return nil
})
}
// Add IDs from descriptors retrieved from the storage layer.
_ = stored.ForEachDescriptor(func(desc catalog.Descriptor) error {
descIDs.Add(desc.GetID())
if sc, ok := desc.(catalog.SchemaDescriptor); ok {
_ = sc.ForEachFunctionSignature(func(sig descpb.SchemaDescriptor_FunctionSignature) error {
descIDs.Add(sig.ID)
return nil
})
}
return nil
})
// Add stored namespace entries which are not shadowed.
_ = stored.ForEachNamespaceEntry(func(e nstree.NamespaceEntry) error {
if tc.isShadowedName(e) {
return nil
}
// Temporary schemas don't have descriptors and are persisted only
// as namespace table entries.
if e.GetParentID() != descpb.InvalidID && e.GetParentSchemaID() == descpb.InvalidID &&
strings.HasPrefix(e.GetName(), catconstants.PgTempSchemaName) {
ret.UpsertDescriptor(schemadesc.NewTemporarySchema(e.GetName(), e.GetID(), e.GetParentID()))
} else {
descIDs.Add(e.GetID())
}
ret.UpsertNamespaceEntry(e, e.GetID(), e.GetMVCCTimestamp())
return nil
})
// Add stored comments which are not shadowed.
_ = stored.ForEachComment(func(key catalogkeys.CommentKey, cmt string) error {
if _, _, isShadowed := tc.uncommittedComments.getUncommitted(key); !isShadowed {
return ret.UpsertComment(key, cmt)
}
return nil
})
// Add stored zone configs which are not shadowed.