Skip to content

Commit fa26ac4

Browse files
authored
Add turso cloud encryption example (#2199)
2 parents 40a151b + bc81ec0 commit fa26ac4

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// Example: Connecting to an encrypted Turso Cloud database
2+
//
3+
// This example shows how to connect to a Turso Cloud database with
4+
// remote encryption using the rust driver.
5+
//
6+
// Documentation of encrypted databases - https://docs.turso.tech/cloud/encryption
7+
//
8+
// Usage:
9+
//
10+
// export LIBSQL_DB_URL="libsql://your-db.aws-us-east-2.turso.io"
11+
// export LIBSQL_AUTH_TOKEN="your-token"
12+
// export LIBSQL_ENCRYPTION_KEY="encryption key in base 64 encoded format"
13+
// cargo run --example encryption_remote
14+
//
15+
// The encryption key must be encoded in base64 format.
16+
17+
use libsql::{params, Builder};
18+
use libsql::{EncryptionContext, EncryptionKey};
19+
20+
#[tokio::main]
21+
async fn main() {
22+
tracing_subscriber::fmt::init();
23+
24+
// The remote DB URL to use.
25+
let db_url = std::env::var("LIBSQL_DB_URL").unwrap();
26+
27+
// The authentication token for the remote db
28+
let auth_token = std::env::var("LIBSQL_AUTH_TOKEN").unwrap_or("".to_string());
29+
30+
// Optional encryption key for the database, if provided.
31+
let encryption = if let Ok(key) = std::env::var("LIBSQL_ENCRYPTION_KEY") {
32+
Some(EncryptionContext {
33+
key: EncryptionKey::Base64Encoded(key),
34+
})
35+
} else {
36+
None
37+
};
38+
39+
let mut db_builder = Builder::new_remote(db_url, auth_token);
40+
if let Some(enc) = encryption {
41+
db_builder = db_builder.remote_encryption(enc);
42+
}
43+
let db = db_builder.build().await.unwrap();
44+
let conn = db.connect().unwrap();
45+
46+
conn.execute(
47+
r#"
48+
CREATE TABLE IF NOT EXISTS guest_book_entries (
49+
text TEXT
50+
)"#,
51+
(),
52+
)
53+
.await
54+
.unwrap();
55+
56+
let mut input = String::new();
57+
println!("Please write your entry to the guestbook:");
58+
match std::io::stdin().read_line(&mut input) {
59+
Ok(_) => {
60+
println!("You entered: {}", input);
61+
let params = params![input.as_str()];
62+
conn.execute("INSERT INTO guest_book_entries (text) VALUES (?)", params)
63+
.await
64+
.unwrap();
65+
}
66+
Err(error) => {
67+
eprintln!("Error reading input: {}", error);
68+
}
69+
}
70+
let mut results = conn
71+
.query("SELECT * FROM guest_book_entries", ())
72+
.await
73+
.unwrap();
74+
println!("Guest book entries:");
75+
while let Some(row) = results.next().await.unwrap() {
76+
let text: String = row.get(0).unwrap();
77+
println!(" {}", text);
78+
}
79+
}

0 commit comments

Comments
 (0)