|
| 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