Skip to content

Commit 56f95e1

Browse files
committed
Add local encryption with attach example
1 parent 67c1841 commit 56f95e1

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

libsql/examples/encryption_loc.rs

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

0 commit comments

Comments
 (0)