Skip to content

Commit 330a3be

Browse files
committed
Add offline writes with encryption example
1 parent ce853e6 commit 330a3be

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

libsql/examples/encryption_sync.rs

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// Example of using offline writes with encryption
2+
3+
use libsql::{params, Builder, EncryptionContext};
4+
5+
#[tokio::main]
6+
async fn main() {
7+
tracing_subscriber::fmt::init();
8+
9+
// The local database path where the data will be stored.
10+
let db_path = std::env::var("LIBSQL_DB_PATH").unwrap();
11+
12+
// The remote sync URL to use.
13+
let sync_url = std::env::var("LIBSQL_SYNC_URL").unwrap();
14+
15+
// The authentication token for the remote sync server.
16+
let auth_token = std::env::var("LIBSQL_AUTH_TOKEN").unwrap_or("".to_string());
17+
18+
// Optional encryption key for the database, if provided.
19+
let encryption = if let Ok(key) = std::env::var("LIBSQL_ENCRYPTION_KEY") {
20+
Some(EncryptionContext {
21+
key_32_bytes_base64_encoded: key.to_string(),
22+
})
23+
} else {
24+
None
25+
};
26+
27+
let db_builder = Builder::new_synced_database(db_path, sync_url, auth_token, encryption);
28+
29+
let db = match db_builder.build().await {
30+
Ok(db) => db,
31+
Err(error) => {
32+
eprintln!("Error connecting to remote sync server: {}", error);
33+
return;
34+
}
35+
};
36+
37+
let conn = db.connect().unwrap();
38+
39+
print!("Syncing with remote database...");
40+
db.sync().await.unwrap();
41+
println!(" done");
42+
43+
let mut results = conn.query("SELECT count(*) FROM dummy", ()).await.unwrap();
44+
let count: u32 = results.next().await.unwrap().unwrap().get(0).unwrap();
45+
println!("dummy table has {} entries", count);
46+
47+
conn.execute(
48+
r#"
49+
CREATE TABLE IF NOT EXISTS guest_book_entries (
50+
text TEXT
51+
)"#,
52+
(),
53+
)
54+
.await
55+
.unwrap();
56+
57+
let mut input = String::new();
58+
println!("Please write your entry to the guestbook:");
59+
match std::io::stdin().read_line(&mut input) {
60+
Ok(_) => {
61+
println!("You entered: {}", input);
62+
let params = params![input.as_str()];
63+
conn.execute("INSERT INTO guest_book_entries (text) VALUES (?)", params)
64+
.await
65+
.unwrap();
66+
}
67+
Err(error) => {
68+
eprintln!("Error reading input: {}", error);
69+
}
70+
}
71+
db.sync().await.unwrap();
72+
let mut results = conn
73+
.query("SELECT * FROM guest_book_entries", ())
74+
.await
75+
.unwrap();
76+
println!("Guest book entries:");
77+
while let Some(row) = results.next().await.unwrap() {
78+
let text: String = row.get(0).unwrap();
79+
println!(" {}", text);
80+
}
81+
}

0 commit comments

Comments
 (0)