-
Notifications
You must be signed in to change notification settings - Fork 19
/
consistency-selector.rs
99 lines (82 loc) · 2.77 KB
/
consistency-selector.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
use firestore::*;
use futures::stream::BoxStream;
use serde::{Deserialize, Serialize};
use tokio_stream::StreamExt;
pub fn config_env_var(name: &str) -> Result<String, String> {
std::env::var(name).map_err(|e| format!("{}: {}", name, e))
}
// Example structure to play with
#[derive(Debug, Clone, Deserialize, Serialize)]
struct MyTestStructure {
some_id: String,
some_string: String,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// Logging with debug enabled
let subscriber = tracing_subscriber::fmt()
.with_env_filter("firestore=debug")
.finish();
tracing::subscriber::set_global_default(subscriber)?;
// Create an instance
let db = FirestoreDb::new(&config_env_var("PROJECT_ID")?).await?;
const TEST_COLLECTION_NAME: &'static str = "test";
println!("Populating a test collection");
for i in 0..10 {
let my_struct = MyTestStructure {
some_id: format!("test-{}", i),
some_string: "Test".to_string(),
};
// Remove if it already exist
db.fluent()
.delete()
.from(TEST_COLLECTION_NAME)
.document_id(&my_struct.some_id)
.execute()
.await?;
// Let's insert some data
db.fluent()
.insert()
.into(TEST_COLLECTION_NAME)
.document_id(&my_struct.some_id)
.object(&my_struct)
.execute::<()>()
.await?;
}
println!("Read only transaction to read the state before changes");
let transaction = db
.begin_transaction_with_options(
FirestoreTransactionOptions::new().with_mode(FirestoreTransactionMode::ReadOnly),
)
.await?;
// Working with consistency selector for reading when necessary
let cdb = db.clone_with_consistency_selector(FirestoreConsistencySelector::Transaction(
transaction.transaction_id.clone(),
));
let consistency_read_test: Option<MyTestStructure> = cdb
.fluent()
.select()
.by_id_in(TEST_COLLECTION_NAME)
.obj()
.one("test-0")
.await?;
println!("The original one: {:?}", consistency_read_test);
transaction.commit().await?;
println!("Listing objects as a stream with updated test-0 and removed test-5");
// Query as a stream our data
let mut objs_stream: BoxStream<MyTestStructure> = db
.fluent()
.list()
.from(TEST_COLLECTION_NAME)
.order_by([(
path!(MyTestStructure::some_id),
FirestoreQueryDirection::Descending,
)])
.obj()
.stream_all()
.await?;
while let Some(object) = objs_stream.next().await {
println!("Object in stream: {:?}", object);
}
Ok(())
}