-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
operation_generator.go
3559 lines (3223 loc) · 112 KB
/
operation_generator.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 2020 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 schemachange
import (
"context"
"fmt"
"math/rand"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/randgen"
"github.com/cockroachdb/cockroach/pkg/sql/schemachange"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/workload"
"github.com/cockroachdb/errors"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
)
// seqNum may be shared across multiple instances of this, so it should only
// be change atomically.
type operationGeneratorParams struct {
seqNum *int64
errorRate int
enumPct int
rng *rand.Rand
ops *deck
maxSourceTables int
sequenceOwnedByPct int
fkParentInvalidPct int
fkChildInvalidPct int
}
// The OperationBuilder has the sole responsibility of generating ops
type operationGenerator struct {
params *operationGeneratorParams
potentialExecErrors errorCodeSet
expectedCommitErrors errorCodeSet
potentialCommitErrors errorCodeSet
// This stores expected commit errors while an op statement
// is still being constructed. It is possible that one of the functions in opFuncs
// fails. In this case, the candidateExpectedCommitErrors will be discarded. If the
// function succeeds and the op statement is constructed, then candidateExpectedCommitErrors
// are added to expectedCommitErrors.
candidateExpectedCommitErrors errorCodeSet
// opsInTxn is a list of previous ops in the current transaction to check
// for DDLs after writes.
opsInTxn []opType
// stmtsInTxn is a list of statements in the current transaction.
stmtsInTxt []*opStmt
// opGenLog log of statement used to generate the current statement.
opGenLog strings.Builder
}
// LogQueryResults logs a string query result.
func (og *operationGenerator) LogQueryResults(queryName string, result string) {
og.opGenLog.WriteString(fmt.Sprintf("QUERY [%s] :", queryName))
og.opGenLog.WriteString(result)
og.opGenLog.WriteString("\n")
}
// LogQueryResultArray logs a query result that is a strng array.
func (og *operationGenerator) LogQueryResultArray(queryName string, results []string) {
og.opGenLog.WriteString(fmt.Sprintf("QUERY [%s] : ", queryName))
for _, result := range results {
og.opGenLog.WriteString(result)
og.opGenLog.WriteString(",")
}
og.opGenLog.WriteString("\n")
}
// GetOpGenLog fetches the generated log entries.
func (og *operationGenerator) GetOpGenLog() string {
return og.opGenLog.String()
}
func makeOperationGenerator(params *operationGeneratorParams) *operationGenerator {
return &operationGenerator{
params: params,
expectedCommitErrors: makeExpectedErrorSet(),
potentialExecErrors: makeExpectedErrorSet(),
potentialCommitErrors: makeExpectedErrorSet(),
candidateExpectedCommitErrors: makeExpectedErrorSet(),
}
}
// Reset internal state used per operation within a transaction
func (og *operationGenerator) resetOpState() {
og.candidateExpectedCommitErrors.reset()
og.potentialExecErrors.reset()
og.opGenLog = strings.Builder{}
}
// Reset internal state used per transaction
func (og *operationGenerator) resetTxnState() {
og.expectedCommitErrors.reset()
og.potentialCommitErrors.reset()
og.opsInTxn = nil
og.stmtsInTxt = nil
}
//go:generate stringer -type=opType
type opType int
const (
addColumn opType = iota // ALTER TABLE <table> ADD [COLUMN] <column> <type>
addConstraint // ALTER TABLE <table> ADD CONSTRAINT <constraint> <def>
addForeignKeyConstraint // ALTER TABLE <table> ADD CONSTRAINT <constraint> FOREIGN KEY (<column>) REFERENCES <table> (<column>)
addRegion // ALTER DATABASE <db> ADD REGION <region>
addUniqueConstraint // ALTER TABLE <table> ADD CONSTRAINT <constraint> UNIQUE (<column>)
alterTableLocality // ALTER TABLE <table> LOCALITY <locality>
createIndex // CREATE INDEX <index> ON <table> <def>
createSequence // CREATE SEQUENCE <sequence> <def>
createTable // CREATE TABLE <table> <def>
createTableAs // CREATE TABLE <table> AS <def>
createView // CREATE VIEW <view> AS <def>
createEnum // CREATE TYPE <type> ENUM AS <def>
createSchema // CREATE SCHEMA <schema>
dropColumn // ALTER TABLE <table> DROP COLUMN <column>
dropColumnDefault // ALTER TABLE <table> ALTER [COLUMN] <column> DROP DEFAULT
dropColumnNotNull // ALTER TABLE <table> ALTER [COLUMN] <column> DROP NOT NULL
dropColumnStored // ALTER TABLE <table> ALTER [COLUMN] <column> DROP STORED
dropConstraint // ALTER TABLE <table> DROP CONSTRAINT <constraint>
dropIndex // DROP INDEX <index>@<table>
dropSequence // DROP SEQUENCE <sequence>
dropTable // DROP TABLE <table>
dropView // DROP VIEW <view>
dropSchema // DROP SCHEMA <schema>
primaryRegion // ALTER DATABASE <db> PRIMARY REGION <region>
renameColumn // ALTER TABLE <table> RENAME [COLUMN] <column> TO <column>
renameIndex // ALTER TABLE <table> RENAME CONSTRAINT <constraint> TO <constraint>
renameSequence // ALTER SEQUENCE <sequence> RENAME TO <sequence>
renameTable // ALTER TABLE <table> RENAME TO <table>
renameView // ALTER VIEW <view> RENAME TO <view>
setColumnDefault // ALTER TABLE <table> ALTER [COLUMN] <column> SET DEFAULT <expr>
setColumnNotNull // ALTER TABLE <table> ALTER [COLUMN] <column> SET NOT NULL
setColumnType // ALTER TABLE <table> ALTER [COLUMN] <column> [SET DATA] TYPE <type>
survive // ALTER DATABASE <db> SURVIVE <failure_mode>
insertRow // INSERT INTO <table> (<cols>) VALUES (<values>)
selectStmt // SELECT..
validate // validate all table descriptors
numOpTypes int = iota
)
var opFuncs = map[opType]func(*operationGenerator, context.Context, pgx.Tx) (*opStmt, error){
addColumn: (*operationGenerator).addColumn,
addConstraint: (*operationGenerator).addConstraint,
addForeignKeyConstraint: (*operationGenerator).addForeignKeyConstraint,
addRegion: (*operationGenerator).addRegion,
addUniqueConstraint: (*operationGenerator).addUniqueConstraint,
alterTableLocality: (*operationGenerator).alterTableLocality,
createIndex: (*operationGenerator).createIndex,
createSequence: (*operationGenerator).createSequence,
createTable: (*operationGenerator).createTable,
createTableAs: (*operationGenerator).createTableAs,
createView: (*operationGenerator).createView,
createEnum: (*operationGenerator).createEnum,
createSchema: (*operationGenerator).createSchema,
dropColumn: (*operationGenerator).dropColumn,
dropColumnDefault: (*operationGenerator).dropColumnDefault,
dropColumnNotNull: (*operationGenerator).dropColumnNotNull,
dropColumnStored: (*operationGenerator).dropColumnStored,
dropConstraint: (*operationGenerator).dropConstraint,
dropIndex: (*operationGenerator).dropIndex,
dropSequence: (*operationGenerator).dropSequence,
dropTable: (*operationGenerator).dropTable,
dropView: (*operationGenerator).dropView,
dropSchema: (*operationGenerator).dropSchema,
primaryRegion: (*operationGenerator).primaryRegion,
renameColumn: (*operationGenerator).renameColumn,
renameIndex: (*operationGenerator).renameIndex,
renameSequence: (*operationGenerator).renameSequence,
renameTable: (*operationGenerator).renameTable,
renameView: (*operationGenerator).renameView,
setColumnDefault: (*operationGenerator).setColumnDefault,
setColumnNotNull: (*operationGenerator).setColumnNotNull,
setColumnType: (*operationGenerator).setColumnType,
survive: (*operationGenerator).survive,
insertRow: (*operationGenerator).insertRow,
selectStmt: (*operationGenerator).selectStmt,
validate: (*operationGenerator).validate,
}
func init() {
// Validate that we have an operation function for each opType.
if len(opFuncs) != numOpTypes {
panic(errors.Errorf("expected %d opFuncs, got %d", numOpTypes, len(opFuncs)))
}
}
var opWeights = []int{
addColumn: 1,
addConstraint: 0, // TODO(spaskob): unimplemented
addForeignKeyConstraint: 1,
addRegion: 1,
addUniqueConstraint: 0,
alterTableLocality: 1,
createIndex: 1,
createSequence: 1,
createTable: 1,
createTableAs: 1,
createView: 1,
createEnum: 1,
createSchema: 1,
dropColumn: 0,
dropColumnDefault: 1,
dropColumnNotNull: 1,
dropColumnStored: 1,
dropConstraint: 1,
dropIndex: 1,
dropSequence: 1,
dropTable: 1,
dropView: 1,
dropSchema: 1,
primaryRegion: 0, // Disabled and tracked with #83831
renameColumn: 1,
renameIndex: 1,
renameSequence: 1,
renameTable: 1,
renameView: 1,
setColumnDefault: 1,
setColumnNotNull: 1,
setColumnType: 0, // Disabled and tracked with #66662.
survive: 0, // Disabled and tracked with #83831
insertRow: 10, // Temporarily reduced because of #80820
selectStmt: 10,
validate: 2, // validate twice more often
}
// adjustOpWeightsForActiveVersion adjusts the weights for the active cockroach
// version, allowing us to disable certain operations in mixed version scenarios.
func adjustOpWeightsForCockroachVersion(
ctx context.Context, pool *workload.MultiConnPool, opWeights []int,
) error {
tx, err := pool.Get().Begin(ctx)
if err != nil {
return err
}
// First validate if we even support foreign key constraints on the active
// version, since we need builtins.
fkConstraintsEnabled, err := isFkConstraintsEnabled(ctx, tx)
if err != nil {
if rbErr := tx.Rollback(ctx); rbErr != nil {
err = errors.WithSecondaryError(err, rbErr)
}
return err
}
if !fkConstraintsEnabled {
opWeights[addForeignKeyConstraint] = 0
}
return tx.Rollback(ctx)
}
// randOp attempts to produce a random schema change operation. It returns a
// triple `(randOp, log, error)`. On success `randOp` is the random schema
// change constructed. Constructing a random schema change may require a few
// stochastic attempts and if verbosity is >= 2 the unsuccessful attempts are
// recorded in `log` to help with debugging of the workload.
func (og *operationGenerator) randOp(ctx context.Context, tx pgx.Tx) (stmt *opStmt, err error) {
for {
op := opType(og.params.ops.Int())
og.resetOpState()
stmt, err = opFuncs[op](og, ctx, tx)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
continue
}
// Table select had a primary key swap, so no statement
// generated.
if errors.Is(err, ErrSchemaChangesDisallowedDueToPkSwap) {
continue
}
return nil, err
}
// Screen for schema change after write in the same transaction.
og.stmtsInTxt = append(og.stmtsInTxt, stmt)
// Add candidateExpectedCommitErrors to expectedCommitErrors
og.expectedCommitErrors.merge(og.candidateExpectedCommitErrors)
og.opsInTxn = append(og.opsInTxn, op)
break
}
return stmt, err
}
func (og *operationGenerator) addColumn(ctx context.Context, tx pgx.Tx) (*opStmt, error) {
tableName, err := og.randTable(ctx, tx, og.pctExisting(true), "")
if err != nil {
return nil, err
}
tableExists, err := og.tableExists(ctx, tx, tableName)
if err != nil {
return nil, err
}
if !tableExists {
return makeOpStmtForSingleError(OpStmtDDL,
fmt.Sprintf(`ALTER TABLE %s ADD COLUMN IrrelevantColumnName string`, tableName),
pgcode.UndefinedTable), nil
}
err = og.tableHasPrimaryKeySwapActive(ctx, tx, tableName)
if err != nil {
return nil, err
}
columnName, err := og.randColumn(ctx, tx, *tableName, og.pctExisting(false))
if err != nil {
return nil, err
}
typName, typ, err := og.randType(ctx, tx, og.pctExisting(true))
if err != nil {
return nil, err
}
def := &tree.ColumnTableDef{
Name: tree.Name(columnName),
Type: typName,
}
def.Nullable.Nullability = tree.Nullability(og.randIntn(1 + int(tree.SilentNull)))
databaseHasRegionChange, err := og.databaseHasRegionChange(ctx, tx)
if err != nil {
return nil, err
}
tableIsRegionalByRow, err := og.tableIsRegionalByRow(ctx, tx, tableName)
if err != nil {
return nil, err
}
if !(tableIsRegionalByRow && databaseHasRegionChange) && og.randIntn(10) == 0 {
def.Unique.IsUnique = true
}
columnExistsOnTable, err := og.columnExistsOnTable(ctx, tx, tableName, columnName)
if err != nil {
return nil, err
}
var hasRows bool
if tableExists {
hasRows, err = og.tableHasRows(ctx, tx, tableName)
if err != nil {
return nil, err
}
}
hasAlterPKSchemaChange, err := og.tableHasOngoingAlterPKSchemaChanges(ctx, tx, tableName)
if err != nil {
return nil, err
}
op := makeOpStmt(OpStmtDDL)
codesWithConditions{
{code: pgcode.DuplicateColumn, condition: columnExistsOnTable},
{code: pgcode.UndefinedObject, condition: typ == nil},
{code: pgcode.NotNullViolation, condition: hasRows && def.Nullable.Nullability == tree.NotNull},
{code: pgcode.FeatureNotSupported, condition: hasAlterPKSchemaChange},
// UNIQUE is only supported for indexable types.
{
code: pgcode.FeatureNotSupported,
condition: def.Unique.IsUnique && typ != nil && !colinfo.ColumnTypeIsIndexable(typ),
},
}.add(op.expectedExecErrors)
op.sql = fmt.Sprintf(`ALTER TABLE %s ADD COLUMN %s`, tableName, tree.Serialize(def))
return op, nil
}
func (og *operationGenerator) addConstraint(ctx context.Context, tx pgx.Tx) (*opStmt, error) {
// TODO(peter): unimplemented
// - Export sqlbase.randColumnTableDef.
return nil, nil
}
func (og *operationGenerator) addUniqueConstraint(ctx context.Context, tx pgx.Tx) (*opStmt, error) {
tableName, err := og.randTable(ctx, tx, og.pctExisting(true), "")
if err != nil {
return nil, err
}
tableExists, err := og.tableExists(ctx, tx, tableName)
if err != nil {
return nil, err
}
if !tableExists {
return makeOpStmtForSingleError(OpStmtDDL,
fmt.Sprintf(`ALTER TABLE %s ADD CONSTRAINT IrrelevantConstraintName UNIQUE (IrrelevantColumnName)`, tableName),
pgcode.UndefinedTable), nil
}
err = og.tableHasPrimaryKeySwapActive(ctx, tx, tableName)
if err != nil {
return nil, err
}
columnForConstraint, err := og.randColumnWithMeta(ctx, tx, *tableName, og.pctExisting(true))
if err != nil {
return nil, err
}
constaintName := fmt.Sprintf("%s_%s_unique", tableName.Object(), columnForConstraint.name)
columnExistsOnTable, err := og.columnExistsOnTable(ctx, tx, tableName, columnForConstraint.name)
if err != nil {
return nil, err
}
constraintExists, err := og.constraintExists(ctx, tx, constaintName)
if err != nil {
return nil, err
}
canApplyConstraint := true
if columnExistsOnTable {
canApplyConstraint, err = og.canApplyUniqueConstraint(ctx, tx, tableName, []string{columnForConstraint.name})
if err != nil {
return nil, err
}
}
hasAlterPKSchemaChange, err := og.tableHasOngoingAlterPKSchemaChanges(ctx, tx, tableName)
if err != nil {
return nil, err
}
databaseHasRegionChange, err := og.databaseHasRegionChange(ctx, tx)
if err != nil {
return nil, err
}
tableIsRegionalByRow, err := og.tableIsRegionalByRow(ctx, tx, tableName)
if err != nil {
return nil, err
}
stmt := makeOpStmt(OpStmtDDL)
codesWithConditions{
{code: pgcode.UndefinedColumn, condition: !columnExistsOnTable},
{code: pgcode.DuplicateObject, condition: constraintExists},
{code: pgcode.FeatureNotSupported, condition: columnExistsOnTable && !colinfo.ColumnTypeIsIndexable(columnForConstraint.typ)},
{pgcode.FeatureNotSupported, hasAlterPKSchemaChange},
{code: pgcode.ObjectNotInPrerequisiteState, condition: databaseHasRegionChange && tableIsRegionalByRow},
}.add(stmt.expectedExecErrors)
if !canApplyConstraint {
og.candidateExpectedCommitErrors.add(pgcode.UniqueViolation)
}
stmt.sql = fmt.Sprintf(`ALTER TABLE %s ADD CONSTRAINT %s UNIQUE (%s)`, tableName, constaintName, columnForConstraint.name)
return stmt, nil
}
func (og *operationGenerator) alterTableLocality(ctx context.Context, tx pgx.Tx) (*opStmt, error) {
tableName, err := og.randTable(ctx, tx, og.pctExisting(true), "")
if err != nil {
return nil, err
}
tableExists, err := og.tableExists(ctx, tx, tableName)
if err != nil {
return nil, err
}
if !tableExists {
return makeOpStmtForSingleError(OpStmtDDL,
fmt.Sprintf(`ALTER TABLE %s SET LOCALITY REGIONAL BY ROW`, tableName),
pgcode.UndefinedTable), nil
}
err = og.tableHasPrimaryKeySwapActive(ctx, tx, tableName)
if err != nil {
return nil, err
}
databaseRegionNames, err := og.getDatabaseRegionNames(ctx, tx)
if err != nil {
return nil, err
}
if len(databaseRegionNames) == 0 {
return makeOpStmtForSingleError(OpStmtDDL,
fmt.Sprintf(`ALTER TABLE %s SET LOCALITY REGIONAL BY ROW`, tableName),
pgcode.InvalidTableDefinition), nil
}
hasSchemaChange, err := og.tableHasOngoingSchemaChanges(ctx, tx, tableName)
if err != nil {
return nil, err
}
databaseHasRegionChange, err := og.databaseHasRegionChange(ctx, tx)
if err != nil {
return nil, err
}
databaseHasMultiRegion, err := og.databaseIsMultiRegion(ctx, tx)
if err != nil {
return nil, err
}
if hasSchemaChange || databaseHasRegionChange || !databaseHasMultiRegion {
return makeOpStmtForSingleError(OpStmtDDL,
`ALTER TABLE invalid_table SET LOCALITY REGIONAL BY ROW`,
pgcode.UndefinedTable), nil
}
stmt := makeOpStmt(OpStmtDDL)
localityOptions := []func() (string, error){
func() (string, error) {
return "REGIONAL BY TABLE", nil
},
func() (string, error) {
idx := og.params.rng.Intn(len(databaseRegionNames))
regionName := tree.Name(databaseRegionNames[idx])
return fmt.Sprintf(`REGIONAL BY TABLE IN %s`, regionName.String()), nil
},
func() (string, error) {
return "GLOBAL", nil
},
func() (string, error) {
columnForAs, err := og.randColumnWithMeta(ctx, tx, *tableName, og.alwaysExisting())
columnForAsUsed := false
if err != nil {
return "", err
}
ret := "REGIONAL BY ROW"
if columnForAs.typ.TypeMeta.Name != nil {
if columnForAs.typ.TypeMeta.Name.Basename() == tree.RegionEnum &&
!columnForAs.nullable {
ret += " AS " + columnForAs.name
columnForAsUsed = true
}
}
// If the table has a crdb_region column, make sure that it's not
// nullable. This is required to handle the case where there's an
// existing crdb_region column, but it is nullable, and therefore
// cannot be used as the implicit partitioning column.
if !columnForAsUsed {
columnNames, err := og.getTableColumns(ctx, tx, tableName.String(), true)
if err != nil {
return "", err
}
for _, col := range columnNames {
if col.name == tree.RegionalByRowRegionDefaultCol &&
col.nullable {
stmt.expectedExecErrors.add(pgcode.InvalidTableDefinition)
}
}
}
return ret, nil
},
}
idx := og.params.rng.Intn(len(localityOptions))
toLocality, err := localityOptions[idx]()
if err != nil {
return nil, err
}
stmt.sql = fmt.Sprintf(`ALTER TABLE %s SET LOCALITY %s`, tableName, toLocality)
return stmt, nil
}
func (og *operationGenerator) getClusterRegionNames(
ctx context.Context, tx pgx.Tx,
) (catpb.RegionNames, error) {
return og.scanRegionNames(ctx, tx, "SELECT region FROM [SHOW REGIONS FROM CLUSTER]")
}
func (og *operationGenerator) getDatabaseRegionNames(
ctx context.Context, tx pgx.Tx,
) (catpb.RegionNames, error) {
return og.scanRegionNames(ctx, tx, "SELECT region FROM [SHOW REGIONS FROM DATABASE]")
}
func (og *operationGenerator) getDatabase(ctx context.Context, tx pgx.Tx) (string, error) {
var database string
err := tx.QueryRow(ctx, "SHOW DATABASE").Scan(&database)
og.LogQueryResults("SHOW DATABASE", database)
return database, err
}
type getRegionsResult struct {
regionNamesInDatabase catpb.RegionNames
regionNamesInCluster catpb.RegionNames
regionNamesNotInDatabase catpb.RegionNames
}
func (og *operationGenerator) getRegions(ctx context.Context, tx pgx.Tx) (getRegionsResult, error) {
regionNamesInCluster, err := og.getClusterRegionNames(ctx, tx)
if err != nil {
return getRegionsResult{}, err
}
regionNamesNotInDatabaseSet := make(map[catpb.RegionName]struct{}, len(regionNamesInCluster))
for _, clusterRegionName := range regionNamesInCluster {
regionNamesNotInDatabaseSet[clusterRegionName] = struct{}{}
}
regionNamesInDatabase, err := og.getDatabaseRegionNames(ctx, tx)
if err != nil {
return getRegionsResult{}, err
}
for _, databaseRegionName := range regionNamesInDatabase {
delete(regionNamesNotInDatabaseSet, databaseRegionName)
}
regionNamesNotInDatabase := make(catpb.RegionNames, 0, len(regionNamesNotInDatabaseSet))
for regionName := range regionNamesNotInDatabaseSet {
regionNamesNotInDatabase = append(regionNamesNotInDatabase, regionName)
}
return getRegionsResult{
regionNamesInDatabase: regionNamesInDatabase,
regionNamesInCluster: regionNamesInCluster,
regionNamesNotInDatabase: regionNamesNotInDatabase,
}, nil
}
func (og *operationGenerator) scanRegionNames(
ctx context.Context, tx pgx.Tx, query string,
) (catpb.RegionNames, error) {
var regionNames catpb.RegionNames
var regionNamesForLog []string
rows, err := tx.Query(ctx, query)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var regionName catpb.RegionName
if err := rows.Scan(®ionName); err != nil {
return nil, err
}
regionNames = append(regionNames, regionName)
regionNamesForLog = append(regionNamesForLog, regionName.String())
}
if rows.Err() != nil {
return nil, errors.Wrapf(rows.Err(), "failed to get regions: %s", query)
}
og.LogQueryResultArray(query, regionNamesForLog)
return regionNames, nil
}
func (og *operationGenerator) addRegion(ctx context.Context, tx pgx.Tx) (*opStmt, error) {
regionResult, err := og.getRegions(ctx, tx)
if err != nil {
return nil, err
}
database, err := og.getDatabase(ctx, tx)
if err != nil {
return nil, err
}
// No regions in cluster, try add an invalid region and expect an error.
if len(regionResult.regionNamesInCluster) == 0 {
return makeOpStmtForSingleError(OpStmtDDL,
fmt.Sprintf(`ALTER DATABASE %s ADD REGION "invalid-region"`, database),
pgcode.InvalidDatabaseDefinition), nil
}
// No regions in database, add a random region from the cluster and expect an error.
if len(regionResult.regionNamesInDatabase) == 0 {
idx := og.params.rng.Intn(len(regionResult.regionNamesInCluster))
return makeOpStmtForSingleError(OpStmtDDL,
fmt.Sprintf(
`ALTER DATABASE %s ADD REGION "%s"`,
database,
regionResult.regionNamesInCluster[idx],
),
pgcode.InvalidDatabaseDefinition), nil
}
// If the database is undergoing a regional by row related change on the
// database, error out.
if len(regionResult.regionNamesInDatabase) > 0 {
databaseHasRegionalByRowChange, err := og.databaseHasRegionalByRowChange(ctx, tx)
if err != nil {
return nil, err
}
if databaseHasRegionalByRowChange {
// There's a timing hole here, as by the time we issue the ADD
// REGION statement, the above REGIONAL BY ROW change may have
// already completed. Either way, we'll get one of the following
// two errors (the first, if the schema change has completed, and
// the second, if it has not).
return makeOpStmtForSingleError(OpStmtDDL,
fmt.Sprintf(`ALTER DATABASE %s ADD REGION "invalid-region"`, database),
pgcode.InvalidName,
pgcode.ObjectNotInPrerequisiteState), nil
}
}
// All regions are already in the database, expect an error with adding an existing one.
if len(regionResult.regionNamesNotInDatabase) == 0 {
idx := og.params.rng.Intn(len(regionResult.regionNamesInDatabase))
return makeOpStmtForSingleError(OpStmtDDL,
fmt.Sprintf(
`ALTER DATABASE %s ADD REGION "%s"`,
database,
regionResult.regionNamesInDatabase[idx],
),
pgcode.DuplicateObject), nil
}
// Here we have a region that is not yet marked as public on the enum.
// Double check this first.
stmt := makeOpStmt(OpStmtDDL)
idx := og.params.rng.Intn(len(regionResult.regionNamesNotInDatabase))
region := regionResult.regionNamesNotInDatabase[idx]
valuePresent, err := og.enumMemberPresent(ctx, tx, tree.RegionEnum, string(region))
if err != nil {
return nil, err
}
if valuePresent {
stmt.expectedExecErrors.add(pgcode.DuplicateObject)
}
stmt.sql = fmt.Sprintf(
`ALTER DATABASE %s ADD REGION "%s"`,
database,
region,
)
return stmt, nil
}
func (og *operationGenerator) primaryRegion(ctx context.Context, tx pgx.Tx) (*opStmt, error) {
regionResult, err := og.getRegions(ctx, tx)
if err != nil {
return nil, err
}
database, err := og.getDatabase(ctx, tx)
if err != nil {
return nil, err
}
// No regions in cluster, try PRIMARY REGION an invalid region and expect an error.
if len(regionResult.regionNamesInCluster) == 0 {
return makeOpStmtForSingleError(OpStmtDDL,
fmt.Sprintf(`ALTER DATABASE %s PRIMARY REGION "invalid-region"`, database),
pgcode.InvalidDatabaseDefinition), nil
}
// Conversion to multi-region is only allowed if the data is not already
// partitioned.
stmt := makeOpStmt(OpStmtDDL)
hasPartitioning, err := og.databaseHasTablesWithPartitioning(ctx, tx, database)
if err != nil {
return nil, err
}
if hasPartitioning {
stmt.expectedExecErrors.add(pgcode.ObjectNotInPrerequisiteState)
}
// No regions in database, set a random region to be the PRIMARY REGION.
if len(regionResult.regionNamesInDatabase) == 0 {
idx := og.params.rng.Intn(len(regionResult.regionNamesInCluster))
stmt.sql = fmt.Sprintf(
`ALTER DATABASE %s PRIMARY REGION "%s"`,
database,
regionResult.regionNamesInCluster[idx],
)
return stmt, nil
}
// Regions exist in database, so set a random region to be the primary region.
idx := og.params.rng.Intn(len(regionResult.regionNamesInDatabase))
stmt.sql = fmt.Sprintf(
`ALTER DATABASE %s PRIMARY REGION "%s"`,
database,
regionResult.regionNamesInDatabase[idx],
)
return stmt, nil
}
func (og *operationGenerator) addForeignKeyConstraint(
ctx context.Context, tx pgx.Tx,
) (*opStmt, error) {
parentTable, parentColumn, err := og.randParentColumnForFkRelation(ctx, tx, og.randIntn(100) >= og.params.fkParentInvalidPct)
if err != nil {
return nil, err
}
fetchInvalidChild := og.randIntn(100) < og.params.fkChildInvalidPct
// Potentially create an error by choosing the wrong type for the child column.
childType := parentColumn.typ
if fetchInvalidChild {
_, typ, err := og.randType(ctx, tx, og.pctExisting(true))
if err != nil {
return nil, err
}
if typ != nil {
childType = typ
}
}
childTable, childColumn, err := og.randChildColumnForFkRelation(ctx, tx, !fetchInvalidChild, childType.SQLString())
if err != nil {
return nil, err
}
constraintName := tree.Name(fmt.Sprintf("%s_%s_%s_%s_fk", parentTable.Object(), parentColumn.name, childTable.Object(), childColumn.name))
def := &tree.AlterTable{
Table: childTable.ToUnresolvedObjectName(),
Cmds: tree.AlterTableCmds{
&tree.AlterTableAddConstraint{
ConstraintDef: &tree.ForeignKeyConstraintTableDef{
Name: constraintName,
Table: *parentTable,
FromCols: tree.NameList{tree.Name(childColumn.name)},
ToCols: tree.NameList{tree.Name(parentColumn.name)},
Actions: tree.ReferenceActions{
Update: tree.Cascade,
Delete: tree.Cascade,
},
},
ValidationBehavior: tree.ValidationDefault,
},
},
}
parentColumnHasUniqueConstraint, err := og.columnHasSingleUniqueConstraint(ctx, tx, parentTable, parentColumn.name)
if err != nil {
return nil, err
}
parentColumnIsVirtualComputed, err := og.columnIsVirtualComputed(ctx, tx, parentTable, parentColumn.name)
if err != nil {
return nil, err
}
childColumnIsVirtualComputed, err := og.columnIsVirtualComputed(ctx, tx, childTable, childColumn.name)
if err != nil {
return nil, err
}
childColumnIsStoredVirtual, err := og.columnIsStoredComputed(ctx, tx, childTable, childColumn.name)
if err != nil {
return nil, err
}
constraintExists, err := og.constraintExists(ctx, tx, string(constraintName))
if err != nil {
return nil, err
}
// If we are intentionally using an invalid child type, then it doesn't make
// sense to validate if the rows validate the constraint.
rowsSatisfyConstraint := true
if !fetchInvalidChild {
rowsSatisfyConstraint, err = og.rowsSatisfyFkConstraint(ctx, tx, parentTable, parentColumn, childTable, childColumn)
if err != nil {
return nil, err
}
}
stmt := makeOpStmt(OpStmtDDL)
codesWithConditions{
{code: pgcode.ForeignKeyViolation, condition: !parentColumnHasUniqueConstraint},
{code: pgcode.FeatureNotSupported, condition: childColumnIsVirtualComputed},
{code: pgcode.FeatureNotSupported, condition: childColumnIsStoredVirtual},
{code: pgcode.FeatureNotSupported, condition: parentColumnIsVirtualComputed},
{code: pgcode.DuplicateObject, condition: constraintExists},
{code: pgcode.DatatypeMismatch, condition: !childColumn.typ.Equivalent(parentColumn.typ)},
}.add(stmt.expectedExecErrors)
codesWithConditions{}.add(og.expectedCommitErrors)
// TODO(fqazi): We need to do after the fact validation for foreign key violations
// errors. Due to how adding foreign key constraints are implemented with a
// separate job validating the constraint, we can't at transaction time predict,
// perfectly if an error is expected. We can confirm post transaction with a time
// travel query.
_ = rowsSatisfyConstraint
og.potentialExecErrors.add(pgcode.ForeignKeyViolation)
og.potentialCommitErrors.add(pgcode.ForeignKeyViolation)
// It's possible for the table to be dropped concurrently, while we are running
// validation. In which case a potential commit error is an undefined table
// error.
og.potentialCommitErrors.add(pgcode.UndefinedTable)
stmt.sql = tree.Serialize(def)
return stmt, nil
}
func (og *operationGenerator) createIndex(ctx context.Context, tx pgx.Tx) (*opStmt, error) {
tableName, err := og.randTable(ctx, tx, og.pctExisting(true), "")
if err != nil {
return nil, err
}
tableExists, err := og.tableExists(ctx, tx, tableName)
if err != nil {
return nil, err
}
if !tableExists {
def := &tree.CreateIndex{
Name: tree.Name("IrrelevantName"),
Table: *tableName,
Columns: tree.IndexElemList{
{Column: "IrrelevantColumn", Direction: tree.Ascending},
},
}
return makeOpStmtForSingleError(OpStmtDDL,
tree.Serialize(def),
pgcode.UndefinedTable), nil
}
err = og.tableHasPrimaryKeySwapActive(ctx, tx, tableName)
if err != nil {
return nil, err
}
columnNames, err := og.getTableColumns(ctx, tx, tableName.String(), true)
if err != nil {
return nil, err
}
indexName, err := og.randIndex(ctx, tx, *tableName, og.pctExisting(false))
if err != nil {
return nil, err
}
indexExists, err := og.indexExists(ctx, tx, tableName, indexName)
if err != nil {
return nil, err
}
def := &tree.CreateIndex{
Name: tree.Name(indexName),
Table: *tableName,
Unique: og.randIntn(4) == 0, // 25% UNIQUE
Inverted: og.randIntn(10) == 0, // 10% INVERTED
IfNotExists: og.randIntn(2) == 0, // 50% IF NOT EXISTS
NotVisible: og.randIntn(20) == 0, // 5% NOT VISIBLE
}
regionColumn := ""
tableIsRegionalByRow, err := og.tableIsRegionalByRow(ctx, tx, tableName)
if err != nil {
return nil, err
}
if tableIsRegionalByRow {
regionColumn, err = og.getRegionColumn(ctx, tx, tableName)
if err != nil {
return nil, err
}
}
// Define columns on which to create an index. Check for types which cannot be indexed.
duplicateRegionColumn := false
nonIndexableType := false
def.Columns = make(tree.IndexElemList, 1+og.randIntn(len(columnNames)))
for i := range def.Columns {
def.Columns[i].Column = tree.Name(columnNames[i].name)
def.Columns[i].Direction = tree.Direction(og.randIntn(1 + int(tree.Descending)))
// When creating an index, the column being used as the region column
// for a REGIONAL BY ROW table can only be included in indexes as the
// first column. If it's not the first column, we need to add an error
// below.
if columnNames[i].name == regionColumn && i != 0 {
duplicateRegionColumn = true
}
if def.Inverted {
// We can have an inverted index on a set of columns if the last column
// is an inverted indexable type and the preceding columns are not.
invertedIndexableType := colinfo.ColumnTypeIsInvertedIndexable(columnNames[i].typ)
if (invertedIndexableType && i < len(def.Columns)-1) ||
(!invertedIndexableType && i == len(def.Columns)-1) {
nonIndexableType = true
}
} else {
if !colinfo.ColumnTypeIsIndexable(columnNames[i].typ) {
nonIndexableType = true
}
}
}
// If there are extra columns not used in the index, randomly use them
// as stored columns.
stmt := makeOpStmt(OpStmtDDL)
duplicateStore := false
virtualComputedStored := false
regionColStored := false
columnNames = columnNames[len(def.Columns):]
if n := len(columnNames); n > 0 {
def.Storing = make(tree.NameList, og.randIntn(1+n))
for i := range def.Storing {
def.Storing[i] = tree.Name(columnNames[i].name)
// The region column can not be stored.