-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
201 lines (171 loc) · 5.87 KB
/
main.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
use futures_util::TryStreamExt;
use sqlx::{
sqlite::{
Sqlite, SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous,
},
Row, SqlitePool,
};
use std::{io::Error, path::Path};
use tempfile::TempDir;
use tokio::{fs, select};
#[tokio::main]
async fn main() {
for run_i in 0..1000 {
database_commit_consistency(run_i).await;
}
}
async fn database_commit_consistency(run_i: u32) {
// Pseudocode:
// 1. Create two databases `a` and `b`, each having pools of one read and one write connection.
// 2. Create table `a_table` in `a` and `b_table` in `b`.
// 3. Write 200 entries into `a_table`
// 4. In parallel:
// a. Do some write operation on `b_table` in a loop.
// b. Try to retrieve the latest entry from `a_table`.
//
// The step 4a occasionally fails
let (_a_base_dir, a_pool) = create_temp_db().await.unwrap();
let (_b_base_dir, b_pool) = create_temp_db().await.unwrap();
{
let mut tx = a_pool.write.begin().await.unwrap();
sqlx::query("CREATE TABLE a_table (id INTEGER PRIMARY KEY)")
.execute(&mut *tx)
.await
.unwrap();
tx.commit().await.unwrap();
}
{
let mut tx = b_pool.write.begin().await.unwrap();
sqlx::query("CREATE TABLE b_table (id INTEGER PRIMARY KEY)")
.execute(&mut *tx)
.await
.unwrap();
tx.commit().await.unwrap();
}
let highest_id = 200;
{
let mut tx = a_pool.write.begin().await.unwrap();
for i in 0..(highest_id + 1) {
let _id = sqlx::query(
"INSERT INTO a_table (id)
VALUES (?)
RETURNING id",
)
.bind(&(i as i64))
.map(|row: sqlx::sqlite::SqliteRow| row.get::<u32, usize>(0))
.fetch_one(&mut *tx)
.await
.unwrap();
}
tx.commit().await.unwrap();
}
select! {
_ = async {
loop {
let mut tx = b_pool.write.begin().await.unwrap();
sqlx::query("DELETE FROM b_table")
.execute(&mut *tx)
.await
.unwrap();
tx.commit().await.unwrap();
}
} => {},
_ = async {
let mut conn = a_pool.reads.acquire().await.unwrap();
let highest_id_i64 = highest_id as i64;
use futures_util::StreamExt;
println!("####################################################################################");
println!("Start SELECT");
let mut stream = sqlx::query("SELECT id FROM a_table WHERE id = ?")
.bind(&highest_id_i64)
.fetch_many(&mut *conn)
.map_ok(|row| match row {
sqlx::Either::Left(x) => {
println!("got left");
sqlx::Either::Left(x)
},
sqlx::Either::Right(row) => {
println!("got right");
sqlx::Either::Right(row.get::<u32, usize>(0))
}
})
.map_err(|e| {
println!("Error {:?}", e);
e
})
;
select! {
_ = tokio::time::sleep(std::time::Duration::from_secs(30)) => {
panic!("Timed out");
}
maybe_row_result = stream.next() => {
match maybe_row_result {
Some(row_result) => {
assert_eq!(row_result.expect("no error").right().unwrap(), highest_id);
},
None => panic!("Row not returned"),
}
}
}
} => {},
}
a_pool.close().await.unwrap();
b_pool.close().await.unwrap();
}
pub(crate) struct Pool {
// Pool with a single read-only connection.
reads: SqlitePool,
// Pool with a single writable connection.
write: SqlitePool,
}
impl Pool {
async fn create(connect_options: SqliteConnectOptions) -> Result<Self, sqlx::Error> {
let common_options = connect_options
//.journal_mode(SqliteJournalMode::Wal)
//.pragma("recursive_triggers", "ON")
.synchronous(SqliteSynchronous::Normal);
let write_options = common_options.clone();
let write = SqlitePoolOptions::new()
.min_connections(1)
.max_connections(1)
.test_before_acquire(false)
.connect_with(write_options)
.await?;
let read_options = common_options.read_only(true);
let reads = SqlitePoolOptions::new()
.min_connections(1)
.max_connections(1)
.test_before_acquire(false)
.connect_with(read_options)
.await?;
Ok(Self { reads, write })
}
pub(crate) async fn close(&self) -> Result<(), sqlx::Error> {
self.write.close().await;
self.reads.close().await;
Ok(())
}
}
async fn create_directory(path: &Path) -> Result<(), Error> {
if let Some(dir) = path.parent() {
fs::create_dir_all(dir).await?
}
Ok(())
}
async fn create_pool(path: impl AsRef<Path>) -> Result<Pool, std::io::Error> {
let path = path.as_ref();
if fs::metadata(path).await.is_ok() {
panic!("Already exists");
}
create_directory(path).await?;
let connect_options = SqliteConnectOptions::new()
.filename(path)
.create_if_missing(true);
let pool = Pool::create(connect_options).await.unwrap();
Ok(pool)
}
async fn create_temp_db() -> Result<(TempDir, Pool), std::io::Error> {
let temp_dir = TempDir::new()?;
let pool = create_pool(temp_dir.path().join("temp.db")).await?;
Ok((temp_dir, pool))
}