/
schema.go
684 lines (637 loc) · 18 KB
/
schema.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
// Copyright 2019 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 sqlsmith
import (
"fmt"
"sort"
"strings"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/randgen"
// Import builtins so they are reflected in tree.FunDefs.
_ "github.com/cockroachdb/cockroach/pkg/sql/sem/builtins"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catid"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree/treebin"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/lib/pq/oid"
"golang.org/x/exp/slices"
)
// tableRef represents a table and its columns.
type tableRef struct {
TableName *tree.TableName
Columns []*tree.ColumnTableDef
}
func (t *tableRef) insertDefaultsAllowed() bool {
for _, column := range t.Columns {
if column.Nullable.Nullability == tree.NotNull &&
!column.HasDefaultExpr() {
return false
}
}
return true
}
type aliasedTableRef struct {
*tableRef
indexFlags *tree.IndexFlags
}
type tableRefs []*tableRef
func WithTableDescriptor(tn tree.TableName, desc descpb.TableDescriptor) SmitherOption {
return option{
name: fmt.Sprintf("inject table %s", tn.FQString()),
apply: func(s *Smither) {
s.lock.Lock()
defer s.lock.Unlock()
if tn.SchemaName != "" {
if !slices.ContainsFunc(s.schemas, func(ref *schemaRef) bool {
return ref.SchemaName == tn.SchemaName
}) {
s.schemas = append(s.schemas, &schemaRef{SchemaName: tn.SchemaName})
}
}
var cols []*tree.ColumnTableDef
for _, col := range desc.Columns {
column := tree.ColumnTableDef{
Name: tree.Name(col.Name),
Type: col.Type,
}
if col.Nullable {
column.Nullable.Nullability = tree.Null
}
if col.IsComputed() {
column.Computed.Computed = true
}
cols = append(cols, &column)
}
s.tables = append(s.tables, &tableRef{
TableName: &tn,
Columns: cols,
})
if s.columns == nil {
s.columns = make(map[tree.TableName]map[tree.Name]*tree.ColumnTableDef)
}
s.columns[tn] = make(map[tree.Name]*tree.ColumnTableDef)
for _, col := range cols {
s.columns[tn][col.Name] = col
}
},
}
}
// ReloadSchemas loads tables from the database.
func (s *Smither) ReloadSchemas() error {
if s.db == nil {
s.schemas = []*schemaRef{{SchemaName: "public"}}
return nil
}
s.lock.Lock()
defer s.lock.Unlock()
var err error
s.types, err = s.extractTypes()
if err != nil {
return err
}
s.tables, err = s.extractTables()
if err != nil {
return err
}
s.schemas, err = s.extractSchemas()
if err != nil {
return err
}
s.sequences, err = s.extractSequences()
if err != nil {
return err
}
s.indexes, err = s.extractIndexes(s.tables)
s.columns = make(map[tree.TableName]map[tree.Name]*tree.ColumnTableDef)
for _, ref := range s.tables {
s.columns[*ref.TableName] = make(map[tree.Name]*tree.ColumnTableDef)
for _, col := range ref.Columns {
s.columns[*ref.TableName][col.Name] = col
}
}
return err
}
// indexesWithNames is a helper struct to sort CreateIndex nodes based on the
// names.
type indexesWithNames struct {
names []string
nodes []*tree.CreateIndex
}
func (t *indexesWithNames) Len() int {
return len(t.names)
}
func (t *indexesWithNames) Less(i, j int) bool {
return t.names[i] < t.names[j]
}
func (t *indexesWithNames) Swap(i, j int) {
t.names[i], t.names[j] = t.names[j], t.names[i]
t.nodes[i], t.nodes[j] = t.nodes[j], t.nodes[i]
}
var _ sort.Interface = &indexesWithNames{}
// getAllIndexesForTableRLocked returns information about all indexes of the
// given table in the deterministic order. s.lock is assumed to be read-locked.
func (s *Smither) getAllIndexesForTableRLocked(tableName tree.TableName) []*tree.CreateIndex {
s.lock.AssertRHeld()
indexes, ok := s.indexes[tableName]
if !ok {
return nil
}
names := make([]string, 0, len(indexes))
nodes := make([]*tree.CreateIndex, 0, len(indexes))
for _, index := range indexes {
names = append(names, string(index.Name))
nodes = append(nodes, index)
}
sort.Sort(&indexesWithNames{names: names, nodes: nodes})
return nodes
}
func (s *Smither) getRandTable() (*aliasedTableRef, bool) {
s.lock.RLock()
defer s.lock.RUnlock()
if len(s.tables) == 0 {
return nil, false
}
table := s.tables[s.rnd.Intn(len(s.tables))]
aliased := &aliasedTableRef{
tableRef: table,
}
if !s.disableIndexHints && s.coin() {
indexes := s.getAllIndexesForTableRLocked(*table.TableName)
var indexFlags tree.IndexFlags
indexNames := make([]tree.Name, 0, len(indexes))
for _, index := range indexes {
if !index.Inverted {
indexNames = append(indexNames, index.Name)
}
}
if len(indexNames) > 0 {
indexFlags.Index = tree.UnrestrictedName(indexNames[s.rnd.Intn(len(indexNames))])
}
aliased.indexFlags = &indexFlags
}
return aliased, true
}
func (s *Smither) getRandTableIndex(
table, alias tree.TableName,
) (*tree.TableIndexName, *tree.CreateIndex, colRefs, bool) {
var indexes []*tree.CreateIndex
func() {
s.lock.RLock()
defer s.lock.RUnlock()
indexes = s.getAllIndexesForTableRLocked(table)
}()
if len(indexes) == 0 {
return nil, nil, nil, false
}
idx := indexes[s.rnd.Intn(len(indexes))]
var refs colRefs
s.lock.RLock()
defer s.lock.RUnlock()
for _, col := range idx.Columns {
ref := s.columns[table][col.Column]
if ref == nil {
// TODO(yuzefovich): there are some cases here where colRef is nil,
// but we aren't yet sure why. Rather than panicking, just return.
return nil, nil, nil, false
}
refs = append(refs, &colRef{
typ: tree.MustBeStaticallyKnownType(ref.Type),
item: tree.NewColumnItem(&alias, col.Column),
})
}
return &tree.TableIndexName{
Table: alias,
Index: tree.UnrestrictedName(idx.Name),
}, idx, refs, true
}
func (s *Smither) getRandIndex() (*tree.TableIndexName, *tree.CreateIndex, colRefs, bool) {
tableRef, ok := s.getRandTable()
if !ok {
return nil, nil, nil, false
}
name := *tableRef.TableName
return s.getRandTableIndex(name, name)
}
func (s *Smither) getRandUserDefinedTypeLabel() (*tree.EnumValue, *tree.TypeName, bool) {
udt, typName, ok := s.getRandUserDefinedType()
if !ok {
return nil, nil, false
}
s.lock.RLock()
defer s.lock.RUnlock()
logicalRepresentations := udt.TypeMeta.EnumData.LogicalRepresentations
// There are no values in this enum.
if len(logicalRepresentations) == 0 {
return nil, nil, false
}
enumVal := tree.EnumValue(logicalRepresentations[s.rnd.Intn(len(logicalRepresentations))])
return &enumVal, typName, true
}
func (s *Smither) getRandUserDefinedType() (*types.T, *tree.TypeName, bool) {
s.lock.RLock()
defer s.lock.RUnlock()
if s.types == nil || len(s.types.udts) == 0 {
return nil, nil, false
}
idx := s.rnd.Intn(len(s.types.udts))
return s.types.udts[idx], &s.types.udtNames[idx], true
}
func (s *Smither) extractTypes() (*typeInfo, error) {
rows, err := s.db.Query(`
SELECT
schema_name, descriptor_name, descriptor_id, enum_members
FROM
crdb_internal.create_type_statements
`)
if err != nil {
return nil, err
}
defer rows.Close()
evalCtx := eval.Context{}
var udts []*types.T
var udtNames []tree.TypeName
for rows.Next() {
// For each row, collect columns.
var scName, name string
var id int
var membersRaw []byte
if err := rows.Scan(&scName, &name, &id, &membersRaw); err != nil {
return nil, err
}
// If enum members were provided, parse the result into a string array.
var members []string
if len(membersRaw) != 0 {
arr, _, err := tree.ParseDArrayFromString(&evalCtx, string(membersRaw), types.String)
if err != nil {
return nil, err
}
for _, d := range arr.Array {
members = append(members, string(tree.MustBeDString(d)))
}
}
// Construct type information from the resulting row. Note that the UDT
// may have no members (e.g., `CREATE TYPE t AS ENUM ()`).
typ := types.MakeEnum(catid.TypeIDToOID(descpb.ID(id)), 0 /* arrayTypeID */)
typ.TypeMeta = types.UserDefinedTypeMetadata{
Name: &types.UserDefinedTypeName{
Schema: scName,
Name: name,
},
EnumData: &types.EnumMetadata{
LogicalRepresentations: members,
// The physical representations don't matter in this case, but the
// enum related code in tree expects that the length of
// PhysicalRepresentations is equal to the length of LogicalRepresentations.
PhysicalRepresentations: make([][]byte, len(members)),
IsMemberReadOnly: make([]bool, len(members)),
},
}
udts = append(udts, typ)
udtNames = append(udtNames, tree.MakeSchemaQualifiedTypeName(scName, name))
}
// Make sure that future appends to udts force a copy.
udts = udts[:len(udts):len(udts)]
return &typeInfo{
udts: udts,
udtNames: udtNames,
scalarTypes: append(udts, types.Scalar...),
seedTypes: append(udts, randgen.SeedTypes...),
}, nil
}
type schemaRef struct {
SchemaName tree.Name
}
func (s *Smither) extractSchemas() ([]*schemaRef, error) {
rows, err := s.db.Query(`
SELECT nspname FROM pg_catalog.pg_namespace
WHERE nspname NOT IN ('crdb_internal', 'pg_catalog', 'pg_extension',
'information_schema')`)
if err != nil {
return nil, err
}
defer rows.Close()
var ret []*schemaRef
for rows.Next() {
var schema tree.Name
if err := rows.Scan(&schema); err != nil {
return nil, err
}
ret = append(ret, &schemaRef{SchemaName: schema})
}
return ret, nil
}
func (s *Smither) extractTables() ([]*tableRef, error) {
rows, err := s.db.Query(`
SELECT
table_catalog,
table_schema,
table_name,
column_name,
crdb_sql_type,
generation_expression != '' AS computed,
is_nullable = 'YES' AS nullable,
is_hidden = 'YES' AS hidden
FROM
information_schema.columns
WHERE
table_schema NOT IN ('crdb_internal', 'pg_catalog', 'pg_extension',
'information_schema')
ORDER BY
table_catalog, table_schema, table_name
`)
// TODO(justin): have a flag that includes system tables?
if err != nil {
return nil, err
}
defer rows.Close()
// This is a little gross: we want to operate on each segment of the results
// that corresponds to a single table. We could maybe json_agg the results
// or something for a cleaner processing step?
firstTime := true
var lastCatalog, lastSchema, lastName tree.Name
var tables []*tableRef
var currentCols []*tree.ColumnTableDef
emit := func() error {
if len(currentCols) == 0 {
return fmt.Errorf("zero columns for %s.%s", lastCatalog, lastName)
}
// All non virtual tables contain implicit system columns.
for i := range colinfo.AllSystemColumnDescs {
col := &colinfo.AllSystemColumnDescs[i]
if s.postgres && col.ID == colinfo.MVCCTimestampColumnID {
continue
}
currentCols = append(currentCols, &tree.ColumnTableDef{
Name: tree.Name(col.Name),
Type: col.Type,
Hidden: true,
})
}
tableName := tree.MakeTableNameWithSchema(lastCatalog, lastSchema, lastName)
tables = append(tables, &tableRef{
TableName: &tableName,
Columns: currentCols,
})
return nil
}
for rows.Next() {
var catalog, schema, name, col tree.Name
var typ string
var computed, nullable, hidden bool
if err := rows.Scan(&catalog, &schema, &name, &col, &typ, &computed, &nullable, &hidden); err != nil {
return nil, err
}
if hidden {
continue
}
if firstTime {
lastCatalog = catalog
lastSchema = schema
lastName = name
}
firstTime = false
if lastCatalog != catalog || lastSchema != schema || lastName != name {
if err := emit(); err != nil {
return nil, err
}
currentCols = nil
}
coltyp, err := s.typeFromSQLTypeSyntax(typ)
if err != nil {
return nil, err
}
column := tree.ColumnTableDef{
Name: col,
Type: coltyp,
}
if nullable {
column.Nullable.Nullability = tree.Null
}
if computed {
column.Computed.Computed = true
}
currentCols = append(currentCols, &column)
lastCatalog = catalog
lastSchema = schema
lastName = name
}
if !firstTime {
if err := emit(); err != nil {
return nil, err
}
}
return tables, rows.Err()
}
func (s *Smither) extractIndexes(
tables tableRefs,
) (map[tree.TableName]map[tree.Name]*tree.CreateIndex, error) {
ret := map[tree.TableName]map[tree.Name]*tree.CreateIndex{}
for _, t := range tables {
indexes := map[tree.Name]*tree.CreateIndex{}
// Ignore rowid indexes since those columns aren't known to
// sqlsmith.
rows, err := s.db.Query(fmt.Sprintf(`
SELECT
si.index_name, column_name, storing, direction = 'ASC',
is_inverted
FROM
[SHOW INDEXES FROM %s] si
JOIN crdb_internal.table_indexes ti
ON si.table_name = ti.descriptor_name
AND si.index_name = ti.index_name
WHERE
column_name != 'rowid'
`, t.TableName))
if err != nil {
return nil, err
}
for rows.Next() {
var idx, col tree.Name
var storing, ascending, inverted bool
if err := rows.Scan(&idx, &col, &storing, &ascending, &inverted); err != nil {
rows.Close()
return nil, err
}
if _, ok := indexes[idx]; !ok {
indexes[idx] = &tree.CreateIndex{
Name: idx,
Table: *t.TableName,
Inverted: inverted,
}
}
create := indexes[idx]
if storing {
create.Storing = append(create.Storing, col)
} else {
dir := tree.Ascending
if !ascending {
dir = tree.Descending
}
create.Columns = append(create.Columns, tree.IndexElem{
Column: col,
Direction: dir,
})
}
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
// Remove indexes with empty Columns. This is the case for rowid indexes
// where the only index column, rowid, is ignored in the SQL statement
// above, but the stored columns are not.
//
// Note that here non-deterministic iteration order over 'indexes' map
// doesn't matter.
for name, idx := range indexes {
if len(idx.Columns) == 0 {
delete(indexes, name)
}
}
ret[*t.TableName] = indexes
}
return ret, nil
}
type sequenceRef struct {
SequenceName tree.TableName
}
func (s *Smither) extractSequences() ([]*sequenceRef, error) {
rows, err := s.db.Query(`SELECT sequence_catalog, sequence_schema, sequence_name FROM information_schema.sequences`)
if err != nil {
return nil, err
}
defer rows.Close()
var ret []*sequenceRef
for rows.Next() {
var db, schema, name tree.Name
if err = rows.Scan(&db, &schema, &name); err != nil {
return nil, err
}
ret = append(ret, &sequenceRef{SequenceName: tree.MakeTableNameWithSchema(db, schema, name)})
}
return ret, nil
}
type operator struct {
*tree.BinOp
Operator treebin.BinaryOperator
}
var operators = func() map[oid.Oid][]operator {
// Ensure deterministic order of populating operators map.
binOps := make([]treebin.BinaryOperatorSymbol, 0, len(tree.BinOps))
for op := range tree.BinOps {
binOps = append(binOps, op)
}
sort.Slice(binOps, func(i, j int) bool {
return binOps[i] < binOps[j]
})
m := map[oid.Oid][]operator{}
for _, binOp := range binOps {
overload := tree.BinOps[binOp]
_ = overload.ForEachBinOp(func(bo *tree.BinOp) error {
m[bo.ReturnType.Oid()] = append(m[bo.ReturnType.Oid()], operator{
BinOp: bo,
Operator: treebin.MakeBinaryOperator(binOp),
})
return nil
})
}
return m
}()
type function struct {
def *tree.FunctionDefinition
overload *tree.Overload
}
type functionsMu struct {
syncutil.Mutex
// User-defined functions are added into the map after the initialization,
// so we need to protect the map with the mutex.
fns map[tree.FunctionClass]map[oid.Oid][]function
}
var functions = func() *functionsMu {
// Ensure deterministic order of populating functions map.
funcNames := make([]string, 0, len(tree.FunDefs))
for name := range tree.FunDefs {
funcNames = append(funcNames, name)
}
sort.Strings(funcNames)
m := map[tree.FunctionClass]map[oid.Oid][]function{}
for _, name := range funcNames {
def := tree.FunDefs[name]
if n := tree.Name(def.Name); n.String() != def.Name {
// sqlsmith doesn't know how to quote function names, e.g. for
// the numeric cast, we need to use `"numeric"(val)`, but sqlsmith
// makes it `numeric(val)` which is incorrect.
continue
}
skip := false
for _, substr := range []string{
"pg_sleep",
// Some spatial functions can be very computationally expensive and
// run for a long time or never finish, so we avoid generating them.
// See #69213.
"st_frechetdistance",
"st_buffer",
"stream_ingestion",
"crdb_internal.force_",
"crdb_internal.unsafe_",
"crdb_internal.create_join_token",
"crdb_internal.reset_multi_region_zone_configs_for_database",
"crdb_internal.reset_index_usage_stats",
"crdb_internal.start_replication_stream",
"crdb_internal.replication_stream_progress",
"crdb_internal.complete_replication_stream",
"crdb_internal.revalidate_unique_constraint",
"crdb_internal.request_statement_bundle",
"crdb_internal.set_compaction_concurrency",
"crdb_internal.reset_sql_stats",
} {
skip = skip || strings.Contains(def.Name, substr)
}
if skip {
continue
}
// Ignore pg compat functions since many are unimplemented.
if def.Category == "Compatibility" {
continue
}
if def.Private {
continue
}
for _, ov := range def.Definition {
if m[ov.Class] == nil {
m[ov.Class] = map[oid.Oid][]function{}
}
// Ignore documented unusable functions.
if strings.Contains(ov.Info, "Not usable") {
continue
}
typ := ov.FixedReturnType()
found := false
for _, scalarTyp := range types.Scalar {
if typ.Family() == scalarTyp.Family() {
found = true
}
}
if !found {
continue
}
m[ov.Class][typ.Oid()] = append(m[ov.Class][typ.Oid()], function{
def: def,
overload: ov,
})
}
}
return &functionsMu{fns: m}
}()