-
Notifications
You must be signed in to change notification settings - Fork 56
/
batch.rs
78 lines (69 loc) · 2.1 KB
/
batch.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
mod help;
use cassandra_cpp::*;
use std::collections::HashSet;
#[derive(Debug, Eq, PartialEq, Hash)]
struct Pair {
key: String,
value: String,
}
async fn insert_into_batch_with_prepared(session: &Session, pairs: &Vec<Pair>) -> Result<()> {
let prepared = session
.prepare("INSERT INTO examples.pairs (key, value) VALUES (?, ?)")
.await?;
let mut batch = session.batch(BatchType::LOGGED);
batch.set_consistency(Consistency::ONE)?;
for pair in pairs {
let mut statement = prepared.bind();
statement.bind(0, pair.key.as_ref() as &str)?;
statement.bind(1, pair.value.as_ref() as &str)?;
batch.add_statement(statement)?;
}
batch.execute().await?;
Ok(())
}
async fn retrieve_batch(session: &Session) -> Result<Vec<Pair>> {
let result = session.execute("SELECT * from examples.pairs").await?;
let mut v = vec![];
let mut iter = result.iter();
while let Some(r) = iter.next() {
v.push(Pair {
key: r.get(0).expect("Key"),
value: r.get(1).expect("Value"),
})
}
Ok(v)
}
#[tokio::test]
async fn test_batch() -> Result<()> {
let pairs = vec![
Pair {
key: "a".to_string(),
value: "1".to_string(),
},
Pair {
key: "b".to_string(),
value: "2".to_string(),
},
Pair {
key: "c".to_string(),
value: "3".to_string(),
},
Pair {
key: "d".to_string(),
value: "4".to_string(),
},
];
let session = help::create_test_session().await;
help::create_example_keyspace(&session).await;
session
.execute(
"CREATE TABLE IF NOT EXISTS examples.pairs (key text, value text, PRIMARY KEY (key));",
)
.await?;
insert_into_batch_with_prepared(&session, &pairs).await?;
let result = retrieve_batch(&session).await?;
let set0: HashSet<_> = pairs.iter().collect();
let set1: HashSet<_> = result.iter().collect();
assert_eq!(set0, set1, "expected {:?} but got {:?}", &pairs, &result);
Ok(())
}