Skip to content

Commit d5cd477

Browse files
committed
Add example of libsql local encryption
1 parent 6671a31 commit d5cd477

File tree

1 file changed

+72
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)