/
ddl_vertical.rs
1250 lines (1174 loc) · 50.7 KB
/
ddl_vertical.rs
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
//! This test suite implements the [Replicator Vertical Testing Doc][doc].
//!
//! [doc]: https://docs.google.com/document/d/1GRYV7okEzz2T-KuF06M5Y4EkyRv7euMSb1viroT9JTk
//!
//! Note that this test suite is ignored by default, and conditionally de-ignored with the
//! `ddl_vertical_tests` feature to prevent it running in normal builds (since it's slow and may
//! find new bugs); to run it locally run:
//!
//! ```notrust
//! cargo test -p replicators --features ddl_vertical_tests --test ddl_vertical
//! ```
//!
//! This test suite will connect to a local Postgres database, which can be set up with all the
//! correct configuration using the `docker-compose.yml` and `docker-compose.override.example.yml`
//! in the root of the repository. To run that Postgres database, run:
//!
//! ```notrust
//! $ cp docker-compose.override.example.yml docker-compose.yml
//! $ docker-compose up -d postgres
//! ```
//!
//! Note that this test suite requires the *exact* configuration specified in that docker-compose
//! configuration, including the port, username, and password.
use std::cell::RefCell;
use std::collections::{BTreeMap, HashSet};
use std::fmt::{Debug, Display, Formatter, Result};
use std::iter::once;
use std::panic::AssertUnwindSafe;
use std::time::Duration;
use async_trait::async_trait;
use itertools::Itertools;
use nom_sql::{DialectDisplay, SqlType};
use proptest::prelude::*;
use proptest::strategy::{BoxedStrategy, Just, Strategy};
use proptest::{collection, sample};
use proptest_stateful::{
proptest_config_with_local_failure_persistence, ModelState, ProptestStatefulConfig,
};
use readyset_client::SingleKeyEviction;
use readyset_client_test_helpers::psql_helpers::{self, PostgreSQLAdapter};
use readyset_client_test_helpers::TestBuilder;
use readyset_data::{DfValue, TimestampTz};
use readyset_server::Handle;
use readyset_util::eventually;
use readyset_util::shutdown::ShutdownSender;
use tokio_postgres::config::Host;
use tokio_postgres::{Client, Config, NoTls, Row};
const SQL_NAME_REGEX: &str = "[a-zA-Z_][a-zA-Z0-9_]*";
/// This struct is used to generate arbitrary column specifications, both for creating tables, and
/// potentially for altering them by adding columns and such.
#[derive(Clone)]
struct ColumnSpec {
name: String,
sql_type: SqlType,
gen: BoxedStrategy<DfValue>,
}
// The debug output for the generators can be really verbose and is usually not helpful, so we
// custom derive Debug to skip that part:
impl Debug for ColumnSpec {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
f.debug_struct("ColumnSpec")
.field("name", &self.name)
.field("sql_type", &self.sql_type)
.finish()
}
}
impl Arbitrary for ColumnSpec {
type Parameters = BTreeMap<String, Vec<String>>;
type Strategy = BoxedStrategy<Self>;
fn arbitrary_with(enum_types: Self::Parameters) -> Self::Strategy {
let name_gen = SQL_NAME_REGEX
.prop_filter("Can't generate additional columns named \"id\"", |s| {
s.to_lowercase() != "id"
});
let mut col_types = vec![
(
SqlType::Int(None),
any::<i32>().prop_map(DfValue::from).boxed(),
),
(
SqlType::Real,
any::<f32>()
// unwrap is fine because the f32 Arbitrary impl only yields finite values
.prop_map(|f| DfValue::try_from(f).unwrap())
.boxed(),
),
(
SqlType::VarChar(None),
any::<String>().prop_map(DfValue::from).boxed(),
),
(
SqlType::TimestampTz,
any::<TimestampTz>().prop_map(DfValue::TimestampTz).boxed(),
),
];
let enum_col_types: Vec<_> = enum_types
.into_iter()
.map(|(name, values)| {
(
// We use SqlType::Other instead of SqlType::Enum because we want to refer
// directly to the named enum type when we use this SqlType value to create a
// column definition in the corresponding CREATE TABLE statement:
SqlType::Other(name.into()),
sample::select(values).prop_map(DfValue::from).boxed(),
)
})
.collect();
col_types.extend_from_slice(&enum_col_types);
(name_gen, sample::select(col_types))
.prop_map(|(name, (sql_type, gen))| ColumnSpec {
name,
sql_type,
gen,
})
.boxed()
}
}
/// Used for the [`Operation::InsertEnumValue`] variant to specify where to add the new enum value.
#[derive(test_strategy::Arbitrary, Clone, Debug)]
enum EnumPos {
Before,
After,
}
impl Display for EnumPos {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
match self {
EnumPos::Before => f.write_str("BEFORE"),
EnumPos::After => f.write_str("AFTER"),
}
}
}
/// Each Operation represents one step to take in a given test run.
#[derive(Clone, Debug)]
enum Operation {
/// Create a new table with the given name and columns
CreateTable(String, Vec<ColumnSpec>),
/// Drop the table with the given name
DropTable(String),
/// Write a random row to a random table with the given primary key
/// (The [`SqlTypes`] values are just to check preconditions so that we don't try to write a
/// row to a table whose column types don't match the row we originally generated.)
WriteRow {
table: String,
pkey: i32,
col_vals: Vec<DfValue>,
col_types: Vec<SqlType>,
},
/// Delete rows to a given table that match a given key
DeleteRow(String, i32),
/// Adds a new column to an existing table
AddColumn(String, ColumnSpec),
/// Removes a column from an existing table
DropColumn(String, String),
/// Alters a column to a different name
AlterColumnName {
table: String,
col_name: String,
new_name: String,
},
/// Creates a simple view that does a SELECT * on a given table
CreateSimpleView { name: String, table_source: String },
/// Creates a view that does a SELECT * on a JOIN of two tables
CreateJoinView {
name: String,
table_a: String,
table_b: String,
},
/// Drops the view with the given name
DropView(String),
/// Creates an ENUM type with the given name and values
CreateEnum(String, Vec<String>),
/// Drops an ENUM type with the given name
DropEnum(String),
/// Adds a value to the end of an existing ENUM type with the given names
AppendEnumValue {
type_name: String,
value_name: String,
},
InsertEnumValue {
type_name: String,
value_name: String,
position: EnumPos,
next_to_value: String,
},
/// Renames an existing ENUM type value
RenameEnumValue {
type_name: String,
value_name: String,
new_name: String,
},
/// This operation triggers an eviction of a single key in ReadySet, using `inner` as the
/// payload for the /evict_single RPC.
///
/// The payload is initialized to `None`, which triggers a random eviction the first time this
/// operation is run. `inner` is then updated with the `SingleKeyResult` returned by the
/// /evict_single RPC, so that if this operation is run again, we can trigger the same eviction
/// again. This behavior is necessary to ensure consistent results when attempting to reproduce
/// a failing test case.
Evict {
inner: RefCell<Option<SingleKeyEviction>>,
},
}
/// Returns an iterator that yields names of tables that use the given type.
fn tables_using_type<'a>(
tables: &'a BTreeMap<String, Vec<ColumnSpec>>,
type_name: &'a str,
) -> impl Iterator<Item = &'a str> {
tables.iter().filter_map(move |(name, columns)| {
if columns.iter().any(|cs| cs.name == type_name) {
Some(name.as_str())
} else {
None
}
})
}
// Generators for Operation:
fn gen_column_specs(
enum_types: BTreeMap<String, Vec<String>>,
) -> impl Strategy<Value = Vec<ColumnSpec>> {
collection::vec(any_with::<ColumnSpec>(enum_types), 1..4)
.prop_filter("duplicate column names not allowed", |specs| {
specs.iter().map(|cs| &cs.name).all_unique()
})
}
prop_compose! {
fn gen_enum_values()(values in collection::hash_set(SQL_NAME_REGEX, 1..4)) -> Vec<String> {
let mut res = values.into_iter().collect::<Vec<_>>();
res.sort();
res
}
}
prop_compose! {
fn gen_create_table(enum_types: BTreeMap<String, Vec<String>>)
(name in SQL_NAME_REGEX, cols in gen_column_specs(enum_types))
-> Operation {
Operation::CreateTable(name, cols)
}
}
prop_compose! {
fn gen_drop_table(tables: Vec<String>)(t in sample::select(tables)) -> Operation {
Operation::DropTable(t)
}
}
prop_compose! {
fn gen_write_row(tables: BTreeMap<String, Vec<ColumnSpec>>, pkeys: BTreeMap<String, Vec<i32>>)
(t in sample::select(tables.keys().cloned().collect::<Vec<_>>()))
(col_vals in tables[&t].iter().map(|cs| cs.gen.clone()).collect::<Vec<_>>(),
col_types in Just(tables[&t].iter().map(|cs| cs.sql_type.clone()).collect()),
table in Just(t))
-> Operation {
let table_keys = &pkeys[&table];
// Find the first unused key:
let pkey = (0..).find(|k| !table_keys.contains(k)).unwrap();
Operation::WriteRow { table, pkey, col_vals, col_types }
}
}
prop_compose! {
fn gen_add_col_unfiltered(tables: Vec<String>)
(t in sample::select(tables), col in any::<ColumnSpec>())
-> Operation {
Operation::AddColumn(t, col)
}
}
fn gen_add_col(tables: BTreeMap<String, Vec<ColumnSpec>>) -> impl Strategy<Value = Operation> {
gen_add_col_unfiltered(tables.keys().cloned().collect()).prop_filter(
"Can't add a new column with a duplicate name",
move |op| match op {
Operation::AddColumn(table, new_cs) => {
new_cs.name != "id"
&& !tables[table]
.iter()
.any(|table_cs| new_cs.name.eq_ignore_ascii_case(&table_cs.name))
}
_ => unreachable!(),
},
)
}
fn gen_non_id_col_name() -> impl Strategy<Value = String> {
SQL_NAME_REGEX.prop_filter("Can't generate additional columns named \"id\"", |s| {
s.to_lowercase() != "id"
})
}
prop_compose! {
fn gen_rename_col(tables: BTreeMap<String, Vec<ColumnSpec>>, tables_with_cols: Vec<String>)
(table in sample::select(tables_with_cols))
(col_name in sample::select(
tables[&table]
.iter()
.map(|cs| cs.name.clone())
.collect::<Vec<_>>()),
new_name in gen_non_id_col_name(),
table in Just(table))
-> Operation {
Operation::AlterColumnName { table, col_name, new_name }
}
}
prop_compose! {
fn gen_drop_col(tables: BTreeMap<String, Vec<ColumnSpec>>, tables_with_cols: Vec<String>)
(table in sample::select(tables_with_cols))
(col_name in sample::select(
tables[&table]
.iter()
.map(|cs| cs.name.clone())
.collect::<Vec<_>>()),
table in Just(table))
-> Operation {
Operation::DropColumn(table, col_name)
}
}
prop_compose! {
fn gen_delete_row(non_empty_tables: Vec<String>, pkeys: BTreeMap<String, Vec<i32>>)
(table in sample::select(non_empty_tables))
(key in sample::select(pkeys[&table].clone()),
table in Just(table))
-> Operation {
Operation::DeleteRow(table, key)
}
}
prop_compose! {
fn gen_create_simple_view(tables: Vec<String>)
(name in SQL_NAME_REGEX,
table_source in sample::select(tables))
-> Operation {
Operation::CreateSimpleView { name, table_source }
}
}
prop_compose! {
fn gen_create_join_view(tables: Vec<String>)
(name in SQL_NAME_REGEX,
source_tables in sample::subsequence(tables, 2..=2))
-> Operation {
let table_a = source_tables[0].clone();
let table_b = source_tables[1].clone();
Operation::CreateJoinView { name, table_a, table_b }
}
}
prop_compose! {
fn gen_drop_view(views: Vec<String>)(name in sample::select(views)) -> Operation {
Operation::DropView(name)
}
}
prop_compose! {
fn gen_create_enum()
(name in SQL_NAME_REGEX, values in gen_enum_values().prop_shuffle())
-> Operation {
Operation::CreateEnum(name, values)
}
}
prop_compose! {
fn gen_drop_enum(enum_types: Vec<String>)(name in sample::select(enum_types)) -> Operation {
Operation::DropEnum(name)
}
}
fn gen_append_enum_value(
enum_types: BTreeMap<String, Vec<String>>,
) -> impl Strategy<Value = Operation> {
gen_append_enum_value_inner(enum_types.keys().cloned().collect()).prop_filter(
"Can't add duplicate value to existing ENUM type",
move |op| match op {
Operation::AppendEnumValue {
type_name,
value_name,
} => !enum_types[type_name].contains(value_name),
_ => unreachable!(),
},
)
}
prop_compose! {
fn gen_append_enum_value_inner(enum_type_names: Vec<String>)
(type_name in sample::select(enum_type_names),
value_name in SQL_NAME_REGEX)
-> Operation {
Operation::AppendEnumValue { type_name, value_name }
}
}
prop_compose! {
fn gen_insert_enum_value(enum_types: BTreeMap<String, Vec<String>>)
(et in sample::select(enum_types.keys().cloned().collect::<Vec<_>>()))
(next_to_value in sample::select(enum_types[&et].clone()),
type_name in Just(et),
position in any::<EnumPos>(),
value_name in SQL_NAME_REGEX)
-> Operation {
Operation::InsertEnumValue { type_name, value_name, position, next_to_value }
}
}
prop_compose! {
fn gen_rename_enum_value(enum_types: BTreeMap<String, Vec<String>>)
(et in sample::select(enum_types.keys().cloned().collect::<Vec<_>>()))
(value_name in sample::select(enum_types[&et].clone()),
type_name in Just(et),
new_name in SQL_NAME_REGEX)
-> Operation {
Operation::RenameEnumValue { type_name, value_name, new_name }
}
}
/// A definition for a test view. Currently one of:
/// - Simple (SELECT * FROM table)
/// - Join (SELECT * FROM table_a JOIN table_b ON table_a.id = table_b.id)
#[derive(Clone, Debug)]
enum TestViewDef {
Simple(String),
Join { table_a: String, table_b: String },
}
struct DDLTestRunContext {
rs_host: String,
rs_conn: Client,
pg_conn: Client,
shutdown_tx: Option<ShutdownSender>, // Needs to be Option so we can move it out of the struct
_handle: Handle,
}
/// A model of the current test state, used to help generate operations in a way that we expect to
/// succeed, as well as to assist in shrinking, and to determine postconditions to check during
/// test runtime.
///
/// Initially we assume an empty database, but as operations are generated, tracking their expected
/// results helps inform which operations we are able to test further along in the test case. For
/// example, when writing a row, we must pick a table to write the row to, so we must look at the
/// model state to see what tables have been previously created. We don't actually run a test case
/// until all the steps have been generated, so [`DDLModelState`] allows us to simulate the
/// expected state of the system for a given test case without having to actually run any of the
/// steps against the system under test.
#[derive(Clone, Debug, Default)]
struct DDLModelState {
// We use BTreeMap instead of HashMap so that the `keys()` method gives us a deterministic
// ordering, which allows us to reliably regenerate the same test case for a given seed.
tables: BTreeMap<String, Vec<ColumnSpec>>,
deleted_tables: HashSet<String>,
pkeys: BTreeMap<String, Vec<i32>>, // Primary keys in use for each table
// Map of view name to view definition
views: BTreeMap<String, TestViewDef>,
deleted_views: HashSet<String>,
// Map of custom ENUM type names to type definitions (represented by a Vec of ENUM elements)
enum_types: BTreeMap<String, Vec<String>>,
}
#[async_trait(?Send)]
impl ModelState for DDLModelState {
type Operation = Operation;
type RunContext = DDLTestRunContext;
type OperationStrategy = BoxedStrategy<Operation>;
/// Each invocation of this function returns a [`Vec`] of [`Strategy`]s for generating
/// [`Operation`]s *given the current state of the test model*. With a brand new model, the only
/// possible operations are [`Operation::CreateTable`] and [`Operation::CreateEnum`], but as
/// tables/types are created and rows are written, other operations become possible.
///
/// Note that there is some redundancy between the logic in this function and the logic in
/// [`Operation::preconditions`](enum.Operation.html#method.preconditions). This is necessary
/// because `gen_op` is used for the initial test generation, but the preconditions are used
/// during shrinking. (Technically, we do also check and filter on preconditions at the start
/// of each test, but it's best to depend on that check as little as possible since test
/// filters like that can lead to slow and lopsided test generation.)
fn op_generators(&self) -> Vec<Self::OperationStrategy> {
// We can always create more tables or enum types, so start with those two generators:
let create_table_strat = gen_create_table(self.enum_types.clone()).boxed();
let create_enum_strat = gen_create_enum().boxed();
// We can also always try to issue an eviction:
let evict_strategy = Just(Operation::Evict {
inner: RefCell::new(None),
})
.boxed();
let mut possible_ops = vec![create_table_strat, create_enum_strat, evict_strategy];
// If we have at least one table, we can do any of:
// * delete a table
// * write a row
// * add a column
// * create a simple view
if !self.tables.is_empty() {
let drop_strategy = gen_drop_table(self.tables.keys().cloned().collect()).boxed();
let write_strategy = gen_write_row(self.tables.clone(), self.pkeys.clone()).boxed();
let add_col_strat = gen_add_col(self.tables.clone()).boxed();
let create_simple_view_strat =
gen_create_simple_view(self.tables.keys().cloned().collect()).boxed();
possible_ops.extend([
drop_strategy,
write_strategy,
add_col_strat,
create_simple_view_strat,
]);
}
// If we have at least two tables, we can create a join view:
if self.tables.len() > 1 {
let create_join_view_strat =
gen_create_join_view(self.tables.keys().cloned().collect()).boxed();
possible_ops.push(create_join_view_strat);
}
// If we have at least one view in existence, we can drop one:
if !self.views.is_empty() {
let drop_view_strategy = gen_drop_view(self.views.keys().cloned().collect()).boxed();
possible_ops.push(drop_view_strategy);
}
// If we have a table with at least one (non-pkey) column, we can rename or drop a column:
let tables_with_cols: Vec<String> = self
.tables
.iter()
.filter_map(|(table, columns)| {
if columns.is_empty() {
None
} else {
Some(table)
}
})
.cloned()
.collect();
if !tables_with_cols.is_empty() {
// This is cloned so that we can move it into the closures for rename_col_strat:
let rename_col_strat =
gen_rename_col(self.tables.clone(), tables_with_cols.clone()).boxed();
possible_ops.push(rename_col_strat);
let _drop_col_strategy = gen_drop_col(self.tables.clone(), tables_with_cols).boxed();
// Commented out for now because this triggers ENG-2548
// possible_ops.push(drop_col_strategy);
}
// If we have at least one row written to a table, we can generate delete ops:
let non_empty_tables: Vec<String> = self
.pkeys
.iter()
.filter_map(|(table, pkeys)| {
if !pkeys.is_empty() {
Some(table.clone())
} else {
None
}
})
.collect();
if !non_empty_tables.is_empty() {
let delete_strategy = gen_delete_row(non_empty_tables, self.pkeys.clone()).boxed();
possible_ops.push(delete_strategy);
}
// If we have at least one enum type created, we can add a value or rename a value
if !self.enum_types.is_empty() {
let append_enum_value_strat = gen_append_enum_value(self.enum_types.clone()).boxed();
possible_ops.push(append_enum_value_strat);
let insert_enum_value_strat = gen_insert_enum_value(self.enum_types.clone()).boxed();
possible_ops.push(insert_enum_value_strat);
let _rename_enum_value_strat = gen_rename_enum_value(self.enum_types.clone()).boxed();
// TODO uncomment after ENG-2823 is fixed
//possible_ops.push(rename_enum_value_strat);
}
// If we have at least one enum type created, and no table is using it, we can drop an enum
let unused_enums: Vec<String> = self
.enum_types
.keys()
.filter_map(|name| {
if !self.tables.values().any(|columns| {
columns
.iter()
.any(|cs| cs.sql_type == SqlType::Other(name.into()))
}) {
Some(name.clone())
} else {
None
}
})
.collect();
if !unused_enums.is_empty() {
let drop_enum_strat = gen_drop_enum(unused_enums).boxed();
possible_ops.push(drop_enum_strat);
}
possible_ops
}
/// This method is used to update `self` based on the expected results of executing a single
/// [`Operation`]. It is used during test generation, but notably, we repeat the same sequence
/// of state updates at runtime since we depend on the current state of the model to check
/// postconditions when we're actually executing a given test case.
///
/// In theory we could choose to only run through the sequence of `next_state` calls once at
/// test generation time, and save each intermediate state for use at runtime, but that would
/// be more complex to implement and it's questionable whether it would actually be more
/// efficient. Additionally, if we ever want to add symbolic placeholders to the state (for
/// representing return values of operations at runtime) then the runtime state will actually
/// differ from the generation-time state, and running through the sequence of `next_state`
/// calls two separate times will become strictly necessary as a result.
fn next_state(&mut self, op: &Operation) {
match op {
Operation::CreateTable(name, cols) => {
self.tables.insert(name.clone(), cols.clone());
self.pkeys.insert(name.clone(), vec![]);
self.deleted_tables.remove(name);
// Also remove the name from deleted_views if it exists, since we should no longer
// expect "SELECT * FROM name" to return an error and can stop checking that
// postcondition:
self.deleted_views.remove(name);
}
Operation::DropTable(name) => {
self.tables.remove(name);
self.deleted_tables.insert(name.clone());
self.pkeys.remove(name);
self.views.retain(|_view_name, view_def| match view_def {
TestViewDef::Simple(table_source) => name != table_source,
TestViewDef::Join { table_a, table_b } => name != table_a && name != table_b,
});
}
Operation::WriteRow { table, pkey, .. } => {
self.pkeys.get_mut(table).unwrap().push(*pkey);
}
Operation::AddColumn(table, col_spec) => {
let col_specs = self.tables.get_mut(table).unwrap();
col_specs.push(col_spec.clone());
}
Operation::DropColumn(table, col_name) => {
let col_specs = self.tables.get_mut(table).unwrap();
col_specs.retain(|cs| cs.name != *col_name);
}
Operation::AlterColumnName {
table,
col_name,
new_name,
} => {
let col_specs = self.tables.get_mut(table).unwrap();
let spec = col_specs
.iter_mut()
.find(|cs| cs.name == *col_name)
.unwrap();
spec.name = new_name.clone();
}
Operation::DeleteRow(..) => (),
Operation::CreateSimpleView { name, table_source } => {
self.views
.insert(name.clone(), TestViewDef::Simple(table_source.clone()));
self.deleted_views.remove(name);
// Also remove the name from deleted_tables if it exists, since we should no longer
// expect "SELECT * FROM name" to return an error and can stop checking that
// postcondition:
self.deleted_tables.remove(name);
}
Operation::CreateJoinView {
name,
table_a,
table_b,
} => {
let table_a = table_a.clone();
let table_b = table_b.clone();
let view_def = TestViewDef::Join { table_a, table_b };
self.views.insert(name.clone(), view_def);
self.deleted_views.remove(name);
// See comment in CreateSimpleView clause above for why this is needed:
self.deleted_tables.remove(name);
}
Operation::DropView(name) => {
self.views.remove(name);
self.deleted_views.insert(name.clone());
}
Operation::CreateEnum(name, values) => {
self.enum_types.insert(name.clone(), values.clone());
}
Operation::DropEnum(name) => {
self.enum_types.remove(name);
}
Operation::AppendEnumValue {
type_name,
value_name,
} => {
self.enum_types
.get_mut(type_name)
.unwrap()
.push(value_name.clone());
}
Operation::InsertEnumValue {
type_name,
value_name,
position,
next_to_value,
} => {
let type_values = self.enum_types.get_mut(type_name).unwrap();
let next_to_idx = type_values.iter().position(|v| v == next_to_value).unwrap();
let insert_idx = match position {
EnumPos::Before => next_to_idx,
EnumPos::After => next_to_idx + 1,
};
type_values.insert(insert_idx, value_name.clone());
}
Operation::RenameEnumValue {
type_name,
value_name,
new_name,
} => {
let val_ref = self
.enum_types
.get_mut(type_name)
.unwrap()
.iter_mut()
.find(|v| *v == value_name)
.unwrap();
*val_ref = new_name.clone();
}
Operation::Evict { .. } => (),
}
}
/// Checks preconditions for an [`Operation`] given a current test model state.
///
/// These are primarily needed for shrinking, so that we can make sure that we don't do things
/// like remove a [`Operation::CreateTable`] when a later [`Operation::WriteRow`] operation
/// depends on the corresponding table.
///
/// We also check preconditions during runtime, and throw out any test cases where the
/// preconditions aren't satisfied. This should be rare, though, because
/// [`DDLModelState::op_generators`] should *usually* only generate cases where the
/// preconditions are already satisfied. It's possible there are weird corner cases though
/// (such as multiple random strings happening to generate the same string value for two
/// different table names) where preconditions could save us from a false positive test
/// failure.
fn preconditions_met(&self, op: &Self::Operation) -> bool {
match op {
Operation::CreateTable(name, cols) => {
!self.name_in_use(name)
&& cols.iter().all(|cs| match cs {
ColumnSpec {
sql_type: SqlType::Other(type_name),
..
} => self.enum_types.contains_key(type_name.name.as_str()),
_ => true,
})
}
Operation::DropTable(name) => self.tables.contains_key(name),
Operation::WriteRow {
table,
pkey,
col_vals,
col_types,
} => {
// Make sure that the table doesn't already contain a row with this key, and also
// make sure that the column types in the table also match up with the types in the
// row that we're trying to write:
self.pkeys
.get(table)
.map_or(false, |table_keys| !table_keys.contains(pkey))
&& self.tables.get(table).map_or(false, |table_cols| {
// Must compare lengths before zipping and comparing individual types
// because zip will drop elements if the Vec lengths don't match up:
table_cols.len() == col_types.len()
// Make sure all types in the WriteRow match the table cols:
&& table_cols
.iter()
.zip(col_types)
.all(|(cs, row_type)| cs.sql_type == *row_type)
// Make sure enum values being inserted are in the current enum defs:
&& col_types.iter().zip(col_vals).all(|(ct, cv)| match ct {
SqlType::Other(enum_name) => self
.enum_types
.get(&enum_name.name.to_string())
.map_or(false, |enum_values| {
enum_values.contains(&cv.as_str().unwrap().to_string())
}),
_ => true,
})
})
}
Operation::DeleteRow(table, key) => self
.pkeys
.get(table)
.map_or(false, |table_keys| table_keys.contains(key)),
Operation::AddColumn(table, column_spec) => self
.tables
.get(table)
.map_or(false, |t| t.iter().all(|cs| cs.name != *column_spec.name)),
Operation::DropColumn(table, col_name) => self
.tables
.get(table)
.map_or(false, |t| t.iter().any(|cs| cs.name == *col_name)),
Operation::AlterColumnName {
table,
col_name,
new_name,
} => self.tables.get(table).map_or(false, |t| {
t.iter().any(|cs| cs.name == *col_name) && t.iter().all(|cs| cs.name != *new_name)
}),
Operation::CreateSimpleView { name, table_source } => {
!self.name_in_use(name) && self.tables.contains_key(table_source)
}
Operation::CreateJoinView {
name,
table_a,
table_b,
} => {
self.tables.contains_key(table_a)
&& self.tables.contains_key(table_b)
&& !self.tables.contains_key(name)
&& !self.views.contains_key(name)
}
Operation::DropView(name) => self.views.contains_key(name),
Operation::CreateEnum(name, _values) => !self.name_in_use(name),
Operation::DropEnum(name) => tables_using_type(&self.tables, name).next().is_none(),
Operation::AppendEnumValue {
type_name,
value_name,
} => self
.enum_types
.get(type_name)
.map_or(false, |t| !t.contains(value_name)),
Operation::InsertEnumValue {
type_name,
value_name,
next_to_value,
..
} => self.enum_types.get(type_name).map_or(false, |t| {
t.contains(next_to_value) && !t.contains(value_name)
}),
Operation::RenameEnumValue {
type_name,
value_name,
new_name,
} => self
.enum_types
.get(type_name)
.map_or(false, |t| t.contains(value_name) && !t.contains(new_name)),
// Even if the key is shrunk out, evicting it is a no-op, so we don't need to worry
// about preconditions at all for evictions:
Operation::Evict { .. } => true,
}
}
/// Get ready to run a single test case by:
/// * Setting up a test instance of ReadySet that connects to an upstream instance of Postgres
/// * Wiping and recreating a fresh copy of the oracle database directly in Postgres, and
/// setting up a connection
async fn init_test_run(&self) -> Self::RunContext {
readyset_tracing::init_test_logging();
let (opts, handle, shutdown_tx) = TestBuilder::default()
.fallback(true)
.build::<PostgreSQLAdapter>()
.await;
// We need the raw hostname for eviction operations later:
let rs_host = match &opts.get_hosts()[0] {
Host::Tcp(host) => host.clone(),
_ => unreachable!(),
};
let rs_conn = connect(opts).await;
recreate_oracle_db().await;
let pg_conn = connect(oracle_db_config()).await;
DDLTestRunContext {
rs_host,
rs_conn,
pg_conn,
_handle: handle,
shutdown_tx: Some(shutdown_tx),
}
}
/// Run the code to test a single operation:
/// * Running each step in `ops`, and checking afterward that:
/// * The contents of the tables tracked by our model match across both ReadySet and Postgres
/// * Any deleted tables appear as deleted in both ReadySet and Postgres
async fn run_op(&self, op: &Self::Operation, ctxt: &mut Self::RunContext) {
let DDLTestRunContext {
rs_conn, pg_conn, ..
} = ctxt;
match op {
Operation::CreateTable(table_name, cols) => {
let non_pkey_cols = cols.iter().map(|ColumnSpec { name, sql_type, .. }| {
format!(
"\"{name}\" {}",
sql_type.display(nom_sql::Dialect::PostgreSQL)
)
});
let col_defs: Vec<String> = once("id INT PRIMARY KEY".to_string())
.chain(non_pkey_cols)
.collect();
let col_defs = col_defs.join(", ");
let query = format!("CREATE TABLE \"{table_name}\" ({col_defs})");
rs_conn.simple_query(&query).await.unwrap();
pg_conn.simple_query(&query).await.unwrap();
let create_cache =
format!("CREATE CACHE ALWAYS FROM SELECT * FROM \"{table_name}\"");
eventually!(run_test: {
let result = rs_conn.simple_query(&create_cache).await;
AssertUnwindSafe(move || result)
}, then_assert: |result| {
result().unwrap()
});
}
Operation::DropTable(name) => {
let query = format!("DROP TABLE \"{name}\" CASCADE");
rs_conn.simple_query(&query).await.unwrap();
pg_conn.simple_query(&query).await.unwrap();
}
Operation::WriteRow {
table,
pkey,
col_vals,
..
} => {
let pkey = DfValue::from(*pkey);
let params: Vec<&DfValue> = once(&pkey).chain(col_vals.iter()).collect();
let placeholders: Vec<_> = (1..=params.len()).map(|n| format!("${n}")).collect();
let placeholders = placeholders.join(", ");
let query = format!("INSERT INTO \"{table}\" VALUES ({placeholders})");
rs_conn.query_raw(&query, ¶ms).await.unwrap();
pg_conn.query_raw(&query, ¶ms).await.unwrap();
}
Operation::AddColumn(table_name, col_spec) => {
let query = format!(
"ALTER TABLE \"{}\" ADD COLUMN \"{}\" {}",
table_name,
col_spec.name,
col_spec.sql_type.display(nom_sql::Dialect::PostgreSQL)
);
rs_conn.simple_query(&query).await.unwrap();
pg_conn.simple_query(&query).await.unwrap();
}
Operation::DropColumn(table_name, col_name) => {
let query = format!(
"ALTER TABLE \"{}\" DROP COLUMN \"{}\"",
table_name, col_name
);
rs_conn.simple_query(&query).await.unwrap();
pg_conn.simple_query(&query).await.unwrap();
}
Operation::AlterColumnName {
table,
col_name,
new_name,
} => {
let query = format!(
"ALTER TABLE \"{}\" RENAME COLUMN \"{}\" TO \"{}\"",
table, col_name, new_name
);
rs_conn.simple_query(&query).await.unwrap();
pg_conn.simple_query(&query).await.unwrap();
}
Operation::DeleteRow(table_name, key) => {
let query = format!("DELETE FROM \"{table_name}\" WHERE id = ({key})");
rs_conn.simple_query(&query).await.unwrap();
pg_conn.simple_query(&query).await.unwrap();
}
Operation::CreateSimpleView { name, table_source } => {
let query = format!("CREATE VIEW \"{name}\" AS SELECT * FROM \"{table_source}\"");
rs_conn.simple_query(&query).await.unwrap();
pg_conn.simple_query(&query).await.unwrap();
let create_cache = format!("CREATE CACHE ALWAYS FROM SELECT * FROM \"{name}\"");
eventually!(run_test: {
let result = rs_conn.simple_query(&create_cache).await;
AssertUnwindSafe(move || result)
}, then_assert: |result| {
result().unwrap()
});
}
Operation::CreateJoinView {
name,
table_a,
table_b,
} => {
// Must give a unique alias to each column in the source tables to avoid issues
// with duplicate column names in the resulting view
let select_list: Vec<String> = self.tables[table_a]