-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathmetadata.go
752 lines (668 loc) · 25.4 KB
/
metadata.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
// 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 opt
import (
"context"
"fmt"
"math/bits"
"strings"
"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
"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/types"
"github.com/cockroachdb/errors"
"github.com/lib/pq/oid"
)
// SchemaID uniquely identifies the usage of a schema within the scope of a
// query. SchemaID 0 is reserved to mean "unknown schema". Internally, the
// SchemaID consists of an index into the Metadata.schemas slice.
//
// See the comment for Metadata for more details on identifiers.
type SchemaID int32
// privilegeBitmap stores a union of zero or more privileges. Each privilege
// that is present in the bitmap is represented by a bit that is shifted by
// 1 << privilege.Kind, so that multiple privileges can be stored.
type privilegeBitmap uint32
// Metadata assigns unique ids to the columns, tables, and other metadata used
// for global identification within the scope of a particular query. These ids
// tend to be small integers that can be efficiently stored and manipulated.
//
// Within a query, every unique column and every projection should be assigned a
// unique column id. Additionally, every separate reference to a table in the
// query should get a new set of output column ids.
//
// For example, consider the query:
//
// SELECT x FROM a WHERE y > 0
//
// There are 2 columns in the above query: x and y. During name resolution, the
// above query becomes:
//
// SELECT [0] FROM a WHERE [1] > 0
// -- [0] -> x
// -- [1] -> y
//
// An operator is allowed to reuse some or all of the column ids of an input if:
//
// 1. For every output row, there exists at least one input row having identical
// values for those columns.
// 2. OR if no such input row exists, there is at least one output row having
// NULL values for all those columns (e.g. when outer join NULL-extends).
//
// For example, is it safe for a Select to use its input's column ids because it
// only filters rows. Likewise, pass-through column ids of a Project can be
// reused.
//
// For an example where columns cannot be reused, consider the query:
//
// SELECT * FROM a AS l JOIN a AS r ON (l.x = r.y)
//
// In this query, `l.x` is not equivalent to `r.x` and `l.y` is not equivalent
// to `r.y`. Therefore, we need to give these columns different ids.
type Metadata struct {
// schemas stores each schema used in the query, indexed by SchemaID.
schemas []cat.Schema
// cols stores information about each metadata column, indexed by
// ColumnID.index().
cols []ColumnMeta
// tables stores information about each metadata table, indexed by
// TableID.index().
tables []TableMeta
// sequences stores information about each metadata sequence, indexed by SequenceID.
sequences []cat.Sequence
// userDefinedTypes contains all user defined types present in expressions
// in this query.
// TODO (rohany): This only contains user defined types present in the query
// because the installation of type metadata in tables doesn't go through
// the type resolver that the optimizer hijacks. However, we could update
// this map when adding a table via metadata.AddTable.
userDefinedTypes map[oid.Oid]struct{}
userDefinedTypesSlice []*types.T
// deps stores information about all data source objects depended on by the
// query, as well as the privileges required to access them. The objects are
// deduplicated: any name/object pair shows up at most once.
// Note: the same data source object can appear multiple times if different
// names were used. For example, in the query `SELECT * from t, db.t` the two
// tables might resolve to the same object now but to different objects later;
// we want to verify the resolution of both names.
deps []mdDep
// views stores the list of referenced views. This information is only
// needed for EXPLAIN (opt, env).
views []cat.View
// currUniqueID is the highest UniqueID that has been assigned.
currUniqueID UniqueID
// withBindings store bindings for relational expressions inside With or
// mutation operators, used to determine the logical properties of WithScan.
withBindings map[WithID]Expr
// NOTE! When adding fields here, update Init (if reusing allocated
// data structures is desired), CopyFrom and TestMetadata.
}
type mdDep struct {
ds cat.DataSource
name MDDepName
// privileges is the union of all required privileges.
privileges privilegeBitmap
}
// MDDepName stores either the unresolved DataSourceName or the StableID from
// the query that was used to resolve a data source.
type MDDepName struct {
// byID is non-zero if and only if the data source was looked up using the
// StableID.
byID cat.StableID
// byName is non-zero if and only if the data source was looked up using a
// name.
byName cat.DataSourceName
}
func (n *MDDepName) equals(other *MDDepName) bool {
return n.byID == other.byID && n.byName.Equals(&other.byName)
}
// Init prepares the metadata for use (or reuse).
func (md *Metadata) Init() {
// Clear the metadata objects to release memory (this clearing pattern is
// optimized by Go).
schemas := md.schemas
for i := range schemas {
schemas[i] = nil
}
cols := md.cols
for i := range cols {
cols[i] = ColumnMeta{}
}
tables := md.tables
for i := range tables {
tables[i] = TableMeta{}
}
sequences := md.sequences
for i := range sequences {
sequences[i] = nil
}
deps := md.deps
for i := range deps {
deps[i] = mdDep{}
}
views := md.views
for i := range views {
views[i] = nil
}
// This initialization pattern ensures that fields are not unwittingly
// reused. Field reuse must be explicit.
*md = Metadata{}
md.schemas = schemas[:0]
md.cols = cols[:0]
md.tables = tables[:0]
md.sequences = sequences[:0]
md.deps = deps[:0]
md.views = views[:0]
}
// CopyFrom initializes the metadata with a copy of the provided metadata.
// This metadata can then be modified independent of the copied metadata.
//
// Table annotations are not transferred over; all annotations are unset on
// the copy.
//
// copyScalarFn must be a function that returns a copy of the given scalar
// expression.
func (md *Metadata) CopyFrom(from *Metadata, copyScalarFn func(Expr) Expr) {
if len(md.schemas) != 0 || len(md.cols) != 0 || len(md.tables) != 0 ||
len(md.sequences) != 0 || len(md.deps) != 0 || len(md.views) != 0 ||
len(md.userDefinedTypes) != 0 || len(md.userDefinedTypesSlice) != 0 {
panic(errors.AssertionFailedf("CopyFrom requires empty destination"))
}
md.schemas = append(md.schemas, from.schemas...)
md.cols = append(md.cols, from.cols...)
if len(from.userDefinedTypesSlice) > 0 {
if md.userDefinedTypes == nil {
md.userDefinedTypes = make(map[oid.Oid]struct{}, len(from.userDefinedTypesSlice))
}
for i := range from.userDefinedTypesSlice {
typ := from.userDefinedTypesSlice[i]
md.userDefinedTypes[typ.Oid()] = struct{}{}
md.userDefinedTypesSlice = append(md.userDefinedTypesSlice, typ)
}
}
if cap(md.tables) >= len(from.tables) {
md.tables = md.tables[:len(from.tables)]
} else {
md.tables = make([]TableMeta, len(from.tables))
}
for i := range from.tables {
// Note: annotations inside TableMeta are not retained.
md.tables[i].copyFrom(&from.tables[i], copyScalarFn)
}
md.sequences = append(md.sequences, from.sequences...)
md.deps = append(md.deps, from.deps...)
md.views = append(md.views, from.views...)
md.currUniqueID = from.currUniqueID
// We cannot copy the bound expressions; they must be rebuilt in the new memo.
md.withBindings = nil
}
// DepByName is used with AddDependency when the data source was looked up using a
// data source name.
func DepByName(name *cat.DataSourceName) MDDepName {
return MDDepName{byName: *name}
}
// DepByID is used with AddDependency when the data source was looked up by ID.
func DepByID(id cat.StableID) MDDepName {
return MDDepName{byID: id}
}
// AddDependency tracks one of the catalog data sources on which the query
// depends, as well as the privilege required to access that data source. If
// the Memo using this metadata is cached, then a call to CheckDependencies can
// detect if the name resolves to a different data source now, or if changes to
// schema or permissions on the data source has invalidated the cached metadata.
func (md *Metadata) AddDependency(name MDDepName, ds cat.DataSource, priv privilege.Kind) {
// Search for the same name / object pair.
for i := range md.deps {
if md.deps[i].ds == ds && md.deps[i].name.equals(&name) {
md.deps[i].privileges |= (1 << priv)
return
}
}
md.deps = append(md.deps, mdDep{
ds: ds,
name: name,
privileges: (1 << priv),
})
}
// CheckDependencies resolves (again) each data source on which this metadata
// depends, in order to check that all data source names resolve to the same
// objects, and that the user still has sufficient privileges to access the
// objects. If the dependencies are no longer up-to-date, then CheckDependencies
// returns false.
//
// This function cannot swallow errors and return only a boolean, as it may
// perform KV operations on behalf of the transaction associated with the
// provided catalog, and those errors are required to be propagated.
func (md *Metadata) CheckDependencies(
ctx context.Context, catalog cat.Catalog,
) (upToDate bool, err error) {
for i := range md.deps {
name := &md.deps[i].name
var toCheck cat.DataSource
var err error
if name.byID != 0 {
toCheck, _, err = catalog.ResolveDataSourceByID(ctx, cat.Flags{}, name.byID)
} else {
// Resolve data source object.
toCheck, _, err = catalog.ResolveDataSource(ctx, cat.Flags{}, &name.byName)
}
if err != nil {
return false, err
}
// Ensure that it's the same object, and there were no schema or table
// statistics changes.
if !toCheck.Equals(md.deps[i].ds) {
return false, nil
}
for privs := md.deps[i].privileges; privs != 0; {
// Strip off each privilege bit and make call to CheckPrivilege for it.
// Note that priv == 0 can occur when a dependency was added with
// privilege.Kind = 0 (e.g. for a table within a view, where the table
// privileges do not need to be checked). Ignore the "zero privilege".
priv := privilege.Kind(bits.TrailingZeros32(uint32(privs)))
if priv != 0 {
if err := catalog.CheckPrivilege(ctx, toCheck, priv); err != nil {
return false, err
}
}
// Set the just-handled privilege bit to zero and look for next.
privs &= ^(1 << priv)
}
}
// Check that all of the user defined types present have not changed.
for _, typ := range md.AllUserDefinedTypes() {
toCheck, err := catalog.ResolveTypeByOID(ctx, typ.Oid())
if err != nil {
// Handle when the type no longer exists.
if pgerror.GetPGCode(err) == pgcode.UndefinedObject {
return false, nil
}
return false, err
}
if typ.TypeMeta.Version != toCheck.TypeMeta.Version {
return false, nil
}
}
return true, nil
}
// AddSchema indexes a new reference to a schema used by the query.
func (md *Metadata) AddSchema(sch cat.Schema) SchemaID {
md.schemas = append(md.schemas, sch)
return SchemaID(len(md.schemas))
}
// Schema looks up the metadata for the schema associated with the given schema
// id.
func (md *Metadata) Schema(schID SchemaID) cat.Schema {
return md.schemas[schID-1]
}
// AddUserDefinedType adds a user defined type to the metadata for this query.
func (md *Metadata) AddUserDefinedType(typ *types.T) {
if !typ.UserDefined() {
return
}
if md.userDefinedTypes == nil {
md.userDefinedTypes = make(map[oid.Oid]struct{})
}
if _, ok := md.userDefinedTypes[typ.Oid()]; !ok {
md.userDefinedTypes[typ.Oid()] = struct{}{}
md.userDefinedTypesSlice = append(md.userDefinedTypesSlice, typ)
}
}
// AllUserDefinedTypes returns all user defined types contained in this query.
func (md *Metadata) AllUserDefinedTypes() []*types.T {
return md.userDefinedTypesSlice
}
// AddTable indexes a new reference to a table within the query. Separate
// references to the same table are assigned different table ids (e.g. in a
// self-join query). All columns are added to the metadata. If mutation columns
// are present, they are added after active columns.
//
// The ExplicitCatalog/ExplicitSchema fields of the table's alias are honored so
// that its original formatting is preserved for error messages,
// pretty-printing, etc.
func (md *Metadata) AddTable(tab cat.Table, alias *tree.TableName) TableID {
tabID := makeTableID(len(md.tables), ColumnID(len(md.cols)+1))
if md.tables == nil {
md.tables = make([]TableMeta, 0, 4)
}
md.tables = append(md.tables, TableMeta{MetaID: tabID, Table: tab, Alias: *alias})
colCount := tab.ColumnCount()
if md.cols == nil {
md.cols = make([]ColumnMeta, 0, colCount)
}
for i := 0; i < colCount; i++ {
col := tab.Column(i)
colID := md.AddColumn(string(col.ColName()), col.DatumType())
md.ColumnMeta(colID).Table = tabID
}
return tabID
}
// DuplicateTable creates a new reference to the table with the given ID. All
// columns are added to the metadata with new column IDs. If mutation columns
// are present, they are added after active columns. The ID of the new table
// reference is returned. This function panics if a table with the given ID does
// not exists in the metadata.
//
// remapColumnIDs must be a function that remaps the column IDs within a
// ScalarExpr to new column IDs. It takes as arguments a ScalarExpr and a
// mapping of old column IDs to new column IDs, and returns a new ScalarExpr.
// This function is used when duplicating Constraints, ComputedCols, and
// partialIndexPredicates. DuplicateTable requires this callback function,
// rather than performing the remapping itself, because remapping column IDs
// requires constructing new expressions with norm.Factory. The norm package
// depends on opt, and cannot be imported here.
//
// The ExplicitCatalog/ExplicitSchema fields of the table's alias are honored so
// that its original formatting is preserved for error messages,
// pretty-printing, etc.
func (md *Metadata) DuplicateTable(
tabID TableID, remapColumnIDs func(e ScalarExpr, colMap ColMap) ScalarExpr,
) TableID {
if md.tables == nil || tabID.index() >= len(md.tables) {
panic(errors.AssertionFailedf("table with ID %d does not exist", tabID))
}
tabMeta := md.TableMeta(tabID)
tab := tabMeta.Table
newTabID := makeTableID(len(md.tables), ColumnID(len(md.cols)+1))
// Generate new column IDs for each column in the table, and keep track of
// a mapping from the original TableMeta's column IDs to the new ones.
var colMap ColMap
for i, n := 0, tab.ColumnCount(); i < n; i++ {
col := tab.Column(i)
oldColID := tabID.ColumnID(i)
newColID := md.AddColumn(string(col.ColName()), col.DatumType())
md.ColumnMeta(newColID).Table = newTabID
colMap.Set(int(oldColID), int(newColID))
}
// Create new constraints by remapping the column IDs to the new TableMeta's
// column IDs.
var constraints ScalarExpr
if tabMeta.Constraints != nil {
constraints = remapColumnIDs(tabMeta.Constraints, colMap)
}
// Create new computed column expressions by remapping the column IDs in
// each ScalarExpr.
var computedCols map[ColumnID]ScalarExpr
if len(tabMeta.ComputedCols) > 0 {
computedCols = make(map[ColumnID]ScalarExpr, len(tabMeta.ComputedCols))
for colID, e := range tabMeta.ComputedCols {
newColID, ok := colMap.Get(int(colID))
if !ok {
panic(errors.AssertionFailedf("column with ID %d does not exist in map", colID))
}
computedCols[ColumnID(newColID)] = remapColumnIDs(e, colMap)
}
}
// Create new partial index predicate expressions by remapping the column
// IDs in each ScalarExpr.
var partialIndexPredicates map[cat.IndexOrdinal]ScalarExpr
if len(tabMeta.partialIndexPredicates) > 0 {
partialIndexPredicates = make(map[cat.IndexOrdinal]ScalarExpr, len(tabMeta.partialIndexPredicates))
for idxOrd, e := range tabMeta.partialIndexPredicates {
partialIndexPredicates[idxOrd] = remapColumnIDs(e, colMap)
}
}
var checkConstraintsStats map[ColumnID]interface{}
if len(tabMeta.checkConstraintsStats) > 0 {
checkConstraintsStats =
make(map[ColumnID]interface{},
len(tabMeta.checkConstraintsStats))
for i := range tabMeta.checkConstraintsStats {
if dstCol, ok := colMap.Get(int(i)); ok {
// We remap the column ID key, but not any column IDs in the
// ColumnStatistic as this is still being used in the statistics of the
// original table and should be treated as immutable. When the Histogram
// is copied in ColumnStatistic.CopyFromOther, it is initialized with
// the proper column ID.
checkConstraintsStats[ColumnID(dstCol)] = tabMeta.checkConstraintsStats[i]
} else {
panic(errors.AssertionFailedf("remapping of check constraint stats column failed"))
}
}
}
md.tables = append(md.tables, TableMeta{
MetaID: newTabID,
Table: tabMeta.Table,
Alias: tabMeta.Alias,
IgnoreForeignKeys: tabMeta.IgnoreForeignKeys,
Constraints: constraints,
ComputedCols: computedCols,
partialIndexPredicates: partialIndexPredicates,
indexPartitionLocalities: tabMeta.indexPartitionLocalities,
checkConstraintsStats: checkConstraintsStats,
})
return newTabID
}
// TableMeta looks up the metadata for the table associated with the given table
// id. The same table can be added multiple times to the query metadata and
// associated with multiple table ids.
func (md *Metadata) TableMeta(tabID TableID) *TableMeta {
return &md.tables[tabID.index()]
}
// Table looks up the catalog table associated with the given metadata id. The
// same table can be associated with multiple metadata ids.
func (md *Metadata) Table(tabID TableID) cat.Table {
return md.TableMeta(tabID).Table
}
// AllTables returns the metadata for all tables. The result must not be
// modified.
func (md *Metadata) AllTables() []TableMeta {
return md.tables
}
// AddColumn assigns a new unique id to a column within the query and records
// its alias and type. If the alias is empty, a "column<ID>" alias is created.
func (md *Metadata) AddColumn(alias string, typ *types.T) ColumnID {
if alias == "" {
alias = fmt.Sprintf("column%d", len(md.cols)+1)
}
colID := ColumnID(len(md.cols) + 1)
md.cols = append(md.cols, ColumnMeta{MetaID: colID, Alias: alias, Type: typ})
return colID
}
// NumColumns returns the count of columns tracked by this Metadata instance.
func (md *Metadata) NumColumns() int {
return len(md.cols)
}
// ColumnMeta looks up the metadata for the column associated with the given
// column id. The same column can be added multiple times to the query metadata
// and associated with multiple column ids.
func (md *Metadata) ColumnMeta(colID ColumnID) *ColumnMeta {
return &md.cols[colID.index()]
}
// QualifiedAlias returns the column alias, possibly qualified with the table,
// schema, or database name:
//
// 1. If fullyQualify is true, then the returned alias is prefixed by the
// original, fully qualified name of the table: tab.Name().FQString().
//
// 2. If there's another column in the metadata with the same column alias but
// a different table name, then prefix the column alias with the table
// name: "tabName.columnAlias".
//
func (md *Metadata) QualifiedAlias(colID ColumnID, fullyQualify bool, catalog cat.Catalog) string {
cm := md.ColumnMeta(colID)
if cm.Table == 0 {
// Column doesn't belong to a table, so no need to qualify it further.
return cm.Alias
}
// If a fully qualified alias has not been requested, then only qualify it if
// it would otherwise be ambiguous.
var tabAlias tree.TableName
qualify := fullyQualify
if !fullyQualify {
for i := range md.cols {
if i == int(cm.MetaID-1) {
continue
}
// If there are two columns with same alias, then column is ambiguous.
cm2 := &md.cols[i]
if cm2.Alias == cm.Alias {
tabAlias = md.TableMeta(cm.Table).Alias
if cm2.Table == 0 {
qualify = true
} else {
// Only qualify if the qualified names are actually different.
tabAlias2 := md.TableMeta(cm2.Table).Alias
if tabAlias.String() != tabAlias2.String() {
qualify = true
}
}
}
}
}
// If the column name should not even be partly qualified, then no more to do.
if !qualify {
return cm.Alias
}
var sb strings.Builder
if fullyQualify {
tn, err := catalog.FullyQualifiedName(context.TODO(), md.TableMeta(cm.Table).Table)
if err != nil {
panic(err)
}
sb.WriteString(tn.FQString())
} else {
sb.WriteString(tabAlias.String())
}
sb.WriteRune('.')
sb.WriteString(cm.Alias)
return sb.String()
}
// UpdateTableMeta allows the caller to replace the cat.Table struct that a
// TableMeta instance stores.
func (md *Metadata) UpdateTableMeta(tables map[cat.StableID]cat.Table) {
for i := range md.tables {
if tab, ok := tables[md.tables[i].Table.ID()]; ok {
// If there are any inverted hypothetical indexes, the hypothetical table
// will have extra inverted columns added. Add any new inverted columns to
// the metadata.
for j, n := md.tables[i].Table.ColumnCount(), tab.ColumnCount(); j < n; j++ {
md.AddColumn(string(tab.Column(i).ColName()), types.Bytes)
}
md.tables[i].Table = tab
}
}
}
// SequenceID uniquely identifies the usage of a sequence within the scope of a
// query. SequenceID 0 is reserved to mean "unknown sequence".
type SequenceID uint64
// index returns the index of the sequence in Metadata.sequences. It's biased by 1, so
// that SequenceID 0 can be be reserved to mean "unknown sequence".
func (s SequenceID) index() int {
return int(s - 1)
}
// makeSequenceID constructs a new SequenceID from its component parts.
func makeSequenceID(index int) SequenceID {
// Bias the sequence index by 1.
return SequenceID(index + 1)
}
// AddSequence adds the sequence to the metadata, returning a SequenceID that
// can be used to retrieve it.
func (md *Metadata) AddSequence(seq cat.Sequence) SequenceID {
seqID := makeSequenceID(len(md.sequences))
if md.sequences == nil {
md.sequences = make([]cat.Sequence, 0, 4)
}
md.sequences = append(md.sequences, seq)
return seqID
}
// Sequence looks up the catalog sequence associated with the given metadata id. The
// same sequence can be associated with multiple metadata ids.
func (md *Metadata) Sequence(seqID SequenceID) cat.Sequence {
return md.sequences[seqID.index()]
}
// UniqueID should be used to disambiguate multiple uses of an expression
// within the scope of a query. For example, a UniqueID field should be
// added to an expression type if two instances of that type might otherwise
// be indistinguishable based on the values of their other fields.
//
// See the comment for Metadata for more details on identifiers.
type UniqueID uint64
// NextUniqueID returns a fresh UniqueID which is guaranteed to never have been
// previously allocated in this memo.
func (md *Metadata) NextUniqueID() UniqueID {
md.currUniqueID++
return md.currUniqueID
}
// AddView adds a new reference to a view used by the query.
func (md *Metadata) AddView(v cat.View) {
md.views = append(md.views, v)
}
// AllViews returns the metadata for all views. The result must not be
// modified.
func (md *Metadata) AllViews() []cat.View {
return md.views
}
// AllDataSourceNames returns the fully qualified names of all datasources
// referenced by the metadata.
func (md *Metadata) AllDataSourceNames(
fullyQualifiedName func(ds cat.DataSource) (cat.DataSourceName, error),
) (tables, sequences, views []tree.TableName, _ error) {
// Catalog objects can show up multiple times in our lists, so deduplicate
// them.
seen := make(map[tree.TableName]struct{})
getNames := func(count int, get func(int) cat.DataSource) ([]tree.TableName, error) {
result := make([]tree.TableName, 0, count)
for i := 0; i < count; i++ {
ds := get(i)
tn, err := fullyQualifiedName(ds)
if err != nil {
return nil, err
}
if _, ok := seen[tn]; !ok {
seen[tn] = struct{}{}
result = append(result, tn)
}
}
return result, nil
}
var err error
tables, err = getNames(len(md.tables), func(i int) cat.DataSource {
return md.tables[i].Table
})
if err != nil {
return nil, nil, nil, err
}
sequences, err = getNames(len(md.sequences), func(i int) cat.DataSource {
return md.sequences[i]
})
if err != nil {
return nil, nil, nil, err
}
views, err = getNames(len(md.views), func(i int) cat.DataSource {
return md.views[i]
})
if err != nil {
return nil, nil, nil, err
}
return tables, sequences, views, nil
}
// WithID uniquely identifies a With expression within the scope of a query.
// WithID=0 is reserved to mean "unknown expression".
// See the comment for Metadata for more details on identifiers.
type WithID uint64
// AddWithBinding associates a WithID to its bound expression.
func (md *Metadata) AddWithBinding(id WithID, expr Expr) {
if md.withBindings == nil {
md.withBindings = make(map[WithID]Expr)
}
md.withBindings[id] = expr
}
// WithBinding returns the bound expression for the given WithID.
// Panics with an assertion error if there is none.
func (md *Metadata) WithBinding(id WithID) Expr {
res, ok := md.withBindings[id]
if !ok {
panic(errors.AssertionFailedf("no binding for WithID %d", id))
}
return res
}