diff --git a/Cargo.lock b/Cargo.lock index fe01e11720..efebf50629 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3842,6 +3842,15 @@ dependencies = [ "tokio", ] +[[package]] +name = "sqlx-example-sqlite-serialize" +version = "0.1.0" +dependencies = [ + "anyhow", + "sqlx", + "tokio", +] + [[package]] name = "sqlx-example-sqlite-todos" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index c88ab231e2..f85324a55a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ members = [ "examples/postgres/transaction", "examples/sqlite/todos", "examples/sqlite/extension", + "examples/sqlite/serialize", ] [workspace.package] diff --git a/examples/sqlite/serialize/Cargo.toml b/examples/sqlite/serialize/Cargo.toml new file mode 100644 index 0000000000..0ccadebad7 --- /dev/null +++ b/examples/sqlite/serialize/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "sqlx-example-sqlite-serialize" +version = "0.1.0" +edition = "2024" +workspace = "../../../" + +[dependencies] +anyhow = "1.0" +sqlx = { path = "../../../", features = ["sqlite", "sqlite-deserialize", "runtime-tokio"] } +tokio = { version = "1", features = ["rt", "macros"] } diff --git a/examples/sqlite/serialize/src/main.rs b/examples/sqlite/serialize/src/main.rs new file mode 100644 index 0000000000..f3c0b709b5 --- /dev/null +++ b/examples/sqlite/serialize/src/main.rs @@ -0,0 +1,31 @@ +use sqlx::sqlite::SqliteOwnedBuf; +use sqlx::{Connection, SqliteConnection}; + +#[tokio::main(flavor = "current_thread")] +async fn main() -> anyhow::Result<()> { + let mut conn = SqliteConnection::connect("sqlite::memory:").await?; + + sqlx::raw_sql( + "create table notes(id integer primary key, body text not null); + insert into notes(body) values ('hello'), ('world');", + ) + .execute(&mut conn) + .await?; + + let snapshot: SqliteOwnedBuf = conn.serialize(None).await?; + let bytes: &[u8] = snapshot.as_ref(); + conn.close().await?; + + let owned = SqliteOwnedBuf::try_from(bytes)?; + let mut restored = SqliteConnection::connect("sqlite::memory:").await?; + restored.deserialize(None, owned, false).await?; + + let rows = sqlx::query_as::<_, (i64, String)>("select id, body from notes order by id") + .fetch_all(&mut restored) + .await?; + + assert_eq!(rows.len(), 2); + assert_eq!(rows[0].1, "hello"); + assert_eq!(rows[1].1, "world"); + Ok(()) +}