Skip to content

Commit 2543b26

Browse files
committed
libsql: Add local encryption example
1 parent 80d3e9b commit 2543b26

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// Example of using offline writes with encryption
2+
3+
use libsql::{params, Builder};
4+
use libsql::{EncryptionConfig, Cipher};
5+
6+
#[tokio::main]
7+
async fn main() {
8+
tracing_subscriber::fmt::init();
9+
10+
// The local database path where the data will be stored.
11+
let db_path = std::env::var("LIBSQL_DB_PATH").unwrap();
12+
13+
// The encryption key for the database.
14+
let encryption_key = std::env::var("LIBSQL_ENCRYPTION_KEY").unwrap();
15+
16+
let mut db_builder = Builder::new_local(db_path);
17+
18+
db_builder = db_builder.encryption_config(EncryptionConfig {
19+
cipher: Cipher::Aes256Cbc,
20+
encryption_key: encryption_key.into(),
21+
});
22+
23+
let db = match db_builder.build().await {
24+
Ok(db) => db,
25+
Err(error) => {
26+
return;
27+
}
28+
};
29+
30+
let conn = db.connect().unwrap();
31+
32+
conn.execute("ATTACH DATABASE 'world.db' AS world KEY secret", ()).await.unwrap();
33+
34+
conn.execute(
35+
r#"
36+
CREATE TABLE IF NOT EXISTS guest_book_entries (
37+
text TEXT
38+
)"#,
39+
(),
40+
)
41+
.await
42+
.unwrap();
43+
44+
let mut input = String::new();
45+
println!("Please write your entry to the guestbook:");
46+
match std::io::stdin().read_line(&mut input) {
47+
Ok(_) => {
48+
println!("You entered: {}", input);
49+
let params = params![input.as_str()];
50+
conn.execute("INSERT INTO guest_book_entries (text) VALUES (?)", params)
51+
.await
52+
.unwrap();
53+
}
54+
Err(error) => {
55+
eprintln!("Error reading input: {}", error);
56+
}
57+
}
58+
let mut results = conn
59+
.query("SELECT * FROM guest_book_entries", ())
60+
.await
61+
.unwrap();
62+
println!("Guest book entries:");
63+
while let Some(row) = results.next().await.unwrap() {
64+
let text: String = row.get(0).unwrap();
65+
println!(" {}", text);
66+
}
67+
}

0 commit comments

Comments
 (0)