mirror of
https://github.com/isar/rusqlite.git
synced 2026-02-11 13:29:11 +08:00
Merge branch 'master' into captured_identifiers
This commit is contained in:
@@ -274,7 +274,6 @@ impl Blob<'_> {
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn len(&self) -> usize {
|
||||
use std::convert::TryInto;
|
||||
self.size().try_into().unwrap()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Prepared statements cache for faster execution.
|
||||
|
||||
use crate::raw_statement::RawStatement;
|
||||
use crate::{Connection, Result, Statement};
|
||||
use crate::{Connection, PrepFlags, Result, Statement};
|
||||
use hashlink::LruCache;
|
||||
use std::cell::RefCell;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
@@ -144,7 +144,7 @@ impl StatementCache {
|
||||
let mut cache = self.0.borrow_mut();
|
||||
let stmt = match cache.remove(trimmed) {
|
||||
Some(raw_stmt) => Ok(Statement::new(conn, raw_stmt)),
|
||||
None => conn.prepare(trimmed),
|
||||
None => conn.prepare_with_flags(trimmed, PrepFlags::SQLITE_PREPARE_PERSISTENT),
|
||||
};
|
||||
stmt.map(|mut stmt| {
|
||||
stmt.stmt.set_statement_cache_key(trimmed);
|
||||
|
||||
@@ -203,7 +203,7 @@ mod test {
|
||||
assert_eq!(ty, Type::Integer);
|
||||
}
|
||||
e => {
|
||||
panic!("Unexpected error type: {:?}", e);
|
||||
panic!("Unexpected error type: {e:?}");
|
||||
}
|
||||
}
|
||||
match row.get::<_, String>("y").unwrap_err() {
|
||||
@@ -213,7 +213,7 @@ mod test {
|
||||
assert_eq!(ty, Type::Null);
|
||||
}
|
||||
e => {
|
||||
panic!("Unexpected error type: {:?}", e);
|
||||
panic!("Unexpected error type: {e:?}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -61,6 +61,13 @@ pub enum DbConfig {
|
||||
/// sqlite_master tables) are untainted by malicious content.
|
||||
#[cfg(feature = "modern_sqlite")]
|
||||
SQLITE_DBCONFIG_TRUSTED_SCHEMA = 1017, // 3.31.0
|
||||
/// Sets or clears a flag that enables collection of the
|
||||
/// sqlite3_stmt_scanstatus_v2() statistics
|
||||
#[cfg(feature = "modern_sqlite")]
|
||||
SQLITE_DBCONFIG_STMT_SCANSTATUS = 1018, // 3.42.0
|
||||
/// Changes the default order in which tables and indexes are scanned
|
||||
#[cfg(feature = "modern_sqlite")]
|
||||
SQLITE_DBCONFIG_REVERSE_SCANORDER = 1019, // 3.42.0
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
|
||||
40
src/error.rs
40
src/error.rs
@@ -252,11 +252,7 @@ impl fmt::Display for Error {
|
||||
),
|
||||
Error::FromSqlConversionFailure(i, ref t, ref err) => {
|
||||
if i != UNKNOWN_COLUMN {
|
||||
write!(
|
||||
f,
|
||||
"Conversion error from type {} at index: {}, {}",
|
||||
t, i, err
|
||||
)
|
||||
write!(f, "Conversion error from type {t} at index: {i}, {err}")
|
||||
} else {
|
||||
err.fmt(f)
|
||||
}
|
||||
@@ -278,15 +274,12 @@ impl fmt::Display for Error {
|
||||
Error::QueryReturnedNoRows => write!(f, "Query returned no rows"),
|
||||
Error::InvalidColumnIndex(i) => write!(f, "Invalid column index: {i}"),
|
||||
Error::InvalidColumnName(ref name) => write!(f, "Invalid column name: {name}"),
|
||||
Error::InvalidColumnType(i, ref name, ref t) => write!(
|
||||
f,
|
||||
"Invalid column type {} at index: {}, name: {}",
|
||||
t, i, name
|
||||
),
|
||||
Error::InvalidColumnType(i, ref name, ref t) => {
|
||||
write!(f, "Invalid column type {t} at index: {i}, name: {name}")
|
||||
}
|
||||
Error::InvalidParameterCount(i1, n1) => write!(
|
||||
f,
|
||||
"Wrong number of parameters passed to query. Got {}, needed {}",
|
||||
i1, n1
|
||||
"Wrong number of parameters passed to query. Got {i1}, needed {n1}"
|
||||
),
|
||||
Error::StatementChangedRows(i) => write!(f, "Query changed {i} rows"),
|
||||
|
||||
@@ -393,7 +386,6 @@ impl Error {
|
||||
|
||||
#[cold]
|
||||
pub fn error_from_sqlite_code(code: c_int, message: Option<String>) -> Error {
|
||||
// TODO sqlite3_error_offset // 3.38.0, #1130
|
||||
Error::SqliteFailure(ffi::Error::new(code), message)
|
||||
}
|
||||
|
||||
@@ -443,3 +435,25 @@ pub fn check(code: c_int) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Transform Rust error to SQLite error (message and code).
|
||||
/// # Safety
|
||||
/// This function is unsafe because it uses raw pointer
|
||||
pub unsafe fn to_sqlite_error(
|
||||
e: &Error,
|
||||
err_msg: *mut *mut std::os::raw::c_char,
|
||||
) -> std::os::raw::c_int {
|
||||
use crate::util::alloc;
|
||||
match e {
|
||||
Error::SqliteFailure(err, s) => {
|
||||
if let Some(s) = s {
|
||||
*err_msg = alloc(s);
|
||||
}
|
||||
err.extended_code
|
||||
}
|
||||
err => {
|
||||
*err_msg = alloc(&err.to_string());
|
||||
ffi::SQLITE_ERROR
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,21 +71,13 @@ use crate::types::{FromSql, FromSqlError, ToSql, ValueRef};
|
||||
use crate::{str_to_cstring, Connection, Error, InnerConnection, Result};
|
||||
|
||||
unsafe fn report_error(ctx: *mut sqlite3_context, err: &Error) {
|
||||
// Extended constraint error codes were added in SQLite 3.7.16. We don't have
|
||||
// an explicit feature check for that, and this doesn't really warrant one.
|
||||
// We'll use the extended code if we're on the bundled version (since it's
|
||||
// at least 3.17.0) and the normal constraint error code if not.
|
||||
fn constraint_error_code() -> i32 {
|
||||
ffi::SQLITE_CONSTRAINT_FUNCTION
|
||||
}
|
||||
|
||||
if let Error::SqliteFailure(ref err, ref s) = *err {
|
||||
ffi::sqlite3_result_error_code(ctx, err.extended_code);
|
||||
if let Some(Ok(cstr)) = s.as_ref().map(|s| str_to_cstring(s)) {
|
||||
ffi::sqlite3_result_error(ctx, cstr.as_ptr(), -1);
|
||||
}
|
||||
} else {
|
||||
ffi::sqlite3_result_error_code(ctx, constraint_error_code());
|
||||
ffi::sqlite3_result_error_code(ctx, ffi::SQLITE_CONSTRAINT_FUNCTION);
|
||||
if let Ok(cstr) = str_to_cstring(&err.to_string()) {
|
||||
ffi::sqlite3_result_error(ctx, cstr.as_ptr(), -1);
|
||||
}
|
||||
@@ -847,7 +839,7 @@ mod test {
|
||||
// This implementation of a regexp scalar function uses SQLite's auxiliary data
|
||||
// (https://www.sqlite.org/c3ref/get_auxdata.html) to avoid recompiling the regular
|
||||
// expression multiple times within one query.
|
||||
fn regexp_with_auxilliary(ctx: &Context<'_>) -> Result<bool> {
|
||||
fn regexp_with_auxiliary(ctx: &Context<'_>) -> Result<bool> {
|
||||
assert_eq!(ctx.len(), 2, "called with unexpected number of arguments");
|
||||
type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
|
||||
let regexp: std::sync::Arc<Regex> = ctx
|
||||
@@ -868,7 +860,7 @@ mod test {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_function_regexp_with_auxilliary() -> Result<()> {
|
||||
fn test_function_regexp_with_auxiliary() -> Result<()> {
|
||||
let db = Connection::open_in_memory()?;
|
||||
db.execute_batch(
|
||||
"BEGIN;
|
||||
@@ -882,7 +874,7 @@ mod test {
|
||||
"regexp",
|
||||
2,
|
||||
FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,
|
||||
regexp_with_auxilliary,
|
||||
regexp_with_auxiliary,
|
||||
)?;
|
||||
|
||||
let result: bool = db.one_column("SELECT regexp('l.s[aeiouy]', 'lisa')")?;
|
||||
|
||||
@@ -656,7 +656,7 @@ unsafe fn free_boxed_hook<F>(p: *mut c_void) {
|
||||
|
||||
unsafe fn expect_utf8<'a>(p_str: *const c_char, description: &'static str) -> &'a str {
|
||||
expect_optional_utf8(p_str, description)
|
||||
.unwrap_or_else(|| panic!("received empty {}", description))
|
||||
.unwrap_or_else(|| panic!("received empty {description}"))
|
||||
}
|
||||
|
||||
unsafe fn expect_optional_utf8<'a>(
|
||||
@@ -667,7 +667,7 @@ unsafe fn expect_optional_utf8<'a>(
|
||||
return None;
|
||||
}
|
||||
std::str::from_utf8(std::ffi::CStr::from_ptr(p_str).to_bytes())
|
||||
.unwrap_or_else(|_| panic!("received non-utf8 string as {}", description))
|
||||
.unwrap_or_else(|_| panic!("received non-utf8 string as {description}"))
|
||||
.into()
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use super::ffi;
|
||||
use super::str_for_sqlite;
|
||||
use super::{Connection, InterruptHandle, OpenFlags, Result};
|
||||
use super::{Connection, InterruptHandle, OpenFlags, PrepFlags, Result};
|
||||
use crate::error::{error_from_handle, error_from_sqlite_code, error_with_offset, Error};
|
||||
use crate::raw_statement::RawStatement;
|
||||
use crate::statement::Statement;
|
||||
@@ -218,33 +218,24 @@ impl InnerConnection {
|
||||
unsafe { ffi::sqlite3_last_insert_rowid(self.db()) }
|
||||
}
|
||||
|
||||
pub fn prepare<'a>(&mut self, conn: &'a Connection, sql: &str) -> Result<Statement<'a>> {
|
||||
let mut c_stmt = ptr::null_mut();
|
||||
pub fn prepare<'a>(
|
||||
&mut self,
|
||||
conn: &'a Connection,
|
||||
sql: &str,
|
||||
flags: PrepFlags,
|
||||
) -> Result<Statement<'a>> {
|
||||
let mut c_stmt: *mut ffi::sqlite3_stmt = ptr::null_mut();
|
||||
let (c_sql, len, _) = str_for_sqlite(sql.as_bytes())?;
|
||||
let mut c_tail = ptr::null();
|
||||
let mut c_tail: *const c_char = ptr::null();
|
||||
// TODO sqlite3_prepare_v3 (https://sqlite.org/c3ref/c_prepare_normalize.html) // 3.20.0, #728
|
||||
#[cfg(not(feature = "unlock_notify"))]
|
||||
let r = unsafe {
|
||||
ffi::sqlite3_prepare_v2(
|
||||
self.db(),
|
||||
c_sql,
|
||||
len,
|
||||
&mut c_stmt as *mut *mut ffi::sqlite3_stmt,
|
||||
&mut c_tail as *mut *const c_char,
|
||||
)
|
||||
};
|
||||
let r = unsafe { self.prepare_(c_sql, len, flags, &mut c_stmt, &mut c_tail) };
|
||||
#[cfg(feature = "unlock_notify")]
|
||||
let r = unsafe {
|
||||
use crate::unlock_notify;
|
||||
let mut rc;
|
||||
loop {
|
||||
rc = ffi::sqlite3_prepare_v2(
|
||||
self.db(),
|
||||
c_sql,
|
||||
len,
|
||||
&mut c_stmt as *mut *mut ffi::sqlite3_stmt,
|
||||
&mut c_tail as *mut *const c_char,
|
||||
);
|
||||
rc = self.prepare_(c_sql, len, flags, &mut c_stmt, &mut c_tail);
|
||||
if !unlock_notify::is_locked(self.db, rc) {
|
||||
break;
|
||||
}
|
||||
@@ -261,8 +252,6 @@ impl InnerConnection {
|
||||
}
|
||||
// If the input text contains no SQL (if the input is an empty string or a
|
||||
// comment) then *ppStmt is set to NULL.
|
||||
let c_stmt: *mut ffi::sqlite3_stmt = c_stmt;
|
||||
let c_tail: *const c_char = c_tail;
|
||||
let tail = if c_tail.is_null() {
|
||||
0
|
||||
} else {
|
||||
@@ -278,6 +267,32 @@ impl InnerConnection {
|
||||
}))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(not(feature = "modern_sqlite"))]
|
||||
unsafe fn prepare_(
|
||||
&self,
|
||||
z_sql: *const c_char,
|
||||
n_byte: c_int,
|
||||
_: PrepFlags,
|
||||
pp_stmt: *mut *mut ffi::sqlite3_stmt,
|
||||
pz_tail: *mut *const c_char,
|
||||
) -> c_int {
|
||||
ffi::sqlite3_prepare_v2(self.db(), z_sql, n_byte, pp_stmt, pz_tail)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "modern_sqlite")]
|
||||
unsafe fn prepare_(
|
||||
&self,
|
||||
z_sql: *const c_char,
|
||||
n_byte: c_int,
|
||||
flags: PrepFlags,
|
||||
pp_stmt: *mut *mut ffi::sqlite3_stmt,
|
||||
pz_tail: *mut *const c_char,
|
||||
) -> c_int {
|
||||
ffi::sqlite3_prepare_v3(self.db(), z_sql, n_byte, flags.bits(), pp_stmt, pz_tail)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn changes(&self) -> u64 {
|
||||
#[cfg(not(feature = "modern_sqlite"))]
|
||||
@@ -382,7 +397,7 @@ pub static BYPASS_SQLITE_INIT: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
// threading mode checks are not necessary (and do not work) on target
|
||||
// platforms that do not have threading (such as webassembly)
|
||||
#[cfg(any(target_arch = "wasm32"))]
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn ensure_safe_sqlite_threading_mode() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
76
src/lib.rs
76
src/lib.rs
@@ -75,7 +75,7 @@ use crate::types::ValueRef;
|
||||
|
||||
pub use crate::cache::CachedStatement;
|
||||
pub use crate::column::Column;
|
||||
pub use crate::error::Error;
|
||||
pub use crate::error::{to_sqlite_error, Error};
|
||||
pub use crate::ffi::ErrorCode;
|
||||
#[cfg(feature = "load_extension")]
|
||||
pub use crate::load_extension_guard::LoadExtensionGuard;
|
||||
@@ -122,6 +122,9 @@ mod params;
|
||||
mod pragma;
|
||||
mod raw_statement;
|
||||
mod row;
|
||||
#[cfg(feature = "serialize")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "serialize")))]
|
||||
pub mod serialize;
|
||||
#[cfg(feature = "session")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "session")))]
|
||||
pub mod session;
|
||||
@@ -759,7 +762,18 @@ impl Connection {
|
||||
/// or if the underlying SQLite call fails.
|
||||
#[inline]
|
||||
pub fn prepare(&self, sql: &str) -> Result<Statement<'_>> {
|
||||
self.db.borrow_mut().prepare(self, sql)
|
||||
self.prepare_with_flags(sql, PrepFlags::default())
|
||||
}
|
||||
|
||||
/// Prepare a SQL statement for execution.
|
||||
///
|
||||
/// # Failure
|
||||
///
|
||||
/// Will return `Err` if `sql` cannot be converted to a C-compatible string
|
||||
/// or if the underlying SQLite call fails.
|
||||
#[inline]
|
||||
pub fn prepare_with_flags(&self, sql: &str, flags: PrepFlags) -> Result<Statement<'_>> {
|
||||
self.db.borrow_mut().prepare(self, sql, flags)
|
||||
}
|
||||
|
||||
/// Close the SQLite connection.
|
||||
@@ -1073,7 +1087,7 @@ impl<'conn> Iterator for Batch<'conn, '_> {
|
||||
|
||||
bitflags::bitflags! {
|
||||
/// Flags for opening SQLite database connections. See
|
||||
/// [sqlite3_open_v2](http://www.sqlite.org/c3ref/open.html) for details.
|
||||
/// [sqlite3_open_v2](https://www.sqlite.org/c3ref/open.html) for details.
|
||||
///
|
||||
/// The default open flags are `SQLITE_OPEN_READ_WRITE | SQLITE_OPEN_CREATE
|
||||
/// | SQLITE_OPEN_URI | SQLITE_OPEN_NO_MUTEX`. See [`Connection::open`] for
|
||||
@@ -1155,6 +1169,19 @@ impl Default for OpenFlags {
|
||||
}
|
||||
}
|
||||
|
||||
bitflags::bitflags! {
|
||||
/// Prepare flags. See
|
||||
/// [sqlite3_prepare_v3](https://sqlite.org/c3ref/c_prepare_normalize.html) for details.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
|
||||
#[repr(C)]
|
||||
pub struct PrepFlags: ::std::os::raw::c_uint {
|
||||
/// A hint to the query planner that the prepared statement will be retained for a long time and probably reused many times.
|
||||
const SQLITE_PREPARE_PERSISTENT = 0x01;
|
||||
/// Causes the SQL compiler to return an error (error code SQLITE_ERROR) if the statement uses any virtual tables.
|
||||
const SQLITE_PREPARE_NO_VTAB = 0x04;
|
||||
}
|
||||
}
|
||||
|
||||
/// rusqlite's check for a safe SQLite threading mode requires SQLite 3.7.0 or
|
||||
/// later. If you are running against a SQLite older than that, rusqlite
|
||||
/// attempts to ensure safety by performing configuration and initialization of
|
||||
@@ -1211,13 +1238,21 @@ mod test {
|
||||
// this function is never called, but is still type checked; in
|
||||
// particular, calls with specific instantiations will require
|
||||
// that those types are `Send`.
|
||||
#[allow(dead_code, unconditional_recursion)]
|
||||
#[allow(
|
||||
dead_code,
|
||||
unconditional_recursion,
|
||||
clippy::extra_unused_type_parameters
|
||||
)]
|
||||
fn ensure_send<T: Send>() {
|
||||
ensure_send::<Connection>();
|
||||
ensure_send::<InterruptHandle>();
|
||||
}
|
||||
|
||||
#[allow(dead_code, unconditional_recursion)]
|
||||
#[allow(
|
||||
dead_code,
|
||||
unconditional_recursion,
|
||||
clippy::extra_unused_type_parameters
|
||||
)]
|
||||
fn ensure_sync<T: Sync>() {
|
||||
ensure_sync::<InterruptHandle>();
|
||||
}
|
||||
@@ -1323,9 +1358,7 @@ mod test {
|
||||
assert_eq!(ffi::SQLITE_CANTOPEN, e.extended_code);
|
||||
assert!(
|
||||
msg.contains(filename),
|
||||
"error message '{}' does not contain '{}'",
|
||||
msg,
|
||||
filename
|
||||
"error message '{msg}' does not contain '{filename}'"
|
||||
);
|
||||
} else {
|
||||
panic!("SqliteFailure expected");
|
||||
@@ -1453,8 +1486,7 @@ mod test {
|
||||
assert_eq!(
|
||||
err,
|
||||
Error::ExecuteReturnedResults,
|
||||
"Unexpected error: {}",
|
||||
err
|
||||
"Unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1470,7 +1502,7 @@ mod test {
|
||||
.unwrap_err();
|
||||
match err {
|
||||
Error::MultipleStatement => (),
|
||||
_ => panic!("Unexpected error: {}", err),
|
||||
_ => panic!("Unexpected error: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1581,7 +1613,7 @@ mod test {
|
||||
let result: Result<i64> = db.one_column("SELECT x FROM foo WHERE x > 5");
|
||||
match result.unwrap_err() {
|
||||
Error::QueryReturnedNoRows => (),
|
||||
err => panic!("Unexpected error {}", err),
|
||||
err => panic!("Unexpected error {err}"),
|
||||
}
|
||||
|
||||
let bad_query_result = db.query_row("NOT A PROPER QUERY; test123", [], |_| Ok(()));
|
||||
@@ -1633,7 +1665,7 @@ mod test {
|
||||
// > MEMORY or OFF and can not be changed to a different value. An
|
||||
// > attempt to change the journal_mode of an in-memory database to
|
||||
// > any setting other than MEMORY or OFF is ignored.
|
||||
assert!(mode == "memory" || mode == "off", "Got mode {:?}", mode);
|
||||
assert!(mode == "memory" || mode == "off", "Got mode {mode:?}");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -1720,7 +1752,7 @@ mod test {
|
||||
assert_eq!(err.code, ErrorCode::ConstraintViolation);
|
||||
check_extended_code(err.extended_code);
|
||||
}
|
||||
err => panic!("Unexpected error {}", err),
|
||||
err => panic!("Unexpected error {err}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1912,7 +1944,7 @@ mod test {
|
||||
|
||||
match bad_type.unwrap_err() {
|
||||
Error::InvalidColumnType(..) => (),
|
||||
err => panic!("Unexpected error {}", err),
|
||||
err => panic!("Unexpected error {err}"),
|
||||
}
|
||||
|
||||
let bad_idx: Result<Vec<String>> =
|
||||
@@ -1920,7 +1952,7 @@ mod test {
|
||||
|
||||
match bad_idx.unwrap_err() {
|
||||
Error::InvalidColumnIndex(_) => (),
|
||||
err => panic!("Unexpected error {}", err),
|
||||
err => panic!("Unexpected error {err}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1965,7 +1997,7 @@ mod test {
|
||||
|
||||
match bad_type.unwrap_err() {
|
||||
CustomError::Sqlite(Error::InvalidColumnType(..)) => (),
|
||||
err => panic!("Unexpected error {}", err),
|
||||
err => panic!("Unexpected error {err}"),
|
||||
}
|
||||
|
||||
let bad_idx: CustomResult<Vec<String>> = query
|
||||
@@ -1974,7 +2006,7 @@ mod test {
|
||||
|
||||
match bad_idx.unwrap_err() {
|
||||
CustomError::Sqlite(Error::InvalidColumnIndex(_)) => (),
|
||||
err => panic!("Unexpected error {}", err),
|
||||
err => panic!("Unexpected error {err}"),
|
||||
}
|
||||
|
||||
let non_sqlite_err: CustomResult<Vec<String>> = query
|
||||
@@ -1983,7 +2015,7 @@ mod test {
|
||||
|
||||
match non_sqlite_err.unwrap_err() {
|
||||
CustomError::SomeError => (),
|
||||
err => panic!("Unexpected error {}", err),
|
||||
err => panic!("Unexpected error {err}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -2020,7 +2052,7 @@ mod test {
|
||||
|
||||
match bad_type.unwrap_err() {
|
||||
CustomError::Sqlite(Error::InvalidColumnType(..)) => (),
|
||||
err => panic!("Unexpected error {}", err),
|
||||
err => panic!("Unexpected error {err}"),
|
||||
}
|
||||
|
||||
let bad_idx: CustomResult<String> =
|
||||
@@ -2028,7 +2060,7 @@ mod test {
|
||||
|
||||
match bad_idx.unwrap_err() {
|
||||
CustomError::Sqlite(Error::InvalidColumnIndex(_)) => (),
|
||||
err => panic!("Unexpected error {}", err),
|
||||
err => panic!("Unexpected error {err}"),
|
||||
}
|
||||
|
||||
let non_sqlite_err: CustomResult<String> =
|
||||
@@ -2036,7 +2068,7 @@ mod test {
|
||||
|
||||
match non_sqlite_err.unwrap_err() {
|
||||
CustomError::SomeError => (),
|
||||
err => panic!("Unexpected error {}", err),
|
||||
err => panic!("Unexpected error {err}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -405,18 +405,17 @@ mod test {
|
||||
db.pragma_update_and_check(None, "journal_mode", "OFF", |row| row.get(0))?;
|
||||
assert!(
|
||||
journal_mode == "off" || journal_mode == "memory",
|
||||
"mode: {:?}",
|
||||
journal_mode,
|
||||
"mode: {journal_mode:?}"
|
||||
);
|
||||
// Sanity checks to ensure the move to a generic `ToSql` wasn't breaking
|
||||
let mode =
|
||||
db.pragma_update_and_check(None, "journal_mode", "OFF", |row| row.get::<_, String>(0))?;
|
||||
assert!(mode == "off" || mode == "memory", "mode: {:?}", mode);
|
||||
assert!(mode == "off" || mode == "memory", "mode: {mode:?}");
|
||||
|
||||
let param: &dyn crate::ToSql = &"OFF";
|
||||
let mode =
|
||||
db.pragma_update_and_check(None, "journal_mode", param, |row| row.get::<_, String>(0))?;
|
||||
assert!(mode == "off" || mode == "memory", "mode: {:?}", mode);
|
||||
assert!(mode == "off" || mode == "memory", "mode: {mode:?}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -257,6 +257,7 @@ impl<'stmt> Row<'stmt> {
|
||||
/// * If the underlying SQLite integral value is outside the range
|
||||
/// representable by `T`
|
||||
/// * If `idx` is outside the range of columns in the returned query
|
||||
#[track_caller]
|
||||
pub fn get_unwrap<I: RowIndex, T: FromSql>(&self, idx: I) -> T {
|
||||
self.get(idx).unwrap()
|
||||
}
|
||||
@@ -277,6 +278,7 @@ impl<'stmt> Row<'stmt> {
|
||||
/// If the result type is i128 (which requires the `i128_blob` feature to be
|
||||
/// enabled), and the underlying SQLite column is a blob whose size is not
|
||||
/// 16 bytes, `Error::InvalidColumnType` will also be returned.
|
||||
#[track_caller]
|
||||
pub fn get<I: RowIndex, T: FromSql>(&self, idx: I) -> Result<T> {
|
||||
let idx = idx.idx(self.stmt)?;
|
||||
let value = self.stmt.value_ref(idx);
|
||||
@@ -335,6 +337,7 @@ impl<'stmt> Row<'stmt> {
|
||||
///
|
||||
/// * If `idx` is outside the range of columns in the returned query.
|
||||
/// * If `idx` is not a valid column name for this row.
|
||||
#[track_caller]
|
||||
pub fn get_ref_unwrap<I: RowIndex>(&self, idx: I) -> ValueRef<'_> {
|
||||
self.get_ref(idx).unwrap()
|
||||
}
|
||||
|
||||
162
src/serialize.rs
Normal file
162
src/serialize.rs
Normal file
@@ -0,0 +1,162 @@
|
||||
//! Serialize a database.
|
||||
use std::convert::TryInto;
|
||||
use std::marker::PhantomData;
|
||||
use std::ops::Deref;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use crate::error::error_from_handle;
|
||||
use crate::ffi;
|
||||
use crate::{Connection, DatabaseName, Result};
|
||||
|
||||
/// Shared (SQLITE_SERIALIZE_NOCOPY) serialized database
|
||||
pub struct SharedData<'conn> {
|
||||
phantom: PhantomData<&'conn Connection>,
|
||||
ptr: NonNull<u8>,
|
||||
sz: usize,
|
||||
}
|
||||
|
||||
/// Owned serialized database
|
||||
pub struct OwnedData {
|
||||
ptr: NonNull<u8>,
|
||||
sz: usize,
|
||||
}
|
||||
|
||||
impl OwnedData {
|
||||
/// SAFETY: Caller must be certain that `ptr` is allocated by
|
||||
/// `sqlite3_malloc`.
|
||||
pub unsafe fn from_raw_nonnull(ptr: NonNull<u8>, sz: usize) -> Self {
|
||||
Self { ptr, sz }
|
||||
}
|
||||
|
||||
fn into_raw(self) -> (*mut u8, usize) {
|
||||
let raw = (self.ptr.as_ptr(), self.sz);
|
||||
std::mem::forget(self);
|
||||
raw
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for OwnedData {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
ffi::sqlite3_free(self.ptr.as_ptr().cast());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialized database
|
||||
pub enum Data<'conn> {
|
||||
/// Shared (SQLITE_SERIALIZE_NOCOPY) serialized database
|
||||
Shared(SharedData<'conn>),
|
||||
/// Owned serialized database
|
||||
Owned(OwnedData),
|
||||
}
|
||||
|
||||
impl<'conn> Deref for Data<'conn> {
|
||||
type Target = [u8];
|
||||
|
||||
fn deref(&self) -> &[u8] {
|
||||
let (ptr, sz) = match self {
|
||||
Data::Owned(OwnedData { ptr, sz }) => (ptr.as_ptr(), *sz),
|
||||
Data::Shared(SharedData { ptr, sz, .. }) => (ptr.as_ptr(), *sz),
|
||||
};
|
||||
unsafe { std::slice::from_raw_parts(ptr, sz) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
/// Serialize a database.
|
||||
pub fn serialize<'conn>(&'conn self, schema: DatabaseName<'_>) -> Result<Data<'conn>> {
|
||||
let schema = schema.as_cstring()?;
|
||||
let mut sz = 0;
|
||||
let mut ptr: *mut u8 = unsafe {
|
||||
ffi::sqlite3_serialize(
|
||||
self.handle(),
|
||||
schema.as_ptr(),
|
||||
&mut sz,
|
||||
ffi::SQLITE_SERIALIZE_NOCOPY,
|
||||
)
|
||||
};
|
||||
Ok(if ptr.is_null() {
|
||||
ptr = unsafe { ffi::sqlite3_serialize(self.handle(), schema.as_ptr(), &mut sz, 0) };
|
||||
if ptr.is_null() {
|
||||
return Err(unsafe { error_from_handle(self.handle(), ffi::SQLITE_NOMEM) });
|
||||
}
|
||||
Data::Owned(OwnedData {
|
||||
ptr: NonNull::new(ptr).unwrap(),
|
||||
sz: sz.try_into().unwrap(),
|
||||
})
|
||||
} else {
|
||||
// shared buffer
|
||||
Data::Shared(SharedData {
|
||||
ptr: NonNull::new(ptr).unwrap(),
|
||||
sz: sz.try_into().unwrap(),
|
||||
phantom: PhantomData,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Deserialize a database.
|
||||
pub fn deserialize(
|
||||
&mut self,
|
||||
schema: DatabaseName<'_>,
|
||||
data: OwnedData,
|
||||
read_only: bool,
|
||||
) -> Result<()> {
|
||||
let schema = schema.as_cstring()?;
|
||||
let (data, sz) = data.into_raw();
|
||||
let sz = sz.try_into().unwrap();
|
||||
let flags = if read_only {
|
||||
ffi::SQLITE_DESERIALIZE_FREEONCLOSE | ffi::SQLITE_DESERIALIZE_READONLY
|
||||
} else {
|
||||
ffi::SQLITE_DESERIALIZE_FREEONCLOSE | ffi::SQLITE_DESERIALIZE_RESIZEABLE
|
||||
};
|
||||
let rc = unsafe {
|
||||
ffi::sqlite3_deserialize(self.handle(), schema.as_ptr(), data, sz, sz, flags)
|
||||
};
|
||||
if rc != ffi::SQLITE_OK {
|
||||
// TODO sqlite3_free(data) ?
|
||||
return Err(unsafe { error_from_handle(self.handle(), rc) });
|
||||
}
|
||||
/* TODO
|
||||
if let Some(mxSize) = mxSize {
|
||||
unsafe {
|
||||
ffi::sqlite3_file_control(
|
||||
self.handle(),
|
||||
schema.as_ptr(),
|
||||
ffi::SQLITE_FCNTL_SIZE_LIMIT,
|
||||
&mut mxSize,
|
||||
)
|
||||
};
|
||||
}*/
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::{Connection, DatabaseName, Result};
|
||||
|
||||
#[test]
|
||||
fn serialize() -> Result<()> {
|
||||
let db = Connection::open_in_memory()?;
|
||||
db.execute_batch("CREATE TABLE x AS SELECT 'data'")?;
|
||||
let data = db.serialize(DatabaseName::Main)?;
|
||||
let Data::Owned(data) = data else { panic!("expected OwnedData")};
|
||||
assert!(data.sz > 0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize() -> Result<()> {
|
||||
let src = Connection::open_in_memory()?;
|
||||
src.execute_batch("CREATE TABLE x AS SELECT 'data'")?;
|
||||
let data = src.serialize(DatabaseName::Main)?;
|
||||
let Data::Owned(data) = data else { panic!("expected OwnedData")};
|
||||
|
||||
let mut dst = Connection::open_in_memory()?;
|
||||
dst.deserialize(DatabaseName::Main, data, false)?;
|
||||
dst.execute("DELETE FROM x", [])?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1081,12 +1081,12 @@ mod test {
|
||||
assert_eq!(stmt.insert([2i32])?, 2);
|
||||
match stmt.insert([1i32]).unwrap_err() {
|
||||
Error::StatementChangedRows(0) => (),
|
||||
err => panic!("Unexpected error {}", err),
|
||||
err => panic!("Unexpected error {err}"),
|
||||
}
|
||||
let mut multi = db.prepare("INSERT INTO foo (x) SELECT 3 UNION ALL SELECT 4")?;
|
||||
match multi.insert([]).unwrap_err() {
|
||||
Error::StatementChangedRows(2) => (),
|
||||
err => panic!("Unexpected error {}", err),
|
||||
err => panic!("Unexpected error {err}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1349,7 +1349,7 @@ mod test {
|
||||
assert_eq!(error.code, ErrorCode::Unknown);
|
||||
assert_eq!(offset, 7);
|
||||
}
|
||||
err => panic!("Unexpected error {}", err),
|
||||
err => panic!("Unexpected error {err}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -91,7 +91,6 @@ pub struct Transaction<'conn> {
|
||||
pub struct Savepoint<'conn> {
|
||||
conn: &'conn Connection,
|
||||
name: String,
|
||||
depth: u32,
|
||||
drop_behavior: DropBehavior,
|
||||
committed: bool,
|
||||
}
|
||||
@@ -158,13 +157,13 @@ impl Transaction<'_> {
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn savepoint(&mut self) -> Result<Savepoint<'_>> {
|
||||
Savepoint::with_depth(self.conn, 1)
|
||||
Savepoint::new_(self.conn)
|
||||
}
|
||||
|
||||
/// Create a new savepoint with a custom savepoint name. See `savepoint()`.
|
||||
#[inline]
|
||||
pub fn savepoint_with_name<T: Into<String>>(&mut self, name: T) -> Result<Savepoint<'_>> {
|
||||
Savepoint::with_depth_and_name(self.conn, 1, name)
|
||||
Savepoint::with_name_(self.conn, name)
|
||||
}
|
||||
|
||||
/// Get the current setting for what happens to the transaction when it is
|
||||
@@ -249,50 +248,44 @@ impl Drop for Transaction<'_> {
|
||||
|
||||
impl Savepoint<'_> {
|
||||
#[inline]
|
||||
fn with_depth_and_name<T: Into<String>>(
|
||||
conn: &Connection,
|
||||
depth: u32,
|
||||
name: T,
|
||||
) -> Result<Savepoint<'_>> {
|
||||
fn with_name_<T: Into<String>>(conn: &Connection, name: T) -> Result<Savepoint<'_>> {
|
||||
let name = name.into();
|
||||
conn.execute_batch(&format!("SAVEPOINT {name}"))
|
||||
.map(|_| Savepoint {
|
||||
conn,
|
||||
name,
|
||||
depth,
|
||||
drop_behavior: DropBehavior::Rollback,
|
||||
committed: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_depth(conn: &Connection, depth: u32) -> Result<Savepoint<'_>> {
|
||||
let name = format!("_rusqlite_sp_{depth}");
|
||||
Savepoint::with_depth_and_name(conn, depth, name)
|
||||
fn new_(conn: &Connection) -> Result<Savepoint<'_>> {
|
||||
Savepoint::with_name_(conn, "_rusqlite_sp")
|
||||
}
|
||||
|
||||
/// Begin a new savepoint. Can be nested.
|
||||
#[inline]
|
||||
pub fn new(conn: &mut Connection) -> Result<Savepoint<'_>> {
|
||||
Savepoint::with_depth(conn, 0)
|
||||
Savepoint::new_(conn)
|
||||
}
|
||||
|
||||
/// Begin a new savepoint with a user-provided savepoint name.
|
||||
#[inline]
|
||||
pub fn with_name<T: Into<String>>(conn: &mut Connection, name: T) -> Result<Savepoint<'_>> {
|
||||
Savepoint::with_depth_and_name(conn, 0, name)
|
||||
Savepoint::with_name_(conn, name)
|
||||
}
|
||||
|
||||
/// Begin a nested savepoint.
|
||||
#[inline]
|
||||
pub fn savepoint(&mut self) -> Result<Savepoint<'_>> {
|
||||
Savepoint::with_depth(self.conn, self.depth + 1)
|
||||
Savepoint::new_(self.conn)
|
||||
}
|
||||
|
||||
/// Begin a nested savepoint with a user-provided savepoint name.
|
||||
#[inline]
|
||||
pub fn savepoint_with_name<T: Into<String>>(&mut self, name: T) -> Result<Savepoint<'_>> {
|
||||
Savepoint::with_depth_and_name(self.conn, self.depth + 1, name)
|
||||
Savepoint::with_name_(self.conn, name)
|
||||
}
|
||||
|
||||
/// Get the current setting for what happens to the savepoint when it is
|
||||
@@ -351,8 +344,10 @@ impl Savepoint<'_> {
|
||||
return Ok(());
|
||||
}
|
||||
match self.drop_behavior() {
|
||||
DropBehavior::Commit => self.commit_().or_else(|_| self.rollback()),
|
||||
DropBehavior::Rollback => self.rollback(),
|
||||
DropBehavior::Commit => self
|
||||
.commit_()
|
||||
.or_else(|_| self.rollback().and_then(|_| self.commit_())),
|
||||
DropBehavior::Rollback => self.rollback().and_then(|_| self.commit_()),
|
||||
DropBehavior::Ignore => Ok(()),
|
||||
DropBehavior::Panic => panic!("Savepoint dropped unexpectedly."),
|
||||
}
|
||||
@@ -563,7 +558,7 @@ mod test {
|
||||
assert_eq!(e.code, crate::ErrorCode::Unknown);
|
||||
assert!(m.contains("transaction"));
|
||||
} else {
|
||||
panic!("Unexpected error type: {:?}", e);
|
||||
panic!("Unexpected error type: {e:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -675,6 +670,40 @@ mod test {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_savepoint_drop_behavior_releases() -> Result<()> {
|
||||
let mut db = checked_memory_handle()?;
|
||||
|
||||
{
|
||||
let mut sp = db.savepoint()?;
|
||||
sp.set_drop_behavior(DropBehavior::Commit);
|
||||
}
|
||||
assert!(db.is_autocommit());
|
||||
{
|
||||
let mut sp = db.savepoint()?;
|
||||
sp.set_drop_behavior(DropBehavior::Rollback);
|
||||
}
|
||||
assert!(db.is_autocommit());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_savepoint_release_error() -> Result<()> {
|
||||
let mut db = checked_memory_handle()?;
|
||||
|
||||
db.pragma_update(None, "foreign_keys", true)?;
|
||||
db.execute_batch("CREATE TABLE r(n INTEGER PRIMARY KEY NOT NULL); CREATE TABLE f(n REFERENCES r(n) DEFERRABLE INITIALLY DEFERRED);")?;
|
||||
{
|
||||
let mut sp = db.savepoint()?;
|
||||
sp.execute("INSERT INTO f VALUES (0)", [])?;
|
||||
sp.set_drop_behavior(DropBehavior::Commit);
|
||||
}
|
||||
assert!(db.is_autocommit());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_savepoint_names() -> Result<()> {
|
||||
let mut db = checked_memory_handle()?;
|
||||
|
||||
@@ -59,8 +59,7 @@ impl fmt::Display for FromSqlError {
|
||||
} => {
|
||||
write!(
|
||||
f,
|
||||
"Cannot read {} byte value out of {} byte blob",
|
||||
expected_size, blob_size
|
||||
"Cannot read {expected_size} byte value out of {blob_size} byte blob"
|
||||
)
|
||||
}
|
||||
FromSqlError::Other(ref err) => err.fmt(f),
|
||||
@@ -96,6 +95,15 @@ macro_rules! from_sql_integral(
|
||||
i.try_into().map_err(|_| FromSqlError::OutOfRange(i))
|
||||
}
|
||||
}
|
||||
);
|
||||
(non_zero $nz:ty, $z:ty) => (
|
||||
impl FromSql for $nz {
|
||||
#[inline]
|
||||
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
|
||||
let i = <$z>::column_result(value)?;
|
||||
<$nz>::new(i).ok_or(FromSqlError::OutOfRange(0))
|
||||
}
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
@@ -110,6 +118,22 @@ from_sql_integral!(u32);
|
||||
from_sql_integral!(u64);
|
||||
from_sql_integral!(usize);
|
||||
|
||||
from_sql_integral!(non_zero std::num::NonZeroIsize, isize);
|
||||
from_sql_integral!(non_zero std::num::NonZeroI8, i8);
|
||||
from_sql_integral!(non_zero std::num::NonZeroI16, i16);
|
||||
from_sql_integral!(non_zero std::num::NonZeroI32, i32);
|
||||
from_sql_integral!(non_zero std::num::NonZeroI64, i64);
|
||||
#[cfg(feature = "i128_blob")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "i128_blob")))]
|
||||
from_sql_integral!(non_zero std::num::NonZeroI128, i128);
|
||||
|
||||
from_sql_integral!(non_zero std::num::NonZeroUsize, usize);
|
||||
from_sql_integral!(non_zero std::num::NonZeroU8, u8);
|
||||
from_sql_integral!(non_zero std::num::NonZeroU16, u16);
|
||||
from_sql_integral!(non_zero std::num::NonZeroU32, u32);
|
||||
from_sql_integral!(non_zero std::num::NonZeroU64, u64);
|
||||
// std::num::NonZeroU128 is not supported since u128 isn't either
|
||||
|
||||
impl FromSql for i64 {
|
||||
#[inline]
|
||||
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
|
||||
@@ -248,7 +272,7 @@ mod test {
|
||||
.unwrap_err();
|
||||
match err {
|
||||
Error::IntegralValueOutOfRange(_, value) => assert_eq!(*n, value),
|
||||
_ => panic!("unexpected error: {}", err),
|
||||
_ => panic!("unexpected error: {err}"),
|
||||
}
|
||||
}
|
||||
for n in in_range {
|
||||
@@ -273,4 +297,70 @@ mod test {
|
||||
check_ranges::<u32>(&db, &[-2, -1, 4_294_967_296], &[0, 1, 4_294_967_295]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nonzero_ranges() -> Result<()> {
|
||||
let db = Connection::open_in_memory()?;
|
||||
|
||||
macro_rules! check_ranges {
|
||||
($nz:ty, $out_of_range:expr, $in_range:expr) => {
|
||||
for &n in $out_of_range {
|
||||
assert_eq!(
|
||||
db.query_row("SELECT ?1", [n], |r| r.get::<_, $nz>(0)),
|
||||
Err(Error::IntegralValueOutOfRange(0, n)),
|
||||
"{}",
|
||||
std::any::type_name::<$nz>()
|
||||
);
|
||||
}
|
||||
for &n in $in_range {
|
||||
let non_zero = <$nz>::new(n).unwrap();
|
||||
assert_eq!(
|
||||
Ok(non_zero),
|
||||
db.query_row("SELECT ?1", [non_zero], |r| r.get::<_, $nz>(0))
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
check_ranges!(std::num::NonZeroI8, &[0, -129, 128], &[-128, 1, 127]);
|
||||
check_ranges!(
|
||||
std::num::NonZeroI16,
|
||||
&[0, -32769, 32768],
|
||||
&[-32768, -1, 1, 32767]
|
||||
);
|
||||
check_ranges!(
|
||||
std::num::NonZeroI32,
|
||||
&[0, -2_147_483_649, 2_147_483_648],
|
||||
&[-2_147_483_648, -1, 1, 2_147_483_647]
|
||||
);
|
||||
check_ranges!(
|
||||
std::num::NonZeroI64,
|
||||
&[0],
|
||||
&[-2_147_483_648, -1, 1, 2_147_483_647, i64::MAX, i64::MIN]
|
||||
);
|
||||
check_ranges!(
|
||||
std::num::NonZeroIsize,
|
||||
&[0],
|
||||
&[-2_147_483_648, -1, 1, 2_147_483_647]
|
||||
);
|
||||
check_ranges!(std::num::NonZeroU8, &[0, -2, -1, 256], &[1, 255]);
|
||||
check_ranges!(std::num::NonZeroU16, &[0, -2, -1, 65536], &[1, 65535]);
|
||||
check_ranges!(
|
||||
std::num::NonZeroU32,
|
||||
&[0, -2, -1, 4_294_967_296],
|
||||
&[1, 4_294_967_295]
|
||||
);
|
||||
check_ranges!(
|
||||
std::num::NonZeroU64,
|
||||
&[0, -2, -1, -4_294_967_296],
|
||||
&[1, 4_294_967_295, i64::MAX as u64]
|
||||
);
|
||||
check_ranges!(
|
||||
std::num::NonZeroUsize,
|
||||
&[0, -2, -1, -4_294_967_296],
|
||||
&[1, 4_294_967_295]
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,8 @@
|
||||
//! [`ToSql`] always succeeds except when storing a `u64` or `usize` value that
|
||||
//! cannot fit in an `INTEGER` (`i64`). Also note that SQLite ignores column
|
||||
//! types, so if you store an `i64` in a column with type `REAL` it will be
|
||||
//! stored as an `INTEGER`, not a `REAL`.
|
||||
//! stored as an `INTEGER`, not a `REAL` (unless the column is part of a
|
||||
//! [STRICT table](https://www.sqlite.org/stricttables.html)).
|
||||
//!
|
||||
//! If the `time` feature is enabled, implementations are
|
||||
//! provided for `time::OffsetDateTime` that use the RFC 3339 date/time format,
|
||||
@@ -210,10 +211,10 @@ mod test {
|
||||
fn test_option() -> Result<()> {
|
||||
let db = checked_memory_handle()?;
|
||||
|
||||
let s = Some("hello, world!");
|
||||
let s = "hello, world!";
|
||||
let b = Some(vec![1u8, 2, 3, 4]);
|
||||
|
||||
db.execute("INSERT INTO foo(t) VALUES (?1)", [&s])?;
|
||||
db.execute("INSERT INTO foo(t) VALUES (?1)", [Some(s)])?;
|
||||
db.execute("INSERT INTO foo(b) VALUES (?1)", [&b])?;
|
||||
|
||||
let mut stmt = db.prepare("SELECT t, b FROM foo ORDER BY ROWID ASC")?;
|
||||
@@ -223,7 +224,7 @@ mod test {
|
||||
let row1 = rows.next()?.unwrap();
|
||||
let s1: Option<String> = row1.get_unwrap(0);
|
||||
let b1: Option<Vec<u8>> = row1.get_unwrap(1);
|
||||
assert_eq!(s.unwrap(), s1.unwrap());
|
||||
assert_eq!(s, s1.unwrap());
|
||||
assert!(b1.is_none());
|
||||
}
|
||||
|
||||
@@ -352,7 +353,7 @@ mod test {
|
||||
assert_eq!(Value::Integer(1), row.get::<_, Value>(2)?);
|
||||
match row.get::<_, Value>(3)? {
|
||||
Value::Real(val) => assert!((1.5 - val).abs() < f64::EPSILON),
|
||||
x => panic!("Invalid Value {:?}", x),
|
||||
x => panic!("Invalid Value {x:?}"),
|
||||
}
|
||||
assert_eq!(Value::Null, row.get::<_, Value>(4)?);
|
||||
Ok(())
|
||||
|
||||
@@ -1,67 +1,155 @@
|
||||
//! Convert formats 1-10 in [Time Values](https://sqlite.org/lang_datefunc.html#time_values) to time types.
|
||||
//! [`ToSql`] and [`FromSql`] implementation for [`time::OffsetDateTime`].
|
||||
//! [`ToSql`] and [`FromSql`] implementation for [`time::PrimitiveDateTime`].
|
||||
//! [`ToSql`] and [`FromSql`] implementation for [`time::Date`].
|
||||
//! [`ToSql`] and [`FromSql`] implementation for [`time::Time`].
|
||||
//! Time Strings in:
|
||||
//! - Format 2: "YYYY-MM-DD HH:MM"
|
||||
//! - Format 5: "YYYY-MM-DDTHH:MM"
|
||||
//! - Format 8: "HH:MM"
|
||||
//! without an explicit second value will assume 0 seconds.
|
||||
//! Time String that contain an optional timezone without an explicit date are unsupported.
|
||||
//! All other assumptions described in [Time Values](https://sqlite.org/lang_datefunc.html#time_values) section are unsupported.
|
||||
|
||||
use crate::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
|
||||
use crate::{Error, Result};
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
use time::format_description::FormatItem;
|
||||
use time::macros::format_description;
|
||||
use time::{OffsetDateTime, PrimitiveDateTime, UtcOffset};
|
||||
use time::{Date, OffsetDateTime, PrimitiveDateTime, Time};
|
||||
|
||||
const PRIMITIVE_SHORT_DATE_TIME_FORMAT: &[FormatItem<'_>] =
|
||||
format_description!("[year]-[month]-[day] [hour]:[minute]:[second]");
|
||||
const PRIMITIVE_DATE_TIME_FORMAT: &[FormatItem<'_>] =
|
||||
format_description!("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond]");
|
||||
const PRIMITIVE_DATE_TIME_Z_FORMAT: &[FormatItem<'_>] =
|
||||
format_description!("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond]Z");
|
||||
const OFFSET_SHORT_DATE_TIME_FORMAT: &[FormatItem<'_>] = format_description!(
|
||||
"[year]-[month]-[day] [hour]:[minute]:[second][offset_hour sign:mandatory]:[offset_minute]"
|
||||
);
|
||||
const OFFSET_DATE_TIME_FORMAT: &[FormatItem<'_>] = format_description!(
|
||||
const OFFSET_DATE_TIME_ENCODING: &[FormatItem<'_>] = format_description!(
|
||||
version = 2,
|
||||
"[year]-[month]-[day] [hour]:[minute]:[second].[subsecond][offset_hour sign:mandatory]:[offset_minute]"
|
||||
);
|
||||
const PRIMITIVE_DATE_TIME_ENCODING: &[FormatItem<'_>] = format_description!(
|
||||
version = 2,
|
||||
"[year]-[month]-[day] [hour]:[minute]:[second].[subsecond]"
|
||||
);
|
||||
const TIME_ENCODING: &[FormatItem<'_>] =
|
||||
format_description!(version = 2, "[hour]:[minute]:[second].[subsecond]");
|
||||
|
||||
const DATE_FORMAT: &[FormatItem<'_>] = format_description!(version = 2, "[year]-[month]-[day]");
|
||||
const TIME_FORMAT: &[FormatItem<'_>] = format_description!(
|
||||
version = 2,
|
||||
"[hour]:[minute][optional [:[second][optional [.[subsecond]]]]]"
|
||||
);
|
||||
const PRIMITIVE_DATE_TIME_FORMAT: &[FormatItem<'_>] = format_description!(
|
||||
version = 2,
|
||||
"[year]-[month]-[day][first [ ][T]][hour]:[minute][optional [:[second][optional [.[subsecond]]]]]"
|
||||
);
|
||||
const UTC_DATE_TIME_FORMAT: &[FormatItem<'_>] = format_description!(
|
||||
version = 2,
|
||||
"[year]-[month]-[day][first [ ][T]][hour]:[minute][optional [:[second][optional [.[subsecond]]]]][optional [Z]]"
|
||||
);
|
||||
const OFFSET_DATE_TIME_FORMAT: &[FormatItem<'_>] = format_description!(
|
||||
version = 2,
|
||||
"[year]-[month]-[day][first [ ][T]][hour]:[minute][optional [:[second][optional [.[subsecond]]]]][offset_hour sign:mandatory]:[offset_minute]"
|
||||
);
|
||||
const LEGACY_DATE_TIME_FORMAT: &[FormatItem<'_>] = format_description!(
|
||||
version = 2,
|
||||
"[year]-[month]-[day] [hour]:[minute]:[second]:[subsecond] [offset_hour sign:mandatory]:[offset_minute]"
|
||||
);
|
||||
|
||||
/// OffsetDatetime => RFC3339 format ("YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM")
|
||||
impl ToSql for OffsetDateTime {
|
||||
#[inline]
|
||||
fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
|
||||
// FIXME keep original offset
|
||||
let time_string = self
|
||||
.to_offset(UtcOffset::UTC)
|
||||
.format(&PRIMITIVE_DATE_TIME_Z_FORMAT)
|
||||
.format(&OFFSET_DATE_TIME_ENCODING)
|
||||
.map_err(|err| Error::ToSqlConversionFailure(err.into()))?;
|
||||
Ok(ToSqlOutput::from(time_string))
|
||||
}
|
||||
}
|
||||
|
||||
// Supports parsing formats 2-7 from https://www.sqlite.org/lang_datefunc.html
|
||||
// Formats 2-7 without a timezone assumes UTC
|
||||
impl FromSql for OffsetDateTime {
|
||||
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
|
||||
value.as_str().and_then(|s| {
|
||||
if s.len() > 10 && s.as_bytes()[10] == b'T' {
|
||||
// YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM
|
||||
return OffsetDateTime::parse(s, &Rfc3339)
|
||||
if let Some(b' ') = s.as_bytes().get(23) {
|
||||
// legacy
|
||||
return OffsetDateTime::parse(s, &LEGACY_DATE_TIME_FORMAT)
|
||||
.map_err(|err| FromSqlError::Other(Box::new(err)));
|
||||
}
|
||||
let s = s.strip_suffix('Z').unwrap_or(s);
|
||||
match s.len() {
|
||||
len if len <= 19 => {
|
||||
// TODO YYYY-MM-DDTHH:MM:SS
|
||||
PrimitiveDateTime::parse(s, &PRIMITIVE_SHORT_DATE_TIME_FORMAT)
|
||||
.map(PrimitiveDateTime::assume_utc)
|
||||
}
|
||||
_ if s.as_bytes()[19] == b':' => {
|
||||
// legacy
|
||||
OffsetDateTime::parse(s, &LEGACY_DATE_TIME_FORMAT)
|
||||
}
|
||||
_ if s.as_bytes()[19] == b'.' => OffsetDateTime::parse(s, &OFFSET_DATE_TIME_FORMAT)
|
||||
.or_else(|err| {
|
||||
PrimitiveDateTime::parse(s, &PRIMITIVE_DATE_TIME_FORMAT)
|
||||
.map(PrimitiveDateTime::assume_utc)
|
||||
.map_err(|_| err)
|
||||
}),
|
||||
_ => OffsetDateTime::parse(s, &OFFSET_SHORT_DATE_TIME_FORMAT),
|
||||
if s[8..].contains('+') || s[8..].contains('-') {
|
||||
// Formats 2-7 with timezone
|
||||
return OffsetDateTime::parse(s, &OFFSET_DATE_TIME_FORMAT)
|
||||
.map_err(|err| FromSqlError::Other(Box::new(err)));
|
||||
}
|
||||
.map_err(|err| FromSqlError::Other(Box::new(err)))
|
||||
// Formats 2-7 without timezone
|
||||
PrimitiveDateTime::parse(s, &UTC_DATE_TIME_FORMAT)
|
||||
.map(|p| p.assume_utc())
|
||||
.map_err(|err| FromSqlError::Other(Box::new(err)))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// ISO 8601 calendar date without timezone => "YYYY-MM-DD"
|
||||
impl ToSql for Date {
|
||||
#[inline]
|
||||
fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
|
||||
let date_str = self
|
||||
.format(&DATE_FORMAT)
|
||||
.map_err(|err| Error::ToSqlConversionFailure(err.into()))?;
|
||||
Ok(ToSqlOutput::from(date_str))
|
||||
}
|
||||
}
|
||||
|
||||
/// "YYYY-MM-DD" => ISO 8601 calendar date without timezone.
|
||||
impl FromSql for Date {
|
||||
#[inline]
|
||||
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
|
||||
value.as_str().and_then(|s| {
|
||||
Date::parse(s, &DATE_FORMAT).map_err(|err| FromSqlError::Other(err.into()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// ISO 8601 time without timezone => "HH:MM:SS.SSS"
|
||||
impl ToSql for Time {
|
||||
#[inline]
|
||||
fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
|
||||
let time_str = self
|
||||
.format(&TIME_ENCODING)
|
||||
.map_err(|err| Error::ToSqlConversionFailure(err.into()))?;
|
||||
Ok(ToSqlOutput::from(time_str))
|
||||
}
|
||||
}
|
||||
|
||||
/// "HH:MM"/"HH:MM:SS"/"HH:MM:SS.SSS" => ISO 8601 time without timezone.
|
||||
impl FromSql for Time {
|
||||
#[inline]
|
||||
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
|
||||
value.as_str().and_then(|s| {
|
||||
Time::parse(s, &TIME_FORMAT).map_err(|err| FromSqlError::Other(err.into()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// ISO 8601 combined date and time without timezone => "YYYY-MM-DD HH:MM:SS.SSS"
|
||||
impl ToSql for PrimitiveDateTime {
|
||||
#[inline]
|
||||
fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
|
||||
let date_time_str = self
|
||||
.format(&PRIMITIVE_DATE_TIME_ENCODING)
|
||||
.map_err(|err| Error::ToSqlConversionFailure(err.into()))?;
|
||||
Ok(ToSqlOutput::from(date_time_str))
|
||||
}
|
||||
}
|
||||
|
||||
/// YYYY-MM-DD HH:MM
|
||||
/// YYYY-MM-DDTHH:MM
|
||||
/// YYYY-MM-DD HH:MM:SS
|
||||
/// YYYY-MM-DDTHH:MM:SS
|
||||
/// YYYY-MM-DD HH:MM:SS.SSS
|
||||
/// YYYY-MM-DDTHH:MM:SS.SSS
|
||||
/// => ISO 8601 combined date and time with timezone
|
||||
impl FromSql for PrimitiveDateTime {
|
||||
#[inline]
|
||||
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
|
||||
value.as_str().and_then(|s| {
|
||||
PrimitiveDateTime::parse(s, &PRIMITIVE_DATE_TIME_FORMAT)
|
||||
.map_err(|err| FromSqlError::Other(err.into()))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -69,13 +157,18 @@ impl FromSql for OffsetDateTime {
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::{Connection, Result};
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
use time::OffsetDateTime;
|
||||
use time::macros::{date, datetime, time};
|
||||
use time::{Date, OffsetDateTime, PrimitiveDateTime, Time};
|
||||
|
||||
fn checked_memory_handle() -> Result<Connection> {
|
||||
let db = Connection::open_in_memory()?;
|
||||
db.execute_batch("CREATE TABLE foo (t TEXT, i INTEGER, f FLOAT, b BLOB)")?;
|
||||
Ok(db)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_offset_date_time() -> Result<()> {
|
||||
let db = Connection::open_in_memory()?;
|
||||
db.execute_batch("CREATE TABLE foo (t TEXT, i INTEGER, f FLOAT)")?;
|
||||
let db = checked_memory_handle()?;
|
||||
|
||||
let mut ts_vec = vec![];
|
||||
|
||||
@@ -103,47 +196,163 @@ mod test {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_string_values() -> Result<()> {
|
||||
let db = Connection::open_in_memory()?;
|
||||
for (s, t) in vec![
|
||||
fn test_offset_date_time_parsing() -> Result<()> {
|
||||
let db = checked_memory_handle()?;
|
||||
let tests = vec![
|
||||
// Rfc3339
|
||||
(
|
||||
"2013-10-07 08:23:19",
|
||||
Ok(OffsetDateTime::parse("2013-10-07T08:23:19Z", &Rfc3339).unwrap()),
|
||||
"2013-10-07T08:23:19.123456789Z",
|
||||
datetime!(2013-10-07 8:23:19.123456789 UTC),
|
||||
),
|
||||
(
|
||||
"2013-10-07 08:23:19Z",
|
||||
Ok(OffsetDateTime::parse("2013-10-07T08:23:19Z", &Rfc3339).unwrap()),
|
||||
"2013-10-07 08:23:19.123456789Z",
|
||||
datetime!(2013-10-07 8:23:19.123456789 UTC),
|
||||
),
|
||||
// Format 2
|
||||
("2013-10-07 08:23", datetime!(2013-10-07 8:23 UTC)),
|
||||
("2013-10-07 08:23Z", datetime!(2013-10-07 8:23 UTC)),
|
||||
("2013-10-07 08:23+04:00", datetime!(2013-10-07 8:23 +4)),
|
||||
// Format 3
|
||||
("2013-10-07 08:23:19", datetime!(2013-10-07 8:23:19 UTC)),
|
||||
("2013-10-07 08:23:19Z", datetime!(2013-10-07 8:23:19 UTC)),
|
||||
(
|
||||
"2013-10-07 08:23:19+04:00",
|
||||
datetime!(2013-10-07 8:23:19 +4),
|
||||
),
|
||||
// Format 4
|
||||
(
|
||||
"2013-10-07 08:23:19.123",
|
||||
datetime!(2013-10-07 8:23:19.123 UTC),
|
||||
),
|
||||
(
|
||||
"2013-10-07T08:23:19Z",
|
||||
Ok(OffsetDateTime::parse("2013-10-07T08:23:19Z", &Rfc3339).unwrap()),
|
||||
"2013-10-07 08:23:19.123Z",
|
||||
datetime!(2013-10-07 8:23:19.123 UTC),
|
||||
),
|
||||
(
|
||||
"2013-10-07 08:23:19.120",
|
||||
Ok(OffsetDateTime::parse("2013-10-07T08:23:19.120Z", &Rfc3339).unwrap()),
|
||||
"2013-10-07 08:23:19.123+04:00",
|
||||
datetime!(2013-10-07 8:23:19.123 +4),
|
||||
),
|
||||
// Format 5
|
||||
("2013-10-07T08:23", datetime!(2013-10-07 8:23 UTC)),
|
||||
("2013-10-07T08:23Z", datetime!(2013-10-07 8:23 UTC)),
|
||||
("2013-10-07T08:23+04:00", datetime!(2013-10-07 8:23 +4)),
|
||||
// Format 6
|
||||
("2013-10-07T08:23:19", datetime!(2013-10-07 8:23:19 UTC)),
|
||||
("2013-10-07T08:23:19Z", datetime!(2013-10-07 8:23:19 UTC)),
|
||||
(
|
||||
"2013-10-07T08:23:19+04:00",
|
||||
datetime!(2013-10-07 8:23:19 +4),
|
||||
),
|
||||
// Format 7
|
||||
(
|
||||
"2013-10-07T08:23:19.123",
|
||||
datetime!(2013-10-07 8:23:19.123 UTC),
|
||||
),
|
||||
(
|
||||
"2013-10-07 08:23:19.120Z",
|
||||
Ok(OffsetDateTime::parse("2013-10-07T08:23:19.120Z", &Rfc3339).unwrap()),
|
||||
"2013-10-07T08:23:19.123Z",
|
||||
datetime!(2013-10-07 8:23:19.123 UTC),
|
||||
),
|
||||
(
|
||||
"2013-10-07T08:23:19.120Z",
|
||||
Ok(OffsetDateTime::parse("2013-10-07T08:23:19.120Z", &Rfc3339).unwrap()),
|
||||
"2013-10-07T08:23:19.123+04:00",
|
||||
datetime!(2013-10-07 8:23:19.123 +4),
|
||||
),
|
||||
// Legacy
|
||||
(
|
||||
"2013-10-07 04:23:19-04:00",
|
||||
Ok(OffsetDateTime::parse("2013-10-07T04:23:19-04:00", &Rfc3339).unwrap()),
|
||||
"2013-10-07 08:23:12:987 -07:00",
|
||||
datetime!(2013-10-07 8:23:12.987 -7),
|
||||
),
|
||||
(
|
||||
"2013-10-07 04:23:19.120-04:00",
|
||||
Ok(OffsetDateTime::parse("2013-10-07T04:23:19.120-04:00", &Rfc3339).unwrap()),
|
||||
),
|
||||
(
|
||||
"2013-10-07T04:23:19.120-04:00",
|
||||
Ok(OffsetDateTime::parse("2013-10-07T04:23:19.120-04:00", &Rfc3339).unwrap()),
|
||||
),
|
||||
] {
|
||||
let result: Result<OffsetDateTime> = db.query_row("SELECT ?1", [s], |r| r.get(0));
|
||||
];
|
||||
|
||||
for (s, t) in tests {
|
||||
let result: OffsetDateTime = db.query_row("SELECT ?1", [s], |r| r.get(0))?;
|
||||
assert_eq!(result, t);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_date() -> Result<()> {
|
||||
let db = checked_memory_handle()?;
|
||||
let date = date!(2016 - 02 - 23);
|
||||
db.execute("INSERT INTO foo (t) VALUES (?1)", [date])?;
|
||||
|
||||
let s: String = db.one_column("SELECT t FROM foo")?;
|
||||
assert_eq!("2016-02-23", s);
|
||||
let t: Date = db.one_column("SELECT t FROM foo")?;
|
||||
assert_eq!(date, t);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_time() -> Result<()> {
|
||||
let db = checked_memory_handle()?;
|
||||
let time = time!(23:56:04.00001);
|
||||
db.execute("INSERT INTO foo (t) VALUES (?1)", [time])?;
|
||||
|
||||
let s: String = db.one_column("SELECT t FROM foo")?;
|
||||
assert_eq!("23:56:04.00001", s);
|
||||
let v: Time = db.one_column("SELECT t FROM foo")?;
|
||||
assert_eq!(time, v);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_primitive_date_time() -> Result<()> {
|
||||
let db = checked_memory_handle()?;
|
||||
let dt = date!(2016 - 02 - 23).with_time(time!(23:56:04));
|
||||
|
||||
db.execute("INSERT INTO foo (t) VALUES (?1)", [dt])?;
|
||||
|
||||
let s: String = db.one_column("SELECT t FROM foo")?;
|
||||
assert_eq!("2016-02-23 23:56:04.0", s);
|
||||
let v: PrimitiveDateTime = db.one_column("SELECT t FROM foo")?;
|
||||
assert_eq!(dt, v);
|
||||
|
||||
db.execute("UPDATE foo set b = datetime(t)", [])?; // "YYYY-MM-DD HH:MM:SS"
|
||||
let hms: PrimitiveDateTime = db.one_column("SELECT b FROM foo")?;
|
||||
assert_eq!(dt, hms);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_date_parsing() -> Result<()> {
|
||||
let db = checked_memory_handle()?;
|
||||
let result: Date = db.query_row("SELECT ?1", ["2013-10-07"], |r| r.get(0))?;
|
||||
assert_eq!(result, date!(2013 - 10 - 07));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_time_parsing() -> Result<()> {
|
||||
let db = checked_memory_handle()?;
|
||||
let tests = vec![
|
||||
("08:23", time!(08:23)),
|
||||
("08:23:19", time!(08:23:19)),
|
||||
("08:23:19.111", time!(08:23:19.111)),
|
||||
];
|
||||
|
||||
for (s, t) in tests {
|
||||
let result: Time = db.query_row("SELECT ?1", [s], |r| r.get(0))?;
|
||||
assert_eq!(result, t);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_primitive_date_time_parsing() -> Result<()> {
|
||||
let db = checked_memory_handle()?;
|
||||
|
||||
let tests = vec![
|
||||
("2013-10-07T08:23", datetime!(2013-10-07 8:23)),
|
||||
("2013-10-07T08:23:19", datetime!(2013-10-07 8:23:19)),
|
||||
("2013-10-07T08:23:19.111", datetime!(2013-10-07 8:23:19.111)),
|
||||
("2013-10-07 08:23", datetime!(2013-10-07 8:23)),
|
||||
("2013-10-07 08:23:19", datetime!(2013-10-07 8:23:19)),
|
||||
("2013-10-07 08:23:19.111", datetime!(2013-10-07 8:23:19.111)),
|
||||
];
|
||||
|
||||
for (s, t) in tests {
|
||||
let result: PrimitiveDateTime = db.query_row("SELECT ?1", [s], |r| r.get(0))?;
|
||||
assert_eq!(result, t);
|
||||
}
|
||||
Ok(())
|
||||
@@ -151,16 +360,66 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn test_sqlite_functions() -> Result<()> {
|
||||
let db = Connection::open_in_memory()?;
|
||||
let result: Result<OffsetDateTime> = db.one_column("SELECT CURRENT_TIMESTAMP");
|
||||
let db = checked_memory_handle()?;
|
||||
db.one_column::<Time>("SELECT CURRENT_TIME").unwrap();
|
||||
db.one_column::<Date>("SELECT CURRENT_DATE").unwrap();
|
||||
db.one_column::<PrimitiveDateTime>("SELECT CURRENT_TIMESTAMP")
|
||||
.unwrap();
|
||||
db.one_column::<OffsetDateTime>("SELECT CURRENT_TIMESTAMP")
|
||||
.unwrap();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_time_param() -> Result<()> {
|
||||
let db = checked_memory_handle()?;
|
||||
let now = OffsetDateTime::now_utc().time();
|
||||
let result: Result<bool> = db.query_row(
|
||||
"SELECT 1 WHERE ?1 BETWEEN time('now', '-1 minute') AND time('now', '+1 minute')",
|
||||
[now],
|
||||
|r| r.get(0),
|
||||
);
|
||||
result.unwrap();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_param() -> Result<()> {
|
||||
let db = Connection::open_in_memory()?;
|
||||
let result: Result<bool> = db.query_row("SELECT 1 WHERE ?1 BETWEEN datetime('now', '-1 minute') AND datetime('now', '+1 minute')", [OffsetDateTime::now_utc()], |r| r.get(0));
|
||||
fn test_date_param() -> Result<()> {
|
||||
let db = checked_memory_handle()?;
|
||||
let now = OffsetDateTime::now_utc().date();
|
||||
let result: Result<bool> = db.query_row(
|
||||
"SELECT 1 WHERE ?1 BETWEEN date('now', '-1 day') AND date('now', '+1 day')",
|
||||
[now],
|
||||
|r| r.get(0),
|
||||
);
|
||||
result.unwrap();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_primitive_date_time_param() -> Result<()> {
|
||||
let db = checked_memory_handle()?;
|
||||
let now = PrimitiveDateTime::new(
|
||||
OffsetDateTime::now_utc().date(),
|
||||
OffsetDateTime::now_utc().time(),
|
||||
);
|
||||
let result: Result<bool> = db.query_row(
|
||||
"SELECT 1 WHERE ?1 BETWEEN datetime('now', '-1 minute') AND datetime('now', '+1 minute')",
|
||||
[now],
|
||||
|r| r.get(0),
|
||||
);
|
||||
result.unwrap();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_offset_date_time_param() -> Result<()> {
|
||||
let db = checked_memory_handle()?;
|
||||
let result: Result<bool> = db.query_row(
|
||||
"SELECT 1 WHERE ?1 BETWEEN datetime('now', '-1 minute') AND datetime('now', '+1 minute')",
|
||||
[OffsetDateTime::now_utc()],
|
||||
|r| r.get(0),
|
||||
);
|
||||
result.unwrap();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -51,6 +51,12 @@ macro_rules! from_value(
|
||||
#[inline]
|
||||
fn from(t: $t) -> Self { ToSqlOutput::Owned(t.into())}
|
||||
}
|
||||
);
|
||||
(non_zero $t:ty) => (
|
||||
impl From<$t> for ToSqlOutput<'_> {
|
||||
#[inline]
|
||||
fn from(t: $t) -> Self { ToSqlOutput::Owned(t.get().into())}
|
||||
}
|
||||
)
|
||||
);
|
||||
from_value!(String);
|
||||
@@ -68,6 +74,15 @@ from_value!(f32);
|
||||
from_value!(f64);
|
||||
from_value!(Vec<u8>);
|
||||
|
||||
from_value!(non_zero std::num::NonZeroI8);
|
||||
from_value!(non_zero std::num::NonZeroI16);
|
||||
from_value!(non_zero std::num::NonZeroI32);
|
||||
from_value!(non_zero std::num::NonZeroI64);
|
||||
from_value!(non_zero std::num::NonZeroIsize);
|
||||
from_value!(non_zero std::num::NonZeroU8);
|
||||
from_value!(non_zero std::num::NonZeroU16);
|
||||
from_value!(non_zero std::num::NonZeroU32);
|
||||
|
||||
// It would be nice if we could avoid the heap allocation (of the `Vec`) that
|
||||
// `i128` needs in `Into<Value>`, but it's probably fine for the moment, and not
|
||||
// worth adding another case to Value.
|
||||
@@ -75,6 +90,10 @@ from_value!(Vec<u8>);
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "i128_blob")))]
|
||||
from_value!(i128);
|
||||
|
||||
#[cfg(feature = "i128_blob")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "i128_blob")))]
|
||||
from_value!(non_zero std::num::NonZeroI128);
|
||||
|
||||
#[cfg(feature = "uuid")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
|
||||
from_value!(uuid::Uuid);
|
||||
@@ -165,10 +184,23 @@ to_sql_self!(u32);
|
||||
to_sql_self!(f32);
|
||||
to_sql_self!(f64);
|
||||
|
||||
to_sql_self!(std::num::NonZeroI8);
|
||||
to_sql_self!(std::num::NonZeroI16);
|
||||
to_sql_self!(std::num::NonZeroI32);
|
||||
to_sql_self!(std::num::NonZeroI64);
|
||||
to_sql_self!(std::num::NonZeroIsize);
|
||||
to_sql_self!(std::num::NonZeroU8);
|
||||
to_sql_self!(std::num::NonZeroU16);
|
||||
to_sql_self!(std::num::NonZeroU32);
|
||||
|
||||
#[cfg(feature = "i128_blob")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "i128_blob")))]
|
||||
to_sql_self!(i128);
|
||||
|
||||
#[cfg(feature = "i128_blob")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "i128_blob")))]
|
||||
to_sql_self!(std::num::NonZeroI128);
|
||||
|
||||
#[cfg(feature = "uuid")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
|
||||
to_sql_self!(uuid::Uuid);
|
||||
@@ -186,12 +218,27 @@ macro_rules! to_sql_self_fallible(
|
||||
)))
|
||||
}
|
||||
}
|
||||
);
|
||||
(non_zero $t:ty) => (
|
||||
impl ToSql for $t {
|
||||
#[inline]
|
||||
fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
|
||||
Ok(ToSqlOutput::Owned(Value::Integer(
|
||||
i64::try_from(self.get()).map_err(
|
||||
// TODO: Include the values in the error message.
|
||||
|err| Error::ToSqlConversionFailure(err.into())
|
||||
)?
|
||||
)))
|
||||
}
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
// Special implementations for usize and u64 because these conversions can fail.
|
||||
to_sql_self_fallible!(u64);
|
||||
to_sql_self_fallible!(usize);
|
||||
to_sql_self_fallible!(non_zero std::num::NonZeroU64);
|
||||
to_sql_self_fallible!(non_zero std::num::NonZeroUsize);
|
||||
|
||||
impl<T: ?Sized> ToSql for &'_ T
|
||||
where
|
||||
@@ -267,9 +314,26 @@ mod test {
|
||||
is_to_sql::<i16>();
|
||||
is_to_sql::<i32>();
|
||||
is_to_sql::<i64>();
|
||||
is_to_sql::<isize>();
|
||||
is_to_sql::<u8>();
|
||||
is_to_sql::<u16>();
|
||||
is_to_sql::<u32>();
|
||||
is_to_sql::<u64>();
|
||||
is_to_sql::<usize>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nonzero_types() {
|
||||
is_to_sql::<std::num::NonZeroI8>();
|
||||
is_to_sql::<std::num::NonZeroI16>();
|
||||
is_to_sql::<std::num::NonZeroI32>();
|
||||
is_to_sql::<std::num::NonZeroI64>();
|
||||
is_to_sql::<std::num::NonZeroIsize>();
|
||||
is_to_sql::<std::num::NonZeroU8>();
|
||||
is_to_sql::<std::num::NonZeroU16>();
|
||||
is_to_sql::<std::num::NonZeroU32>();
|
||||
is_to_sql::<std::num::NonZeroU64>();
|
||||
is_to_sql::<std::num::NonZeroUsize>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -398,6 +462,54 @@ mod test {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "i128_blob")]
|
||||
#[test]
|
||||
fn test_non_zero_i128() -> crate::Result<()> {
|
||||
use std::num::NonZeroI128;
|
||||
macro_rules! nz {
|
||||
($x:expr) => {
|
||||
NonZeroI128::new($x).unwrap()
|
||||
};
|
||||
}
|
||||
|
||||
let db = crate::Connection::open_in_memory()?;
|
||||
db.execute_batch("CREATE TABLE foo (i128 BLOB, desc TEXT)")?;
|
||||
db.execute(
|
||||
"INSERT INTO foo(i128, desc) VALUES
|
||||
(?1, 'neg one'), (?2, 'neg two'),
|
||||
(?3, 'pos one'), (?4, 'pos two'),
|
||||
(?5, 'min'), (?6, 'max')",
|
||||
[
|
||||
nz!(-1),
|
||||
nz!(-2),
|
||||
nz!(1),
|
||||
nz!(2),
|
||||
nz!(i128::MIN),
|
||||
nz!(i128::MAX),
|
||||
],
|
||||
)?;
|
||||
let mut stmt = db.prepare("SELECT i128, desc FROM foo ORDER BY i128 ASC")?;
|
||||
|
||||
let res = stmt
|
||||
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
|
||||
.collect::<Result<Vec<(NonZeroI128, String)>, _>>()?;
|
||||
|
||||
assert_eq!(
|
||||
res,
|
||||
&[
|
||||
(nz!(i128::MIN), "min".to_owned()),
|
||||
(nz!(-2), "neg two".to_owned()),
|
||||
(nz!(-1), "neg one".to_owned()),
|
||||
(nz!(1), "pos one".to_owned()),
|
||||
(nz!(2), "pos two".to_owned()),
|
||||
(nz!(i128::MAX), "max".to_owned()),
|
||||
]
|
||||
);
|
||||
let err = db.query_row("SELECT ?1", [0i128], |row| row.get::<_, NonZeroI128>(0));
|
||||
assert_eq!(err, Err(crate::Error::IntegralValueOutOfRange(0, 0)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "uuid")]
|
||||
#[test]
|
||||
fn test_uuid() -> crate::Result<()> {
|
||||
|
||||
@@ -74,7 +74,7 @@ mod test {
|
||||
);
|
||||
}
|
||||
e => {
|
||||
panic!("Expected conversion failure, got {}", e);
|
||||
panic!("Expected conversion failure, got {e}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -158,6 +158,7 @@ impl<'a> ValueRef<'a> {
|
||||
|
||||
impl From<ValueRef<'_>> for Value {
|
||||
#[inline]
|
||||
#[track_caller]
|
||||
fn from(borrowed: ValueRef<'_>) -> Value {
|
||||
match borrowed {
|
||||
ValueRef::Null => Value::Null,
|
||||
|
||||
@@ -6,4 +6,4 @@ pub(crate) use small_cstr::SmallCString;
|
||||
|
||||
// Doesn't use any modern features or vtab stuff, but is only used by them.
|
||||
mod sqlite_string;
|
||||
pub(crate) use sqlite_string::SqliteMallocString;
|
||||
pub(crate) use sqlite_string::{alloc, SqliteMallocString};
|
||||
|
||||
@@ -7,6 +7,12 @@ use std::marker::PhantomData;
|
||||
use std::os::raw::{c_char, c_int};
|
||||
use std::ptr::NonNull;
|
||||
|
||||
// Space to hold this string must be obtained
|
||||
// from an SQLite memory allocation function
|
||||
pub(crate) fn alloc(s: &str) -> *mut c_char {
|
||||
SqliteMallocString::from_str(s).into_raw()
|
||||
}
|
||||
|
||||
/// A string we own that's allocated on the SQLite heap. Automatically calls
|
||||
/// `sqlite3_free` when dropped, unless `into_raw` (or `into_inner`) is called
|
||||
/// on it. If constructed from a rust string, `sqlite3_malloc` is used.
|
||||
@@ -100,7 +106,6 @@ impl SqliteMallocString {
|
||||
/// This means it's safe to use in extern "C" functions even outside of
|
||||
/// `catch_unwind`.
|
||||
pub(crate) fn from_str(s: &str) -> Self {
|
||||
use std::convert::TryFrom;
|
||||
let s = if s.as_bytes().contains(&0) {
|
||||
std::borrow::Cow::Owned(make_nonnull(s))
|
||||
} else {
|
||||
|
||||
@@ -113,10 +113,7 @@ unsafe impl<'vtab> VTab<'vtab> for CsvTab {
|
||||
match param {
|
||||
"filename" => {
|
||||
if !Path::new(value).exists() {
|
||||
return Err(Error::ModuleError(format!(
|
||||
"file '{}' does not exist",
|
||||
value
|
||||
)));
|
||||
return Err(Error::ModuleError(format!("file '{value}' does not exist")));
|
||||
}
|
||||
vtab.filename = value.to_owned();
|
||||
}
|
||||
@@ -137,8 +134,7 @@ unsafe impl<'vtab> VTab<'vtab> for CsvTab {
|
||||
n_col = Some(n);
|
||||
} else {
|
||||
return Err(Error::ModuleError(format!(
|
||||
"unrecognized argument to 'columns': {}",
|
||||
value
|
||||
"unrecognized argument to 'columns': {value}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
@@ -147,8 +143,7 @@ unsafe impl<'vtab> VTab<'vtab> for CsvTab {
|
||||
vtab.has_headers = b;
|
||||
} else {
|
||||
return Err(Error::ModuleError(format!(
|
||||
"unrecognized argument to 'header': {}",
|
||||
value
|
||||
"unrecognized argument to 'header': {value}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
@@ -157,8 +152,7 @@ unsafe impl<'vtab> VTab<'vtab> for CsvTab {
|
||||
vtab.delimiter = b;
|
||||
} else {
|
||||
return Err(Error::ModuleError(format!(
|
||||
"unrecognized argument to 'delimiter': {}",
|
||||
value
|
||||
"unrecognized argument to 'delimiter': {value}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
@@ -171,15 +165,13 @@ unsafe impl<'vtab> VTab<'vtab> for CsvTab {
|
||||
}
|
||||
} else {
|
||||
return Err(Error::ModuleError(format!(
|
||||
"unrecognized argument to 'quote': {}",
|
||||
value
|
||||
"unrecognized argument to 'quote': {value}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::ModuleError(format!(
|
||||
"unrecognized parameter '{}'",
|
||||
param
|
||||
"unrecognized parameter '{param}'"
|
||||
)));
|
||||
}
|
||||
}
|
||||
@@ -326,8 +318,7 @@ unsafe impl VTabCursor for CsvTabCursor<'_> {
|
||||
fn column(&self, ctx: &mut Context, col: c_int) -> Result<()> {
|
||||
if col < 0 || col as usize >= self.cols.len() {
|
||||
return Err(Error::ModuleError(format!(
|
||||
"column index out of bounds: {}",
|
||||
col
|
||||
"column index out of bounds: {col}"
|
||||
)));
|
||||
}
|
||||
if self.cols.is_empty() {
|
||||
|
||||
@@ -17,10 +17,11 @@ use std::ptr;
|
||||
use std::slice;
|
||||
|
||||
use crate::context::set_result;
|
||||
use crate::error::error_from_sqlite_code;
|
||||
use crate::error::{error_from_sqlite_code, to_sqlite_error};
|
||||
use crate::ffi;
|
||||
pub use crate::ffi::{sqlite3_vtab, sqlite3_vtab_cursor};
|
||||
use crate::types::{FromSql, FromSqlError, ToSql, ValueRef};
|
||||
use crate::util::alloc;
|
||||
use crate::{str_to_cstring, Connection, Error, InnerConnection, Result};
|
||||
|
||||
// let conn: Connection = ...;
|
||||
@@ -195,6 +196,8 @@ pub enum VTabConfig {
|
||||
Innocuous = 2,
|
||||
/// Equivalent to SQLITE_VTAB_DIRECTONLY
|
||||
DirectOnly = 3,
|
||||
/// Equivalent to SQLITE_VTAB_USES_ALL_SCHEMAS
|
||||
UsesAllSchemas = 4,
|
||||
}
|
||||
|
||||
/// `feature = "vtab"`
|
||||
@@ -882,7 +885,7 @@ pub fn dequote(s: &str) -> &str {
|
||||
return s;
|
||||
}
|
||||
match s.bytes().next() {
|
||||
Some(b) if b == b'"' || b == b'\'' => match s.bytes().rev().next() {
|
||||
Some(b) if b == b'"' || b == b'\'' => match s.bytes().next_back() {
|
||||
Some(e) if e == b => &s[1..s.len() - 1], // FIXME handle inner escaped quote(s)
|
||||
_ => s,
|
||||
},
|
||||
@@ -962,8 +965,7 @@ where
|
||||
ffi::SQLITE_OK
|
||||
} else {
|
||||
let err = error_from_sqlite_code(rc, None);
|
||||
*err_msg = alloc(&err.to_string());
|
||||
rc
|
||||
to_sqlite_error(&err, err_msg)
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
@@ -971,16 +973,7 @@ where
|
||||
ffi::SQLITE_ERROR
|
||||
}
|
||||
},
|
||||
Err(Error::SqliteFailure(err, s)) => {
|
||||
if let Some(s) = s {
|
||||
*err_msg = alloc(&s);
|
||||
}
|
||||
err.extended_code
|
||||
}
|
||||
Err(err) => {
|
||||
*err_msg = alloc(&err.to_string());
|
||||
ffi::SQLITE_ERROR
|
||||
}
|
||||
Err(err) => to_sqlite_error(&err, err_msg),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1014,8 +1007,7 @@ where
|
||||
ffi::SQLITE_OK
|
||||
} else {
|
||||
let err = error_from_sqlite_code(rc, None);
|
||||
*err_msg = alloc(&err.to_string());
|
||||
rc
|
||||
to_sqlite_error(&err, err_msg)
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
@@ -1023,16 +1015,7 @@ where
|
||||
ffi::SQLITE_ERROR
|
||||
}
|
||||
},
|
||||
Err(Error::SqliteFailure(err, s)) => {
|
||||
if let Some(s) = s {
|
||||
*err_msg = alloc(&s);
|
||||
}
|
||||
err.extended_code
|
||||
}
|
||||
Err(err) => {
|
||||
*err_msg = alloc(&err.to_string());
|
||||
ffi::SQLITE_ERROR
|
||||
}
|
||||
Err(err) => to_sqlite_error(&err, err_msg),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1309,12 +1292,6 @@ unsafe fn result_error<T>(ctx: *mut ffi::sqlite3_context, result: Result<T>) ->
|
||||
}
|
||||
}
|
||||
|
||||
// Space to hold this string must be obtained
|
||||
// from an SQLite memory allocation function
|
||||
fn alloc(s: &str) -> *mut c_char {
|
||||
crate::util::SqliteMallocString::from_str(s).into_raw()
|
||||
}
|
||||
|
||||
#[cfg(feature = "array")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "array")))]
|
||||
pub mod array;
|
||||
|
||||
@@ -200,19 +200,19 @@ unsafe impl VTabCursor for SeriesTabCursor<'_> {
|
||||
let mut idx_num = QueryPlanFlags::from_bits_truncate(idx_num);
|
||||
let mut i = 0;
|
||||
if idx_num.contains(QueryPlanFlags::START) {
|
||||
self.min_value = args.get(i)?;
|
||||
self.min_value = args.get::<Option<_>>(i)?.unwrap_or_default();
|
||||
i += 1;
|
||||
} else {
|
||||
self.min_value = 0;
|
||||
}
|
||||
if idx_num.contains(QueryPlanFlags::STOP) {
|
||||
self.max_value = args.get(i)?;
|
||||
self.max_value = args.get::<Option<_>>(i)?.unwrap_or_default();
|
||||
i += 1;
|
||||
} else {
|
||||
self.max_value = 0xffff_ffff;
|
||||
}
|
||||
if idx_num.contains(QueryPlanFlags::STEP) {
|
||||
self.step = args.get(i)?;
|
||||
self.step = args.get::<Option<_>>(i)?.unwrap_or_default();
|
||||
if self.step == 0 {
|
||||
self.step = 1;
|
||||
} else if self.step < 0 {
|
||||
@@ -316,6 +316,26 @@ mod test {
|
||||
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?;
|
||||
assert_eq!(vec![30, 25, 20, 15, 10, 5, 0], series);
|
||||
|
||||
let mut s = db.prepare("SELECT * FROM generate_series(NULL)")?;
|
||||
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?;
|
||||
let empty = Vec::<i32>::new();
|
||||
assert_eq!(empty, series);
|
||||
let mut s = db.prepare("SELECT * FROM generate_series(5,NULL)")?;
|
||||
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?;
|
||||
assert_eq!(empty, series);
|
||||
let mut s = db.prepare("SELECT * FROM generate_series(5,10,NULL)")?;
|
||||
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?;
|
||||
assert_eq!(empty, series);
|
||||
let mut s = db.prepare("SELECT * FROM generate_series(NULL,10,2)")?;
|
||||
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?;
|
||||
assert_eq!(empty, series);
|
||||
let mut s = db.prepare("SELECT * FROM generate_series(5,NULL,2)")?;
|
||||
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?;
|
||||
assert_eq!(empty, series);
|
||||
let mut s = db.prepare("SELECT * FROM generate_series(NULL) ORDER BY value DESC")?;
|
||||
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?;
|
||||
assert_eq!(empty, series);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,8 +56,7 @@ impl VTabLog {
|
||||
"schema" => {
|
||||
if schema.is_some() {
|
||||
return Err(Error::ModuleError(format!(
|
||||
"more than one '{}' parameter",
|
||||
param
|
||||
"more than one '{param}' parameter"
|
||||
)));
|
||||
}
|
||||
schema = Some(value.to_owned())
|
||||
@@ -65,8 +64,7 @@ impl VTabLog {
|
||||
"rows" => {
|
||||
if n_row.is_some() {
|
||||
return Err(Error::ModuleError(format!(
|
||||
"more than one '{}' parameter",
|
||||
param
|
||||
"more than one '{param}' parameter"
|
||||
)));
|
||||
}
|
||||
if let Ok(n) = i64::from_str(value) {
|
||||
@@ -75,8 +73,7 @@ impl VTabLog {
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::ModuleError(format!(
|
||||
"unrecognized parameter '{}'",
|
||||
param
|
||||
"unrecognized parameter '{param}'"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user