Skip to content

Commit fe5227a

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

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

libsql/examples/encryption_loc.rs

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
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+
eprintln!("failed to build: {}", error);
25+
return;
26+
}
27+
};
28+
29+
let conn = db.connect().unwrap();
30+
31+
println!("connecting to main db");
32+
conn.execute(
33+
r#"
34+
CREATE TABLE IF NOT EXISTS guest_book_entries (
35+
text TEXT
36+
)"#,
37+
(),
38+
)
39+
.await
40+
.unwrap();
41+
42+
println!("doing attach and printing attached db entries");
43+
conn.execute(
44+
"ATTACH DATABASE 'world.db' AS world KEY attached_secret",
45+
(),
46+
)
47+
.await
48+
.unwrap();
49+
50+
let mut attached_results = conn
51+
.query("SELECT * FROM world.guest_book_entries", ())
52+
.await
53+
.unwrap();
54+
println!("Attached database guest book entries:");
55+
while let Some(row) = attached_results.next().await.unwrap() {
56+
let text: String = row.get(0).unwrap();
57+
println!(" {}", text);
58+
}
59+
60+
let mut input = String::new();
61+
println!("Please write your entry to the guestbook:");
62+
match std::io::stdin().read_line(&mut input) {
63+
Ok(_) => {
64+
println!("You entered: {}", input);
65+
let params = params![input.as_str()];
66+
conn.execute("INSERT INTO guest_book_entries (text) VALUES (?)", params)
67+
.await
68+
.unwrap();
69+
}
70+
Err(error) => {
71+
eprintln!("Error reading input: {}", error);
72+
}
73+
}
74+
let mut results = conn
75+
.query("SELECT * FROM guest_book_entries", ())
76+
.await
77+
.unwrap();
78+
println!("Guest book entries:");
79+
while let Some(row) = results.next().await.unwrap() {
80+
let text: String = row.get(0).unwrap();
81+
println!(" {}", text);
82+
}
83+
}

0 commit comments

Comments
 (0)