-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathtest_catalog.go
1053 lines (878 loc) · 28 KB
/
test_catalog.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 testcat
import (
"context"
"fmt"
"sort"
"time"
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"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/stats"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/treeprinter"
"github.com/cockroachdb/errors"
)
const (
// testDB is the default current database for testing purposes.
testDB = "t"
)
// Catalog implements the cat.Catalog interface for testing purposes.
type Catalog struct {
testSchema Schema
counter int
}
var _ cat.Catalog = &Catalog{}
// New creates a new empty instance of the test catalog.
func New() *Catalog {
return &Catalog{
testSchema: Schema{
SchemaID: 1,
SchemaName: cat.SchemaName{
CatalogName: testDB,
SchemaName: tree.PublicSchemaName,
ExplicitSchema: true,
ExplicitCatalog: true,
},
dataSources: make(map[string]cat.DataSource),
},
}
}
// ResolveSchema is part of the cat.Catalog interface.
func (tc *Catalog) ResolveSchema(
_ context.Context, _ cat.Flags, name *cat.SchemaName,
) (cat.Schema, cat.SchemaName, error) {
// This is a simplified version of tree.TableName.ResolveTarget() from
// sql/tree/name_resolution.go.
toResolve := *name
if name.ExplicitSchema {
if name.ExplicitCatalog {
// Already 2 parts: nothing to do.
return tc.resolveSchema(&toResolve)
}
// Only one part specified; assume it's a schema name and determine
// whether the current database has that schema.
toResolve.CatalogName = testDB
if sch, resName, err := tc.resolveSchema(&toResolve); err == nil {
return sch, resName, nil
}
// No luck so far. Compatibility with CockroachDB v1.1: use D.public
// instead.
toResolve.CatalogName = name.SchemaName
toResolve.SchemaName = tree.PublicSchemaName
toResolve.ExplicitCatalog = true
return tc.resolveSchema(&toResolve)
}
// Neither schema or catalog was specified, so use t.public.
toResolve.CatalogName = tree.Name(testDB)
toResolve.SchemaName = tree.PublicSchemaName
return tc.resolveSchema(&toResolve)
}
// ResolveDataSource is part of the cat.Catalog interface.
func (tc *Catalog) ResolveDataSource(
_ context.Context, _ cat.Flags, name *cat.DataSourceName,
) (cat.DataSource, cat.DataSourceName, error) {
// This is a simplified version of tree.TableName.ResolveExisting() from
// sql/tree/name_resolution.go.
var ds cat.DataSource
var err error
toResolve := *name
if name.ExplicitSchema && name.ExplicitCatalog {
// Already 3 parts.
ds, err = tc.resolveDataSource(&toResolve)
if err == nil {
return ds, toResolve, nil
}
} else if name.ExplicitSchema {
// Two parts: Try to use the current database, and be satisfied if it's
// sufficient to find the object.
toResolve.CatalogName = testDB
if tab, err := tc.resolveDataSource(&toResolve); err == nil {
return tab, toResolve, nil
}
// No luck so far. Compatibility with CockroachDB v1.1: try D.public.T
// instead.
toResolve.CatalogName = name.SchemaName
toResolve.SchemaName = tree.PublicSchemaName
toResolve.ExplicitCatalog = true
ds, err = tc.resolveDataSource(&toResolve)
if err == nil {
return ds, toResolve, nil
}
} else {
// This is a naked data source name. Use the current database.
toResolve.CatalogName = tree.Name(testDB)
toResolve.SchemaName = tree.PublicSchemaName
ds, err = tc.resolveDataSource(&toResolve)
if err == nil {
return ds, toResolve, nil
}
}
// If we didn't find the table in the catalog, try to lazily resolve it as
// a virtual table.
if table, ok := resolveVTable(name); ok {
// We rely on the check in CreateTable against this table's schema to infer
// that this is a virtual table.
return tc.CreateTable(table), *name, nil
}
// If this didn't end up being a virtual table, then return the original
// error returned by resolveDataSource.
return nil, cat.DataSourceName{}, err
}
// ResolveDataSourceByID is part of the cat.Catalog interface.
func (tc *Catalog) ResolveDataSourceByID(
ctx context.Context, id cat.StableID,
) (cat.DataSource, error) {
for _, ds := range tc.testSchema.dataSources {
if tab, ok := ds.(*Table); ok && tab.TabID == id {
return ds, nil
}
if v, ok := ds.(*View); ok && v.ViewID == id {
return ds, nil
}
if v, ok := ds.(*Sequence); ok && v.SeqID == id {
return ds, nil
}
}
return nil, pgerror.Newf(pgcode.UndefinedTable,
"relation [%d] does not exist", id)
}
// CheckPrivilege is part of the cat.Catalog interface.
func (tc *Catalog) CheckPrivilege(ctx context.Context, o cat.Object, priv privilege.Kind) error {
return tc.CheckAnyPrivilege(ctx, o)
}
// CheckAnyPrivilege is part of the cat.Catalog interface.
func (tc *Catalog) CheckAnyPrivilege(ctx context.Context, o cat.Object) error {
switch t := o.(type) {
case *Schema:
if t.Revoked {
return pgerror.Newf(pgcode.InsufficientPrivilege, "user does not have privilege to access %v", t.SchemaName)
}
case *Table:
if t.Revoked {
return pgerror.Newf(pgcode.InsufficientPrivilege, "user does not have privilege to access %v", t.TabName)
}
case *View:
if t.Revoked {
return pgerror.Newf(pgcode.InsufficientPrivilege, "user does not have privilege to access %v", t.ViewName)
}
case *Sequence:
if t.Revoked {
return pgerror.Newf(pgcode.InsufficientPrivilege, "user does not have privilege to access %v", t.SeqName)
}
default:
panic("invalid Object")
}
return nil
}
// IsSuperUser is part of the cat.Catalog interface.
func (tc *Catalog) IsSuperUser(ctx context.Context, action string) (bool, error) {
return true, nil
}
// RequireSuperUser is part of the cat.Catalog interface.
func (tc *Catalog) RequireSuperUser(ctx context.Context, action string) error {
return nil
}
func (tc *Catalog) resolveSchema(toResolve *cat.SchemaName) (cat.Schema, cat.SchemaName, error) {
if string(toResolve.CatalogName) != testDB {
return nil, cat.SchemaName{}, pgerror.Newf(pgcode.InvalidSchemaName,
"target database or schema does not exist")
}
if string(toResolve.SchemaName) != tree.PublicSchema {
return nil, cat.SchemaName{}, pgerror.Newf(pgcode.InvalidName,
"schema cannot be modified: %q", tree.ErrString(toResolve))
}
return &tc.testSchema, *toResolve, nil
}
// resolveDataSource checks if `toResolve` exists among the data sources in this
// Catalog. If it does, returns the corresponding data source. Otherwise, it
// returns an error.
func (tc *Catalog) resolveDataSource(toResolve *cat.DataSourceName) (cat.DataSource, error) {
if table, ok := tc.testSchema.dataSources[toResolve.FQString()]; ok {
return table, nil
}
return nil, pgerror.Newf(pgcode.UndefinedTable,
"no data source matches prefix: %q", tree.ErrString(toResolve))
}
// Schema returns the singleton test schema.
func (tc *Catalog) Schema() *Schema {
return &tc.testSchema
}
// Table returns the test table that was previously added with the given name.
func (tc *Catalog) Table(name *tree.TableName) *Table {
ds, _, err := tc.ResolveDataSource(context.TODO(), cat.Flags{}, name)
if err != nil {
panic(err)
}
if tab, ok := ds.(*Table); ok {
return tab
}
panic(pgerror.Newf(pgcode.WrongObjectType,
"\"%q\" is not a table", tree.ErrString(name)))
}
// AddTable adds the given test table to the catalog.
func (tc *Catalog) AddTable(tab *Table) {
fq := tab.TabName.FQString()
if _, ok := tc.testSchema.dataSources[fq]; ok {
panic(pgerror.Newf(pgcode.DuplicateObject,
"table %q already exists", tree.ErrString(&tab.TabName)))
}
tc.testSchema.dataSources[fq] = tab
}
// View returns the test view that was previously added with the given name.
func (tc *Catalog) View(name *cat.DataSourceName) *View {
ds, _, err := tc.ResolveDataSource(context.TODO(), cat.Flags{}, name)
if err != nil {
panic(err)
}
if vw, ok := ds.(*View); ok {
return vw
}
panic(pgerror.Newf(pgcode.WrongObjectType,
"\"%q\" is not a view", tree.ErrString(name)))
}
// AddView adds the given test view to the catalog.
func (tc *Catalog) AddView(view *View) {
fq := view.ViewName.FQString()
if _, ok := tc.testSchema.dataSources[fq]; ok {
panic(pgerror.Newf(pgcode.DuplicateObject,
"view %q already exists", tree.ErrString(&view.ViewName)))
}
tc.testSchema.dataSources[fq] = view
}
// AddSequence adds the given test sequence to the catalog.
func (tc *Catalog) AddSequence(seq *Sequence) {
fq := seq.SeqName.FQString()
if _, ok := tc.testSchema.dataSources[fq]; ok {
panic(pgerror.Newf(pgcode.DuplicateObject,
"sequence %q already exists", tree.ErrString(&seq.SeqName)))
}
tc.testSchema.dataSources[fq] = seq
}
// ExecuteMultipleDDL parses the given semicolon-separated DDL SQL statements
// and applies each of them to the test catalog.
func (tc *Catalog) ExecuteMultipleDDL(sql string) error {
stmts, err := parser.Parse(sql)
if err != nil {
return err
}
for _, stmt := range stmts {
_, err := tc.ExecuteDDL(stmt.SQL)
if err != nil {
return err
}
}
return nil
}
// ExecuteDDL parses the given DDL SQL statement and creates objects in the test
// catalog. This is used to test without spinning up a cluster.
func (tc *Catalog) ExecuteDDL(sql string) (string, error) {
stmt, err := parser.ParseOne(sql)
if err != nil {
return "", err
}
switch stmt := stmt.AST.(type) {
case *tree.CreateTable:
tc.CreateTable(stmt)
return "", nil
case *tree.CreateView:
tc.CreateView(stmt)
return "", nil
case *tree.AlterTable:
tc.AlterTable(stmt)
return "", nil
case *tree.DropTable:
tc.DropTable(stmt)
return "", nil
case *tree.CreateSequence:
tc.CreateSequence(stmt)
return "", nil
case *tree.SetZoneConfig:
tc.SetZoneConfig(stmt)
return "", nil
case *tree.ShowCreate:
tn := stmt.Name.ToTableName()
ds, _, err := tc.ResolveDataSource(context.Background(), cat.Flags{}, &tn)
if err != nil {
return "", err
}
return ds.(fmt.Stringer).String(), nil
default:
return "", errors.AssertionFailedf("unsupported statement: %v", stmt)
}
}
// nextStableID returns a new unique StableID for a data source.
func (tc *Catalog) nextStableID() cat.StableID {
tc.counter++
// 53 is a magic number derived from how CRDB internally stores tables. The
// first user table is 53. Use this to have the test catalog look more
// consistent with the real catalog.
return cat.StableID(53 + tc.counter - 1)
}
// qualifyTableName updates the given table name to include catalog and schema
// if not already included.
func (tc *Catalog) qualifyTableName(name *tree.TableName) {
hadExplicitSchema := name.ExplicitSchema
hadExplicitCatalog := name.ExplicitCatalog
name.ExplicitSchema = true
name.ExplicitCatalog = true
if hadExplicitSchema {
if hadExplicitCatalog {
// Already 3 parts: nothing to do.
return
}
if name.SchemaName == tree.PublicSchemaName {
// Use the current database.
name.CatalogName = testDB
return
}
// Compatibility with CockroachDB v1.1: use D.public.T.
name.CatalogName = name.SchemaName
name.SchemaName = tree.PublicSchemaName
return
}
// Use the current database.
name.CatalogName = testDB
name.SchemaName = tree.PublicSchemaName
}
// Schema implements the cat.Schema interface for testing purposes.
type Schema struct {
SchemaID cat.StableID
SchemaName cat.SchemaName
// If Revoked is true, then the user has had privileges on the schema revoked.
Revoked bool
dataSources map[string]cat.DataSource
}
var _ cat.Schema = &Schema{}
// ID is part of the cat.Object interface.
func (s *Schema) ID() cat.StableID {
return s.SchemaID
}
// Equals is part of the cat.Object interface.
func (s *Schema) Equals(other cat.Object) bool {
otherSchema, ok := other.(*Schema)
return ok && s.SchemaID == otherSchema.SchemaID
}
// Name is part of the cat.Schema interface.
func (s *Schema) Name() *cat.SchemaName {
return &s.SchemaName
}
// GetDataSourceNames is part of the cat.Schema interface.
func (s *Schema) GetDataSourceNames(ctx context.Context) ([]cat.DataSourceName, error) {
var keys []string
for k := range s.dataSources {
keys = append(keys, k)
}
sort.Strings(keys)
var res []cat.DataSourceName
for _, k := range keys {
res = append(res, *s.dataSources[k].Name())
}
return res, nil
}
// View implements the cat.View interface for testing purposes.
type View struct {
ViewID cat.StableID
ViewVersion int
ViewName cat.DataSourceName
QueryText string
ColumnNames tree.NameList
// If Revoked is true, then the user has had privileges on the view revoked.
Revoked bool
}
var _ cat.View = &View{}
func (tv *View) String() string {
tp := treeprinter.New()
cat.FormatView(tv, tp)
return tp.String()
}
// ID is part of the cat.DataSource interface.
func (tv *View) ID() cat.StableID {
return tv.ViewID
}
// Equals is part of the cat.Object interface.
func (tv *View) Equals(other cat.Object) bool {
otherView, ok := other.(*View)
if !ok {
return false
}
return tv.ViewID == otherView.ViewID && tv.ViewVersion == otherView.ViewVersion
}
// Name is part of the cat.DataSource interface.
func (tv *View) Name() *cat.DataSourceName {
return &tv.ViewName
}
// Query is part of the cat.View interface.
func (tv *View) Query() string {
return tv.QueryText
}
// ColumnNameCount is part of the cat.View interface.
func (tv *View) ColumnNameCount() int {
return len(tv.ColumnNames)
}
// ColumnName is part of the cat.View interface.
func (tv *View) ColumnName(i int) tree.Name {
return tv.ColumnNames[i]
}
// Table implements the cat.Table interface for testing purposes.
type Table struct {
TabID cat.StableID
TabVersion int
TabName tree.TableName
Columns []*Column
Indexes []*Index
Stats TableStats
Checks []cat.CheckConstraint
Families []*Family
IsVirtual bool
Catalog cat.Catalog
// If Revoked is true, then the user has had privileges on the table revoked.
Revoked bool
writeOnlyColCount int
deleteOnlyColCount int
writeOnlyIdxCount int
deleteOnlyIdxCount int
// interleaved is true if the table's rows are interleaved with rows from
// other table(s).
interleaved bool
outboundFKs []ForeignKeyConstraint
inboundFKs []ForeignKeyConstraint
}
var _ cat.Table = &Table{}
func (tt *Table) String() string {
tp := treeprinter.New()
cat.FormatTable(tt.Catalog, tt, tp)
return tp.String()
}
// ID is part of the cat.DataSource interface.
func (tt *Table) ID() cat.StableID {
return tt.TabID
}
// Equals is part of the cat.Object interface.
func (tt *Table) Equals(other cat.Object) bool {
otherTable, ok := other.(*Table)
if !ok {
return false
}
return tt.TabID == otherTable.TabID && tt.TabVersion == otherTable.TabVersion
}
// Name is part of the cat.DataSource interface.
func (tt *Table) Name() *cat.DataSourceName {
return &tt.TabName
}
// IsVirtualTable is part of the cat.Table interface.
func (tt *Table) IsVirtualTable() bool {
return tt.IsVirtual
}
// IsInterleaved is part of the cat.Table interface.
func (tt *Table) IsInterleaved() bool {
return false
}
// ColumnCount is part of the cat.Table interface.
func (tt *Table) ColumnCount() int {
return len(tt.Columns) - tt.writeOnlyColCount - tt.deleteOnlyColCount
}
// WritableColumnCount is part of the cat.Table interface.
func (tt *Table) WritableColumnCount() int {
return len(tt.Columns) - tt.deleteOnlyColCount
}
// DeletableColumnCount is part of the cat.Table interface.
func (tt *Table) DeletableColumnCount() int {
return len(tt.Columns)
}
// Column is part of the cat.Table interface.
func (tt *Table) Column(i int) cat.Column {
return tt.Columns[i]
}
// IndexCount is part of the cat.Table interface.
func (tt *Table) IndexCount() int {
return len(tt.Indexes) - tt.writeOnlyIdxCount - tt.deleteOnlyIdxCount
}
// WritableIndexCount is part of the cat.Table interface.
func (tt *Table) WritableIndexCount() int {
return len(tt.Indexes) - tt.deleteOnlyIdxCount
}
// DeletableIndexCount is part of the cat.Table interface.
func (tt *Table) DeletableIndexCount() int {
return len(tt.Indexes)
}
// Index is part of the cat.Table interface.
func (tt *Table) Index(i int) cat.Index {
return tt.Indexes[i]
}
// StatisticCount is part of the cat.Table interface.
func (tt *Table) StatisticCount() int {
return len(tt.Stats)
}
// Statistic is part of the cat.Table interface.
func (tt *Table) Statistic(i int) cat.TableStatistic {
return tt.Stats[i]
}
// CheckCount is part of the cat.Table interface.
func (tt *Table) CheckCount() int {
return len(tt.Checks)
}
// Check is part of the cat.Table interface.
func (tt *Table) Check(i int) cat.CheckConstraint {
return tt.Checks[i]
}
// FamilyCount is part of the cat.Table interface.
func (tt *Table) FamilyCount() int {
return len(tt.Families)
}
// Family is part of the cat.Table interface.
func (tt *Table) Family(i int) cat.Family {
return tt.Families[i]
}
// OutboundForeignKeyCount is part of the cat.Table interface.
func (tt *Table) OutboundForeignKeyCount() int {
return len(tt.outboundFKs)
}
// OutboundForeignKey is part of the cat.Table interface.
func (tt *Table) OutboundForeignKey(i int) cat.ForeignKeyConstraint {
return &tt.outboundFKs[i]
}
// InboundForeignKeyCount is part of the cat.Table interface.
func (tt *Table) InboundForeignKeyCount() int {
return len(tt.inboundFKs)
}
// InboundForeignKey is part of the cat.Table interface.
func (tt *Table) InboundForeignKey(i int) cat.ForeignKeyConstraint {
return &tt.inboundFKs[i]
}
// FindOrdinal returns the ordinal of the column with the given name.
func (tt *Table) FindOrdinal(name string) int {
for i, col := range tt.Columns {
if col.Name == name {
return i
}
}
panic(pgerror.Newf(pgcode.UndefinedColumn,
"cannot find column %q in table %q",
tree.ErrString((*tree.Name)(&name)),
tree.ErrString(&tt.TabName),
))
}
// Index implements the cat.Index interface for testing purposes.
type Index struct {
IdxName string
// KeyCount is the number of columns that make up the unique key for the
// index. See the cat.Index.KeyColumnCount for more details.
KeyCount int
// LaxKeyCount is the number of columns that make up a lax key for the
// index, which allows duplicate rows when at least one of the values is
// NULL. See the cat.Index.LaxKeyColumnCount for more details.
LaxKeyCount int
// Unique is true if this index is declared as UNIQUE in the schema.
Unique bool
// Inverted is true when this index is an inverted index.
Inverted bool
Columns []cat.IndexColumn
// IdxZone is the zone associated with the index. This may be inherited from
// the parent table, database, or even the default zone.
IdxZone *config.ZoneConfig
// Ordinal is the ordinal of this index in the table.
ordinal int
// table is a back reference to the table this index is on.
table *Table
}
// ID is part of the cat.Index interface.
func (ti *Index) ID() cat.StableID {
return 1 + cat.StableID(ti.ordinal)
}
// Name is part of the cat.Index interface.
func (ti *Index) Name() tree.Name {
return tree.Name(ti.IdxName)
}
// Table is part of the cat.Index interface.
func (ti *Index) Table() cat.Table {
return ti.table
}
// Ordinal is part of the cat.Index interface.
func (ti *Index) Ordinal() int {
return ti.ordinal
}
// IsUnique is part of the cat.Index interface.
func (ti *Index) IsUnique() bool {
return ti.Unique
}
// IsInverted is part of the cat.Index interface.
func (ti *Index) IsInverted() bool {
return ti.Inverted
}
// ColumnCount is part of the cat.Index interface.
func (ti *Index) ColumnCount() int {
return len(ti.Columns)
}
// KeyColumnCount is part of the cat.Index interface.
func (ti *Index) KeyColumnCount() int {
return ti.KeyCount
}
// LaxKeyColumnCount is part of the cat.Index interface.
func (ti *Index) LaxKeyColumnCount() int {
return ti.LaxKeyCount
}
// Column is part of the cat.Index interface.
func (ti *Index) Column(i int) cat.IndexColumn {
return ti.Columns[i]
}
// Zone is part of the cat.Index interface.
func (ti *Index) Zone() cat.Zone {
return ti.IdxZone
}
// Span is part of the cat.Index interface.
func (ti *Index) Span() roachpb.Span {
panic("not implemented")
}
// Column implements the cat.Column interface for testing purposes.
type Column struct {
Ordinal int
Hidden bool
Nullable bool
Name string
Type *types.T
ColType types.T
DefaultExpr *string
ComputedExpr *string
}
var _ cat.Column = &Column{}
// ColID is part of the cat.Index interface.
func (tc *Column) ColID() cat.StableID {
return 1 + cat.StableID(tc.Ordinal)
}
// IsNullable is part of the cat.Column interface.
func (tc *Column) IsNullable() bool {
return tc.Nullable
}
// ColName is part of the cat.Column interface.
func (tc *Column) ColName() tree.Name {
return tree.Name(tc.Name)
}
// DatumType is part of the cat.Column interface.
func (tc *Column) DatumType() *types.T {
return tc.Type
}
// ColTypePrecision is part of the cat.Column interface.
func (tc *Column) ColTypePrecision() int {
if tc.ColType.Family() == types.ArrayFamily {
if tc.ColType.ArrayContents().Family() == types.ArrayFamily {
panic(errors.AssertionFailedf("column type should never be a nested array"))
}
return int(tc.ColType.ArrayContents().Precision())
}
return int(tc.ColType.Precision())
}
// ColTypeWidth is part of the cat.Column interface.
func (tc *Column) ColTypeWidth() int {
if tc.ColType.Family() == types.ArrayFamily {
if tc.ColType.ArrayContents().Family() == types.ArrayFamily {
panic(errors.AssertionFailedf("column type should never be a nested array"))
}
return int(tc.ColType.ArrayContents().Width())
}
return int(tc.ColType.Width())
}
// ColTypeStr is part of the cat.Column interface.
func (tc *Column) ColTypeStr() string {
return tc.ColType.SQLString()
}
// IsHidden is part of the cat.Column interface.
func (tc *Column) IsHidden() bool {
return tc.Hidden
}
// HasDefault is part of the cat.Column interface.
func (tc *Column) HasDefault() bool {
return tc.DefaultExpr != nil
}
// IsComputed is part of the cat.Column interface.
func (tc *Column) IsComputed() bool {
return tc.ComputedExpr != nil
}
// DefaultExprStr is part of the cat.Column interface.
func (tc *Column) DefaultExprStr() string {
return *tc.DefaultExpr
}
// ComputedExprStr is part of the cat.Column interface.
func (tc *Column) ComputedExprStr() string {
return *tc.ComputedExpr
}
// TableStat implements the cat.TableStatistic interface for testing purposes.
type TableStat struct {
js stats.JSONStatistic
tt *Table
}
var _ cat.TableStatistic = &TableStat{}
// CreatedAt is part of the cat.TableStatistic interface.
func (ts *TableStat) CreatedAt() time.Time {
d, err := tree.ParseDTimestamp(nil, ts.js.CreatedAt, time.Microsecond)
if err != nil {
panic(err)
}
return d.Time
}
// ColumnCount is part of the cat.TableStatistic interface.
func (ts *TableStat) ColumnCount() int {
return len(ts.js.Columns)
}
// ColumnOrdinal is part of the cat.TableStatistic interface.
func (ts *TableStat) ColumnOrdinal(i int) int {
return ts.tt.FindOrdinal(ts.js.Columns[i])
}
// RowCount is part of the cat.TableStatistic interface.
func (ts *TableStat) RowCount() uint64 {
return ts.js.RowCount
}
// DistinctCount is part of the cat.TableStatistic interface.
func (ts *TableStat) DistinctCount() uint64 {
return ts.js.DistinctCount
}
// NullCount is part of the cat.TableStatistic interface.
func (ts *TableStat) NullCount() uint64 {
return ts.js.NullCount
}
// TableStats is a slice of TableStat pointers.
type TableStats []*TableStat
// Len is part of the Sorter interface.
func (ts TableStats) Len() int { return len(ts) }
// Less is part of the Sorter interface.
func (ts TableStats) Less(i, j int) bool {
// Sort with most recent first.
return ts[i].CreatedAt().Unix() > ts[j].CreatedAt().Unix()
}
// Swap is part of the Sorter interface.
func (ts TableStats) Swap(i, j int) {
ts[i], ts[j] = ts[j], ts[i]
}
// ForeignKeyConstraint implements cat.ForeignKeyConstraint. See that interface
// for more information on the fields.
type ForeignKeyConstraint struct {
name string
originTableID cat.StableID
referencedTableID cat.StableID
originColumnOrdinals []int
referencedColumnOrdinals []int
validated bool
matchMethod tree.CompositeKeyMatchMethod
}
var _ cat.ForeignKeyConstraint = &ForeignKeyConstraint{}
// Name is part of the cat.ForeignKeyConstraint interface.
func (fk *ForeignKeyConstraint) Name() string {
return fk.name
}
// OriginTableID is part of the cat.ForeignKeyConstraint interface.
func (fk *ForeignKeyConstraint) OriginTableID() cat.StableID {
return fk.originTableID
}
// ReferencedTableID is part of the cat.ForeignKeyConstraint interface.
func (fk *ForeignKeyConstraint) ReferencedTableID() cat.StableID {
return fk.referencedTableID
}
// ColumnCount is part of the cat.ForeignKeyConstraint interface.
func (fk *ForeignKeyConstraint) ColumnCount() int {
return len(fk.originColumnOrdinals)
}
// OriginColumnOrdinal is part of the cat.ForeignKeyConstraint interface.
func (fk *ForeignKeyConstraint) OriginColumnOrdinal(originTable cat.Table, i int) int {
if originTable.ID() != fk.originTableID {
panic(errors.AssertionFailedf(
"invalid table %d passed to OriginColumnOrdinal (expected %d)",
originTable.ID(), fk.originTableID,
))
}
return fk.originColumnOrdinals[i]
}
// ReferencedColumnOrdinal is part of the cat.ForeignKeyConstraint interface.
func (fk *ForeignKeyConstraint) ReferencedColumnOrdinal(referencedTable cat.Table, i int) int {
if referencedTable.ID() != fk.referencedTableID {
panic(errors.AssertionFailedf(
"invalid table %d passed to ReferencedColumnOrdinal (expected %d)",
referencedTable.ID(), fk.referencedTableID,
))
}
return fk.referencedColumnOrdinals[i]
}
// Validated is part of the cat.ForeignKeyConstraint interface.
func (fk *ForeignKeyConstraint) Validated() bool {
return fk.validated
}
// MatchMethod is part of the cat.ForeignKeyConstraint interface.
func (fk *ForeignKeyConstraint) MatchMethod() tree.CompositeKeyMatchMethod {
return fk.matchMethod
}
// Sequence implements the cat.Sequence interface for testing purposes.
type Sequence struct {
SeqID cat.StableID
SeqVersion int
SeqName tree.TableName
Catalog cat.Catalog
// If Revoked is true, then the user has had privileges on the sequence revoked.
Revoked bool
}
var _ cat.Sequence = &Sequence{}
// ID is part of the cat.DataSource interface.
func (ts *Sequence) ID() cat.StableID {
return ts.SeqID
}
// Equals is part of the cat.Object interface.
func (ts *Sequence) Equals(other cat.Object) bool {
otherSequence, ok := other.(*Sequence)
if !ok {
return false
}
return ts.SeqID == otherSequence.SeqID && ts.SeqVersion == otherSequence.SeqVersion
}