Skip to content

Commit c2ef783

Browse files
committed
add sqlite serialize/deserialize example
- Use SqliteOwnedBuf with serialize/deserialize to snapshot an in-memory database as raw bytes - Embed the bytes in a custom container format (magic header + db) - Round-trip: create → serialize → write → read → deserialize → query
1 parent f5cdf33 commit c2ef783

File tree

4 files changed

+51
-0
lines changed

4 files changed

+51
-0
lines changed

Cargo.lock

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ members = [
2424
"examples/postgres/transaction",
2525
"examples/sqlite/todos",
2626
"examples/sqlite/extension",
27+
"examples/sqlite/serialize",
2728
]
2829

2930
[workspace.package]
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
[package]
2+
name = "sqlx-example-sqlite-serialize"
3+
version = "0.1.0"
4+
edition = "2024"
5+
workspace = "../../../"
6+
7+
[dependencies]
8+
anyhow = "1.0"
9+
sqlx = { path = "../../../", features = ["sqlite", "sqlite-deserialize", "runtime-tokio"] }
10+
tokio = { version = "1", features = ["rt", "macros"] }
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
use sqlx::sqlite::SqliteOwnedBuf;
2+
use sqlx::{Connection, SqliteConnection};
3+
4+
#[tokio::main(flavor = "current_thread")]
5+
async fn main() -> anyhow::Result<()> {
6+
let mut conn = SqliteConnection::connect("sqlite::memory:").await?;
7+
8+
sqlx::raw_sql(
9+
"create table notes(id integer primary key, body text not null);
10+
insert into notes(body) values ('hello'), ('world');",
11+
)
12+
.execute(&mut conn)
13+
.await?;
14+
15+
let snapshot: SqliteOwnedBuf = conn.serialize(None).await?;
16+
let bytes: &[u8] = snapshot.as_ref();
17+
conn.close().await?;
18+
19+
let owned = SqliteOwnedBuf::try_from(bytes)?;
20+
let mut restored = SqliteConnection::connect("sqlite::memory:").await?;
21+
restored.deserialize(None, owned, false).await?;
22+
23+
let rows = sqlx::query_as::<_, (i64, String)>("select id, body from notes order by id")
24+
.fetch_all(&mut restored)
25+
.await?;
26+
27+
assert_eq!(rows.len(), 2);
28+
assert_eq!(rows[0].1, "hello");
29+
assert_eq!(rows[1].1, "world");
30+
Ok(())
31+
}

0 commit comments

Comments
 (0)