forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollection.go
2234 lines (2062 loc) · 80.3 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 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 descs provides abstractions for dealing with sets of descriptors.
// It is utilized during schema changes and by catalog.Accessor implementations.
package descs
import (
"bytes"
"context"
"fmt"
"sort"
"strings"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/settings"
"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/catalogkv"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/dbdesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/hydratedtables"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/lease"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/resolver"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/systemschema"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/typedesc"
"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/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlerrors"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/errors"
"github.com/lib/pq/oid"
)
// uncommittedDescriptor is a descriptor that has been modified in the current
// transaction.
type uncommittedDescriptor struct {
mutable catalog.MutableDescriptor
immutable catalog.Descriptor
}
// leasedDescriptors holds references to all the descriptors leased in the
// transaction, and supports access by name and by ID.
type leasedDescriptors struct {
descs []lease.LeasedDescriptor
}
func (ld *leasedDescriptors) add(desc lease.LeasedDescriptor) {
ld.descs = append(ld.descs, desc)
}
func (ld *leasedDescriptors) releaseAll() (toRelease []lease.LeasedDescriptor) {
toRelease = append(toRelease, ld.descs...)
ld.descs = ld.descs[:0]
return toRelease
}
func (ld *leasedDescriptors) release(ids []descpb.ID) (toRelease []lease.LeasedDescriptor) {
// Sort the descriptors and leases to make it easy to find the leases to release.
leasedDescs := ld.descs
sort.Slice(ids, func(i, j int) bool {
return ids[i] < ids[j]
})
sort.Slice(leasedDescs, func(i, j int) bool {
return leasedDescs[i].Desc().GetID() < leasedDescs[j].Desc().GetID()
})
filteredLeases := leasedDescs[:0] // will store the remaining leases
idsToConsider := ids
shouldRelease := func(id descpb.ID) (found bool) {
for len(idsToConsider) > 0 && idsToConsider[0] < id {
idsToConsider = idsToConsider[1:]
}
return len(idsToConsider) > 0 && idsToConsider[0] == id
}
for _, l := range leasedDescs {
if !shouldRelease(l.Desc().GetID()) {
filteredLeases = append(filteredLeases, l)
} else {
toRelease = append(toRelease, l)
}
}
ld.descs = filteredLeases
return toRelease
}
func (ld *leasedDescriptors) getByID(id descpb.ID) catalog.Descriptor {
for i := range ld.descs {
desc := ld.descs[i]
if desc.Desc().GetID() == id {
return desc.Desc()
}
}
return nil
}
func (ld *leasedDescriptors) getByName(
dbID descpb.ID, schemaID descpb.ID, name string,
) catalog.Descriptor {
for i := range ld.descs {
desc := ld.descs[i]
if lease.NameMatchesDescriptor(desc.Desc(), dbID, schemaID, name) {
return desc.Desc()
}
}
return nil
}
func (ld *leasedDescriptors) numDescriptors() int {
return len(ld.descs)
}
// MakeCollection constructs a Collection.
func MakeCollection(
leaseMgr *lease.Manager,
settings *cluster.Settings,
sessionData *sessiondata.SessionData,
hydratedTables *hydratedtables.Cache,
virtualSchemas catalog.VirtualSchemas,
) Collection {
return Collection{
leaseMgr: leaseMgr,
settings: settings,
sessionData: sessionData,
hydratedTables: hydratedTables,
virtualSchemas: virtualSchemas,
}
}
// NewCollection constructs a new *Collection.
func NewCollection(
settings *cluster.Settings,
leaseMgr *lease.Manager,
hydratedTables *hydratedtables.Cache,
virtualSchemas catalog.VirtualSchemas,
) *Collection {
tc := MakeCollection(leaseMgr, settings, nil, hydratedTables, virtualSchemas)
return &tc
}
// 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.
type Collection struct {
// leaseMgr manages acquiring and releasing per-descriptor leases.
leaseMgr *lease.Manager
// virtualSchemas optionally holds the virtual schemas.
virtualSchemas catalog.VirtualSchemas
// A collection of descriptors valid for the timestamp. They are released once
// the transaction using them is complete. If the transaction gets pushed and
// the timestamp changes, the descriptors are released.
// TODO (lucy): Use something other than an unsorted slice for faster lookups.
leasedDescriptors leasedDescriptors
// Descriptors modified by the uncommitted transaction affiliated with this
// Collection. This 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. These descriptors are local to this
// Collection and invisible to other transactions.
// TODO (lucy): Replace this with a data structure for faster lookups.
// Currently, the order in which descriptors are inserted matters, since we
// look at the draining names to account for descriptors being renamed. Any
// replacement data structure may have to store the name information in some
// different, more explicit way.
uncommittedDescriptors []*uncommittedDescriptor
// allDescriptors is a slice of all available descriptors. The descriptors
// are cached to avoid repeated lookups by users like virtual tables. The
// cache is purged whenever events would cause a scan of all descriptors to
// return different values, such as when the txn timestamp changes or when
// new descriptors are written in the txn.
//
// TODO(ajwerner): This cache may be problematic in clusters with very large
// numbers of descriptors.
allDescriptors allDescriptors
// allDatabaseDescriptors is a slice of all available database descriptors.
// These are purged at the same time as allDescriptors.
allDatabaseDescriptors []catalog.DatabaseDescriptor
// allSchemasForDatabase maps databaseID -> schemaID -> schemaName.
// For each databaseID, all schemas visible under the database can be
// observed.
// These are purged at the same time as allDescriptors.
allSchemasForDatabase map[descpb.ID]map[descpb.ID]string
// settings are required to correctly resolve system.namespace accesses in
// mixed version (19.2/20.1) clusters.
// TODO(solon): This field could maybe be removed in 20.2.
settings *cluster.Settings
// sessionData is the SessionData of the current session, if this Collection
// is being used in the context of a session. It is stored so that the Collection
// knows about state of temporary schemas (name and ID) for resolution.
sessionData *sessiondata.SessionData
// hydratedTables is node-level cache of table descriptors which utlize
// user-defined types.
hydratedTables *hydratedtables.Cache
// 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). Attempting to resolve
// a mutable descriptor by name or ID when a matching synthetic descriptor
// exists is illegal.
syntheticDescriptors []catalog.Descriptor
// skipValidationOnWrite should only be set to true during forced descriptor
// repairs.
skipValidationOnWrite bool
}
var _ catalog.Accessor = (*Collection)(nil)
// allDescriptors is an abstraction to capture the complete set of descriptors
// read from the store. It is used to accelerate repeated invocations of virtual
// tables which utilize descriptors. It tends to get used to build a
// sql.internalLookupCtx.
//
// TODO(ajwerner): Memory monitoring.
// TODO(ajwerner): Unify this struct with the uncommittedDescriptors set.
// TODO(ajwerner): Unify the sql.internalLookupCtx with the descs.Collection.
type allDescriptors struct {
descs []catalog.Descriptor
byID map[descpb.ID]int
}
func (d *allDescriptors) init(descriptors []catalog.Descriptor) {
d.descs = descriptors
d.byID = make(map[descpb.ID]int, len(descriptors))
for i, desc := range descriptors {
d.byID[desc.GetID()] = i
}
}
func (d *allDescriptors) clear() {
d.descs = nil
d.byID = nil
}
func (d *allDescriptors) isEmpty() bool {
return d.descs == nil
}
func (d *allDescriptors) contains(id descpb.ID) bool {
_, exists := d.byID[id]
return exists
}
// getLeasedDescriptorByName return a leased descriptor valid for the
// transaction, acquiring one if necessary. Due to a bug in lease acquisition
// for dropped descriptors, the descriptor may have to be read from the store,
// in which case shouldReadFromStore will be true.
func (tc *Collection) getLeasedDescriptorByName(
ctx context.Context, txn *kv.Txn, parentID descpb.ID, parentSchemaID descpb.ID, name string,
) (desc catalog.Descriptor, shouldReadFromStore bool, err error) {
// First, look to see if we already have the descriptor.
// This ensures that, once a SQL transaction resolved name N to id X, it will
// continue to use N to refer to X even if N is renamed during the
// transaction.
if desc = tc.leasedDescriptors.getByName(parentID, parentSchemaID, name); desc != nil {
if log.V(2) {
log.Eventf(ctx, "found descriptor in collection for '%s'", name)
}
return desc, false, nil
}
readTimestamp := txn.ReadTimestamp()
ldesc, err := tc.leaseMgr.AcquireByName(ctx, readTimestamp, parentID, parentSchemaID, name)
if err != nil {
// Read the descriptor from the store in the face of some specific errors
// because of a known limitation of AcquireByName. See the known
// limitations of AcquireByName for details.
if (catalog.HasInactiveDescriptorError(err) && errors.Is(err, catalog.ErrDescriptorDropped)) ||
errors.Is(err, catalog.ErrDescriptorNotFound) {
return nil, true, nil
}
// Lease acquisition failed with some other error. This we don't
// know how to deal with, so propagate the error.
return nil, false, err
}
expiration := ldesc.Expiration()
if expiration.LessEq(readTimestamp) {
log.Fatalf(ctx, "bad descriptor for T=%s, expiration=%s", readTimestamp, expiration)
}
tc.leasedDescriptors.add(ldesc)
if log.V(2) {
log.Eventf(ctx, "added descriptor '%s' to collection: %+v", name, ldesc.Desc())
}
// If the descriptor we just acquired expires before the txn's deadline,
// reduce the deadline. We use ReadTimestamp() that doesn't return the commit
// timestamp, so we need to set a deadline on the transaction to prevent it
// from committing beyond the version's expiration time.
err = tc.MaybeUpdateDeadline(ctx, txn)
if err != nil {
return nil, false, err
}
return ldesc.Desc(), false, nil
}
// Deadline returns the latest expiration from our leased
// descriptors which should b e the transactions deadline.
func (tc *Collection) Deadline() (deadline hlc.Timestamp, haveDeadline bool) {
for _, l := range tc.leasedDescriptors.descs {
expiration := l.Expiration()
if !haveDeadline || expiration.Less(deadline) {
haveDeadline = true
deadline = expiration
}
}
return deadline, haveDeadline
}
// 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) {
if deadline, haveDeadline := tc.Deadline(); haveDeadline {
err = txn.UpdateDeadline(ctx, deadline)
}
return err
}
// getLeasedDescriptorByID return a leased descriptor valid for the transaction,
// acquiring one if necessary.
// We set a deadline on the transaction based on the lease expiration, which is
// the usual case, unless setTxnDeadline is false.
func (tc *Collection) getLeasedDescriptorByID(
ctx context.Context, txn *kv.Txn, id descpb.ID, setTxnDeadline bool,
) (catalog.Descriptor, error) {
// First, look to see if we already have the table in the shared cache.
if desc := tc.leasedDescriptors.getByID(id); desc != nil {
log.VEventf(ctx, 2, "found descriptor %d in cache", id)
return desc, nil
}
readTimestamp := txn.ReadTimestamp()
desc, err := tc.leaseMgr.Acquire(ctx, readTimestamp, id)
if err != nil {
return nil, err
}
expiration := desc.Expiration()
if expiration.LessEq(readTimestamp) {
log.Fatalf(ctx, "bad descriptor for T=%s, expiration=%s", readTimestamp, expiration)
}
tc.leasedDescriptors.add(desc)
log.VEventf(ctx, 2, "added descriptor %q to collection", desc.Desc().GetName())
if setTxnDeadline {
err := tc.MaybeUpdateDeadline(ctx, txn)
if err != nil {
return nil, err
}
}
return desc.Desc(), nil
}
// getDescriptorFromStore gets a descriptor from its namespace entry. It does
// not return the descriptor if the name is being drained.
func (tc *Collection) getDescriptorFromStore(
ctx context.Context,
txn *kv.Txn,
parentID descpb.ID,
parentSchemaID descpb.ID,
name string,
mutable bool,
) (found bool, desc catalog.Descriptor, err error) {
// Bypass the namespace lookup from the store for system tables.
descID := bootstrap.LookupSystemTableDescriptorID(ctx, tc.settings, tc.codec(), parentID, name)
isSystemDescriptor := descID != descpb.InvalidID
if !isSystemDescriptor {
var found bool
var err error
found, descID, err = catalogkv.LookupObjectID(ctx, txn, tc.codec(), parentID, parentSchemaID, name)
if err != nil || !found {
return found, nil, err
}
}
// Always pick up a mutable copy so it can be cached.
desc, err = catalogkv.GetMutableDescriptorByID(ctx, txn, tc.codec(), descID)
if err != nil {
return false, nil, err
} else if desc == nil && isSystemDescriptor {
// This can happen during startup because we're not actually looking up the
// system descriptor IDs in KV.
return false, nil, errors.Wrapf(catalog.ErrDescriptorNotFound, "descriptor %d not found", descID)
} else if desc == nil {
// Having done the namespace lookup, the descriptor must exist.
return false, nil, errors.AssertionFailedf("descriptor %d not found", descID)
}
isNamespace2 := parentID == keys.SystemDatabaseID && name == systemschema.NamespaceTableName
// Immediately after a RENAME an old name still points to the descriptor
// during the drain phase for the name. Do not return a descriptor during
// draining.
if desc.GetName() != name && !isNamespace2 {
// Special case for the namespace table, whose name is namespace2 in its
// descriptor and namespace entry.
return false, nil, nil
}
ud, err := tc.addUncommittedDescriptor(desc.(catalog.MutableDescriptor))
if err != nil {
return false, nil, err
}
if !mutable {
desc = ud.immutable
}
return true, desc, nil
}
// GetMutableDatabaseByName returns a mutable database descriptor with
// properties according to the provided lookup flags. RequireMutable is ignored.
func (tc *Collection) GetMutableDatabaseByName(
ctx context.Context, txn *kv.Txn, name string, flags tree.DatabaseLookupFlags,
) (found bool, _ *dbdesc.Mutable, _ error) {
flags.RequireMutable = true
found, desc, err := tc.getDatabaseByName(ctx, txn, name, flags)
if err != nil || !found {
return false, nil, err
}
return true, desc.(*dbdesc.Mutable), nil
}
// GetImmutableDatabaseByName returns an immutable database descriptor with
// properties according to the provided lookup flags. RequireMutable is ignored.
func (tc *Collection) GetImmutableDatabaseByName(
ctx context.Context, txn *kv.Txn, name string, flags tree.DatabaseLookupFlags,
) (found bool, _ catalog.DatabaseDescriptor, _ error) {
flags.RequireMutable = false
return tc.getDatabaseByName(ctx, txn, name, flags)
}
// GetDatabaseDesc implements the Accessor interface.
//
// TODO(ajwerner): This exists to support the SchemaResolver interface and
// should be removed or adjusted.
func (tc *Collection) GetDatabaseDesc(
ctx context.Context, txn *kv.Txn, name string, flags tree.DatabaseLookupFlags,
) (desc catalog.DatabaseDescriptor, err error) {
_, desc, err = tc.getDatabaseByName(ctx, txn, name, flags)
return desc, err
}
// getDatabaseByName returns a database descriptor with properties according to
// the provided lookup flags.
func (tc *Collection) getDatabaseByName(
ctx context.Context, txn *kv.Txn, name string, flags tree.DatabaseLookupFlags,
) (bool, catalog.DatabaseDescriptor, error) {
if name == systemschema.SystemDatabaseName {
// The system database descriptor should never actually be mutated, which is
// why we return the same hard-coded descriptor every time. It's assumed
// that callers of this method will check the privileges on the descriptor
// (like any other database) and return an error.
if flags.RequireMutable {
return true, dbdesc.NewBuilder(systemschema.MakeSystemDatabaseDesc().DatabaseDesc()).BuildExistingMutableDatabase(), nil
}
return true, systemschema.MakeSystemDatabaseDesc(), nil
}
getDatabaseByName := func() (found bool, _ catalog.Descriptor, err error) {
if found, refuseFurtherLookup, desc, err := tc.getSyntheticOrUncommittedDescriptor(
keys.RootNamespaceID, keys.RootNamespaceID, name, flags.RequireMutable,
); err != nil || refuseFurtherLookup {
return false, nil, err
} else if found {
log.VEventf(ctx, 2, "found uncommitted descriptor %d", desc.GetID())
return true, desc, nil
}
if flags.AvoidCached || flags.RequireMutable || lease.TestingTableLeasesAreDisabled() {
return tc.getDescriptorFromStore(
ctx, txn, keys.RootNamespaceID, keys.RootNamespaceID, name, flags.RequireMutable,
)
}
desc, shouldReadFromStore, err := tc.getLeasedDescriptorByName(
ctx, txn, keys.RootNamespaceID, keys.RootNamespaceID, name)
if err != nil {
return false, nil, err
}
if shouldReadFromStore {
return tc.getDescriptorFromStore(
ctx, txn, keys.RootNamespaceID, keys.RootNamespaceID, name, flags.RequireMutable,
)
}
return true, desc, nil
}
found, desc, err := getDatabaseByName()
if err != nil {
return false, nil, err
} else if !found {
if flags.Required {
return false, nil, sqlerrors.NewUndefinedDatabaseError(name)
}
return false, nil, nil
}
db, ok := desc.(catalog.DatabaseDescriptor)
if !ok {
if flags.Required {
return false, nil, sqlerrors.NewUndefinedDatabaseError(name)
}
return false, nil, nil
}
if dropped, err := filterDescriptorState(db, flags.Required, flags); err != nil || dropped {
return false, nil, err
}
return true, db, nil
}
// GetObjectDesc looks up an object by name and returns both its
// descriptor and that of its parent database. If the object is not
// found and flags.required is true, an error is returned, otherwise
// a nil reference is returned.
//
// TODO(ajwerner): clarify the purpose of the transaction here. It's used in
// some cases for some lookups but not in others. For example, if a mutable
// descriptor is requested, it will be utilized however if an immutable
// descriptor is requested then it will only be used for its timestamp and to
// set the deadline.
func (tc *Collection) GetObjectDesc(
ctx context.Context, txn *kv.Txn, db, schema, object string, flags tree.ObjectLookupFlags,
) (desc catalog.Descriptor, err error) {
if isVirtual, desc, err := tc.maybeGetVirtualObjectDesc(
schema, object, flags, db,
); isVirtual || err != nil {
return desc, err
}
// Fall back to physical descriptor access.
switch flags.DesiredObjectKind {
case tree.TypeObject:
typeName := tree.MakeNewQualifiedTypeName(db, schema, object)
_, desc, err := tc.getTypeByName(ctx, txn, &typeName, flags)
return desc, err
case tree.TableObject:
tableName := tree.MakeTableNameWithSchema(tree.Name(db), tree.Name(schema), tree.Name(object))
_, desc, err := tc.getTableByName(ctx, txn, &tableName, flags)
return desc, err
default:
return nil, errors.AssertionFailedf("unknown desired object kind %d", flags.DesiredObjectKind)
}
}
func (tc *Collection) maybeGetVirtualObjectDesc(
schema string, object string, flags tree.ObjectLookupFlags, db string,
) (isVirtual bool, _ catalog.Descriptor, _ error) {
if tc.virtualSchemas == nil {
return false, nil, nil
}
scEntry, ok := tc.virtualSchemas.GetVirtualSchema(schema)
if !ok {
return false, nil, nil
}
desc, err := scEntry.GetObjectByName(object, flags)
if err != nil {
return true, nil, err
}
if desc == nil {
if flags.Required {
obj := tree.NewQualifiedObjectName(db, schema, object, flags.DesiredObjectKind)
return true, nil, sqlerrors.NewUndefinedObjectError(obj, flags.DesiredObjectKind)
}
return true, nil, nil
}
if flags.RequireMutable {
return true, nil, catalog.NewMutableAccessToVirtualSchemaError(scEntry, object)
}
return true, desc.Desc(), nil
}
func (tc *Collection) getObjectByName(
ctx context.Context,
txn *kv.Txn,
catalogName, schemaName, objectName string,
flags tree.ObjectLookupFlags,
) (found bool, _ catalog.Descriptor, err error) {
// If we're reading the object descriptor from the store,
// we should read its parents from the store too to ensure
// that subsequent name resolution finds the latest name
// in the face of a concurrent rename.
avoidCachedForParent := flags.AvoidCached || flags.RequireMutable
// Resolve the database.
found, db, err := tc.GetImmutableDatabaseByName(ctx, txn, catalogName,
tree.DatabaseLookupFlags{
Required: flags.Required,
AvoidCached: avoidCachedForParent,
IncludeDropped: flags.IncludeDropped,
IncludeOffline: flags.IncludeOffline,
})
if err != nil || !found {
return false, nil, err
}
dbID := db.GetID()
// Resolve the schema.
foundSchema, resolvedSchema, err := tc.GetImmutableSchemaByName(ctx, txn, dbID, schemaName,
tree.SchemaLookupFlags{
Required: flags.Required,
AvoidCached: avoidCachedForParent,
IncludeDropped: flags.IncludeDropped,
IncludeOffline: flags.IncludeOffline,
})
if err != nil || !foundSchema {
return false, nil, err
}
schemaID := resolvedSchema.ID
if found, refuseFurtherLookup, desc, err := tc.getSyntheticOrUncommittedDescriptor(
dbID, schemaID, objectName, flags.RequireMutable,
); err != nil || refuseFurtherLookup {
return false, nil, err
} else if found {
log.VEventf(ctx, 2, "found uncommitted descriptor %d", desc.GetID())
return true, desc, nil
}
// TODO(vivek): Ideally we'd avoid caching for only the
// system.descriptor and system.lease tables, because they are
// used for acquiring leases, creating a chicken&egg problem.
// But doing so turned problematic and the tests pass only by also
// disabling caching of system.eventlog, system.rangelog, and
// system.users. For now we're sticking to disabling caching of
// all system descriptors except role_members, role_options, and users
// (i.e., the ones used during authn/authz flows).
// TODO (lucy): Reevaluate the above. We have many more system tables now and
// should be able to lease most of them.
isAllowedSystemTable := objectName == systemschema.RoleMembersTable.GetName() ||
objectName == systemschema.RoleOptionsTable.GetName() ||
objectName == systemschema.UsersTable.GetName() ||
objectName == systemschema.JobsTable.GetName() ||
objectName == systemschema.EventLogTable.GetName()
avoidCache := flags.AvoidCached || flags.RequireMutable || lease.TestingTableLeasesAreDisabled() ||
(catalogName == systemschema.SystemDatabaseName && !isAllowedSystemTable)
if avoidCache {
return tc.getDescriptorFromStore(
ctx, txn, dbID, schemaID, objectName, flags.RequireMutable,
)
}
desc, shouldReadFromStore, err := tc.getLeasedDescriptorByName(
ctx, txn, dbID, schemaID, objectName)
if err != nil {
return false, nil, err
}
if shouldReadFromStore {
return tc.getDescriptorFromStore(
ctx, txn, dbID, schemaID, objectName, flags.RequireMutable,
)
}
return true, desc, nil
}
// GetMutableTableByName returns a mutable table descriptor with properties
// according to the provided lookup flags. RequireMutable is ignored.
func (tc *Collection) GetMutableTableByName(
ctx context.Context, txn *kv.Txn, name tree.ObjectName, flags tree.ObjectLookupFlags,
) (found bool, _ *tabledesc.Mutable, _ error) {
flags.RequireMutable = true
found, desc, err := tc.getTableByName(ctx, txn, name, flags)
if err != nil || !found {
return false, nil, err
}
return true, desc.(*tabledesc.Mutable), nil
}
// GetImmutableTableByName returns a mutable table descriptor with properties
// according to the provided lookup flags. RequireMutable is ignored.
func (tc *Collection) GetImmutableTableByName(
ctx context.Context, txn *kv.Txn, name tree.ObjectName, flags tree.ObjectLookupFlags,
) (found bool, _ catalog.TableDescriptor, _ error) {
flags.RequireMutable = false
found, desc, err := tc.getTableByName(ctx, txn, name, flags)
if err != nil || !found {
return false, nil, err
}
return true, desc, nil
}
// getTableByName returns a table descriptor with properties according to the
// provided lookup flags.
func (tc *Collection) getTableByName(
ctx context.Context, txn *kv.Txn, name tree.ObjectName, flags tree.ObjectLookupFlags,
) (found bool, _ catalog.TableDescriptor, err error) {
found, desc, err := tc.getObjectByName(
ctx, txn, name.Catalog(), name.Schema(), name.Object(), flags)
if err != nil {
return false, nil, err
} else if !found {
if flags.Required {
return false, nil, sqlerrors.NewUndefinedRelationError(name)
}
return false, nil, nil
}
table, ok := desc.(catalog.TableDescriptor)
if !ok {
if flags.Required {
return false, nil, sqlerrors.NewUndefinedRelationError(name)
}
return false, nil, nil
}
if table.Adding() && table.IsUncommittedVersion() &&
(flags.RequireMutable || flags.CommonLookupFlags.AvoidCached) {
// Special case: We always return tables in the adding state if they were
// created in the same transaction and a descriptor (effectively) read in
// the same transaction is requested. What this basically amounts to is
// resolving adding descriptors only for DDLs (etc.).
// TODO (lucy): I'm not sure where this logic should live. We could add an
// IncludeAdding flag and pull the special case handling up into the
// callers. Figure that out after we clean up the name resolution layers
// and it becomes more clear what the callers should be.
return true, table, nil
}
if dropped, err := filterDescriptorState(
table, flags.Required, flags.CommonLookupFlags,
); err != nil || dropped {
return false, nil, err
}
hydrated, err := tc.hydrateTypesInTableDesc(ctx, txn, table)
if err != nil {
return false, nil, err
}
return true, hydrated, nil
}
// GetMutableTypeByName returns a mutable type descriptor with properties
// according to the provided lookup flags. RequireMutable is ignored.
func (tc *Collection) GetMutableTypeByName(
ctx context.Context, txn *kv.Txn, name tree.ObjectName, flags tree.ObjectLookupFlags,
) (found bool, _ *typedesc.Mutable, _ error) {
flags.RequireMutable = true
found, desc, err := tc.getTypeByName(ctx, txn, name, flags)
if err != nil || !found {
return false, nil, err
}
return true, desc.(*typedesc.Mutable), nil
}
// GetImmutableTypeByName returns a mutable type descriptor with properties
// according to the provided lookup flags. RequireMutable is ignored.
func (tc *Collection) GetImmutableTypeByName(
ctx context.Context, txn *kv.Txn, name tree.ObjectName, flags tree.ObjectLookupFlags,
) (found bool, _ catalog.TypeDescriptor, _ error) {
flags.RequireMutable = false
return tc.getTypeByName(ctx, txn, name, flags)
}
// getTypeByName returns a type descriptor with properties according to the
// provided lookup flags.
func (tc *Collection) getTypeByName(
ctx context.Context, txn *kv.Txn, name tree.ObjectName, flags tree.ObjectLookupFlags,
) (found bool, _ catalog.TypeDescriptor, err error) {
found, desc, err := tc.getObjectByName(
ctx, txn, name.Catalog(), name.Schema(), name.Object(), flags)
if err != nil {
return false, nil, err
} else if !found {
if flags.Required {
return false, nil, sqlerrors.NewUndefinedTypeError(name)
}
return false, nil, nil
}
typ, ok := desc.(catalog.TypeDescriptor)
if !ok {
if flags.Required {
return false, nil, sqlerrors.NewUndefinedTypeError(name)
}
return false, nil, nil
}
if dropped, err := filterDescriptorState(typ, flags.Required, flags.CommonLookupFlags); err != nil || dropped {
return false, nil, err
}
return true, typ, nil
}
// TODO (lucy): Should this just take a database name? We're separately
// resolving the database name in lots of places where we (indirectly) call
// this.
func (tc *Collection) getUserDefinedSchemaByName(
ctx context.Context, txn *kv.Txn, dbID descpb.ID, schemaName string, flags tree.SchemaLookupFlags,
) (catalog.SchemaDescriptor, error) {
getSchemaByName := func() (found bool, _ catalog.Descriptor, err error) {
if descFound, refuseFurtherLookup, desc, err := tc.getSyntheticOrUncommittedDescriptor(
dbID, keys.RootNamespaceID, schemaName, flags.RequireMutable,
); err != nil || refuseFurtherLookup {
return false, nil, err
} else if descFound {
log.VEventf(ctx, 2, "found uncommitted descriptor %d", desc.GetID())
return true, desc, nil
}
if flags.AvoidCached || flags.RequireMutable || lease.TestingTableLeasesAreDisabled() {
return tc.getDescriptorFromStore(
ctx, txn, dbID, keys.RootNamespaceID, schemaName, flags.RequireMutable,
)
}
// Look up whether the schema is on the database descriptor and return early
// if it's not.
_, dbDesc, err := tc.GetImmutableDatabaseByID(
ctx, txn, dbID, tree.DatabaseLookupFlags{Required: true},
)
if err != nil {
return false, nil, err
}
schemaID := dbDesc.GetSchemaID(schemaName)
if schemaID == descpb.InvalidID {
return false, nil, nil
}
foundSchemaName := dbDesc.GetNonDroppedSchemaName(schemaID)
if foundSchemaName != schemaName {
// If there's another schema name entry with the same ID as this one, then
// the schema has been renamed, so don't return anything.
if foundSchemaName != "" {
return false, nil, nil
}
// Otherwise, the schema has been dropped. Return early, except in the
// specific case where flags.Required and flags.IncludeDropped are both
// true, which forces us to look up the dropped descriptor and return it.
if !flags.Required {
return false, nil, nil
}
if !flags.IncludeDropped {
return false, nil, catalog.NewInactiveDescriptorError(catalog.ErrDescriptorDropped)
}
}
// If we have a schema ID from the database, get the schema descriptor. Since
// the schema and database descriptors are updated in the same transaction,
// their leased "versions" (not the descriptor version, but the state in the
// abstract sequence of states in adding, renaming, or dropping a schema) can
// differ by at most 1 while waiting for old leases to drain. So false
// negatives can occur from the database lookup, in some sense, if we have a
// lease on the latest version of the schema and on the previous version of
// the database which doesn't reflect the changes to the schema. But this
// isn't a problem for correctness; it can only happen on other sessions
// before the schema change has returned results.
desc, err := tc.getDescriptorByID(ctx, txn, schemaID, flags)
if err != nil {
if errors.Is(err, catalog.ErrDescriptorNotFound) ||
errors.Is(err, catalog.ErrDescriptorDropped) {
return false, nil, nil
}
return false, nil, err
}
return true, desc, nil
}
found, desc, err := getSchemaByName()
if err != nil {
return nil, err
} else if !found {
if flags.Required {
return nil, sqlerrors.NewUndefinedSchemaError(schemaName)
}
return nil, nil
}
schema, ok := desc.(catalog.SchemaDescriptor)
if !ok {
if flags.Required {
return nil, sqlerrors.NewUndefinedSchemaError(schemaName)
}
return nil, nil
}
if dropped, err := filterDescriptorState(schema, flags.Required, flags); dropped || err != nil {
return nil, err
}
return schema, nil
}
// filterDescriptorState wraps the more general catalog function to swallow
// the error if the descriptor is being dropped and the descriptor is not
// required. In that case, dropped will be true. A return value of false, nil
// means this descriptor is okay given the flags.
// TODO (lucy): We would like the ByID methods to ignore the Required flag and
// unconditionally return an error for dropped descriptors if IncludeDropped is
// not set, so we can't just pass the flags passed into the methods into this
// function, hence the boolean argument. This is the only user of
// catalog.FilterDescriptorState which needs to pass in nontrivial flags, at
// time of writing, so we should clean up the interface around this bit of
// functionality.
func filterDescriptorState(
desc catalog.Descriptor, required bool, flags tree.CommonLookupFlags,
) (dropped bool, _ error) {
flags = tree.CommonLookupFlags{
Required: required,
IncludeOffline: flags.IncludeOffline,
IncludeDropped: flags.IncludeDropped,
}
if err := catalog.FilterDescriptorState(desc, flags); err != nil {
if required || !errors.Is(err, catalog.ErrDescriptorDropped) {
return false, err
}
return true, nil
}
return false, nil
}
// GetMutableSchemaByName resolves the schema and, if applicable, returns a
// mutable descriptor usable by the transaction. RequireMutable is ignored.
func (tc *Collection) GetMutableSchemaByName(
ctx context.Context, txn *kv.Txn, dbID descpb.ID, schemaName string, flags tree.SchemaLookupFlags,
) (bool, catalog.ResolvedSchema, error) {
flags.RequireMutable = true
return tc.getSchemaByName(ctx, txn, dbID, schemaName, flags)
}
// GetImmutableSchemaByName resolves the schema and, if applicable, returns an
// immutable descriptor usable by the transaction. RequireMutable is ignored.
func (tc *Collection) GetImmutableSchemaByName(
ctx context.Context, txn *kv.Txn, dbID descpb.ID, schemaName string, flags tree.SchemaLookupFlags,
) (bool, catalog.ResolvedSchema, error) {
flags.RequireMutable = false
return tc.getSchemaByName(ctx, txn, dbID, schemaName, flags)
}
// GetSchemaByName returns true and a ResolvedSchema object if the target schema
// exists under the target database.
func (tc *Collection) GetSchemaByName(
ctx context.Context, txn *kv.Txn, dbID descpb.ID, schemaName string, flags tree.SchemaLookupFlags,
) (found bool, _ catalog.ResolvedSchema, _ error) {
return tc.getSchemaByName(ctx, txn, dbID, schemaName, flags)
}
// getSchemaByName resolves the schema and, if applicable, returns a descriptor
// usable by the transaction.
func (tc *Collection) getSchemaByName(
ctx context.Context, txn *kv.Txn, dbID descpb.ID, schemaName string, flags tree.SchemaLookupFlags,
) (bool, catalog.ResolvedSchema, error) {
// Fast path public schema, as it is always found.
if schemaName == tree.PublicSchema {
return true, catalog.ResolvedSchema{
ID: keys.PublicSchemaID, Kind: catalog.SchemaPublic, Name: tree.PublicSchema,
}, nil
}
if tc.virtualSchemas != nil {
if _, ok := tc.virtualSchemas.GetVirtualSchema(schemaName); ok {
return true, catalog.ResolvedSchema{
Kind: catalog.SchemaVirtual,
Name: schemaName,
}, nil
}
}
// If a temp schema is requested, check if it's for the current session, or
// else fall back to reading from the store.
if strings.HasPrefix(schemaName, sessiondata.PgTempSchemaName) {
if tc.sessionData != nil {
if schemaName == sessiondata.PgTempSchemaName ||
schemaName == tc.sessionData.SearchPath.GetTemporarySchemaName() {
schemaID, found := tc.sessionData.GetTemporarySchemaIDForDb(uint32(dbID))
if found {
schema := catalog.ResolvedSchema{
Kind: catalog.SchemaTemporary,
Name: tc.sessionData.SearchPath.GetTemporarySchemaName(),
ID: descpb.ID(schemaID),
}
return true, schema, nil
}
}
}
exists, schemaID, err := catalogkv.ResolveSchemaID(ctx, txn, tc.codec(), dbID, schemaName)
if err != nil {
return false, catalog.ResolvedSchema{}, err
} else if !exists {
if flags.Required {
return false, catalog.ResolvedSchema{}, sqlerrors.NewUndefinedSchemaError(schemaName)
}
return false, catalog.ResolvedSchema{}, nil
}
schema := catalog.ResolvedSchema{
Kind: catalog.SchemaTemporary,
Name: schemaName,