-
Notifications
You must be signed in to change notification settings - Fork 1.6k
add sqlite serialize/deserialize example #4167
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mattrighetti
wants to merge
1
commit into
launchbadge:main
Choose a base branch
from
mattrighetti:example/sqlx-sqlite-serialize
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+92
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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"] } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| /// Demonstrates serialize/deserialize by embedding a SQLite database inside a custom | ||
| /// binary container format. | ||
| /// | ||
| /// The container prepends a magic header to the raw SQLite bytes, making it impossible | ||
| /// to open directly with `SqliteConnectOptions::filename()`. This is the whole point: | ||
| /// `sqlite3_serialize` / `sqlite3_deserialize` let you treat a database as an opaque | ||
| /// byte slice that can live inside any format you control. | ||
| /// | ||
| /// Container layout: | ||
| /// [4 bytes] magic: b"SQLX" | ||
| /// [n bytes] SQLite database bytes | ||
| use sqlx::sqlite::SqliteOwnedBuf; | ||
| use sqlx::{Connection, SqliteConnection}; | ||
| use std::io::{self, Write}; | ||
| use std::path::Path; | ||
|
|
||
| const MAGIC: &[u8; 4] = b"SQLX"; | ||
|
|
||
| fn write_container(path: &Path, db_bytes: &[u8]) -> io::Result<()> { | ||
| let mut file = std::fs::File::create(path)?; | ||
| file.write_all(MAGIC)?; | ||
| file.write_all(db_bytes)?; | ||
| Ok(()) | ||
| } | ||
|
|
||
| fn read_container(path: &Path) -> io::Result<Vec<u8>> { | ||
| let raw = std::fs::read(path)?; | ||
| assert_eq!(&raw[..4], MAGIC, "not a valid container file"); | ||
| Ok(raw[4..].to_vec()) | ||
| } | ||
|
|
||
| #[tokio::main(flavor = "current_thread")] | ||
| async fn main() -> anyhow::Result<()> { | ||
| let container_path = Path::new("notes.sqlx"); | ||
|
|
||
| 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?; | ||
|
|
||
| // serialize and persist inside the custom container | ||
| let snapshot: SqliteOwnedBuf = conn.serialize(None).await?; | ||
| write_container(container_path, snapshot.as_ref())?; | ||
| conn.close().await?; | ||
|
|
||
| // restore into a fresh in-memory connection | ||
| let db_bytes = read_container(container_path)?; | ||
| let owned = SqliteOwnedBuf::try_from(db_bytes.as_slice())?; | ||
| 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); | ||
|
|
||
| sqlx::query("insert into notes(body) values ('from restored connection')") | ||
| .execute(&mut restored) | ||
| .await?; | ||
|
|
||
| // serialize the updated database back into the container | ||
| let updated: SqliteOwnedBuf = restored.serialize(None).await?; | ||
| write_container(container_path, updated.as_ref())?; | ||
|
|
||
| std::fs::remove_file(container_path)?; | ||
|
|
||
| Ok(()) | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't feel that this really makes sense to carry as an example, because this is a really niche use-case. These examples are targeted more at beginners and common use-cases to use as a basis. This is more like a demo/proof-of-concept.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do you have anything specific in mind?