-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
resolver.go
1464 lines (1349 loc) · 47.3 KB
/
resolver.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 2018 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 sql
import (
"context"
"fmt"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/dbdesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descbuilder"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/resolver"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/typedesc"
"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"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/errors"
"github.com/lib/pq/oid"
)
var _ resolver.SchemaResolver = &planner{}
// runWithOptions sets the provided resolution flags for the
// duration of the call of the passed argument fn.
//
// This is meant to be used like this (for example):
//
// var someVar T
// var err error
// p.runWithOptions(resolveFlags{skipCache: true}, func() {
// someVar, err = ResolveExistingTableObject(ctx, p, ...)
// })
// if err != nil { ... }
// use(someVar)
func (p *planner) runWithOptions(flags resolveFlags, fn func()) {
if flags.skipCache {
defer func(prev bool) { p.avoidLeasedDescriptors = prev }(p.avoidLeasedDescriptors)
p.avoidLeasedDescriptors = true
}
if flags.contextDatabaseID != descpb.InvalidID {
defer func(prev descpb.ID) { p.contextDatabaseID = prev }(p.contextDatabaseID)
p.contextDatabaseID = flags.contextDatabaseID
}
fn()
}
type resolveFlags struct {
skipCache bool
contextDatabaseID descpb.ID
}
func (p *planner) ResolveMutableTableDescriptor(
ctx context.Context, tn *tree.TableName, required bool, requiredType tree.RequiredTableKind,
) (prefix catalog.ResolvedObjectPrefix, table *tabledesc.Mutable, err error) {
prefix, desc, err := resolver.ResolveMutableExistingTableObject(ctx, p, tn, required, requiredType)
if err != nil {
return prefix, nil, err
}
// Ensure that the current user can access the target schema.
if desc != nil {
if err := p.canResolveDescUnderSchema(ctx, prefix.Schema, desc); err != nil {
return catalog.ResolvedObjectPrefix{}, nil, err
}
}
return prefix, desc, nil
}
// TODO(ajwerner): Remove this and things like it to use more generic
// functionality. We really need to centralize the privilege checking.
func (p *planner) resolveUncachedTableDescriptor(
ctx context.Context, tn *tree.TableName, required bool, requiredType tree.RequiredTableKind,
) (table catalog.TableDescriptor, err error) {
var prefix catalog.ResolvedObjectPrefix
var desc catalog.Descriptor
p.runWithOptions(resolveFlags{skipCache: true}, func() {
lookupFlags := tree.ObjectLookupFlags{
CommonLookupFlags: tree.CommonLookupFlags{Required: required},
DesiredObjectKind: tree.TableObject,
DesiredTableDescKind: requiredType,
}
desc, prefix, err = resolver.ResolveExistingObject(
ctx, p, tn.ToUnresolvedObjectName(), lookupFlags,
)
})
if err != nil || desc == nil {
return nil, err
}
table = desc.(catalog.TableDescriptor)
// Ensure that the current user can access the target schema.
if err := p.canResolveDescUnderSchema(ctx, prefix.Schema, table); err != nil {
return nil, err
}
return table, nil
}
func (p *planner) ResolveTargetObject(
ctx context.Context, un *tree.UnresolvedObjectName,
) (
db catalog.DatabaseDescriptor,
schema catalog.SchemaDescriptor,
namePrefix tree.ObjectNamePrefix,
err error,
) {
var prefix catalog.ResolvedObjectPrefix
p.runWithOptions(resolveFlags{skipCache: true}, func() {
prefix, namePrefix, err = resolver.ResolveTargetObject(ctx, p, un)
})
if err != nil {
return nil, nil, namePrefix, err
}
return prefix.Database, prefix.Schema, namePrefix, err
}
// LookupSchema implements the resolver.ObjectNameTargetResolver interface.
func (p *planner) LookupSchema(
ctx context.Context, dbName, scName string,
) (found bool, scMeta catalog.ResolvedObjectPrefix, err error) {
dbDesc, err := p.Descriptors().GetImmutableDatabaseByName(ctx, p.txn, dbName,
tree.DatabaseLookupFlags{AvoidLeased: p.avoidLeasedDescriptors})
if err != nil || dbDesc == nil {
return false, catalog.ResolvedObjectPrefix{}, err
}
sc := p.Accessor()
var resolvedSchema catalog.SchemaDescriptor
resolvedSchema, err = sc.GetSchemaByName(
ctx, p.txn, dbDesc, scName, p.CommonLookupFlags(false /* required */),
)
if err != nil || resolvedSchema == nil {
return false, catalog.ResolvedObjectPrefix{}, err
}
return true, catalog.ResolvedObjectPrefix{
Database: dbDesc,
Schema: resolvedSchema,
}, nil
}
// SchemaExists implements the tree.EvalDatabase interface.
func (p *planner) SchemaExists(ctx context.Context, dbName, scName string) (found bool, err error) {
found, _, err = p.LookupSchema(ctx, dbName, scName)
return found, err
}
// LookupObject implements the tree.ObjectNameExistingResolver interface.
func (p *planner) LookupObject(
ctx context.Context, flags tree.ObjectLookupFlags, dbName, scName, obName string,
) (found bool, prefix catalog.ResolvedObjectPrefix, objMeta catalog.Descriptor, err error) {
sc := p.Accessor()
flags.CommonLookupFlags.Required = false
flags.CommonLookupFlags.AvoidLeased = p.avoidLeasedDescriptors
// Check if we are looking up a type which matches a built-in type in
// CockroachDB but is an extension type on the public schema in PostgreSQL.
if flags.DesiredObjectKind == tree.TypeObject && scName == tree.PublicSchema {
if alias, ok := types.PublicSchemaAliases[obName]; ok {
if flags.RequireMutable {
return true, catalog.ResolvedObjectPrefix{}, nil, pgerror.Newf(pgcode.WrongObjectType, "type %q is a built-in type", obName)
}
found, prefix, err = p.LookupSchema(ctx, dbName, scName)
if err != nil || !found {
return found, prefix, nil, err
}
dbDesc, err := p.Descriptors().GetImmutableDatabaseByName(ctx, p.txn, dbName,
tree.DatabaseLookupFlags{AvoidLeased: p.avoidLeasedDescriptors})
if err != nil {
return found, prefix, nil, err
}
if dbDesc.HasPublicSchemaWithDescriptor() {
publicSchemaID := dbDesc.GetSchemaID(tree.PublicSchema)
return true, prefix, typedesc.MakeSimpleAlias(alias, publicSchemaID), nil
}
return true, prefix, typedesc.MakeSimpleAlias(alias, keys.PublicSchemaID), nil
}
}
prefix, objMeta, err = sc.GetObjectDesc(ctx, p.txn, dbName, scName, obName, flags)
return objMeta != nil, prefix, objMeta, err
}
// CommonLookupFlags is part of the resolver.SchemaResolver interface.
func (p *planner) CommonLookupFlags(required bool) tree.CommonLookupFlags {
return tree.CommonLookupFlags{
Required: required,
AvoidLeased: p.avoidLeasedDescriptors,
}
}
// IsTableVisible is part of the tree.EvalDatabase interface.
func (p *planner) IsTableVisible(
ctx context.Context, curDB string, searchPath sessiondata.SearchPath, tableID oid.Oid,
) (isVisible, exists bool, err error) {
tableDesc, err := p.LookupTableByID(ctx, descpb.ID(tableID))
if err != nil {
// If a "not found" error happened here, we return "not exists" rather than
// the error.
if errors.Is(err, catalog.ErrDescriptorNotFound) ||
errors.Is(err, catalog.ErrDescriptorDropped) ||
pgerror.GetPGCode(err) == pgcode.UndefinedTable ||
pgerror.GetPGCode(err) == pgcode.UndefinedObject {
return false, false, nil //nolint:returnerrcheck
}
return false, false, err
}
schemaID := tableDesc.GetParentSchemaID()
schemaDesc, err := p.Descriptors().GetImmutableSchemaByID(ctx, p.Txn(), schemaID,
tree.SchemaLookupFlags{
Required: true,
AvoidLeased: p.avoidLeasedDescriptors})
if err != nil {
return false, false, err
}
if schemaDesc.SchemaKind() != catalog.SchemaVirtual {
dbID := tableDesc.GetParentID()
_, dbDesc, err := p.Descriptors().GetImmutableDatabaseByID(ctx, p.Txn(), dbID,
tree.DatabaseLookupFlags{
Required: true,
AvoidLeased: p.avoidLeasedDescriptors})
if err != nil {
return false, false, err
}
if dbDesc.GetName() != curDB {
// If the table is in a different database, then it's considered to be
// "not existing" instead of just "not visible"; this matches PostgreSQL.
return false, false, nil
}
}
iter := searchPath.Iter()
for scName, ok := iter.Next(); ok; scName, ok = iter.Next() {
if schemaDesc.GetName() == scName {
return true, true, nil
}
}
return false, true, nil
}
// IsTypeVisible is part of the tree.EvalDatabase interface.
func (p *planner) IsTypeVisible(
ctx context.Context, curDB string, searchPath sessiondata.SearchPath, typeID oid.Oid,
) (isVisible bool, exists bool, err error) {
// Check builtin types first. They are always globally visible.
if _, ok := types.OidToType[typeID]; ok {
return true, true, nil
}
if !types.IsOIDUserDefinedType(typeID) {
return false, false, nil //nolint:returnerrcheck
}
id, err := typedesc.UserDefinedTypeOIDToID(typeID)
if err != nil {
return false, false, err
}
typName, _, err := p.GetTypeDescriptor(ctx, id)
if err != nil {
// If a "not found" error happened here, we return "not exists" rather than
// the error.
if errors.Is(err, catalog.ErrDescriptorNotFound) ||
errors.Is(err, catalog.ErrDescriptorDropped) ||
pgerror.GetPGCode(err) == pgcode.UndefinedObject {
return false, false, nil //nolint:returnerrcheck
}
return false, false, err
}
if typName.CatalogName.String() != curDB {
// If the type is in a different database, then it's considered to be
// "not existing" instead of just "not visible"; this matches PostgreSQL.
return false, false, nil
}
iter := searchPath.Iter()
for scName, ok := iter.Next(); ok; scName, ok = iter.Next() {
if typName.SchemaName.String() == scName {
return true, true, nil
}
}
return false, true, nil
}
// HasPrivilege is part of the tree.EvalDatabase interface.
func (p *planner) HasPrivilege(
ctx context.Context,
specifier tree.HasPrivilegeSpecifier,
user security.SQLUsername,
priv privilege.Privilege,
) (bool, error) {
desc, err := p.ResolveDescriptorForPrivilegeSpecifier(
ctx,
specifier,
)
if err != nil {
return false, err
}
// hasPrivilegeFunc checks whether any role has the given privilege.
hasPrivilegeFunc := func(priv privilege.Privilege) (bool, error) {
err := p.CheckPrivilegeForUser(ctx, desc, priv.Kind, user)
if err != nil {
if pgerror.GetPGCode(err) == pgcode.InsufficientPrivilege {
return false, nil
}
return false, err
}
if priv.GrantOption {
if !p.ExecCfg().Settings.Version.IsActive(ctx, clusterversion.ValidateGrantOption) {
err := p.CheckPrivilegeForUser(ctx, desc, privilege.GRANT, user)
if err != nil {
if pgerror.GetPGCode(err) == pgcode.InsufficientPrivilege {
return false, nil
}
return false, err
}
} else {
err := p.CheckGrantOptionsForUser(ctx, desc, []privilege.Kind{priv.Kind}, user, true /* isGrant */)
if err != nil {
if pgerror.GetPGCode(err) == pgcode.WarningPrivilegeNotGranted {
return false, nil
}
return false, err
}
}
}
return true, nil
}
if priv.Kind == privilege.RULE {
// RULE was only added for compatibility with Postgres, and Postgres
// never allows RULE to be granted, even if the user has ALL privileges.
// See https://www.postgresql.org/docs/8.1/sql-grant.html
// and https://www.postgresql.org/docs/release/8.2.0/.
return false, nil
}
hasPrivilege, err := hasPrivilegeFunc(privilege.Privilege{Kind: privilege.ALL})
if err != nil {
return false, err
}
if hasPrivilege {
return true, nil
}
return hasPrivilegeFunc(priv)
}
// ResolveDescriptorForPrivilegeSpecifier resolves a tree.HasPrivilegeSpecifier
// and returns the descriptor for the given object.
func (p *planner) ResolveDescriptorForPrivilegeSpecifier(
ctx context.Context, specifier tree.HasPrivilegeSpecifier,
) (catalog.Descriptor, error) {
if specifier.DatabaseName != nil {
return p.Descriptors().GetImmutableDatabaseByName(
ctx, p.txn, *specifier.DatabaseName, tree.DatabaseLookupFlags{Required: true},
)
} else if specifier.DatabaseOID != nil {
_, database, err := p.Descriptors().GetImmutableDatabaseByID(
ctx, p.txn, descpb.ID(*specifier.DatabaseOID), tree.DatabaseLookupFlags{Required: true},
)
return database, err
} else if specifier.SchemaName != nil {
database, err := p.Descriptors().GetImmutableDatabaseByName(
ctx, p.txn, *specifier.SchemaDatabaseName, tree.DatabaseLookupFlags{Required: true},
)
if err != nil {
return nil, err
}
return p.Descriptors().GetImmutableSchemaByName(
ctx, p.txn, database, *specifier.SchemaName, tree.SchemaLookupFlags{Required: true},
)
} else if specifier.TableName != nil || specifier.TableOID != nil {
var table catalog.TableDescriptor
var err error
if specifier.TableName != nil {
var tn *tree.TableName
tn, err = parser.ParseQualifiedTableName(*specifier.TableName)
if err != nil {
return nil, err
}
if _, err = p.ResolveTableName(ctx, tn); err != nil {
return nil, err
}
if p.SessionData().Database != "" && p.SessionData().Database != string(tn.CatalogName) {
// Postgres does not allow cross-database references in these
// functions, so we don't either.
return nil, pgerror.Newf(pgcode.FeatureNotSupported,
"cross-database references are not implemented: %s", tn)
}
_, table, err = p.Descriptors().GetImmutableTableByName(
ctx, p.txn, tn, tree.ObjectLookupFlags{
CommonLookupFlags: tree.CommonLookupFlags{
Required: true,
},
},
)
} else {
table, err = p.Descriptors().GetImmutableTableByID(
ctx, p.txn, descpb.ID(*specifier.TableOID),
tree.ObjectLookupFlags{
CommonLookupFlags: tree.CommonLookupFlags{
Required: true,
},
},
)
}
if err != nil {
return nil, err
}
if *specifier.IsSequence {
// has_table_privilege works with sequences, but has_sequence_privilege does not work with tables
if !table.IsSequence() {
return nil, pgerror.Newf(pgcode.WrongObjectType,
"\"%s\" is not a sequence", table.GetName())
}
} else {
if err := validateColumnForHasPrivilegeSpecifier(
table,
specifier,
); err != nil {
return nil, err
}
}
return table, nil
}
return nil, errors.AssertionFailedf("invalid HasPrivilegeSpecifier")
}
func validateColumnForHasPrivilegeSpecifier(
table catalog.TableDescriptor, specifier tree.HasPrivilegeSpecifier,
) error {
if specifier.ColumnName != nil {
_, err := table.FindColumnWithName(*specifier.ColumnName)
return err
}
if specifier.ColumnAttNum != nil {
for _, col := range table.PublicColumns() {
if col.GetPGAttributeNum() == *specifier.ColumnAttNum {
return nil
}
}
return pgerror.Newf(
pgcode.UndefinedColumn,
"column %d of relation %s does not exist",
*specifier.ColumnAttNum,
tree.Name(table.GetName()),
)
}
return nil
}
// GetTypeDescriptor implements the descpb.TypeDescriptorResolver interface.
func (p *planner) GetTypeDescriptor(
ctx context.Context, id descpb.ID,
) (tree.TypeName, catalog.TypeDescriptor, error) {
desc, err := p.Descriptors().GetImmutableTypeByID(ctx, p.txn, id, tree.ObjectLookupFlags{})
if err != nil {
return tree.TypeName{}, nil, err
}
// Note that the value of required doesn't matter for lookups by ID.
_, dbDesc, err := p.Descriptors().GetImmutableDatabaseByID(ctx, p.txn, desc.GetParentID(), p.CommonLookupFlags(true /* required */))
if err != nil {
return tree.TypeName{}, nil, err
}
sc, err := p.Descriptors().GetImmutableSchemaByID(
ctx, p.txn, desc.GetParentSchemaID(), tree.SchemaLookupFlags{})
if err != nil {
return tree.TypeName{}, nil, err
}
name := tree.MakeQualifiedTypeName(dbDesc.GetName(), sc.GetName(), desc.GetName())
return name, desc, nil
}
// ResolveType implements the TypeReferenceResolver interface.
func (p *planner) ResolveType(
ctx context.Context, name *tree.UnresolvedObjectName,
) (*types.T, error) {
lookupFlags := tree.ObjectLookupFlags{
CommonLookupFlags: tree.CommonLookupFlags{Required: true, RequireMutable: false},
DesiredObjectKind: tree.TypeObject,
}
desc, prefix, err := resolver.ResolveExistingObject(ctx, p, name, lookupFlags)
if err != nil {
return nil, err
}
// For "reasons" we always fully qualify type names which are resolved via
// the type reference resolver.
//
// TODO(ajwerner): Understand these reasons.
prefix.ExplicitDatabase = prefix.Database != nil
prefix.ExplicitSchema = prefix.Schema != nil
tn := tree.MakeTypeNameWithPrefix(prefix.NamePrefix(), name.Object())
tdesc := desc.(catalog.TypeDescriptor)
// Disllow cross-database type resolution. Note that we check
// p.contextDatabaseID != descpb.InvalidID when we have been restricted to
// accessing types in the database with ID = p.contextDatabaseID by
// p.runWithOptions. So, check to see if the resolved descriptor's parentID
// matches, unless the descriptor's parentID is invalid. This could happen
// when the type being resolved is a builtin type prefaced with a virtual
// schema like `pg_catalog.int`. Resolution for these types returns a dummy
// TypeDescriptor, so ignore those cases.
if p.contextDatabaseID != descpb.InvalidID && tdesc.GetParentID() != descpb.InvalidID && tdesc.GetParentID() != p.contextDatabaseID {
return nil, pgerror.Newf(
pgcode.FeatureNotSupported, "cross database type references are not supported: %s", tn.String())
}
// Ensure that the user can access the target schema.
if err := p.canResolveDescUnderSchema(ctx, prefix.Schema, tdesc); err != nil {
return nil, err
}
return tdesc.MakeTypesT(ctx, &tn, p)
}
// ResolveTypeByOID implements the tree.TypeResolver interface.
func (p *planner) ResolveTypeByOID(ctx context.Context, oid oid.Oid) (*types.T, error) {
id, err := typedesc.UserDefinedTypeOIDToID(oid)
if err != nil {
return nil, err
}
name, desc, err := p.GetTypeDescriptor(ctx, id)
if err != nil {
return nil, err
}
return desc.MakeTypesT(ctx, &name, p)
}
// ObjectLookupFlags is part of the resolver.SchemaResolver interface.
func (p *planner) ObjectLookupFlags(required, requireMutable bool) tree.ObjectLookupFlags {
flags := p.CommonLookupFlags(required)
flags.RequireMutable = requireMutable
return tree.ObjectLookupFlags{CommonLookupFlags: flags}
}
// getDescriptorsFromTargetListForPrivilegeChange fetches the descriptors for the targets.
func getDescriptorsFromTargetListForPrivilegeChange(
ctx context.Context, p *planner, targets tree.TargetList,
) ([]catalog.Descriptor, error) {
const required = true
flags := tree.CommonLookupFlags{
Required: required,
AvoidLeased: p.avoidLeasedDescriptors,
RequireMutable: true,
}
if targets.Databases != nil {
if len(targets.Databases) == 0 {
return nil, errNoDatabase
}
descs := make([]catalog.Descriptor, 0, len(targets.Databases))
for _, database := range targets.Databases {
descriptor, err := p.Descriptors().
GetMutableDatabaseByName(ctx, p.txn, string(database), flags)
if err != nil {
return nil, err
}
descs = append(descs, descriptor)
}
if len(descs) == 0 {
return nil, errNoMatch
}
return descs, nil
}
if targets.Types != nil {
if len(targets.Types) == 0 {
return nil, errNoType
}
descs := make([]catalog.Descriptor, 0, len(targets.Types))
for _, typ := range targets.Types {
_, descriptor, err := p.ResolveMutableTypeDescriptor(ctx, typ, required)
if err != nil {
return nil, err
}
descs = append(descs, descriptor)
}
if len(descs) == 0 {
return nil, errNoMatch
}
return descs, nil
}
if targets.Schemas != nil {
if len(targets.Schemas) == 0 {
return nil, errNoSchema
}
if targets.AllTablesInSchema {
// Get all the descriptors for the tables in the specified schemas.
db, err := p.Descriptors().GetMutableDatabaseByName(ctx, p.txn, p.CurrentDatabase(), flags)
if err != nil {
return nil, err
}
var descs []catalog.Descriptor
for _, sc := range targets.Schemas {
_, objectIDs, err := resolver.GetObjectNamesAndIDs(
ctx, p.txn, p, p.ExecCfg().Codec, db, sc.Schema(), true, /* explicitPrefix */
)
if err != nil {
return nil, err
}
for i := range objectIDs {
descriptor, err := p.Descriptors().GetMutableDescriptorByID(ctx, objectIDs[i], p.txn)
if err != nil {
return nil, err
}
if descriptor != nil && descriptor.DescriptorType() == catalog.Table {
descs = append(descs, descriptor)
}
}
}
return descs, nil
}
descs := make([]catalog.Descriptor, 0, len(targets.Schemas))
// Resolve the databases being changed
type schemaWithDBDesc struct {
schema string
dbDesc *dbdesc.Mutable
}
var targetSchemas []schemaWithDBDesc
for _, sc := range targets.Schemas {
dbName := p.CurrentDatabase()
if sc.ExplicitCatalog {
dbName = sc.Catalog()
}
db, err := p.Descriptors().GetMutableDatabaseByName(ctx, p.txn, dbName, flags)
if err != nil {
return nil, err
}
targetSchemas = append(targetSchemas, schemaWithDBDesc{schema: sc.Schema(), dbDesc: db})
}
for _, sc := range targetSchemas {
resSchema, err := p.Descriptors().GetSchemaByName(
ctx, p.txn, sc.dbDesc, sc.schema, flags)
if err != nil {
return nil, err
}
switch resSchema.SchemaKind() {
case catalog.SchemaUserDefined:
descs = append(descs, resSchema)
default:
return nil, pgerror.Newf(pgcode.InvalidSchemaName,
"cannot change privileges on schema %q", resSchema.GetName())
}
}
return descs, nil
}
if len(targets.Tables) == 0 {
return nil, errNoTable
}
descs := make([]catalog.Descriptor, 0, len(targets.Tables))
for _, tableTarget := range targets.Tables {
tableGlob, err := tableTarget.NormalizeTablePattern()
if err != nil {
return nil, err
}
_, objectIDs, err := expandTableGlob(ctx, p, tableGlob)
if err != nil {
return nil, err
}
for i := range objectIDs {
descriptor, err := p.Descriptors().GetMutableDescriptorByID(ctx, objectIDs[i], p.txn)
if err != nil {
return nil, err
}
if descriptor != nil && descriptor.DescriptorType() == catalog.Table {
descs = append(descs, descriptor)
}
}
}
if len(descs) == 0 {
return nil, errNoMatch
}
return descs, nil
}
// getFullyQualifiedTableNamesFromIDs resolves a list of table IDs to their
// fully qualified names.
func (p *planner) getFullyQualifiedTableNamesFromIDs(
ctx context.Context, ids []descpb.ID,
) (fullyQualifiedNames []*tree.TableName, _ error) {
for _, id := range ids {
desc, err := p.Descriptors().GetImmutableTableByID(ctx, p.txn, id, tree.ObjectLookupFlags{
CommonLookupFlags: tree.CommonLookupFlags{
AvoidLeased: true,
IncludeDropped: true,
IncludeOffline: true,
},
})
if err != nil {
return nil, err
}
fqName, err := p.getQualifiedTableName(ctx, desc)
if err != nil {
return nil, err
}
fullyQualifiedNames = append(fullyQualifiedNames, fqName)
}
return fullyQualifiedNames, nil
}
// getQualifiedTableName returns the database-qualified name of the table
// or view represented by the provided descriptor. It is a sort of
// reverse of the Resolve() functions.
func (p *planner) getQualifiedTableName(
ctx context.Context, desc catalog.TableDescriptor,
) (*tree.TableName, error) {
_, dbDesc, err := p.Descriptors().GetImmutableDatabaseByID(ctx, p.txn, desc.GetParentID(),
tree.DatabaseLookupFlags{
Required: true,
IncludeOffline: true,
IncludeDropped: true,
AvoidLeased: true,
})
if err != nil {
return nil, err
}
// Get the schema name. Use some specialized logic to deal with descriptors
// from other temporary schemas.
//
// TODO(ajwerner): We shouldn't need this temporary logic if we properly
// tracked all descriptors as we read them and made them available in the
// collection. We should only be hitting this edge case when dropping a
// database, in which case we've already read all of the temporary schema
// information from the namespace table.
var schemaName tree.Name
schemaID := desc.GetParentSchemaID()
scDesc, err := p.Descriptors().GetImmutableSchemaByID(ctx, p.txn, schemaID,
tree.SchemaLookupFlags{
IncludeOffline: true,
IncludeDropped: true,
AvoidLeased: true,
})
switch {
case err == nil:
schemaName = tree.Name(scDesc.GetName())
case desc.IsTemporary() && errors.Is(err, catalog.ErrDescriptorNotFound):
// We've lost track of the session which owned this schema, but we
// can come up with a name that is also going to be unique and
// informative and looks like a pg_temp_<session_id> name.
schemaName = tree.Name(fmt.Sprintf("pg_temp_%d", schemaID))
default:
return nil, errors.Wrapf(err,
"resolving schema name for %s.[%d].%s",
tree.Name(dbDesc.GetName()),
schemaID,
tree.Name(desc.GetName()),
)
}
tbName := tree.MakeTableNameWithSchema(
tree.Name(dbDesc.GetName()),
schemaName,
tree.Name(desc.GetName()),
)
return &tbName, nil
}
// GetQualifiedTableNameByID returns the qualified name of the table,
// view or sequence represented by the provided ID and table kind.
func (p *planner) GetQualifiedTableNameByID(
ctx context.Context, id int64, requiredType tree.RequiredTableKind,
) (*tree.TableName, error) {
lookupFlags := tree.ObjectLookupFlags{
CommonLookupFlags: tree.CommonLookupFlags{Required: true},
DesiredObjectKind: tree.TableObject,
DesiredTableDescKind: requiredType,
}
table, err := p.Descriptors().GetImmutableTableByID(
ctx, p.txn, descpb.ID(id), lookupFlags)
if err != nil {
return nil, err
}
return p.getQualifiedTableName(ctx, table)
}
// getQualifiedSchemaName returns the database-qualified name of the
// schema represented by the provided descriptor.
func (p *planner) getQualifiedSchemaName(
ctx context.Context, desc catalog.SchemaDescriptor,
) (*tree.ObjectNamePrefix, error) {
_, dbDesc, err := p.Descriptors().GetImmutableDatabaseByID(ctx, p.txn, desc.GetParentID(),
tree.DatabaseLookupFlags{
Required: true,
})
if err != nil {
return nil, err
}
return &tree.ObjectNamePrefix{
CatalogName: tree.Name(dbDesc.GetName()),
SchemaName: tree.Name(desc.GetName()),
ExplicitCatalog: true,
ExplicitSchema: true,
}, nil
}
// getQualifiedTypeName returns the database-qualified name of the type
// represented by the provided descriptor.
func (p *planner) getQualifiedTypeName(
ctx context.Context, desc catalog.TypeDescriptor,
) (*tree.TypeName, error) {
_, dbDesc, err := p.Descriptors().GetImmutableDatabaseByID(ctx, p.txn, desc.GetParentID(),
tree.DatabaseLookupFlags{
Required: true,
})
if err != nil {
return nil, err
}
schemaID := desc.GetParentSchemaID()
scDesc, err := p.Descriptors().GetImmutableSchemaByID(
ctx, p.txn, schemaID, tree.SchemaLookupFlags{},
)
if err != nil {
return nil, err
}
typeName := tree.MakeQualifiedTypeName(
dbDesc.GetName(),
scDesc.GetName(),
desc.GetName(),
)
return &typeName, nil
}
// findTableContainingIndex returns the descriptor of a table
// containing the index of the given name.
// This is used by expandMutableIndexName().
//
// An error is returned if the index name is ambiguous (i.e. exists in
// multiple tables). If no table is found and requireTable is true, an
// error will be returned, otherwise the TableName and descriptor
// returned will be nil.
func findTableContainingIndex(
ctx context.Context,
txn *kv.Txn,
sc resolver.SchemaResolver,
codec keys.SQLCodec,
dbName, scName string,
idxName tree.UnrestrictedName,
lookupFlags tree.CommonLookupFlags,
) (result *tree.TableName, desc *tabledesc.Mutable, err error) {
sa := sc.Accessor()
dbDesc, err := sa.GetDatabaseDesc(ctx, txn, dbName, lookupFlags)
if dbDesc == nil || err != nil {
return nil, nil, err
}
tns, _, err := sa.GetObjectNamesAndIDs(
ctx, txn, dbDesc, scName, tree.DatabaseListFlags{
CommonLookupFlags: lookupFlags,
ExplicitPrefix: true,
},
)
if err != nil {
return nil, nil, err
}
result = nil
for i := range tns {
tn := &tns[i]
_, tableDesc, err := resolver.ResolveMutableExistingTableObject(
ctx, sc, tn, false /*required*/, tree.ResolveAnyTableKind,
)
if err != nil {
return nil, nil, err
}
if tableDesc == nil || !(tableDesc.IsTable() || tableDesc.MaterializedView()) {
continue
}
idx, err := tableDesc.FindIndexWithName(string(idxName))
if err != nil || idx.Dropped() {
// err is nil if the index does not exist on the table.
continue
}
if result != nil {
return nil, nil, pgerror.Newf(pgcode.AmbiguousParameter,
"index name %q is ambiguous (found in %s and %s)",
idxName, tn.String(), result.String())
}
result = tn
desc = tableDesc
}
if result == nil && lookupFlags.Required {
return nil, nil, pgerror.Newf(pgcode.UndefinedObject,
"index %q does not exist", idxName)
}
return result, desc, nil
}
// expandMutableIndexName ensures that the index name is qualified with a table
// name, and searches the table name if not yet specified.
//
// It returns the TableName of the underlying table for convenience.
// If no table is found and requireTable is true an error will be
// returned, otherwise the TableName returned will be nil.
//
// It *may* return the descriptor of the underlying table, depending
// on the lookup path. This can be used in the caller to avoid a 2nd
// lookup.
func expandMutableIndexName(
ctx context.Context, p *planner, index *tree.TableIndexName, requireTable bool,
) (tn *tree.TableName, desc *tabledesc.Mutable, err error) {
p.runWithOptions(resolveFlags{skipCache: true}, func() {
tn, desc, err = expandIndexName(ctx, p.txn, p, p.ExecCfg().Codec, index, requireTable)
})
return tn, desc, err
}
func expandIndexName(
ctx context.Context,
txn *kv.Txn,
sc resolver.SchemaResolver,
codec keys.SQLCodec,
index *tree.TableIndexName,
requireTable bool,
) (tn *tree.TableName, desc *tabledesc.Mutable, err error) {
tn = &index.Table
if tn.Table() != "" {
// The index and its table prefix must exist already. Resolve the table.
_, desc, err = resolver.ResolveMutableExistingTableObject(ctx, sc, tn, requireTable, tree.ResolveRequireTableOrViewDesc)
if err != nil {
return nil, nil, err
}
if desc != nil && desc.IsView() && !desc.MaterializedView() {
return nil, nil, pgerror.Newf(pgcode.WrongObjectType,
"%q is not a table or materialized view", tn.Table())
}
return tn, desc, nil
}
// On the first call to expandMutableIndexName(), index.Table.Table() is empty.
// Once the table name is resolved for the index below, index.Table
// references the table name.
// Look up the table prefix.
found, _, err := resolver.ResolveObjectNamePrefix(
ctx, sc, sc.CurrentDatabase(), sc.CurrentSearchPath(), &tn.ObjectNamePrefix,
)
if err != nil {
return nil, nil, err
}
if !found {
if requireTable {
err = pgerror.Newf(pgcode.UndefinedObject,
"schema or database was not found while searching index: %q",
tree.ErrString(&index.Index))
err = errors.WithHint(err, "check the current database and search_path are valid")
return nil, nil, err
}
return nil, nil, nil
}
lookupFlags := sc.CommonLookupFlags(requireTable)
var foundTn *tree.TableName
foundTn, desc, err = findTableContainingIndex(
ctx, txn, sc, codec, tn.Catalog(), tn.Schema(), index.Index, lookupFlags,
)
if err != nil {
return nil, nil, err
}
if foundTn != nil {
// Memoize the table name that was found. tn is a reference to the table name
// stored in index.Table.
*tn = *foundTn
}
return tn, desc, nil
}