/
schema.go
404 lines (365 loc) · 12.8 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
// Copyright 2021 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 randgen
import (
gosql "database/sql"
"fmt"
"math/rand"
"strings"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/errors"
)
// MakeSchemaName creates a CreateSchema definition.
func MakeSchemaName(ifNotExists bool, schema string, authRole tree.RoleSpec) *tree.CreateSchema {
return &tree.CreateSchema{
IfNotExists: ifNotExists,
Schema: tree.ObjectNamePrefix{
SchemaName: tree.Name(schema),
ExplicitSchema: true,
},
AuthRole: authRole,
}
}
// RandCreateType creates a random CREATE TYPE statement. The resulting
// type's name will be name, and if the type is an enum, the members will
// be random strings generated from alphabet.
func RandCreateType(rng *rand.Rand, name, alphabet string) tree.Statement {
numLabels := rng.Intn(6) + 1
labels := make(tree.EnumValueList, numLabels)
labelsMap := make(map[string]struct{})
i := 0
for i < numLabels {
s := RandString(rng, rng.Intn(6)+1, alphabet)
if _, ok := labelsMap[s]; !ok {
labels[i] = tree.EnumValue(s)
labelsMap[s] = struct{}{}
i++
}
}
un, err := tree.NewUnresolvedObjectName(1, [3]string{name}, 0)
if err != nil {
panic(err)
}
return &tree.CreateType{
TypeName: un,
Variety: tree.Enum,
EnumLabels: labels,
}
}
// RandCreateTables creates random table definitions.
func RandCreateTables(
rng *rand.Rand, prefix string, num int, mutators ...Mutator,
) []tree.Statement {
if num < 1 {
panic("at least one table required")
}
// Make some random tables.
tables := make([]tree.Statement, num)
for i := 0; i < num; i++ {
t := RandCreateTableWithColumnIndexNumberGenerator(rng, prefix, i+1, nil /* generateColumnIndexNumber */)
tables[i] = t
}
for _, m := range mutators {
tables, _ = m.Mutate(rng, tables)
}
return tables
}
// RandCreateTable creates a random CreateTable definition.
func RandCreateTable(rng *rand.Rand, prefix string, tableIdx int) *tree.CreateTable {
return RandCreateTableWithColumnIndexNumberGenerator(rng, prefix, tableIdx, nil /* generateColumnIndexNumber */)
}
// RandCreateTableWithColumnIndexNumberGenerator creates a random CreateTable definition
// using the passed function to generate column index numbers for column names.
func RandCreateTableWithColumnIndexNumberGenerator(
rng *rand.Rand, prefix string, tableIdx int, generateColumnIndexNumber func() int64,
) *tree.CreateTable {
// columnDefs contains the list of Columns we'll add to our table.
nColumns := randutil.RandIntInRange(rng, 1, 20)
columnDefs := make([]*tree.ColumnTableDef, 0, nColumns)
// defs contains the list of Columns and other attributes (indexes, column
// families, etc) we'll add to our table.
defs := make(tree.TableDefs, 0, len(columnDefs))
// colIdx generates numbers that are incorporated into column names.
colIdx := func(ordinal int) int {
if generateColumnIndexNumber != nil {
return int(generateColumnIndexNumber())
}
return ordinal
}
// Make new defs from scratch.
nComputedColumns := randutil.RandIntInRange(rng, 0, (nColumns+1)/2)
nNormalColumns := nColumns - nComputedColumns
for i := 0; i < nNormalColumns; i++ {
columnDef := randColumnTableDef(rng, tableIdx, colIdx(i))
columnDefs = append(columnDefs, columnDef)
defs = append(defs, columnDef)
}
// Make a random primary key with high likelihood.
if rng.Intn(8) != 0 {
indexDef, ok := randIndexTableDefFromCols(rng, columnDefs, false /* allowExpressions */)
if ok && !indexDef.Inverted {
defs = append(defs, &tree.UniqueConstraintTableDef{
PrimaryKey: true,
IndexTableDef: indexDef,
})
}
// Although not necessary for Cockroach to function correctly,
// but for ease of use for any code that introspects on the
// AST data structure (instead of the descriptor which doesn't
// exist yet), explicitly set all PK cols as NOT NULL.
for _, col := range columnDefs {
for _, elem := range indexDef.Columns {
if col.Name == elem.Column {
col.Nullable.Nullability = tree.NotNull
}
}
}
}
// Make defs for computed columns.
normalColDefs := columnDefs
for i := nNormalColumns; i < nColumns; i++ {
columnDef := randComputedColumnTableDef(rng, normalColDefs, tableIdx, colIdx(i))
columnDefs = append(columnDefs, columnDef)
defs = append(defs, columnDef)
}
// Make indexes.
nIdxs := rng.Intn(10)
for i := 0; i < nIdxs; i++ {
indexDef, ok := randIndexTableDefFromCols(rng, columnDefs, true /* allowExpressions */)
if !ok {
continue
}
// Make forward indexes unique 50% of the time. Inverted indexes cannot
// be unique.
unique := !indexDef.Inverted && rng.Intn(2) == 0
if unique {
defs = append(defs, &tree.UniqueConstraintTableDef{
IndexTableDef: indexDef,
})
} else {
defs = append(defs, &indexDef)
}
}
ret := &tree.CreateTable{
Table: tree.MakeUnqualifiedTableName(tree.Name(fmt.Sprintf("%s%d", prefix, tableIdx))),
Defs: defs,
}
// Create some random column families.
if rng.Intn(2) == 0 {
ColumnFamilyMutator(rng, ret)
}
// Maybe add some storing columns.
res, _ := IndexStoringMutator(rng, []tree.Statement{ret})
return res[0].(*tree.CreateTable)
}
// GenerateRandInterestingTable takes a gosql.DB connection and creates
// a table with all the types in randInterestingDatums and rows of the
// interesting datums.
func GenerateRandInterestingTable(db *gosql.DB, dbName, tableName string) error {
var (
randTypes []*types.T
colNames []string
)
numRows := 0
for _, v := range randInterestingDatums {
colTyp := v[0].ResolvedType()
randTypes = append(randTypes, colTyp)
colNames = append(colNames, colTyp.Name())
if len(v) > numRows {
numRows = len(v)
}
}
var columns strings.Builder
comma := ""
for i, typ := range randTypes {
columns.WriteString(comma)
columns.WriteString(colNames[i])
columns.WriteString(" ")
columns.WriteString(typ.SQLString())
comma = ", "
}
createStatement := fmt.Sprintf("CREATE TABLE %s.%s (%s)", dbName, tableName, columns.String())
if _, err := db.Exec(createStatement); err != nil {
return err
}
row := make([]string, len(randTypes))
for i := 0; i < numRows; i++ {
for j, typ := range randTypes {
datums := randInterestingDatums[typ.Family()]
var d tree.Datum
if i < len(datums) {
d = datums[i]
} else {
d = tree.DNull
}
row[j] = tree.AsStringWithFlags(d, tree.FmtParsable)
}
var builder strings.Builder
comma := ""
for _, d := range row {
builder.WriteString(comma)
builder.WriteString(d)
comma = ", "
}
insertStmt := fmt.Sprintf("INSERT INTO %s.%s VALUES (%s)", dbName, tableName, builder.String())
if _, err := db.Exec(insertStmt); err != nil {
return err
}
}
return nil
}
// randColumnTableDef produces a random ColumnTableDef for a non-computed
// column, with a random type and nullability.
func randColumnTableDef(rand *rand.Rand, tableIdx int, colIdx int) *tree.ColumnTableDef {
columnDef := &tree.ColumnTableDef{
// We make a unique name for all columns by prefixing them with the table
// index to make it easier to reference columns from different tables.
Name: tree.Name(fmt.Sprintf("col%d_%d", tableIdx, colIdx)),
Type: RandColumnType(rand),
}
columnDef.Nullable.Nullability = tree.Nullability(rand.Intn(int(tree.SilentNull) + 1))
return columnDef
}
// randComputedColumnTableDef produces a random ColumnTableDef for a computed
// column (either STORED or VIRTUAL). The computed expressions refer to columns
// in normalColDefs.
func randComputedColumnTableDef(
rng *rand.Rand, normalColDefs []*tree.ColumnTableDef, tableIdx int, colIdx int,
) *tree.ColumnTableDef {
newDef := randColumnTableDef(rng, tableIdx, colIdx)
newDef.Computed.Computed = true
newDef.Computed.Virtual = (rng.Intn(2) == 0)
expr, typ, nullability := randExpr(rng, normalColDefs, true /* nullOk */)
newDef.Computed.Expr = expr
newDef.Type = typ
newDef.Nullable.Nullability = nullability
return newDef
}
// randIndexTableDefFromCols attempts to create an IndexTableDef with a random
// subset of the given columns and a random direction. If unsuccessful, ok=false
// is returned.
func randIndexTableDefFromCols(
rng *rand.Rand, columnTableDefs []*tree.ColumnTableDef, allowExpressions bool,
) (def tree.IndexTableDef, ok bool) {
cpy := make([]*tree.ColumnTableDef, len(columnTableDefs))
copy(cpy, columnTableDefs)
rng.Shuffle(len(cpy), func(i, j int) { cpy[i], cpy[j] = cpy[j], cpy[i] })
nCols := rng.Intn(len(cpy)) + 1
cols := cpy[:nCols]
def.Columns = make(tree.IndexElemList, 0, len(cols))
for i := range cols {
semType := tree.MustBeStaticallyKnownType(cols[i].Type)
elem := tree.IndexElem{
Column: cols[i].Name,
Direction: tree.Direction(rng.Intn(int(tree.Descending) + 1)),
}
// Replace the column with an expression 10% of the time.
if allowExpressions && rng.Intn(10) == 0 {
var expr tree.Expr
// Expression indexes do not currently support references to
// computed columns, so only make expressions with non-computed
// columns. Do not allow NULL in expressions to avoid expressions
// that have an ambiguous type.
expr, semType, _ = randExpr(rng, nonComputedColumnTableDefs(columnTableDefs), false /* nullOk */)
elem.Expr = expr
elem.Column = ""
}
// The non-terminal index columns must be indexable.
if isLastCol := i == len(cols)-1; !isLastCol && !colinfo.ColumnTypeIsIndexable(semType) {
return tree.IndexTableDef{}, false
}
// The last index column can be inverted-indexable, which makes the
// index an inverted index.
if colinfo.ColumnTypeIsInvertedIndexable(semType) {
def.Inverted = true
}
def.Columns = append(def.Columns, elem)
}
return def, true
}
// nonComputedColumnTableDefs returns a slice containing all the columns in cols
// that are not computed columns.
func nonComputedColumnTableDefs(cols []*tree.ColumnTableDef) []*tree.ColumnTableDef {
nonComputedCols := make([]*tree.ColumnTableDef, 0, len(cols))
for _, col := range cols {
if !col.Computed.Computed {
nonComputedCols = append(nonComputedCols, col)
}
}
return nonComputedCols
}
// TestingMakePrimaryIndexKey creates a key prefix that corresponds to
// a table row (in the primary index); it is intended for tests.
//
// It is exported because it is used by tests outside of this package.
//
// The value types must match the primary key columns (or a prefix of them);
// supported types are: - Datum
// - bool (converts to DBool)
// - int (converts to DInt)
// - string (converts to DString)
func TestingMakePrimaryIndexKey(
desc catalog.TableDescriptor, vals ...interface{},
) (roachpb.Key, error) {
return TestingMakePrimaryIndexKeyForTenant(desc, keys.SystemSQLCodec, vals...)
}
// TestingMakePrimaryIndexKeyForTenant is the same as TestingMakePrimaryIndexKey, but
// allows specification of the codec to use when encoding keys.
func TestingMakePrimaryIndexKeyForTenant(
desc catalog.TableDescriptor, codec keys.SQLCodec, vals ...interface{},
) (roachpb.Key, error) {
index := desc.GetPrimaryIndex()
if len(vals) > index.NumKeyColumns() {
return nil, errors.Errorf("got %d values, PK has %d columns", len(vals), index.NumKeyColumns())
}
datums := make([]tree.Datum, len(vals))
for i, v := range vals {
switch v := v.(type) {
case bool:
datums[i] = tree.MakeDBool(tree.DBool(v))
case int:
datums[i] = tree.NewDInt(tree.DInt(v))
case string:
datums[i] = tree.NewDString(v)
case tree.Datum:
datums[i] = v
default:
return nil, errors.Errorf("unexpected value type %T", v)
}
// Check that the value type matches.
colID := index.GetKeyColumnID(i)
col, _ := desc.FindColumnWithID(colID)
if col != nil && col.Public() {
colTyp := datums[i].ResolvedType()
if t := colTyp.Family(); t != col.GetType().Family() {
return nil, errors.Errorf("column %d of type %s, got value of type %s", i, col.GetType().Family(), t)
}
}
}
// Create the ColumnID to index in datums slice map needed by
// MakeIndexKeyPrefix.
var colIDToRowIndex catalog.TableColMap
for i := range vals {
colIDToRowIndex.Set(index.GetKeyColumnID(i), i)
}
keyPrefix := rowenc.MakeIndexKeyPrefix(codec, desc, index.GetID())
key, _, err := rowenc.EncodeIndexKey(desc, index, colIDToRowIndex, datums, keyPrefix)
if err != nil {
return nil, err
}
return key, nil
}