-
Notifications
You must be signed in to change notification settings - Fork 107
/
custom_deserialization.rs
66 lines (53 loc) · 2.08 KB
/
custom_deserialization.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
use anyhow::Result;
use scylla::deserialize::DeserializeValue;
use scylla::frame::response::result::ColumnType;
use scylla::transport::session::Session;
use scylla::SessionBuilder;
use std::env;
#[tokio::main]
async fn main() -> Result<()> {
let uri = env::var("SCYLLA_URI").unwrap_or_else(|_| "127.0.0.1:9042".to_string());
println!("Connecting to {} ...", uri);
let session: Session = SessionBuilder::new().known_node(uri).build().await?;
session.query_unpaged("CREATE KEYSPACE IF NOT EXISTS examples_ks WITH REPLICATION = {'class' : 'NetworkTopologyStrategy', 'replication_factor' : 1}", &[]).await?;
session
.query_unpaged(
"CREATE TABLE IF NOT EXISTS examples_ks.custom_deserialization (pk int primary key, v text)",
&[],
)
.await?;
session
.query_unpaged(
"INSERT INTO examples_ks.custom_deserialization (pk, v) VALUES (1, 'asdf')",
(),
)
.await?;
// You can implement DeserializeValue for your own types
#[derive(PartialEq, Eq, Debug)]
struct MyType<'a>(&'a str);
impl<'frame, 'metadata> DeserializeValue<'frame, 'metadata> for MyType<'frame> {
fn type_check(
typ: &scylla::frame::response::result::ColumnType,
) -> std::result::Result<(), scylla::deserialize::TypeCheckError> {
<&str as DeserializeValue<'frame, 'metadata>>::type_check(typ)
}
fn deserialize(
typ: &'metadata ColumnType<'metadata>,
v: Option<scylla::deserialize::FrameSlice<'frame>>,
) -> std::result::Result<Self, scylla::deserialize::DeserializationError> {
let s = <&str as DeserializeValue<'frame, 'metadata>>::deserialize(typ, v)?;
Ok(Self(s))
}
}
let rows_result = session
.query_unpaged(
"SELECT v FROM examples_ks.custom_deserialization WHERE pk = 1",
(),
)
.await?
.into_rows_result()?;
let (v,) = rows_result.single_row::<(MyType,)>()?;
assert_eq!(v, MyType("asdf"));
println!("Ok.");
Ok(())
}