-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
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
SQLite: Deserialize database from in-memory buffer #3792
Changes from all commits
d09419f
26f8c87
b7dfe80
db3b6d2
a2aa141
dd5a43a
c35bb60
c191aef
4bb8424
1a5c67f
ff1634d
9fd4f5b
7eac8cc
f6b6a6f
ac0b036
cc0e515
27e61fc
97b801e
f3a8f9c
79bd2e5
2be0d9e
6f5c9cd
ae3ebf6
b4e3284
be24ecd
c322bef
fe27275
2205492
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,12 +4,14 @@ mod bind_collector; | |
mod functions; | ||
mod raw; | ||
mod row; | ||
mod serialized_database; | ||
mod sqlite_value; | ||
mod statement_iterator; | ||
mod stmt; | ||
|
||
pub(in crate::sqlite) use self::bind_collector::SqliteBindCollector; | ||
pub use self::bind_collector::SqliteBindValue; | ||
pub use self::serialized_database::SerializedDatabase; | ||
pub use self::sqlite_value::SqliteValue; | ||
|
||
use std::os::raw as libc; | ||
|
@@ -406,6 +408,58 @@ impl SqliteConnection { | |
.register_collation_function(collation_name, collation) | ||
} | ||
|
||
/// Serialize the current SQLite database into a byte buffer. | ||
/// | ||
/// The serialized data is identical to the data that would be written to disk if the database | ||
/// was saved in a file. | ||
/// | ||
/// # Returns | ||
/// | ||
/// This function returns a byte slice representing the serialized database. | ||
pub fn serialize_database_to_buffer(&mut self) -> SerializedDatabase { | ||
self.raw_connection.serialize() | ||
} | ||
|
||
/// Deserialize an SQLite database from a byte buffer. | ||
/// | ||
/// This function takes a byte slice and attempts to deserialize it into a SQLite database. | ||
/// If successful, the database is loaded into the connection. If the deserialization fails, | ||
/// an error is returned. | ||
/// | ||
/// The database is opened in READONLY mode. | ||
/// | ||
/// # Example | ||
/// | ||
/// ```no_run | ||
/// # use diesel::sqlite::SerializedDatabase; | ||
/// # use diesel::sqlite::SqliteConnection; | ||
/// # use diesel::result::QueryResult; | ||
/// # use diesel::sql_query; | ||
/// # use diesel::Connection; | ||
/// # use diesel::RunQueryDsl; | ||
/// # fn main() { | ||
/// let connection = &mut SqliteConnection::establish(":memory:").unwrap(); | ||
/// | ||
/// sql_query("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)") | ||
/// .execute(connection).unwrap(); | ||
/// sql_query("INSERT INTO users (name, email) VALUES ('John Doe', '[email protected]'), ('Jane Doe', '[email protected]')") | ||
/// .execute(connection).unwrap(); | ||
/// | ||
/// // Serialize the database to a byte vector | ||
/// let serialized_db: SerializedDatabase = connection.serialize_database_to_buffer(); | ||
/// | ||
/// // Create a new in-memory SQLite database | ||
/// let connection = &mut SqliteConnection::establish(":memory:").unwrap(); | ||
/// | ||
/// // Deserialize the byte vector into the new database | ||
/// connection.deserialize_readonly_database_from_buffer(serialized_db.as_slice()).unwrap(); | ||
/// # | ||
/// # } | ||
/// ``` | ||
pub fn deserialize_readonly_database_from_buffer(&mut self, data: &[u8]) -> QueryResult<()> { | ||
self.raw_connection.deserialize(data) | ||
} | ||
|
||
fn register_diesel_sql_functions(&self) -> QueryResult<()> { | ||
use crate::sql_types::{Integer, Text}; | ||
|
||
|
@@ -436,6 +490,41 @@ mod tests { | |
use crate::prelude::*; | ||
use crate::sql_types::Integer; | ||
|
||
#[test] | ||
fn database_serializes_and_deserializes_successfully() { | ||
let expected_users = vec![ | ||
( | ||
1, | ||
"John Doe".to_string(), | ||
"[email protected]".to_string(), | ||
), | ||
( | ||
2, | ||
"Jane Doe".to_string(), | ||
"[email protected]".to_string(), | ||
), | ||
]; | ||
|
||
let connection = &mut SqliteConnection::establish(":memory:").unwrap(); | ||
let _ = | ||
crate::sql_query("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)") | ||
.execute(connection); | ||
let _ = crate::sql_query("INSERT INTO users (name, email) VALUES ('John Doe', '[email protected]'), ('Jane Doe', '[email protected]')") | ||
.execute(connection); | ||
|
||
let serialized_database = connection.serialize_database_to_buffer(); | ||
|
||
let connection = &mut SqliteConnection::establish(":memory:").unwrap(); | ||
connection | ||
.deserialize_readonly_database_from_buffer(serialized_database.as_slice()) | ||
.unwrap(); | ||
|
||
let query = sql::<(Integer, Text, Text)>("SELECT id, name, email FROM users ORDER BY id"); | ||
let actual_users = query.load::<(i32, String, String)>(connection).unwrap(); | ||
|
||
assert_eq!(expected_users, actual_users); | ||
} | ||
|
||
#[test] | ||
fn prepared_statements_are_cached_when_run() { | ||
let connection = &mut SqliteConnection::establish(":memory:").unwrap(); | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
#![allow(unsafe_code)] | ||
extern crate libsqlite3_sys as ffi; | ||
|
||
use std::ops::Deref; | ||
|
||
/// `SerializedDatabase` is a wrapper for a serialized database that is dynamically allocated by calling `sqlite3_serialize`. | ||
/// This RAII wrapper is necessary to deallocate the memory when it goes out of scope with `sqlite3_free`. | ||
#[derive(Debug)] | ||
pub struct SerializedDatabase { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think it might be meaningful to implement |
||
data: *mut u8, | ||
len: usize, | ||
} | ||
|
||
impl SerializedDatabase { | ||
/// Creates a new `SerializedDatabase` with the given data pointer and length. | ||
pub fn new(data: *mut u8, len: usize) -> Self { | ||
Self { data, len } | ||
} | ||
|
||
/// Returns a slice of the serialized database. | ||
pub fn as_slice(&self) -> &[u8] { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would like to see an additional comment on this unsafe block that the pointer is never null because we don't pass the |
||
// The pointer is never null because we don't pass the NO_COPY flag | ||
unsafe { std::slice::from_raw_parts(self.data, self.len) } | ||
} | ||
} | ||
|
||
impl Deref for SerializedDatabase { | ||
type Target = [u8]; | ||
|
||
fn deref(&self) -> &Self::Target { | ||
self.as_slice() | ||
} | ||
} | ||
|
||
impl Drop for SerializedDatabase { | ||
/// Deallocates the memory of the serialized database when it goes out of scope. | ||
fn drop(&mut self) { | ||
unsafe { | ||
ffi::sqlite3_free(self.data as _); | ||
} | ||
} | ||
} |
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.
The documentation needs to mention that it will open the database in read only mode. It might be even a good idea to change the method name to
deserialize_read_only_database_from_buffer()