mirror of
https://github.com/isar/rusqlite.git
synced 2024-11-23 00:39:20 +08:00
Merge remote-tracking branch 'jgallagher/master' into 0.14
This commit is contained in:
commit
af2d29ce84
10
.travis.yml
10
.travis.yml
@ -30,6 +30,7 @@ script:
|
||||
- cargo test --features backup
|
||||
- cargo test --features blob
|
||||
- cargo test --features functions
|
||||
- cargo test --features hooks
|
||||
- cargo test --features limits
|
||||
- cargo test --features load_extension
|
||||
- cargo test --features trace
|
||||
@ -37,7 +38,8 @@ script:
|
||||
- cargo test --features serde_json
|
||||
- cargo test --features bundled
|
||||
- cargo test --features sqlcipher
|
||||
- cargo test --features "backup blob chrono functions limits load_extension serde_json trace"
|
||||
- cargo test --features "backup blob chrono functions limits load_extension serde_json trace buildtime_bindgen"
|
||||
- cargo test --features "backup blob chrono functions limits load_extension serde_json trace bundled"
|
||||
- cargo test --features "backup blob chrono functions limits load_extension serde_json trace bundled buildtime_bindgen"
|
||||
- cargo test --features "unlock_notify bundled"
|
||||
- cargo test --features "backup blob chrono functions hooks limits load_extension serde_json trace"
|
||||
- cargo test --features "backup blob chrono functions hooks limits load_extension serde_json trace buildtime_bindgen"
|
||||
- cargo test --features "backup blob chrono functions hooks limits load_extension serde_json trace bundled"
|
||||
- cargo test --features "backup blob chrono functions hooks limits load_extension serde_json trace bundled buildtime_bindgen"
|
||||
|
@ -26,7 +26,9 @@ trace = ["libsqlite3-sys/min_sqlite_version_3_6_23"]
|
||||
bundled = ["libsqlite3-sys/bundled"]
|
||||
buildtime_bindgen = ["libsqlite3-sys/buildtime_bindgen"]
|
||||
limits = []
|
||||
hooks = []
|
||||
sqlcipher = ["libsqlite3-sys/sqlcipher"]
|
||||
unlock_notify = ["libsqlite3-sys/unlock_notify"]
|
||||
|
||||
[dependencies]
|
||||
time = "0.1.0"
|
||||
@ -37,8 +39,8 @@ serde_json = { version = "1.0", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tempdir = "0.3"
|
||||
lazy_static = "0.2"
|
||||
regex = "0.2"
|
||||
lazy_static = "1.0"
|
||||
regex = "1.0"
|
||||
|
||||
[dependencies.libsqlite3-sys]
|
||||
path = "libsqlite3-sys"
|
||||
|
12
appveyor.yml
12
appveyor.yml
@ -1,8 +1,8 @@
|
||||
environment:
|
||||
matrix:
|
||||
- TARGET: 1.21.0-x86_64-pc-windows-gnu
|
||||
- TARGET: 1.25.0-x86_64-pc-windows-gnu
|
||||
MSYS2_BITS: 64
|
||||
- TARGET: 1.21.0-x86_64-pc-windows-msvc
|
||||
- TARGET: 1.25.0-x86_64-pc-windows-msvc
|
||||
VCPKG_DEFAULT_TRIPLET: x64-windows
|
||||
VCPKGRS_DYNAMIC: 1
|
||||
- TARGET: nightly-x86_64-pc-windows-msvc
|
||||
@ -34,10 +34,10 @@ build: false
|
||||
test_script:
|
||||
- cargo test --lib --verbose
|
||||
- cargo test --lib --verbose --features bundled
|
||||
- cargo test --lib --features "backup blob chrono functions limits load_extension serde_json trace"
|
||||
- cargo test --lib --features "backup blob chrono functions limits load_extension serde_json trace buildtime_bindgen"
|
||||
- cargo test --lib --features "backup blob chrono functions limits load_extension serde_json trace bundled"
|
||||
- cargo test --lib --features "backup blob chrono functions limits load_extension serde_json trace bundled buildtime_bindgen"
|
||||
- cargo test --lib --features "backup blob chrono functions hooks limits load_extension serde_json trace"
|
||||
- cargo test --lib --features "backup blob chrono functions hooks limits load_extension serde_json trace buildtime_bindgen"
|
||||
- cargo test --lib --features "backup blob chrono functions hooks limits load_extension serde_json trace bundled"
|
||||
- cargo test --lib --features "backup blob chrono functions hooks limits load_extension serde_json trace bundled buildtime_bindgen"
|
||||
|
||||
cache:
|
||||
- C:\Users\appveyor\.cargo
|
||||
|
@ -21,9 +21,11 @@ min_sqlite_version_3_6_23 = ["pkg-config", "vcpkg"]
|
||||
min_sqlite_version_3_7_3 = ["pkg-config", "vcpkg"]
|
||||
min_sqlite_version_3_7_4 = ["pkg-config", "vcpkg"]
|
||||
min_sqlite_version_3_7_16 = ["pkg-config", "vcpkg"]
|
||||
# sqlite3_unlock_notify >= 3.6.12
|
||||
unlock_notify = []
|
||||
|
||||
[build-dependencies]
|
||||
bindgen = { version = "0.32", optional = true }
|
||||
bindgen = { version = "0.36", optional = true }
|
||||
pkg-config = { version = "0.3", optional = true }
|
||||
cc = { version = "1.0", optional = true }
|
||||
|
||||
|
@ -18,8 +18,8 @@ mod build {
|
||||
fs::copy("sqlite3/bindgen_bundled_version.rs", out_path)
|
||||
.expect("Could not copy bindings to output directory");
|
||||
|
||||
cc::Build::new()
|
||||
.file("sqlite3/sqlite3.c")
|
||||
let mut cfg = cc::Build::new();
|
||||
cfg.file("sqlite3/sqlite3.c")
|
||||
.flag("-DSQLITE_CORE")
|
||||
.flag("-DSQLITE_DEFAULT_FOREIGN_KEYS=1")
|
||||
.flag("-DSQLITE_ENABLE_API_ARMOR")
|
||||
@ -38,8 +38,11 @@ mod build {
|
||||
.flag("-DSQLITE_SOUNDEX")
|
||||
.flag("-DSQLITE_THREADSAFE=1")
|
||||
.flag("-DSQLITE_USE_URI")
|
||||
.flag("-DHAVE_USLEEP=1")
|
||||
.compile("libsqlite3.a");
|
||||
.flag("-DHAVE_USLEEP=1");
|
||||
if cfg!(feature = "unlock_notify") {
|
||||
cfg.flag("-DSQLITE_ENABLE_UNLOCK_NOTIFY");
|
||||
}
|
||||
cfg.compile("libsqlite3.a");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -91,7 +91,7 @@ impl Error {
|
||||
};
|
||||
|
||||
Error {
|
||||
code: code,
|
||||
code,
|
||||
extended_code: result_code,
|
||||
}
|
||||
}
|
||||
|
@ -208,7 +208,7 @@ impl<'a, 'b> Backup<'a, 'b> {
|
||||
Ok(Backup {
|
||||
phantom_from: PhantomData,
|
||||
phantom_to: PhantomData,
|
||||
b: b,
|
||||
b,
|
||||
})
|
||||
}
|
||||
|
||||
|
19
src/blob.rs
19
src/blob.rs
@ -50,7 +50,6 @@
|
||||
//! ```
|
||||
use std::io;
|
||||
use std::cmp::min;
|
||||
use std::mem;
|
||||
use std::ptr;
|
||||
|
||||
use super::ffi;
|
||||
@ -65,7 +64,7 @@ pub struct Blob<'conn> {
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
/// Open a handle to the BLOB located in `row`, `column`, `table` in database `db`.
|
||||
/// Open a handle to the BLOB located in `row_id`, `column`, `table` in database `db`.
|
||||
///
|
||||
/// # Failure
|
||||
///
|
||||
@ -75,7 +74,7 @@ impl Connection {
|
||||
db: DatabaseName,
|
||||
table: &str,
|
||||
column: &str,
|
||||
row: i64,
|
||||
row_id: i64,
|
||||
read_only: bool)
|
||||
-> Result<Blob<'a>> {
|
||||
let mut c = self.db.borrow_mut();
|
||||
@ -88,7 +87,7 @@ impl Connection {
|
||||
db.as_ptr(),
|
||||
table.as_ptr(),
|
||||
column.as_ptr(),
|
||||
row,
|
||||
row_id,
|
||||
if read_only { 0 } else { 1 },
|
||||
&mut blob)
|
||||
};
|
||||
@ -96,7 +95,7 @@ impl Connection {
|
||||
.map(|_| {
|
||||
Blob {
|
||||
conn: self,
|
||||
blob: blob,
|
||||
blob,
|
||||
pos: 0,
|
||||
}
|
||||
})
|
||||
@ -156,7 +155,7 @@ impl<'conn> io::Read for Blob<'conn> {
|
||||
return Ok(0);
|
||||
}
|
||||
let rc =
|
||||
unsafe { ffi::sqlite3_blob_read(self.blob, mem::transmute(buf.as_ptr()), n, self.pos) };
|
||||
unsafe { ffi::sqlite3_blob_read(self.blob, buf.as_ptr() as *mut _, n, self.pos) };
|
||||
self.conn
|
||||
.decode_result(rc)
|
||||
.map(|_| {
|
||||
@ -185,7 +184,7 @@ impl<'conn> io::Write for Blob<'conn> {
|
||||
return Ok(0);
|
||||
}
|
||||
let rc = unsafe {
|
||||
ffi::sqlite3_blob_write(self.blob, mem::transmute(buf.as_ptr()), n, self.pos)
|
||||
ffi::sqlite3_blob_write(self.blob, buf.as_ptr() as *mut _, n, self.pos)
|
||||
};
|
||||
self.conn
|
||||
.decode_result(rc)
|
||||
@ -206,14 +205,14 @@ impl<'conn> io::Seek for Blob<'conn> {
|
||||
fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
|
||||
let pos = match pos {
|
||||
io::SeekFrom::Start(offset) => offset as i64,
|
||||
io::SeekFrom::Current(offset) => self.pos as i64 + offset,
|
||||
io::SeekFrom::End(offset) => self.size() as i64 + offset,
|
||||
io::SeekFrom::Current(offset) => i64::from(self.pos) + offset,
|
||||
io::SeekFrom::End(offset) => i64::from(self.size()) + offset,
|
||||
};
|
||||
|
||||
if pos < 0 {
|
||||
Err(io::Error::new(io::ErrorKind::InvalidInput,
|
||||
"invalid seek to negative position"))
|
||||
} else if pos > self.size() as i64 {
|
||||
} else if pos > i64::from(self.size()) {
|
||||
Err(io::Error::new(io::ErrorKind::InvalidInput,
|
||||
"invalid seek to position past end of blob"))
|
||||
} else {
|
||||
|
30
src/cache.rs
30
src/cache.rs
@ -46,6 +46,7 @@ impl Connection {
|
||||
self.cache.set_capacity(capacity)
|
||||
}
|
||||
|
||||
/// Remove/finalize all prepared statements currently in the cache.
|
||||
pub fn flush_prepared_statement_cache(&self) {
|
||||
self.cache.flush()
|
||||
}
|
||||
@ -91,7 +92,7 @@ impl<'conn> CachedStatement<'conn> {
|
||||
fn new(stmt: Statement<'conn>, cache: &'conn StatementCache) -> CachedStatement<'conn> {
|
||||
CachedStatement {
|
||||
stmt: Some(stmt),
|
||||
cache: cache,
|
||||
cache,
|
||||
}
|
||||
}
|
||||
|
||||
@ -124,7 +125,7 @@ impl StatementCache {
|
||||
sql: &str)
|
||||
-> Result<CachedStatement<'conn>> {
|
||||
let mut cache = self.0.borrow_mut();
|
||||
let stmt = match cache.remove(sql) {
|
||||
let stmt = match cache.remove(sql.trim()) {
|
||||
Some(raw_stmt) => Ok(Statement::new(conn, raw_stmt)),
|
||||
None => conn.prepare(sql),
|
||||
};
|
||||
@ -135,7 +136,7 @@ impl StatementCache {
|
||||
fn cache_stmt(&self, stmt: RawStatement) {
|
||||
let mut cache = self.0.borrow_mut();
|
||||
stmt.clear_bindings();
|
||||
let sql = String::from_utf8_lossy(stmt.sql().to_bytes()).to_string();
|
||||
let sql = String::from_utf8_lossy(stmt.sql().to_bytes()).trim().to_string();
|
||||
cache.insert(sql, stmt);
|
||||
}
|
||||
|
||||
@ -285,4 +286,27 @@ mod test {
|
||||
|
||||
conn.close().expect("connection not closed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cache_key() {
|
||||
let db = Connection::open_in_memory().unwrap();
|
||||
let cache = &db.cache;
|
||||
assert_eq!(0, cache.len());
|
||||
|
||||
//let sql = " PRAGMA schema_version; -- comment";
|
||||
let sql = "PRAGMA schema_version; ";
|
||||
{
|
||||
let mut stmt = db.prepare_cached(sql).unwrap();
|
||||
assert_eq!(0, cache.len());
|
||||
assert_eq!(0, stmt.query_row(&[], |r| r.get::<i32, i64>(0)).unwrap());
|
||||
}
|
||||
assert_eq!(1, cache.len());
|
||||
|
||||
{
|
||||
let mut stmt = db.prepare_cached(sql).unwrap();
|
||||
assert_eq!(0, cache.len());
|
||||
assert_eq!(0, stmt.query_row(&[], |r| r.get::<i32, i64>(0)).unwrap());
|
||||
}
|
||||
assert_eq!(1, cache.len());
|
||||
}
|
||||
}
|
||||
|
@ -51,7 +51,6 @@
|
||||
//! ```
|
||||
use std::error::Error as StdError;
|
||||
use std::ffi::CStr;
|
||||
use std::mem;
|
||||
use std::ptr;
|
||||
use std::slice;
|
||||
use std::os::raw::{c_int, c_char, c_void};
|
||||
@ -183,7 +182,7 @@ impl<'a> ValueRef<'a> {
|
||||
}
|
||||
|
||||
unsafe extern "C" fn free_boxed_value<T>(p: *mut c_void) {
|
||||
let _: Box<T> = Box::from_raw(mem::transmute(p));
|
||||
let _: Box<T> = Box::from_raw(p as *mut T);
|
||||
}
|
||||
|
||||
/// Context is a wrapper for the SQLite function evaluation context.
|
||||
@ -234,7 +233,7 @@ impl<'a> Context<'a> {
|
||||
unsafe {
|
||||
ffi::sqlite3_set_auxdata(self.ctx,
|
||||
arg,
|
||||
mem::transmute(boxed),
|
||||
boxed as *mut c_void,
|
||||
Some(free_boxed_value::<T>))
|
||||
};
|
||||
}
|
||||
@ -370,10 +369,10 @@ impl InnerConnection {
|
||||
T: ToSql
|
||||
{
|
||||
let ctx = Context {
|
||||
ctx: ctx,
|
||||
ctx,
|
||||
args: slice::from_raw_parts(argv, argc as usize),
|
||||
};
|
||||
let boxed_f: *mut F = mem::transmute(ffi::sqlite3_user_data(ctx.ctx));
|
||||
let boxed_f: *mut F = ffi::sqlite3_user_data(ctx.ctx) as *mut F;
|
||||
assert!(!boxed_f.is_null(), "Internal error - null function pointer");
|
||||
|
||||
let t = (*boxed_f)(&ctx);
|
||||
@ -397,7 +396,7 @@ impl InnerConnection {
|
||||
c_name.as_ptr(),
|
||||
n_arg,
|
||||
flags,
|
||||
mem::transmute(boxed_f),
|
||||
boxed_f as *mut c_void,
|
||||
Some(call_boxed_closure::<F, T>),
|
||||
None,
|
||||
None,
|
||||
@ -431,7 +430,7 @@ impl InnerConnection {
|
||||
where D: Aggregate<A, T>,
|
||||
T: ToSql
|
||||
{
|
||||
let boxed_aggr: *mut D = mem::transmute(ffi::sqlite3_user_data(ctx));
|
||||
let boxed_aggr: *mut D = ffi::sqlite3_user_data(ctx) as *mut D;
|
||||
assert!(!boxed_aggr.is_null(),
|
||||
"Internal error - null aggregate pointer");
|
||||
|
||||
@ -448,7 +447,7 @@ impl InnerConnection {
|
||||
}
|
||||
|
||||
let mut ctx = Context {
|
||||
ctx: ctx,
|
||||
ctx,
|
||||
args: slice::from_raw_parts(argv, argc as usize),
|
||||
};
|
||||
|
||||
@ -462,7 +461,7 @@ impl InnerConnection {
|
||||
where D: Aggregate<A, T>,
|
||||
T: ToSql
|
||||
{
|
||||
let boxed_aggr: *mut D = mem::transmute(ffi::sqlite3_user_data(ctx));
|
||||
let boxed_aggr: *mut D = ffi::sqlite3_user_data(ctx) as *mut D;
|
||||
assert!(!boxed_aggr.is_null(),
|
||||
"Internal error - null aggregate pointer");
|
||||
|
||||
@ -500,7 +499,7 @@ impl InnerConnection {
|
||||
c_name.as_ptr(),
|
||||
n_arg,
|
||||
flags,
|
||||
mem::transmute(boxed_aggr),
|
||||
boxed_aggr as *mut c_void,
|
||||
None,
|
||||
Some(call_boxed_step::<A, D, T>),
|
||||
Some(call_boxed_final::<A, D, T>),
|
||||
|
308
src/hooks.rs
Normal file
308
src/hooks.rs
Normal file
@ -0,0 +1,308 @@
|
||||
//! Commit, Data Change and Rollback Notification Callbacks
|
||||
#![allow(non_camel_case_types)]
|
||||
|
||||
use std::ptr;
|
||||
use std::os::raw::{c_int, c_char, c_void};
|
||||
|
||||
use ffi;
|
||||
|
||||
use {Connection, InnerConnection};
|
||||
|
||||
/// Authorizer Action Codes
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Action {
|
||||
UNKNOWN = -1,
|
||||
SQLITE_CREATE_INDEX = ffi::SQLITE_CREATE_INDEX as isize,
|
||||
SQLITE_CREATE_TABLE = ffi::SQLITE_CREATE_TABLE as isize,
|
||||
SQLITE_CREATE_TEMP_INDEX = ffi::SQLITE_CREATE_TEMP_INDEX as isize,
|
||||
SQLITE_CREATE_TEMP_TABLE = ffi::SQLITE_CREATE_TEMP_TABLE as isize,
|
||||
SQLITE_CREATE_TEMP_TRIGGER = ffi::SQLITE_CREATE_TEMP_TRIGGER as isize,
|
||||
SQLITE_CREATE_TEMP_VIEW = ffi::SQLITE_CREATE_TEMP_VIEW as isize,
|
||||
SQLITE_CREATE_TRIGGER = ffi::SQLITE_CREATE_TRIGGER as isize,
|
||||
SQLITE_CREATE_VIEW = ffi::SQLITE_CREATE_VIEW as isize,
|
||||
SQLITE_DELETE = ffi::SQLITE_DELETE as isize,
|
||||
SQLITE_DROP_INDEX = ffi::SQLITE_DROP_INDEX as isize,
|
||||
SQLITE_DROP_TABLE = ffi::SQLITE_DROP_TABLE as isize,
|
||||
SQLITE_DROP_TEMP_INDEX = ffi::SQLITE_DROP_TEMP_INDEX as isize,
|
||||
SQLITE_DROP_TEMP_TABLE = ffi::SQLITE_DROP_TEMP_TABLE as isize,
|
||||
SQLITE_DROP_TEMP_TRIGGER = ffi::SQLITE_DROP_TEMP_TRIGGER as isize,
|
||||
SQLITE_DROP_TEMP_VIEW = ffi::SQLITE_DROP_TEMP_VIEW as isize,
|
||||
SQLITE_DROP_TRIGGER = ffi::SQLITE_DROP_TRIGGER as isize,
|
||||
SQLITE_DROP_VIEW = ffi::SQLITE_DROP_VIEW as isize,
|
||||
SQLITE_INSERT = ffi::SQLITE_INSERT as isize,
|
||||
SQLITE_PRAGMA = ffi::SQLITE_PRAGMA as isize,
|
||||
SQLITE_READ = ffi::SQLITE_READ as isize,
|
||||
SQLITE_SELECT = ffi::SQLITE_SELECT as isize,
|
||||
SQLITE_TRANSACTION = ffi::SQLITE_TRANSACTION as isize,
|
||||
SQLITE_UPDATE = ffi::SQLITE_UPDATE as isize,
|
||||
SQLITE_ATTACH = ffi::SQLITE_ATTACH as isize,
|
||||
SQLITE_DETACH = ffi::SQLITE_DETACH as isize,
|
||||
SQLITE_ALTER_TABLE = ffi::SQLITE_ALTER_TABLE as isize,
|
||||
SQLITE_REINDEX = ffi::SQLITE_REINDEX as isize,
|
||||
SQLITE_ANALYZE = ffi::SQLITE_ANALYZE as isize,
|
||||
SQLITE_CREATE_VTABLE = ffi::SQLITE_CREATE_VTABLE as isize,
|
||||
SQLITE_DROP_VTABLE = ffi::SQLITE_DROP_VTABLE as isize,
|
||||
SQLITE_FUNCTION = ffi::SQLITE_FUNCTION as isize,
|
||||
SQLITE_SAVEPOINT = ffi::SQLITE_SAVEPOINT as isize,
|
||||
SQLITE_COPY = ffi::SQLITE_COPY as isize,
|
||||
SQLITE_RECURSIVE = 33,
|
||||
}
|
||||
|
||||
impl From<i32> for Action {
|
||||
fn from(code: i32) -> Action {
|
||||
match code {
|
||||
ffi::SQLITE_CREATE_INDEX => Action::SQLITE_CREATE_INDEX,
|
||||
ffi::SQLITE_CREATE_TABLE => Action::SQLITE_CREATE_TABLE,
|
||||
ffi::SQLITE_CREATE_TEMP_INDEX => Action::SQLITE_CREATE_TEMP_INDEX,
|
||||
ffi::SQLITE_CREATE_TEMP_TABLE => Action::SQLITE_CREATE_TEMP_TABLE,
|
||||
ffi::SQLITE_CREATE_TEMP_TRIGGER => Action::SQLITE_CREATE_TEMP_TRIGGER,
|
||||
ffi::SQLITE_CREATE_TEMP_VIEW => Action::SQLITE_CREATE_TEMP_VIEW,
|
||||
ffi::SQLITE_CREATE_TRIGGER => Action::SQLITE_CREATE_TRIGGER,
|
||||
ffi::SQLITE_CREATE_VIEW => Action::SQLITE_CREATE_VIEW,
|
||||
ffi::SQLITE_DELETE => Action::SQLITE_DELETE,
|
||||
ffi::SQLITE_DROP_INDEX => Action::SQLITE_DROP_INDEX,
|
||||
ffi::SQLITE_DROP_TABLE => Action::SQLITE_DROP_TABLE,
|
||||
ffi::SQLITE_DROP_TEMP_INDEX => Action::SQLITE_DROP_TEMP_INDEX,
|
||||
ffi::SQLITE_DROP_TEMP_TABLE => Action::SQLITE_DROP_TEMP_TABLE,
|
||||
ffi::SQLITE_DROP_TEMP_TRIGGER => Action::SQLITE_DROP_TEMP_TRIGGER,
|
||||
ffi::SQLITE_DROP_TEMP_VIEW => Action::SQLITE_DROP_TEMP_VIEW,
|
||||
ffi::SQLITE_DROP_TRIGGER => Action::SQLITE_DROP_TRIGGER,
|
||||
ffi::SQLITE_DROP_VIEW => Action::SQLITE_DROP_VIEW,
|
||||
ffi::SQLITE_INSERT => Action::SQLITE_INSERT,
|
||||
ffi::SQLITE_PRAGMA => Action::SQLITE_PRAGMA,
|
||||
ffi::SQLITE_READ => Action::SQLITE_READ,
|
||||
ffi::SQLITE_SELECT => Action::SQLITE_SELECT,
|
||||
ffi::SQLITE_TRANSACTION => Action::SQLITE_TRANSACTION,
|
||||
ffi::SQLITE_UPDATE => Action::SQLITE_UPDATE,
|
||||
ffi::SQLITE_ATTACH => Action::SQLITE_ATTACH,
|
||||
ffi::SQLITE_DETACH => Action::SQLITE_DETACH,
|
||||
ffi::SQLITE_ALTER_TABLE => Action::SQLITE_ALTER_TABLE,
|
||||
ffi::SQLITE_REINDEX => Action::SQLITE_REINDEX,
|
||||
ffi::SQLITE_ANALYZE => Action::SQLITE_ANALYZE,
|
||||
ffi::SQLITE_CREATE_VTABLE => Action::SQLITE_CREATE_VTABLE,
|
||||
ffi::SQLITE_DROP_VTABLE => Action::SQLITE_DROP_VTABLE,
|
||||
ffi::SQLITE_FUNCTION => Action::SQLITE_FUNCTION,
|
||||
ffi::SQLITE_SAVEPOINT => Action::SQLITE_SAVEPOINT,
|
||||
ffi::SQLITE_COPY => Action::SQLITE_COPY,
|
||||
33 => Action::SQLITE_RECURSIVE,
|
||||
_ => Action::UNKNOWN,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
/// Register a callback function to be invoked whenever a transaction is committed.
|
||||
///
|
||||
/// The callback returns `true` to rollback.
|
||||
pub fn commit_hook<F>(&self, hook: F)
|
||||
where F: FnMut() -> bool
|
||||
{
|
||||
self.db.borrow_mut().commit_hook(hook);
|
||||
}
|
||||
|
||||
/// Register a callback function to be invoked whenever a transaction is committed.
|
||||
///
|
||||
/// The callback returns `true` to rollback.
|
||||
pub fn rollback_hook<F>(&self, hook: F)
|
||||
where F: FnMut()
|
||||
{
|
||||
self.db.borrow_mut().rollback_hook(hook);
|
||||
}
|
||||
|
||||
/// Register a callback function to be invoked whenever a row is updated,
|
||||
/// inserted or deleted in a rowid table.
|
||||
///
|
||||
/// The callback parameters are:
|
||||
///
|
||||
/// - the type of database update (SQLITE_INSERT, SQLITE_UPDATE or SQLITE_DELETE),
|
||||
/// - the name of the database ("main", "temp", ...),
|
||||
/// - the name of the table that is updated,
|
||||
/// - the ROWID of the row that is updated.
|
||||
pub fn update_hook<F>(&self, hook: F)
|
||||
where F: FnMut(Action, &str, &str, i64)
|
||||
{
|
||||
self.db.borrow_mut().update_hook(hook);
|
||||
}
|
||||
|
||||
/// Remove hook installed by `update_hook`.
|
||||
pub fn remove_update_hook(&self) {
|
||||
self.db.borrow_mut().remove_update_hook();
|
||||
}
|
||||
|
||||
/// Remove hook installed by `commit_hook`.
|
||||
pub fn remove_commit_hook(&self) {
|
||||
self.db.borrow_mut().remove_commit_hook();
|
||||
}
|
||||
|
||||
/// Remove hook installed by `rollback_hook`.
|
||||
pub fn remove_rollback_hook(&self) {
|
||||
self.db.borrow_mut().remove_rollback_hook();
|
||||
}
|
||||
}
|
||||
|
||||
impl InnerConnection {
|
||||
pub fn remove_hooks(&mut self) {
|
||||
self.remove_update_hook();
|
||||
self.remove_commit_hook();
|
||||
self.remove_rollback_hook();
|
||||
}
|
||||
|
||||
fn commit_hook<F>(&self, hook: F)
|
||||
where F: FnMut() -> bool
|
||||
{
|
||||
unsafe extern "C" fn call_boxed_closure<F>(p_arg: *mut c_void) -> c_int
|
||||
where F: FnMut() -> bool
|
||||
{
|
||||
let boxed_hook: *mut F = p_arg as *mut F;
|
||||
assert!(!boxed_hook.is_null(),
|
||||
"Internal error - null function pointer");
|
||||
|
||||
if (*boxed_hook)() { 1 } else { 0 }
|
||||
}
|
||||
|
||||
let previous_hook = {
|
||||
let boxed_hook: *mut F = Box::into_raw(Box::new(hook));
|
||||
unsafe {
|
||||
ffi::sqlite3_commit_hook(self.db(),
|
||||
Some(call_boxed_closure::<F>),
|
||||
boxed_hook as *mut _)
|
||||
}
|
||||
};
|
||||
free_boxed_hook(previous_hook);
|
||||
}
|
||||
|
||||
fn rollback_hook<F>(&self, hook: F)
|
||||
where F: FnMut()
|
||||
{
|
||||
unsafe extern "C" fn call_boxed_closure<F>(p_arg: *mut c_void)
|
||||
where F: FnMut()
|
||||
{
|
||||
let boxed_hook: *mut F = p_arg as *mut F;
|
||||
assert!(!boxed_hook.is_null(),
|
||||
"Internal error - null function pointer");
|
||||
|
||||
(*boxed_hook)();
|
||||
}
|
||||
|
||||
let previous_hook = {
|
||||
let boxed_hook: *mut F = Box::into_raw(Box::new(hook));
|
||||
unsafe {
|
||||
ffi::sqlite3_rollback_hook(self.db(),
|
||||
Some(call_boxed_closure::<F>),
|
||||
boxed_hook as *mut _)
|
||||
}
|
||||
};
|
||||
free_boxed_hook(previous_hook);
|
||||
}
|
||||
|
||||
fn update_hook<F>(&mut self, hook: F)
|
||||
where F: FnMut(Action, &str, &str, i64)
|
||||
{
|
||||
unsafe extern "C" fn call_boxed_closure<F>(p_arg: *mut c_void,
|
||||
action_code: c_int,
|
||||
db_str: *const c_char,
|
||||
tbl_str: *const c_char,
|
||||
row_id: i64)
|
||||
where F: FnMut(Action, &str, &str, i64)
|
||||
{
|
||||
use std::ffi::CStr;
|
||||
use std::str;
|
||||
|
||||
let boxed_hook: *mut F = p_arg as *mut F;
|
||||
assert!(!boxed_hook.is_null(),
|
||||
"Internal error - null function pointer");
|
||||
|
||||
let action = Action::from(action_code);
|
||||
let db_name = {
|
||||
let c_slice = CStr::from_ptr(db_str).to_bytes();
|
||||
str::from_utf8_unchecked(c_slice)
|
||||
};
|
||||
let tbl_name = {
|
||||
let c_slice = CStr::from_ptr(tbl_str).to_bytes();
|
||||
str::from_utf8_unchecked(c_slice)
|
||||
};
|
||||
|
||||
(*boxed_hook)(action, db_name, tbl_name, row_id);
|
||||
}
|
||||
|
||||
let previous_hook = {
|
||||
let boxed_hook: *mut F = Box::into_raw(Box::new(hook));
|
||||
unsafe {
|
||||
ffi::sqlite3_update_hook(self.db(),
|
||||
Some(call_boxed_closure::<F>),
|
||||
boxed_hook as *mut _)
|
||||
}
|
||||
};
|
||||
free_boxed_hook(previous_hook);
|
||||
}
|
||||
|
||||
fn remove_update_hook(&mut self) {
|
||||
let previous_hook = unsafe { ffi::sqlite3_update_hook(self.db(), None, ptr::null_mut()) };
|
||||
free_boxed_hook(previous_hook);
|
||||
}
|
||||
|
||||
fn remove_commit_hook(&mut self) {
|
||||
let previous_hook = unsafe { ffi::sqlite3_commit_hook(self.db(), None, ptr::null_mut()) };
|
||||
free_boxed_hook(previous_hook);
|
||||
}
|
||||
|
||||
fn remove_rollback_hook(&mut self) {
|
||||
let previous_hook = unsafe { ffi::sqlite3_rollback_hook(self.db(), None, ptr::null_mut()) };
|
||||
free_boxed_hook(previous_hook);
|
||||
}
|
||||
}
|
||||
|
||||
fn free_boxed_hook(hook: *mut c_void) {
|
||||
if !hook.is_null() {
|
||||
// TODO make sure that size_of::<*mut F>() is always equal to size_of::<*mut c_void>()
|
||||
let _: Box<*mut c_void> = unsafe { Box::from_raw(hook as *mut _) };
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::Action;
|
||||
use Connection;
|
||||
|
||||
#[test]
|
||||
fn test_commit_hook() {
|
||||
let db = Connection::open_in_memory().unwrap();
|
||||
|
||||
let mut called = false;
|
||||
db.commit_hook(|| {
|
||||
called = true;
|
||||
false
|
||||
});
|
||||
db.execute_batch("BEGIN; CREATE TABLE foo (t TEXT); COMMIT;")
|
||||
.unwrap();
|
||||
assert!(called);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rollback_hook() {
|
||||
let db = Connection::open_in_memory().unwrap();
|
||||
|
||||
let mut called = false;
|
||||
db.rollback_hook(|| { called = true; });
|
||||
db.execute_batch("BEGIN; CREATE TABLE foo (t TEXT); ROLLBACK;")
|
||||
.unwrap();
|
||||
assert!(called);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_update_hook() {
|
||||
let db = Connection::open_in_memory().unwrap();
|
||||
|
||||
let mut called = false;
|
||||
db.update_hook(|action, db, tbl, row_id| {
|
||||
assert_eq!(Action::SQLITE_INSERT, action);
|
||||
assert_eq!("main", db);
|
||||
assert_eq!("foo", tbl);
|
||||
assert_eq!(1, row_id);
|
||||
called = true;
|
||||
});
|
||||
db.execute_batch("CREATE TABLE foo (t TEXT)").unwrap();
|
||||
db.execute_batch("INSERT INTO foo VALUES ('lisa')").unwrap();
|
||||
assert!(called);
|
||||
}
|
||||
}
|
51
src/lib.rs
51
src/lib.rs
@ -121,6 +121,11 @@ pub mod functions;
|
||||
pub mod blob;
|
||||
#[cfg(feature = "limits")]
|
||||
pub mod limits;
|
||||
#[cfg(feature = "hooks")]
|
||||
mod hooks;
|
||||
#[cfg(feature = "hooks")]
|
||||
pub use hooks::*;
|
||||
mod unlock_notify;
|
||||
|
||||
// Number of cached prepared statements we'll hold on to.
|
||||
const STATEMENT_CACHE_DEFAULT_CAPACITY: usize = 16;
|
||||
@ -195,7 +200,7 @@ impl Connection {
|
||||
/// Open a new connection to a SQLite database.
|
||||
///
|
||||
/// `Connection::open(path)` is equivalent to `Connection::open_with_flags(path,
|
||||
/// SQLITE_OPEN_READ_WRITE | SQLITE_OPEN_CREATE)`.
|
||||
/// OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_CREATE)`.
|
||||
///
|
||||
/// # Failure
|
||||
///
|
||||
@ -775,7 +780,7 @@ impl InnerConnection {
|
||||
// attempt to turn on extended results code; don't fail if we can't.
|
||||
ffi::sqlite3_extended_result_codes(db, 1);
|
||||
|
||||
Ok(InnerConnection { db: db })
|
||||
Ok(InnerConnection { db })
|
||||
}
|
||||
}
|
||||
|
||||
@ -792,6 +797,10 @@ impl InnerConnection {
|
||||
}
|
||||
|
||||
fn close(&mut self) -> Result<()> {
|
||||
if self.db.is_null() {
|
||||
return Ok(());
|
||||
}
|
||||
self.remove_hooks();
|
||||
unsafe {
|
||||
let r = ffi::sqlite3_close(self.db());
|
||||
let r = self.decode_result(r);
|
||||
@ -854,21 +863,49 @@ impl InnerConnection {
|
||||
}
|
||||
let mut c_stmt: *mut ffi::sqlite3_stmt = unsafe { mem::uninitialized() };
|
||||
let c_sql = try!(str_to_cstring(sql));
|
||||
let r = unsafe {
|
||||
let len_with_nul = (sql.len() + 1) as c_int;
|
||||
ffi::sqlite3_prepare_v2(self.db(),
|
||||
let r = unsafe {
|
||||
if cfg!(feature = "unlock_notify") {
|
||||
let mut rc;
|
||||
loop {
|
||||
rc = ffi::sqlite3_prepare_v2(
|
||||
self.db(),
|
||||
c_sql.as_ptr(),
|
||||
len_with_nul,
|
||||
&mut c_stmt,
|
||||
ptr::null_mut())
|
||||
ptr::null_mut(),
|
||||
);
|
||||
if !unlock_notify::is_locked(self.db, rc) {
|
||||
break;
|
||||
}
|
||||
rc = unlock_notify::wait_for_unlock_notify(self.db);
|
||||
if rc != ffi::SQLITE_OK {
|
||||
break;
|
||||
}
|
||||
}
|
||||
rc
|
||||
} else {
|
||||
ffi::sqlite3_prepare_v2(
|
||||
self.db(),
|
||||
c_sql.as_ptr(),
|
||||
len_with_nul,
|
||||
&mut c_stmt,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
}
|
||||
};
|
||||
self.decode_result(r)
|
||||
.map(|_| Statement::new(conn, RawStatement::new(c_stmt)))
|
||||
self.decode_result(r).map(|_| {
|
||||
Statement::new(conn, RawStatement::new(c_stmt))
|
||||
})
|
||||
}
|
||||
|
||||
fn changes(&mut self) -> c_int {
|
||||
unsafe { ffi::sqlite3_changes(self.db()) }
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "hooks"))]
|
||||
fn remove_hooks(&mut self) {
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for InnerConnection {
|
||||
|
@ -26,7 +26,7 @@ impl<'conn> LoadExtensionGuard<'conn> {
|
||||
/// guard goes out of scope. Cannot be meaningfully nested.
|
||||
pub fn new(conn: &Connection) -> Result<LoadExtensionGuard> {
|
||||
conn.load_extension_enable()
|
||||
.map(|_| LoadExtensionGuard { conn: conn })
|
||||
.map(|_| LoadExtensionGuard { conn })
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -2,6 +2,7 @@ use std::ffi::CStr;
|
||||
use std::ptr;
|
||||
use std::os::raw::c_int;
|
||||
use super::ffi;
|
||||
use super::unlock_notify;
|
||||
|
||||
// Private newtype for raw sqlite3_stmts that finalize themselves when dropped.
|
||||
#[derive(Debug)]
|
||||
@ -29,8 +30,25 @@ impl RawStatement {
|
||||
}
|
||||
|
||||
pub fn step(&self) -> c_int {
|
||||
if cfg!(feature = "unlock_notify") {
|
||||
let db = unsafe { ffi::sqlite3_db_handle(self.0) };
|
||||
let mut rc;
|
||||
loop {
|
||||
rc = unsafe { ffi::sqlite3_step(self.0) };
|
||||
if !unlock_notify::is_locked(db, rc) {
|
||||
break;
|
||||
}
|
||||
rc = unlock_notify::wait_for_unlock_notify(db);
|
||||
if rc != ffi::SQLITE_OK {
|
||||
break;
|
||||
}
|
||||
self.reset();
|
||||
}
|
||||
rc
|
||||
} else {
|
||||
unsafe { ffi::sqlite3_step(self.0) }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset(&self) -> c_int {
|
||||
unsafe { ffi::sqlite3_reset(self.0) }
|
||||
|
@ -32,7 +32,7 @@ impl<'stmt> Rows<'stmt> {
|
||||
.and_then(|stmt| match stmt.step() {
|
||||
Ok(true) => {
|
||||
Some(Ok(Row {
|
||||
stmt: stmt,
|
||||
stmt,
|
||||
phantom: PhantomData,
|
||||
}))
|
||||
}
|
||||
@ -90,7 +90,7 @@ impl<'stmt, T, F> MappedRowsCrateImpl<'stmt, T, F> for MappedRows<'stmt, F>
|
||||
where F: FnMut(&Row) -> T
|
||||
{
|
||||
fn new(rows: Rows<'stmt>, f: F) -> MappedRows<'stmt, F> {
|
||||
MappedRows { rows: rows, map: f }
|
||||
MappedRows { rows, map: f }
|
||||
}
|
||||
}
|
||||
|
||||
@ -124,7 +124,7 @@ impl<'stmt, T, E, F> AndThenRowsCrateImpl<'stmt, T, E, F> for AndThenRows<'stmt,
|
||||
where F: FnMut(&Row) -> result::Result<T, E>
|
||||
{
|
||||
fn new(rows: Rows<'stmt>, f: F) -> AndThenRows<'stmt, F> {
|
||||
AndThenRows { rows: rows, map: f }
|
||||
AndThenRows { rows, map: f }
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -45,7 +45,7 @@ impl<'conn> Statement<'conn> {
|
||||
let bytes = name.as_bytes();
|
||||
let n = self.column_count();
|
||||
for i in 0..n {
|
||||
if bytes == self.stmt.column_name(i).to_bytes() {
|
||||
if bytes.eq_ignore_ascii_case(self.stmt.column_name(i).to_bytes()) {
|
||||
return Ok(i);
|
||||
}
|
||||
}
|
||||
@ -506,8 +506,8 @@ pub trait StatementCrateImpl<'conn> {
|
||||
impl<'conn> StatementCrateImpl<'conn> for Statement<'conn> {
|
||||
fn new(conn: &Connection, stmt: RawStatement) -> Statement {
|
||||
Statement {
|
||||
conn: conn,
|
||||
stmt: stmt,
|
||||
conn,
|
||||
stmt,
|
||||
}
|
||||
}
|
||||
|
||||
@ -785,4 +785,30 @@ mod test {
|
||||
let y: Result<i64> = stmt.query_row(&[&1i32], |r| r.get(0));
|
||||
assert_eq!(3i64, y.unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_query_by_column_name() {
|
||||
let db = Connection::open_in_memory().unwrap();
|
||||
let sql = "BEGIN;
|
||||
CREATE TABLE foo(x INTEGER, y INTEGER);
|
||||
INSERT INTO foo VALUES(1, 3);
|
||||
END;";
|
||||
db.execute_batch(sql).unwrap();
|
||||
let mut stmt = db.prepare("SELECT y FROM foo").unwrap();
|
||||
let y: Result<i64> = stmt.query_row(&[], |r| r.get("y"));
|
||||
assert_eq!(3i64, y.unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_query_by_column_name_ignore_case() {
|
||||
let db = Connection::open_in_memory().unwrap();
|
||||
let sql = "BEGIN;
|
||||
CREATE TABLE foo(x INTEGER, y INTEGER);
|
||||
INSERT INTO foo VALUES(1, 3);
|
||||
END;";
|
||||
db.execute_batch(sql).unwrap();
|
||||
let mut stmt = db.prepare("SELECT y as Y FROM foo").unwrap();
|
||||
let y: Result<i64> = stmt.query_row(&[], |r| r.get("y"));
|
||||
assert_eq!(3i64, y.unwrap());
|
||||
}
|
||||
}
|
||||
|
@ -26,6 +26,9 @@ pub enum DropBehavior {
|
||||
/// Do not commit or roll back changes - this will leave the transaction or savepoint
|
||||
/// open, so should be used with care.
|
||||
Ignore,
|
||||
|
||||
/// Panic. Used to enforce intentional behavior during development.
|
||||
Panic,
|
||||
}
|
||||
|
||||
/// Old name for `Transaction`. `SqliteTransaction` is deprecated.
|
||||
@ -106,7 +109,7 @@ impl<'conn> Transaction<'conn> {
|
||||
conn.execute_batch(query)
|
||||
.map(move |_| {
|
||||
Transaction {
|
||||
conn: conn,
|
||||
conn,
|
||||
drop_behavior: DropBehavior::Rollback,
|
||||
committed: false,
|
||||
}
|
||||
@ -195,6 +198,7 @@ impl<'conn> Transaction<'conn> {
|
||||
DropBehavior::Commit => self.commit_(),
|
||||
DropBehavior::Rollback => self.rollback_(),
|
||||
DropBehavior::Ignore => Ok(()),
|
||||
DropBehavior::Panic => panic!("Transaction dropped unexpectedly."),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -223,9 +227,9 @@ impl<'conn> Savepoint<'conn> {
|
||||
conn.execute_batch(&format!("SAVEPOINT {}", name))
|
||||
.map(|_| {
|
||||
Savepoint {
|
||||
conn: conn,
|
||||
name: name,
|
||||
depth: depth,
|
||||
conn,
|
||||
name,
|
||||
depth,
|
||||
drop_behavior: DropBehavior::Rollback,
|
||||
committed: false,
|
||||
}
|
||||
@ -306,6 +310,7 @@ impl<'conn> Savepoint<'conn> {
|
||||
DropBehavior::Commit => self.commit_(),
|
||||
DropBehavior::Rollback => self.rollback(),
|
||||
DropBehavior::Ignore => Ok(()),
|
||||
DropBehavior::Panic => panic!("Savepoint dropped unexpectedly."),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -10,12 +10,13 @@
|
||||
//! * Strings (`String` and `&str`)
|
||||
//! * Blobs (`Vec<u8>` and `&[u8]`)
|
||||
//!
|
||||
//! Additionally, because it is such a common data type, implementations are provided for
|
||||
//! `time::Timespec` that use a string for storage (using the same format string,
|
||||
//! `"%Y-%m-%d %H:%M:%S"`, as SQLite's builtin
|
||||
//! [datetime](https://www.sqlite.org/lang_datefunc.html) function. Note that this storage
|
||||
//! truncates timespecs to the nearest second. If you want different storage for timespecs, you can
|
||||
//! use a newtype. For example, to store timespecs as `f64`s:
|
||||
//! Additionally, because it is such a common data type, implementations are
|
||||
//! provided for `time::Timespec` that use the RFC 3339 date/time format,
|
||||
//! `"%Y-%m-%dT%H:%M:%S.%fZ"`, to store time values as strings. These values
|
||||
//! can be parsed by SQLite's builtin
|
||||
//! [datetime](https://www.sqlite.org/lang_datefunc.html) functions. If you
|
||||
//! want different storage for timespecs, you can use a newtype. For example, to
|
||||
//! store timespecs as `f64`s:
|
||||
//!
|
||||
//! ```rust
|
||||
//! extern crate rusqlite;
|
||||
|
@ -3,7 +3,8 @@ extern crate time;
|
||||
use Result;
|
||||
use types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
|
||||
|
||||
const SQLITE_DATETIME_FMT: &str = "%Y-%m-%d %H:%M:%S:%f %Z";
|
||||
const SQLITE_DATETIME_FMT: &str = "%Y-%m-%dT%H:%M:%S.%fZ";
|
||||
const SQLITE_DATETIME_FMT_LEGACY: &str = "%Y-%m-%d %H:%M:%S:%f %Z";
|
||||
|
||||
impl ToSql for time::Timespec {
|
||||
fn to_sql(&self) -> Result<ToSqlOutput> {
|
||||
@ -19,10 +20,12 @@ impl FromSql for time::Timespec {
|
||||
fn column_result(value: ValueRef) -> FromSqlResult<Self> {
|
||||
value
|
||||
.as_str()
|
||||
.and_then(|s| match time::strptime(s, SQLITE_DATETIME_FMT) {
|
||||
Ok(tm) => Ok(tm.to_timespec()),
|
||||
Err(err) => Err(FromSqlError::Other(Box::new(err))),
|
||||
})
|
||||
.and_then(|s| {
|
||||
time::strptime(s, SQLITE_DATETIME_FMT)
|
||||
.or_else(|err| {
|
||||
time::strptime(s, SQLITE_DATETIME_FMT_LEGACY)
|
||||
.or_else(|_| Err(FromSqlError::Other(Box::new(err))))})})
|
||||
.map(|tm| tm.to_timespec())
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -15,6 +15,8 @@ pub enum ToSqlOutput<'a> {
|
||||
ZeroBlob(i32),
|
||||
}
|
||||
|
||||
// Generically allow any type that can be converted into a ValueRef
|
||||
// to be converted into a ToSqlOutput as well.
|
||||
impl<'a, T: ?Sized> From<&'a T> for ToSqlOutput<'a>
|
||||
where &'a T: Into<ValueRef<'a>>
|
||||
{
|
||||
@ -23,11 +25,31 @@ impl<'a, T: ?Sized> From<&'a T> for ToSqlOutput<'a>
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: Into<Value>> From<T> for ToSqlOutput<'a> {
|
||||
fn from(t: T) -> Self {
|
||||
ToSqlOutput::Owned(t.into())
|
||||
}
|
||||
// We cannot also generically allow any type that can be converted
|
||||
// into a Value to be converted into a ToSqlOutput because of
|
||||
// coherence rules (https://github.com/rust-lang/rust/pull/46192),
|
||||
// so we'll manually implement it for all the types we know can
|
||||
// be converted into Values.
|
||||
macro_rules! from_value(
|
||||
($t:ty) => (
|
||||
impl<'a> From<$t> for ToSqlOutput<'a> {
|
||||
fn from(t: $t) -> Self { ToSqlOutput::Owned(t.into())}
|
||||
}
|
||||
)
|
||||
);
|
||||
from_value!(String);
|
||||
from_value!(Null);
|
||||
from_value!(bool);
|
||||
from_value!(i8);
|
||||
from_value!(i16);
|
||||
from_value!(i32);
|
||||
from_value!(i64);
|
||||
from_value!(isize);
|
||||
from_value!(u8);
|
||||
from_value!(u16);
|
||||
from_value!(u32);
|
||||
from_value!(f64);
|
||||
from_value!(Vec<u8>);
|
||||
|
||||
impl<'a> ToSql for ToSqlOutput<'a> {
|
||||
fn to_sql(&self) -> Result<ToSqlOutput> {
|
||||
|
129
src/unlock_notify.rs
Normal file
129
src/unlock_notify.rs
Normal file
@ -0,0 +1,129 @@
|
||||
//! [Unlock Notification](http://sqlite.org/unlock_notify.html)
|
||||
|
||||
#[cfg(feature = "unlock_notify")]
|
||||
use std::sync::{Condvar, Mutex};
|
||||
use std::os::raw::c_int;
|
||||
#[cfg(feature = "unlock_notify")]
|
||||
use std::os::raw::c_void;
|
||||
|
||||
use ffi;
|
||||
|
||||
#[cfg(feature = "unlock_notify")]
|
||||
struct UnlockNotification {
|
||||
cond: Condvar, // Condition variable to wait on
|
||||
mutex: Mutex<bool>, // Mutex to protect structure
|
||||
}
|
||||
|
||||
#[cfg(feature = "unlock_notify")]
|
||||
impl UnlockNotification {
|
||||
fn new() -> UnlockNotification {
|
||||
UnlockNotification {
|
||||
cond: Condvar::new(),
|
||||
mutex: Mutex::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
fn fired(&mut self) {
|
||||
*self.mutex.lock().unwrap() = true;
|
||||
self.cond.notify_one();
|
||||
}
|
||||
|
||||
fn wait(&mut self) {
|
||||
let mut fired = self.mutex.lock().unwrap();
|
||||
while !*fired {
|
||||
fired = self.cond.wait(fired).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This function is an unlock-notify callback
|
||||
#[cfg(feature = "unlock_notify")]
|
||||
unsafe extern "C" fn unlock_notify_cb(ap_arg: *mut *mut c_void, n_arg: c_int) {
|
||||
use std::slice::from_raw_parts;
|
||||
let args = from_raw_parts(ap_arg, n_arg as usize);
|
||||
for arg in args {
|
||||
let un: &mut UnlockNotification = &mut *(*arg as *mut UnlockNotification);
|
||||
un.fired();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unlock_notify")]
|
||||
pub fn is_locked(db: *mut ffi::sqlite3, rc: c_int) -> bool {
|
||||
rc == ffi::SQLITE_LOCKED_SHAREDCACHE || (rc & 0xFF) == ffi::SQLITE_LOCKED && unsafe {
|
||||
ffi::sqlite3_extended_errcode(db)
|
||||
}
|
||||
== ffi::SQLITE_LOCKED_SHAREDCACHE
|
||||
}
|
||||
|
||||
/// This function assumes that an SQLite API call (either `sqlite3_prepare_v2()`
|
||||
/// or `sqlite3_step()`) has just returned `SQLITE_LOCKED`. The argument is the
|
||||
/// associated database connection.
|
||||
///
|
||||
/// This function calls `sqlite3_unlock_notify()` to register for an
|
||||
/// unlock-notify callback, then blocks until that callback is delivered
|
||||
/// and returns `SQLITE_OK`. The caller should then retry the failed operation.
|
||||
///
|
||||
/// Or, if `sqlite3_unlock_notify()` indicates that to block would deadlock
|
||||
/// the system, then this function returns `SQLITE_LOCKED` immediately. In
|
||||
/// this case the caller should not retry the operation and should roll
|
||||
/// back the current transaction (if any).
|
||||
#[cfg(feature = "unlock_notify")]
|
||||
pub fn wait_for_unlock_notify(db: *mut ffi::sqlite3) -> c_int {
|
||||
let mut un = UnlockNotification::new();
|
||||
/* Register for an unlock-notify callback. */
|
||||
let rc = unsafe {
|
||||
ffi::sqlite3_unlock_notify(
|
||||
db,
|
||||
Some(unlock_notify_cb),
|
||||
&mut un as *mut UnlockNotification as *mut c_void,
|
||||
)
|
||||
};
|
||||
debug_assert!(
|
||||
rc == ffi::SQLITE_LOCKED || rc == ffi::SQLITE_LOCKED_SHAREDCACHE || rc == ffi::SQLITE_OK
|
||||
);
|
||||
if rc == ffi::SQLITE_OK {
|
||||
un.wait();
|
||||
}
|
||||
rc
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "unlock_notify"))]
|
||||
pub fn is_locked(_db: *mut ffi::sqlite3, _rc: c_int) -> bool {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "unlock_notify"))]
|
||||
pub fn wait_for_unlock_notify(_db: *mut ffi::sqlite3) -> c_int {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
#[cfg(feature = "unlock_notify")]
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::sync::mpsc::sync_channel;
|
||||
use std::thread;
|
||||
use std::time;
|
||||
use {Connection, OpenFlags, Result, Transaction, TransactionBehavior};
|
||||
|
||||
#[test]
|
||||
fn test_unlock_notify() {
|
||||
let url = "file::memory:?cache=shared";
|
||||
let flags = OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_URI;
|
||||
let db1 = Connection::open_with_flags(url, flags).unwrap();
|
||||
db1.execute_batch("CREATE TABLE foo (x)").unwrap();
|
||||
let (rx, tx) = sync_channel(0);
|
||||
let child = thread::spawn(move || {
|
||||
let mut db2 = Connection::open_with_flags(url, flags).unwrap();
|
||||
let tx2 = Transaction::new(&mut db2, TransactionBehavior::Immediate).unwrap();
|
||||
tx2.execute_batch("INSERT INTO foo VALUES (42)").unwrap();
|
||||
rx.send(1).unwrap();
|
||||
let ten_millis = time::Duration::from_millis(10);
|
||||
thread::sleep(ten_millis);
|
||||
tx2.commit().unwrap();
|
||||
});
|
||||
assert_eq!(tx.recv().unwrap(), 1);
|
||||
let the_answer: Result<i64> = db1.query_row("SELECT x FROM foo", &[], |r| r.get(0));
|
||||
assert_eq!(42i64, the_answer.unwrap());
|
||||
child.join().unwrap();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user