Merge pull request #1552 from gwenn/clippy

Clippy
This commit is contained in:
gwenn 2024-08-10 15:41:50 +02:00 committed by GitHub
commit 1e3492bd93
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
37 changed files with 320 additions and 332 deletions

View File

@ -1,4 +1,4 @@
//! Ensure loadable_extension.rs works.
//! Ensure `loadable_extension.rs` works.
use rusqlite::{Connection, Result};
use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
@ -9,10 +9,7 @@ fn main() -> Result<()> {
unsafe {
db.load_extension_enable()?;
db.load_extension(
format!(
"target/debug/examples/{}loadable_extension{}",
DLL_PREFIX, DLL_SUFFIX
),
format!("target/debug/examples/{DLL_PREFIX}loadable_extension{DLL_SUFFIX}"),
None,
)?;
db.load_extension_disable()?;

View File

@ -6,7 +6,7 @@ use std::path::Path;
///
/// Note that there is no way to know at compile-time which system we'll be
/// targeting, and this test must be made at run-time (of the build script) See
/// https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts
/// <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts>
fn win_target() -> bool {
env::var("CARGO_CFG_WINDOWS").is_ok()
}
@ -182,7 +182,7 @@ mod build_bundled {
let inc_dir = inc_dir.unwrap_or_else(|| openssl_dir.join("include"));
if !lib_dir.iter().all(|p| p.exists()) {
panic!("OpenSSL library directory does not exist: {:?}", lib_dir);
panic!("OpenSSL library directory does not exist: {lib_dir:?}");
}
if !Path::new(&inc_dir).exists() {
@ -205,8 +205,8 @@ mod build_bundled {
} else if use_openssl {
cfg.include(inc_dir.to_string_lossy().as_ref());
let lib_name = if is_windows { "libcrypto" } else { "crypto" };
println!("cargo:rustc-link-lib=dylib={}", lib_name);
for lib_dir_item in lib_dir.iter() {
println!("cargo:rustc-link-lib=dylib={lib_name}");
for lib_dir_item in &lib_dir {
println!("cargo:rustc-link-search={}", lib_dir_item.to_string_lossy());
}
} else if is_apple {
@ -285,7 +285,7 @@ mod build_bundled {
} else if extra.starts_with("SQLITE_") {
cfg.flag(format!("-D{extra}"));
} else {
panic!("Don't understand {} in LIBSQLITE3_FLAGS", extra);
panic!("Don't understand {extra} in LIBSQLITE3_FLAGS");
}
}
}
@ -336,7 +336,7 @@ pub enum HeaderLocation {
}
impl From<HeaderLocation> for String {
fn from(header: HeaderLocation) -> String {
fn from(header: HeaderLocation) -> Self {
match header {
HeaderLocation::FromEnvironment => {
let prefix = env_prefix();

View File

@ -16,17 +16,17 @@ pub enum ErrorCode {
DatabaseBusy,
/// A table in the database is locked
DatabaseLocked,
/// A malloc() failed
/// A `malloc()` failed
OutOfMemory,
/// Attempt to write a readonly database
ReadOnly,
/// Operation terminated by sqlite3_interrupt()
/// Operation terminated by `sqlite3_interrupt()`
OperationInterrupted,
/// Some kind of disk I/O error occurred
SystemIoFailure,
/// The database disk image is malformed
DatabaseCorrupt,
/// Unknown opcode in sqlite3_file_control()
/// Unknown opcode in `sqlite3_file_control()`
NotFound,
/// Insertion failed because database is full
DiskFull,
@ -48,7 +48,7 @@ pub enum ErrorCode {
NoLargeFileSupport,
/// Authorization denied
AuthorizationForStatementDenied,
/// 2nd parameter to sqlite3_bind out of range
/// 2nd parameter to `sqlite3_bind` out of range
ParameterOutOfRange,
/// File opened that is not a database file
NotADatabase,
@ -64,7 +64,7 @@ pub struct Error {
impl Error {
#[must_use]
pub fn new(result_code: c_int) -> Error {
pub fn new(result_code: c_int) -> Self {
let code = match result_code & 0xff {
super::SQLITE_INTERNAL => ErrorCode::InternalMalfunction,
super::SQLITE_PERM => ErrorCode::PermissionDenied,
@ -92,7 +92,7 @@ impl Error {
_ => ErrorCode::Unknown,
};
Error {
Self {
code,
extended_code: result_code,
}
@ -281,20 +281,20 @@ pub fn code_to_str(code: c_int) -> &'static str {
pub enum InitError {
/// Version mismatch between the extension and the SQLite3 library
VersionMismatch { compile_time: i32, runtime: i32 },
/// Invalid function pointer in one of sqlite3_api_routines fields
/// Invalid function pointer in one of `sqlite3_api_routines` fields
NullFunctionPointer,
}
#[cfg(feature = "loadable_extension")]
impl ::std::fmt::Display for InitError {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
match *self {
InitError::VersionMismatch {
Self::VersionMismatch {
compile_time,
runtime,
} => {
write!(f, "SQLite version mismatch: {runtime} < {compile_time}")
}
InitError::NullFunctionPointer => {
Self::NullFunctionPointer => {
write!(f, "Some sqlite3_api_routines fields are null")
}
}
@ -336,7 +336,7 @@ mod test {
extended_code: sqlite_code
}
);
let s = format!("{}", err);
let s = format!("{err}");
assert!(!s.is_empty());
}
}

View File

@ -27,9 +27,8 @@ fn try_bind(input: TokenStream) -> Result<TokenStream> {
(stmt, literal)
};
let literal = match into_literal(&literal) {
Some(it) => it,
None => return Err("expected a plain string literal".to_string()),
let Some(literal) = into_literal(&literal) else {
return Err("expected a plain string literal".to_string());
};
let call_site = literal.span();
let string_lit = match StringLit::try_from(literal) {

View File

@ -65,7 +65,7 @@ impl Connection {
progress: Option<fn(Progress)>,
) -> Result<()> {
use self::StepResult::{Busy, Done, Locked, More};
let mut dst = Connection::open(dst_path)?;
let mut dst = Self::open(dst_path)?;
let backup = Backup::new_with_names(self, name, &mut dst, DatabaseName::Main)?;
let mut r = More;
@ -103,7 +103,7 @@ impl Connection {
progress: Option<F>,
) -> Result<()> {
use self::StepResult::{Busy, Done, Locked, More};
let src = Connection::open(src_path)?;
let src = Self::open(src_path)?;
let restore = Backup::new_with_names(&src, DatabaseName::Main, self, name)?;
let mut r = More;

View File

@ -413,7 +413,7 @@ pub struct ZeroBlob(pub i32);
impl ToSql for ZeroBlob {
#[inline]
fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
let ZeroBlob(length) = *self;
let Self(length) = *self;
Ok(ToSqlOutput::ZeroBlob(length))
}
}

View File

@ -119,8 +119,8 @@ impl CachedStatement<'_> {
impl StatementCache {
/// Create a statement cache.
#[inline]
pub fn with_capacity(capacity: usize) -> StatementCache {
StatementCache(RefCell::new(LruCache::new(capacity)))
pub fn with_capacity(capacity: usize) -> Self {
Self(RefCell::new(LruCache::new(capacity)))
}
#[inline]
@ -278,10 +278,10 @@ mod test {
fn test_ddl() -> Result<()> {
let db = Connection::open_in_memory()?;
db.execute_batch(
r#"
r"
CREATE TABLE foo (x INT);
INSERT INTO foo VALUES (1);
"#,
",
)?;
let sql = "SELECT * FROM foo";
@ -292,10 +292,10 @@ mod test {
}
db.execute_batch(
r#"
r"
ALTER TABLE foo ADD COLUMN y INT;
UPDATE foo SET y = 2;
"#,
",
)?;
{

View File

@ -27,10 +27,7 @@ impl Connection {
/// Collation needed callback
#[inline]
pub fn collation_needed(
&self,
x_coll_needed: fn(&Connection, &str) -> Result<()>,
) -> Result<()> {
pub fn collation_needed(&self, x_coll_needed: fn(&Self, &str) -> Result<()>) -> Result<()> {
self.db.borrow_mut().collation_needed(x_coll_needed)
}

View File

@ -57,7 +57,7 @@ impl Statement<'_> {
}
/// Check that column name reference lifetime is limited:
/// https://www.sqlite.org/c3ref/column_name.html
/// <https://www.sqlite.org/c3ref/column_name.html>
/// > The returned string pointer is valid...
///
/// `column_name` reference can become invalid if `stmt` is reprepared
@ -231,7 +231,7 @@ mod test {
/// `column_name` reference should stay valid until `stmt` is reprepared (or
/// reset) even if DB schema is altered (SQLite documentation is
/// ambiguous here because it says reference "is valid until (...) the next
/// call to sqlite3_column_name() or sqlite3_column_name16() on the same
/// call to `sqlite3_column_name()` or `sqlite3_column_name16()` on the same
/// column.". We assume that reference is valid if only
/// `sqlite3_column_name()` is used):
#[test]

View File

@ -20,7 +20,7 @@ pub enum DbConfig {
SQLITE_DBCONFIG_ENABLE_FKEY = ffi::SQLITE_DBCONFIG_ENABLE_FKEY,
/// Enable or disable triggers.
SQLITE_DBCONFIG_ENABLE_TRIGGER = ffi::SQLITE_DBCONFIG_ENABLE_TRIGGER,
/// Enable or disable the fts3_tokenizer() function which is part of the
/// Enable or disable the `fts3_tokenizer()` function which is part of the
/// FTS3 full-text search engine extension.
SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER = ffi::SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, // 3.12.0
//SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION = 1005,
@ -37,7 +37,7 @@ pub enum DbConfig {
SQLITE_DBCONFIG_RESET_DATABASE = 1009, // 3.24.0
/// Activates or deactivates the "defensive" flag for a database connection.
SQLITE_DBCONFIG_DEFENSIVE = 1010, // 3.26.0
/// Activates or deactivates the "writable_schema" flag.
/// Activates or deactivates the `writable_schema` flag.
#[cfg(feature = "modern_sqlite")]
SQLITE_DBCONFIG_WRITABLE_SCHEMA = 1011, // 3.28.0
/// Activates or deactivates the legacy behavior of the ALTER TABLE RENAME
@ -59,11 +59,11 @@ pub enum DbConfig {
#[cfg(feature = "modern_sqlite")]
SQLITE_DBCONFIG_LEGACY_FILE_FORMAT = 1016, // 3.31.0
/// Tells SQLite to assume that database schemas (the contents of the
/// sqlite_master tables) are untainted by malicious content.
/// `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
/// `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

View File

@ -55,10 +55,9 @@ pub(super) unsafe fn set_result(
if length > c_int::MAX as usize {
ffi::sqlite3_result_error_toobig(ctx);
} else {
let (c_str, len, destructor) = match str_for_sqlite(s) {
Ok(c_str) => c_str,
let Ok((c_str, len, destructor)) = str_for_sqlite(s) else {
// TODO sqlite3_result_error
Err(_) => return ffi::sqlite3_result_error_code(ctx, ffi::SQLITE_MISUSE),
return ffi::sqlite3_result_error_code(ctx, ffi::SQLITE_MISUSE);
};
// TODO sqlite3_result_text64 // 3.8.7
ffi::sqlite3_result_text(ctx, c_str, len, destructor);

View File

@ -151,55 +151,55 @@ pub enum Error {
}
impl PartialEq for Error {
fn eq(&self, other: &Error) -> bool {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Error::SqliteFailure(e1, s1), Error::SqliteFailure(e2, s2)) => e1 == e2 && s1 == s2,
(Error::SqliteSingleThreadedMode, Error::SqliteSingleThreadedMode) => true,
(Error::IntegralValueOutOfRange(i1, n1), Error::IntegralValueOutOfRange(i2, n2)) => {
(Self::SqliteFailure(e1, s1), Self::SqliteFailure(e2, s2)) => e1 == e2 && s1 == s2,
(Self::SqliteSingleThreadedMode, Self::SqliteSingleThreadedMode) => true,
(Self::IntegralValueOutOfRange(i1, n1), Self::IntegralValueOutOfRange(i2, n2)) => {
i1 == i2 && n1 == n2
}
(Error::Utf8Error(e1), Error::Utf8Error(e2)) => e1 == e2,
(Error::NulError(e1), Error::NulError(e2)) => e1 == e2,
(Error::InvalidParameterName(n1), Error::InvalidParameterName(n2)) => n1 == n2,
(Error::InvalidPath(p1), Error::InvalidPath(p2)) => p1 == p2,
(Error::ExecuteReturnedResults, Error::ExecuteReturnedResults) => true,
(Error::QueryReturnedNoRows, Error::QueryReturnedNoRows) => true,
(Error::InvalidColumnIndex(i1), Error::InvalidColumnIndex(i2)) => i1 == i2,
(Error::InvalidColumnName(n1), Error::InvalidColumnName(n2)) => n1 == n2,
(Error::InvalidColumnType(i1, n1, t1), Error::InvalidColumnType(i2, n2, t2)) => {
(Self::Utf8Error(e1), Self::Utf8Error(e2)) => e1 == e2,
(Self::NulError(e1), Self::NulError(e2)) => e1 == e2,
(Self::InvalidParameterName(n1), Self::InvalidParameterName(n2)) => n1 == n2,
(Self::InvalidPath(p1), Self::InvalidPath(p2)) => p1 == p2,
(Self::ExecuteReturnedResults, Self::ExecuteReturnedResults) => true,
(Self::QueryReturnedNoRows, Self::QueryReturnedNoRows) => true,
(Self::InvalidColumnIndex(i1), Self::InvalidColumnIndex(i2)) => i1 == i2,
(Self::InvalidColumnName(n1), Self::InvalidColumnName(n2)) => n1 == n2,
(Self::InvalidColumnType(i1, n1, t1), Self::InvalidColumnType(i2, n2, t2)) => {
i1 == i2 && t1 == t2 && n1 == n2
}
(Error::StatementChangedRows(n1), Error::StatementChangedRows(n2)) => n1 == n2,
(Self::StatementChangedRows(n1), Self::StatementChangedRows(n2)) => n1 == n2,
#[cfg(feature = "functions")]
(
Error::InvalidFunctionParameterType(i1, t1),
Error::InvalidFunctionParameterType(i2, t2),
Self::InvalidFunctionParameterType(i1, t1),
Self::InvalidFunctionParameterType(i2, t2),
) => i1 == i2 && t1 == t2,
#[cfg(feature = "vtab")]
(
Error::InvalidFilterParameterType(i1, t1),
Error::InvalidFilterParameterType(i2, t2),
Self::InvalidFilterParameterType(i1, t1),
Self::InvalidFilterParameterType(i2, t2),
) => i1 == i2 && t1 == t2,
(Error::InvalidQuery, Error::InvalidQuery) => true,
(Self::InvalidQuery, Self::InvalidQuery) => true,
#[cfg(feature = "vtab")]
(Error::ModuleError(s1), Error::ModuleError(s2)) => s1 == s2,
(Error::UnwindingPanic, Error::UnwindingPanic) => true,
(Self::ModuleError(s1), Self::ModuleError(s2)) => s1 == s2,
(Self::UnwindingPanic, Self::UnwindingPanic) => true,
#[cfg(feature = "functions")]
(Error::GetAuxWrongType, Error::GetAuxWrongType) => true,
(Error::InvalidParameterCount(i1, n1), Error::InvalidParameterCount(i2, n2)) => {
(Self::GetAuxWrongType, Self::GetAuxWrongType) => true,
(Self::InvalidParameterCount(i1, n1), Self::InvalidParameterCount(i2, n2)) => {
i1 == i2 && n1 == n2
}
#[cfg(feature = "blob")]
(Error::BlobSizeError, Error::BlobSizeError) => true,
(Self::BlobSizeError, Self::BlobSizeError) => true,
#[cfg(feature = "modern_sqlite")]
(
Error::SqlInputError {
Self::SqlInputError {
error: e1,
msg: m1,
sql: s1,
offset: o1,
},
Error::SqlInputError {
Self::SqlInputError {
error: e2,
msg: m2,
sql: s2,
@ -207,9 +207,9 @@ impl PartialEq for Error {
},
) => e1 == e2 && m1 == m2 && s1 == s2 && o1 == o2,
#[cfg(feature = "loadable_extension")]
(Error::InitError(e1), Error::InitError(e2)) => e1 == e2,
(Self::InitError(e1), Self::InitError(e2)) => e1 == e2,
#[cfg(feature = "modern_sqlite")]
(Error::InvalidDatabaseIndex(i1), Error::InvalidDatabaseIndex(i2)) => i1 == i2,
(Self::InvalidDatabaseIndex(i1), Self::InvalidDatabaseIndex(i2)) => i1 == i2,
(..) => false,
}
}
@ -217,15 +217,15 @@ impl PartialEq for Error {
impl From<str::Utf8Error> for Error {
#[cold]
fn from(err: str::Utf8Error) -> Error {
Error::Utf8Error(err)
fn from(err: str::Utf8Error) -> Self {
Self::Utf8Error(err)
}
}
impl From<std::ffi::NulError> for Error {
#[cold]
fn from(err: std::ffi::NulError) -> Error {
Error::NulError(err)
fn from(err: std::ffi::NulError) -> Self {
Self::NulError(err)
}
}
@ -235,18 +235,18 @@ const UNKNOWN_COLUMN: usize = usize::MAX;
/// to allow use of `get_raw(…).as_…()?` in callbacks that take `Error`.
impl From<FromSqlError> for Error {
#[cold]
fn from(err: FromSqlError) -> Error {
fn from(err: FromSqlError) -> Self {
// The error type requires index and type fields, but they aren't known in this
// context.
match err {
FromSqlError::OutOfRange(val) => Error::IntegralValueOutOfRange(UNKNOWN_COLUMN, val),
FromSqlError::OutOfRange(val) => Self::IntegralValueOutOfRange(UNKNOWN_COLUMN, val),
FromSqlError::InvalidBlobSize { .. } => {
Error::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Blob, Box::new(err))
Self::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Blob, Box::new(err))
}
FromSqlError::Other(source) => {
Error::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Null, source)
Self::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Null, source)
}
_ => Error::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Null, Box::new(err)),
_ => Self::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Null, Box::new(err)),
}
}
}
@ -254,84 +254,84 @@ impl From<FromSqlError> for Error {
#[cfg(feature = "loadable_extension")]
impl From<ffi::InitError> for Error {
#[cold]
fn from(err: ffi::InitError) -> Error {
Error::InitError(err)
fn from(err: ffi::InitError) -> Self {
Self::InitError(err)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Error::SqliteFailure(ref err, None) => err.fmt(f),
Error::SqliteFailure(_, Some(ref s)) => write!(f, "{s}"),
Error::SqliteSingleThreadedMode => write!(
Self::SqliteFailure(ref err, None) => err.fmt(f),
Self::SqliteFailure(_, Some(ref s)) => write!(f, "{s}"),
Self::SqliteSingleThreadedMode => write!(
f,
"SQLite was compiled or configured for single-threaded use only"
),
Error::FromSqlConversionFailure(i, ref t, ref err) => {
Self::FromSqlConversionFailure(i, ref t, ref err) => {
if i != UNKNOWN_COLUMN {
write!(f, "Conversion error from type {t} at index: {i}, {err}")
} else {
err.fmt(f)
}
}
Error::IntegralValueOutOfRange(col, val) => {
Self::IntegralValueOutOfRange(col, val) => {
if col != UNKNOWN_COLUMN {
write!(f, "Integer {val} out of range at index {col}")
} else {
write!(f, "Integer {val} out of range")
}
}
Error::Utf8Error(ref err) => err.fmt(f),
Error::NulError(ref err) => err.fmt(f),
Error::InvalidParameterName(ref name) => write!(f, "Invalid parameter name: {name}"),
Error::InvalidPath(ref p) => write!(f, "Invalid path: {}", p.to_string_lossy()),
Error::ExecuteReturnedResults => {
Self::Utf8Error(ref err) => err.fmt(f),
Self::NulError(ref err) => err.fmt(f),
Self::InvalidParameterName(ref name) => write!(f, "Invalid parameter name: {name}"),
Self::InvalidPath(ref p) => write!(f, "Invalid path: {}", p.to_string_lossy()),
Self::ExecuteReturnedResults => {
write!(f, "Execute returned results - did you mean to call query?")
}
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) => {
Self::QueryReturnedNoRows => write!(f, "Query returned no rows"),
Self::InvalidColumnIndex(i) => write!(f, "Invalid column index: {i}"),
Self::InvalidColumnName(ref name) => write!(f, "Invalid column name: {name}"),
Self::InvalidColumnType(i, ref name, ref t) => {
write!(f, "Invalid column type {t} at index: {i}, name: {name}")
}
Error::InvalidParameterCount(i1, n1) => write!(
Self::InvalidParameterCount(i1, n1) => write!(
f,
"Wrong number of parameters passed to query. Got {i1}, needed {n1}"
),
Error::StatementChangedRows(i) => write!(f, "Query changed {i} rows"),
Self::StatementChangedRows(i) => write!(f, "Query changed {i} rows"),
#[cfg(feature = "functions")]
Error::InvalidFunctionParameterType(i, ref t) => {
Self::InvalidFunctionParameterType(i, ref t) => {
write!(f, "Invalid function parameter type {t} at index {i}")
}
#[cfg(feature = "vtab")]
Error::InvalidFilterParameterType(i, ref t) => {
Self::InvalidFilterParameterType(i, ref t) => {
write!(f, "Invalid filter parameter type {t} at index {i}")
}
#[cfg(feature = "functions")]
Error::UserFunctionError(ref err) => err.fmt(f),
Error::ToSqlConversionFailure(ref err) => err.fmt(f),
Error::InvalidQuery => write!(f, "Query is not read-only"),
Self::UserFunctionError(ref err) => err.fmt(f),
Self::ToSqlConversionFailure(ref err) => err.fmt(f),
Self::InvalidQuery => write!(f, "Query is not read-only"),
#[cfg(feature = "vtab")]
Error::ModuleError(ref desc) => write!(f, "{desc}"),
Error::UnwindingPanic => write!(f, "unwinding panic"),
Self::ModuleError(ref desc) => write!(f, "{desc}"),
Self::UnwindingPanic => write!(f, "unwinding panic"),
#[cfg(feature = "functions")]
Error::GetAuxWrongType => write!(f, "get_aux called with wrong type"),
Error::MultipleStatement => write!(f, "Multiple statements provided"),
Self::GetAuxWrongType => write!(f, "get_aux called with wrong type"),
Self::MultipleStatement => write!(f, "Multiple statements provided"),
#[cfg(feature = "blob")]
Error::BlobSizeError => "Blob size is insufficient".fmt(f),
Self::BlobSizeError => "Blob size is insufficient".fmt(f),
#[cfg(feature = "modern_sqlite")]
Error::SqlInputError {
Self::SqlInputError {
ref msg,
offset,
ref sql,
..
} => write!(f, "{msg} in {sql} at offset {offset}"),
#[cfg(feature = "loadable_extension")]
Error::InitError(ref err) => err.fmt(f),
Self::InitError(ref err) => err.fmt(f),
#[cfg(feature = "modern_sqlite")]
Error::InvalidDatabaseIndex(i) => write!(f, "Invalid database index: {i}"),
Self::InvalidDatabaseIndex(i) => write!(f, "Invalid database index: {i}"),
}
}
}
@ -339,51 +339,51 @@ impl fmt::Display for Error {
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match *self {
Error::SqliteFailure(ref err, _) => Some(err),
Error::Utf8Error(ref err) => Some(err),
Error::NulError(ref err) => Some(err),
Self::SqliteFailure(ref err, _) => Some(err),
Self::Utf8Error(ref err) => Some(err),
Self::NulError(ref err) => Some(err),
Error::IntegralValueOutOfRange(..)
| Error::SqliteSingleThreadedMode
| Error::InvalidParameterName(_)
| Error::ExecuteReturnedResults
| Error::QueryReturnedNoRows
| Error::InvalidColumnIndex(_)
| Error::InvalidColumnName(_)
| Error::InvalidColumnType(..)
| Error::InvalidPath(_)
| Error::InvalidParameterCount(..)
| Error::StatementChangedRows(_)
| Error::InvalidQuery
| Error::MultipleStatement => None,
Self::IntegralValueOutOfRange(..)
| Self::SqliteSingleThreadedMode
| Self::InvalidParameterName(_)
| Self::ExecuteReturnedResults
| Self::QueryReturnedNoRows
| Self::InvalidColumnIndex(_)
| Self::InvalidColumnName(_)
| Self::InvalidColumnType(..)
| Self::InvalidPath(_)
| Self::InvalidParameterCount(..)
| Self::StatementChangedRows(_)
| Self::InvalidQuery
| Self::MultipleStatement => None,
#[cfg(feature = "functions")]
Error::InvalidFunctionParameterType(..) => None,
Self::InvalidFunctionParameterType(..) => None,
#[cfg(feature = "vtab")]
Error::InvalidFilterParameterType(..) => None,
Self::InvalidFilterParameterType(..) => None,
#[cfg(feature = "functions")]
Error::UserFunctionError(ref err) => Some(&**err),
Self::UserFunctionError(ref err) => Some(&**err),
Error::FromSqlConversionFailure(_, _, ref err)
| Error::ToSqlConversionFailure(ref err) => Some(&**err),
Self::FromSqlConversionFailure(_, _, ref err)
| Self::ToSqlConversionFailure(ref err) => Some(&**err),
#[cfg(feature = "vtab")]
Error::ModuleError(_) => None,
Self::ModuleError(_) => None,
Error::UnwindingPanic => None,
Self::UnwindingPanic => None,
#[cfg(feature = "functions")]
Error::GetAuxWrongType => None,
Self::GetAuxWrongType => None,
#[cfg(feature = "blob")]
Error::BlobSizeError => None,
Self::BlobSizeError => None,
#[cfg(feature = "modern_sqlite")]
Error::SqlInputError { ref error, .. } => Some(error),
Self::SqlInputError { ref error, .. } => Some(error),
#[cfg(feature = "loadable_extension")]
Error::InitError(ref err) => Some(err),
Self::InitError(ref err) => Some(err),
#[cfg(feature = "modern_sqlite")]
Error::InvalidDatabaseIndex(_) => None,
Self::InvalidDatabaseIndex(_) => None,
}
}
}

View File

@ -392,8 +392,8 @@ bitflags::bitflags! {
impl Default for FunctionFlags {
#[inline]
fn default() -> FunctionFlags {
FunctionFlags::SQLITE_UTF8
fn default() -> Self {
Self::SQLITE_UTF8
}
}
@ -691,9 +691,7 @@ unsafe extern "C" fn call_boxed_step<A, D, T>(
D: Aggregate<A, T>,
T: SqlFnOutput,
{
let pac = if let Some(pac) = aggregate_context(ctx, std::mem::size_of::<*mut A>()) {
pac
} else {
let Some(pac) = aggregate_context(ctx, std::mem::size_of::<*mut A>()) else {
ffi::sqlite3_result_error_nomem(ctx);
return;
};
@ -739,9 +737,7 @@ unsafe extern "C" fn call_boxed_inverse<A, W, T>(
W: WindowAggregate<A, T>,
T: SqlFnOutput,
{
let pac = if let Some(pac) = aggregate_context(ctx, std::mem::size_of::<*mut A>()) {
pac
} else {
let Some(pac) = aggregate_context(ctx, std::mem::size_of::<*mut A>()) else {
ffi::sqlite3_result_error_nomem(ctx);
return;
};

View File

@ -33,12 +33,12 @@ pub enum Action {
impl From<i32> for Action {
#[inline]
fn from(code: i32) -> Action {
fn from(code: i32) -> Self {
match code {
ffi::SQLITE_DELETE => Action::SQLITE_DELETE,
ffi::SQLITE_INSERT => Action::SQLITE_INSERT,
ffi::SQLITE_UPDATE => Action::SQLITE_UPDATE,
_ => Action::UNKNOWN,
ffi::SQLITE_DELETE => Self::SQLITE_DELETE,
ffi::SQLITE_INSERT => Self::SQLITE_INSERT,
ffi::SQLITE_UPDATE => Self::SQLITE_UPDATE,
_ => Self::UNKNOWN,
}
}
}

View File

@ -43,8 +43,8 @@ unsafe impl Send for InnerConnection {}
impl InnerConnection {
#[allow(clippy::mutex_atomic, clippy::arc_with_non_send_sync)] // See unsafe impl Send / Sync for InterruptHandle
#[inline]
pub unsafe fn new(db: *mut ffi::sqlite3, owned: bool) -> InnerConnection {
InnerConnection {
pub unsafe fn new(db: *mut ffi::sqlite3, owned: bool) -> Self {
Self {
db,
interrupt_lock: Arc::new(Mutex::new(if owned { db } else { ptr::null_mut() })),
#[cfg(feature = "hooks")]
@ -67,7 +67,7 @@ impl InnerConnection {
c_path: &CStr,
mut flags: OpenFlags,
vfs: Option<&CStr>,
) -> Result<InnerConnection> {
) -> Result<Self> {
ensure_safe_sqlite_threading_mode()?;
let z_vfs = match vfs {
@ -123,7 +123,7 @@ impl InnerConnection {
return Err(e);
}
Ok(InnerConnection::new(db, true))
Ok(Self::new(db, true))
}
}
@ -134,7 +134,7 @@ impl InnerConnection {
#[inline]
pub fn decode_result(&self, code: c_int) -> Result<()> {
unsafe { InnerConnection::decode_result_raw(self.db(), code) }
unsafe { Self::decode_result_raw(self.db(), code) }
}
#[inline]
@ -166,7 +166,7 @@ impl InnerConnection {
let r = ffi::sqlite3_close(self.db);
// Need to use _raw because _guard has a reference out, and
// decode_result takes &mut self.
let r = InnerConnection::decode_result_raw(self.db, r);
let r = Self::decode_result_raw(self.db, r);
if r.is_ok() {
*shared_handle = ptr::null_mut();
self.db = ptr::null_mut();

View File

@ -443,9 +443,9 @@ impl Connection {
/// Will return `Err` if `path` cannot be converted to a C-compatible string
/// or if the underlying SQLite open call fails.
#[inline]
pub fn open<P: AsRef<Path>>(path: P) -> Result<Connection> {
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
let flags = OpenFlags::default();
Connection::open_with_flags(path, flags)
Self::open_with_flags(path, flags)
}
/// Open a new connection to an in-memory SQLite database.
@ -454,9 +454,9 @@ impl Connection {
///
/// Will return `Err` if the underlying SQLite open call fails.
#[inline]
pub fn open_in_memory() -> Result<Connection> {
pub fn open_in_memory() -> Result<Self> {
let flags = OpenFlags::default();
Connection::open_in_memory_with_flags(flags)
Self::open_in_memory_with_flags(flags)
}
/// Open a new connection to a SQLite database.
@ -469,9 +469,9 @@ impl Connection {
/// Will return `Err` if `path` cannot be converted to a C-compatible
/// string or if the underlying SQLite open call fails.
#[inline]
pub fn open_with_flags<P: AsRef<Path>>(path: P, flags: OpenFlags) -> Result<Connection> {
pub fn open_with_flags<P: AsRef<Path>>(path: P, flags: OpenFlags) -> Result<Self> {
let c_path = path_to_cstring(path.as_ref())?;
InnerConnection::open_with_flags(&c_path, flags, None).map(|db| Connection {
InnerConnection::open_with_flags(&c_path, flags, None).map(|db| Self {
db: RefCell::new(db),
cache: StatementCache::with_capacity(STATEMENT_CACHE_DEFAULT_CAPACITY),
transaction_behavior: TransactionBehavior::Deferred,
@ -493,10 +493,10 @@ impl Connection {
path: P,
flags: OpenFlags,
vfs: &str,
) -> Result<Connection> {
) -> Result<Self> {
let c_path = path_to_cstring(path.as_ref())?;
let c_vfs = str_to_cstring(vfs)?;
InnerConnection::open_with_flags(&c_path, flags, Some(&c_vfs)).map(|db| Connection {
InnerConnection::open_with_flags(&c_path, flags, Some(&c_vfs)).map(|db| Self {
db: RefCell::new(db),
cache: StatementCache::with_capacity(STATEMENT_CACHE_DEFAULT_CAPACITY),
transaction_behavior: TransactionBehavior::Deferred,
@ -512,8 +512,8 @@ impl Connection {
///
/// Will return `Err` if the underlying SQLite open call fails.
#[inline]
pub fn open_in_memory_with_flags(flags: OpenFlags) -> Result<Connection> {
Connection::open_with_flags(":memory:", flags)
pub fn open_in_memory_with_flags(flags: OpenFlags) -> Result<Self> {
Self::open_with_flags(":memory:", flags)
}
/// Open a new connection to an in-memory SQLite database using the specific
@ -527,8 +527,8 @@ impl Connection {
/// Will return `Err` if `vfs` cannot be converted to a C-compatible
/// string or if the underlying SQLite open call fails.
#[inline]
pub fn open_in_memory_with_flags_and_vfs(flags: OpenFlags, vfs: &str) -> Result<Connection> {
Connection::open_with_flags_and_vfs(":memory:", flags, vfs)
pub fn open_in_memory_with_flags_and_vfs(flags: OpenFlags, vfs: &str) -> Result<Self> {
Self::open_with_flags_and_vfs(":memory:", flags, vfs)
}
/// Convenience method to run multiple SQL statements (that cannot take any
@ -792,7 +792,7 @@ impl Connection {
///
/// Will return `Err` if the underlying SQLite call fails.
#[inline]
pub fn close(self) -> Result<(), (Connection, Error)> {
pub fn close(self) -> Result<(), (Self, Error)> {
self.flush_prepared_statement_cache();
let r = self.db.borrow_mut().close();
r.map_err(move |err| (self, err))
@ -947,9 +947,9 @@ impl Connection {
///
/// This function is unsafe because improper use may impact the Connection.
#[inline]
pub unsafe fn from_handle(db: *mut ffi::sqlite3) -> Result<Connection> {
pub unsafe fn from_handle(db: *mut ffi::sqlite3) -> Result<Self> {
let db = InnerConnection::new(db, false);
Ok(Connection {
Ok(Self {
db: RefCell::new(db),
cache: StatementCache::with_capacity(STATEMENT_CACHE_DEFAULT_CAPACITY),
transaction_behavior: TransactionBehavior::Deferred,
@ -967,14 +967,14 @@ impl Connection {
db: *mut ffi::sqlite3,
pz_err_msg: *mut *mut c_char,
p_api: *mut ffi::sqlite3_api_routines,
init: fn(Connection) -> Result<bool>,
init: fn(Self) -> Result<bool>,
) -> c_int {
if p_api.is_null() {
return ffi::SQLITE_ERROR;
}
match ffi::rusqlite_extension_init2(p_api)
.map_err(Error::from)
.and(Connection::from_handle(db))
.and(Self::from_handle(db))
.and_then(init)
{
Err(err) => to_sqlite_error(&err, pz_err_msg),
@ -996,9 +996,9 @@ impl Connection {
/// and owned by the caller, e.g. as a result of calling
/// `ffi::sqlite3_open`().
#[inline]
pub unsafe fn from_handle_owned(db: *mut ffi::sqlite3) -> Result<Connection> {
pub unsafe fn from_handle_owned(db: *mut ffi::sqlite3) -> Result<Self> {
let db = InnerConnection::new(db, true);
Ok(Connection {
Ok(Self {
db: RefCell::new(db),
cache: StatementCache::with_capacity(STATEMENT_CACHE_DEFAULT_CAPACITY),
transaction_behavior: TransactionBehavior::Deferred,
@ -1121,7 +1121,7 @@ pub struct Batch<'conn, 'sql> {
impl<'conn, 'sql> Batch<'conn, 'sql> {
/// Constructor
pub fn new(conn: &'conn Connection, sql: &'sql str) -> Batch<'conn, 'sql> {
pub fn new(conn: &'conn Connection, sql: &'sql str) -> Self {
Batch { conn, sql, tail: 0 }
}
@ -1230,13 +1230,13 @@ bitflags::bitflags! {
impl Default for OpenFlags {
#[inline]
fn default() -> OpenFlags {
fn default() -> Self {
// Note: update the `Connection::open` and top-level `OpenFlags` docs if
// you change these.
OpenFlags::SQLITE_OPEN_READ_WRITE
| OpenFlags::SQLITE_OPEN_CREATE
| OpenFlags::SQLITE_OPEN_NO_MUTEX
| OpenFlags::SQLITE_OPEN_URI
Self::SQLITE_OPEN_READ_WRITE
| Self::SQLITE_OPEN_CREATE
| Self::SQLITE_OPEN_NO_MUTEX
| Self::SQLITE_OPEN_URI
}
}
@ -1391,7 +1391,7 @@ mod test {
assert_eq!(Some(""), db.path());
let path = tmp.path().join("file.db");
let db = Connection::open(path)?;
assert!(db.path().map(|p| p.ends_with("file.db")).unwrap_or(false));
assert!(db.path().is_some_and(|p| p.ends_with("file.db")));
Ok(())
}
@ -1951,8 +1951,8 @@ mod test {
impl fmt::Display for CustomError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match *self {
CustomError::SomeError => write!(f, "my custom error"),
CustomError::Sqlite(ref se) => write!(f, "my custom error: {se}"),
Self::SomeError => write!(f, "my custom error"),
Self::Sqlite(ref se) => write!(f, "my custom error: {se}"),
}
}
}
@ -1964,15 +1964,15 @@ mod test {
fn cause(&self) -> Option<&dyn StdError> {
match *self {
CustomError::SomeError => None,
CustomError::Sqlite(ref se) => Some(se),
Self::SomeError => None,
Self::Sqlite(ref se) => Some(se),
}
}
}
impl From<Error> for CustomError {
fn from(se: Error) -> CustomError {
CustomError::Sqlite(se)
fn from(se: Error) -> Self {
Self::Sqlite(se)
}
}

View File

@ -12,8 +12,8 @@ pub struct Sql {
}
impl Sql {
pub fn new() -> Sql {
Sql { buf: String::new() }
pub fn new() -> Self {
Self { buf: String::new() }
}
pub fn push_pragma(

View File

@ -29,8 +29,8 @@ pub struct RawStatement {
impl RawStatement {
#[inline]
pub unsafe fn new(stmt: *mut ffi::sqlite3_stmt, tail: usize) -> RawStatement {
RawStatement {
pub unsafe fn new(stmt: *mut ffi::sqlite3_stmt, tail: usize) -> Self {
Self {
ptr: stmt,
tail,
cache: ParamIndexCache::default(),

View File

@ -90,7 +90,7 @@ impl<'stmt> Rows<'stmt> {
impl<'stmt> Rows<'stmt> {
#[inline]
pub(crate) fn new(stmt: &'stmt Statement<'stmt>) -> Rows<'stmt> {
pub(crate) fn new(stmt: &'stmt Statement<'stmt>) -> Self {
Rows {
stmt: Some(stmt),
row: None,
@ -631,7 +631,7 @@ mod tests {
)?;
let mut rows = stmt.query([])?;
let row = rows.next()?.unwrap();
let s = format!("{:?}", row);
let s = format!("{row:?}");
assert_eq!(
s,
r#"{"name": (Text, "Lisa"), "id": (Integer, 1), "pi": (Real, 3.14), "blob": (Blob, 6), "void": (Null, ())}"#

View File

@ -876,23 +876,23 @@ impl Statement<'_> {
#[derive(Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum StatementStatus {
/// Equivalent to SQLITE_STMTSTATUS_FULLSCAN_STEP
/// Equivalent to `SQLITE_STMTSTATUS_FULLSCAN_STEP`
FullscanStep = 1,
/// Equivalent to SQLITE_STMTSTATUS_SORT
/// Equivalent to `SQLITE_STMTSTATUS_SORT`
Sort = 2,
/// Equivalent to SQLITE_STMTSTATUS_AUTOINDEX
/// Equivalent to `SQLITE_STMTSTATUS_AUTOINDEX`
AutoIndex = 3,
/// Equivalent to SQLITE_STMTSTATUS_VM_STEP
/// Equivalent to `SQLITE_STMTSTATUS_VM_STEP`
VmStep = 4,
/// Equivalent to SQLITE_STMTSTATUS_REPREPARE (3.20.0)
/// Equivalent to `SQLITE_STMTSTATUS_REPREPARE` (3.20.0)
RePrepare = 5,
/// Equivalent to SQLITE_STMTSTATUS_RUN (3.20.0)
/// Equivalent to `SQLITE_STMTSTATUS_RUN` (3.20.0)
Run = 6,
/// Equivalent to SQLITE_STMTSTATUS_FILTER_MISS
/// Equivalent to `SQLITE_STMTSTATUS_FILTER_MISS`
FilterMiss = 7,
/// Equivalent to SQLITE_STMTSTATUS_FILTER_HIT
/// Equivalent to `SQLITE_STMTSTATUS_FILTER_HIT`
FilterHit = 8,
/// Equivalent to SQLITE_STMTSTATUS_MEMUSED (3.20.0)
/// Equivalent to `SQLITE_STMTSTATUS_MEMUSED` (3.20.0)
MemUsed = 99,
}

View File

@ -377,11 +377,11 @@ impl Drop for Savepoint<'_> {
#[cfg(feature = "modern_sqlite")] // 3.37.0
#[cfg_attr(docsrs, doc(cfg(feature = "modern_sqlite")))]
pub enum TransactionState {
/// Equivalent to SQLITE_TXN_NONE
/// Equivalent to `SQLITE_TXN_NONE`
None,
/// Equivalent to SQLITE_TXN_READ
/// Equivalent to `SQLITE_TXN_READ`
Read,
/// Equivalent to SQLITE_TXN_WRITE
/// Equivalent to `SQLITE_TXN_WRITE`
Write,
}

View File

@ -20,7 +20,7 @@ impl FromSql for NaiveDate {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
value
.as_str()
.and_then(|s| match NaiveDate::parse_from_str(s, "%F") {
.and_then(|s| match Self::parse_from_str(s, "%F") {
Ok(dt) => Ok(dt),
Err(err) => Err(FromSqlError::Other(Box::new(err))),
})
@ -45,7 +45,7 @@ impl FromSql for NaiveTime {
8 => "%T",
_ => "%T%.f",
};
match NaiveTime::parse_from_str(s, fmt) {
match Self::parse_from_str(s, fmt) {
Ok(dt) => Ok(dt),
Err(err) => Err(FromSqlError::Other(Box::new(err))),
}
@ -75,7 +75,7 @@ impl FromSql for NaiveDateTime {
"%F %T%.f"
};
match NaiveDateTime::parse_from_str(s, fmt) {
match Self::parse_from_str(s, fmt) {
Ok(dt) => Ok(dt),
Err(err) => Err(FromSqlError::Other(Box::new(err))),
}

View File

@ -28,16 +28,16 @@ pub enum FromSqlError {
}
impl PartialEq for FromSqlError {
fn eq(&self, other: &FromSqlError) -> bool {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(FromSqlError::InvalidType, FromSqlError::InvalidType) => true,
(FromSqlError::OutOfRange(n1), FromSqlError::OutOfRange(n2)) => n1 == n2,
(Self::InvalidType, Self::InvalidType) => true,
(Self::OutOfRange(n1), Self::OutOfRange(n2)) => n1 == n2,
(
FromSqlError::InvalidBlobSize {
Self::InvalidBlobSize {
expected_size: es1,
blob_size: bs1,
},
FromSqlError::InvalidBlobSize {
Self::InvalidBlobSize {
expected_size: es2,
blob_size: bs2,
},
@ -50,9 +50,9 @@ impl PartialEq for FromSqlError {
impl fmt::Display for FromSqlError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
FromSqlError::InvalidType => write!(f, "Invalid type"),
FromSqlError::OutOfRange(i) => write!(f, "Value {i} out of range"),
FromSqlError::InvalidBlobSize {
Self::InvalidType => write!(f, "Invalid type"),
Self::OutOfRange(i) => write!(f, "Value {i} out of range"),
Self::InvalidBlobSize {
expected_size,
blob_size,
} => {
@ -61,14 +61,14 @@ impl fmt::Display for FromSqlError {
"Cannot read {expected_size} byte value out of {blob_size} byte blob"
)
}
FromSqlError::Other(ref err) => err.fmt(f),
Self::Other(ref err) => err.fmt(f),
}
}
}
impl Error for FromSqlError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
if let FromSqlError::Other(ref err) = self {
if let Self::Other(ref err) = self {
Some(&**err)
} else {
None
@ -144,8 +144,8 @@ impl FromSql for f32 {
#[inline]
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
match value {
ValueRef::Integer(i) => Ok(i as f32),
ValueRef::Real(f) => Ok(f as f32),
ValueRef::Integer(i) => Ok(i as Self),
ValueRef::Real(f) => Ok(f as Self),
_ => Err(FromSqlError::InvalidType),
}
}
@ -155,7 +155,7 @@ impl FromSql for f64 {
#[inline]
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
match value {
ValueRef::Integer(i) => Ok(i as f64),
ValueRef::Integer(i) => Ok(i as Self),
ValueRef::Real(f) => Ok(f),
_ => Err(FromSqlError::InvalidType),
}
@ -221,7 +221,7 @@ impl FromSql for i128 {
#[inline]
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
let bytes = <[u8; 16]>::column_result(value)?;
Ok(i128::from_be_bytes(bytes) ^ (1_i128 << 127))
Ok(Self::from_be_bytes(bytes) ^ (1_i128 << 127))
}
}
@ -231,7 +231,7 @@ impl FromSql for uuid::Uuid {
#[inline]
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
let bytes = <[u8; 16]>::column_result(value)?;
Ok(uuid::Uuid::from_u128(u128::from_be_bytes(bytes)))
Ok(Self::from_u128(u128::from_be_bytes(bytes)))
}
}

View File

@ -19,7 +19,7 @@ impl ToSql for Date {
impl FromSql for Date {
#[inline]
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
value.as_str().and_then(|s| match Date::from_str(s) {
value.as_str().and_then(|s| match Self::from_str(s) {
Ok(d) => Ok(d),
Err(err) => Err(FromSqlError::Other(Box::new(err))),
})
@ -37,7 +37,7 @@ impl ToSql for Time {
/// "HH:MM:SS.SSS" => time.
impl FromSql for Time {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
value.as_str().and_then(|s| match Time::from_str(s) {
value.as_str().and_then(|s| match Self::from_str(s) {
Ok(t) => Ok(t),
Err(err) => Err(FromSqlError::Other(Box::new(err))),
})
@ -56,7 +56,7 @@ impl ToSql for DateTime {
/// "YYYY-MM-DDTHH:MM:SS.SSS" => Gregorian datetime.
impl FromSql for DateTime {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
value.as_str().and_then(|s| match DateTime::from_str(s) {
value.as_str().and_then(|s| match Self::from_str(s) {
Ok(dt) => Ok(dt),
Err(err) => Err(FromSqlError::Other(Box::new(err))),
})

View File

@ -131,11 +131,11 @@ pub enum Type {
impl fmt::Display for Type {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Type::Null => f.pad("Null"),
Type::Integer => f.pad("Integer"),
Type::Real => f.pad("Real"),
Type::Text => f.pad("Text"),
Type::Blob => f.pad("Blob"),
Self::Null => f.pad("Null"),
Self::Integer => f.pad("Integer"),
Self::Real => f.pad("Real"),
Self::Text => f.pad("Text"),
Self::Blob => f.pad("Blob"),
}
}
}

View File

@ -18,9 +18,9 @@ impl ToSql for Value {
#[inline]
fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
match self {
Value::Null => Ok(ToSqlOutput::Borrowed(ValueRef::Null)),
Value::Number(n) if n.is_i64() => Ok(ToSqlOutput::from(n.as_i64().unwrap())),
Value::Number(n) if n.is_f64() => Ok(ToSqlOutput::from(n.as_f64().unwrap())),
Self::Null => Ok(ToSqlOutput::Borrowed(ValueRef::Null)),
Self::Number(n) if n.is_i64() => Ok(ToSqlOutput::from(n.as_i64().unwrap())),
Self::Number(n) if n.is_f64() => Ok(ToSqlOutput::from(n.as_f64().unwrap())),
_ => serde_json::to_string(self)
.map(ToSqlOutput::from)
.map_err(|err| Error::ToSqlConversionFailure(err.into())),
@ -47,14 +47,14 @@ impl FromSql for Value {
match value {
ValueRef::Text(s) => serde_json::from_slice(s), // KO for b"text"
ValueRef::Blob(b) => serde_json::from_slice(b),
ValueRef::Integer(i) => Ok(Value::Number(Number::from(i))),
ValueRef::Integer(i) => Ok(Self::Number(Number::from(i))),
ValueRef::Real(f) => {
match Number::from_f64(f) {
Some(n) => Ok(Value::Number(n)),
Some(n) => Ok(Self::Number(n)),
_ => return Err(FromSqlError::InvalidType), // FIXME
}
}
ValueRef::Null => Ok(Value::Null),
ValueRef::Null => Ok(Self::Null),
}
.map_err(|err| FromSqlError::Other(Box::new(err)))
}

View File

@ -51,7 +51,7 @@ const LEGACY_DATE_TIME_FORMAT: &[FormatItem<'_>] = format_description!(
"[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")
/// `OffsetDatetime` => RFC3339 format ("YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM")
impl ToSql for OffsetDateTime {
#[inline]
fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
@ -69,12 +69,12 @@ impl FromSql for OffsetDateTime {
value.as_str().and_then(|s| {
if let Some(b' ') = s.as_bytes().get(23) {
// legacy
return OffsetDateTime::parse(s, &LEGACY_DATE_TIME_FORMAT)
return Self::parse(s, &LEGACY_DATE_TIME_FORMAT)
.map_err(|err| FromSqlError::Other(Box::new(err)));
}
if s[8..].contains('+') || s[8..].contains('-') {
// Formats 2-7 with timezone
return OffsetDateTime::parse(s, &OFFSET_DATE_TIME_FORMAT)
return Self::parse(s, &OFFSET_DATE_TIME_FORMAT)
.map_err(|err| FromSqlError::Other(Box::new(err)));
}
// Formats 2-7 without timezone
@ -101,7 +101,7 @@ 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()))
Self::parse(s, &DATE_FORMAT).map_err(|err| FromSqlError::Other(err.into()))
})
}
}
@ -122,7 +122,7 @@ 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()))
Self::parse(s, &TIME_FORMAT).map_err(|err| FromSqlError::Other(err.into()))
})
}
}
@ -149,7 +149,7 @@ 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)
Self::parse(s, &PRIMITIVE_DATE_TIME_FORMAT)
.map_err(|err| FromSqlError::Other(err.into()))
})
}

View File

@ -18,7 +18,7 @@ impl FromSql for Url {
match value {
ValueRef::Text(s) => {
let s = std::str::from_utf8(s).map_err(|e| FromSqlError::Other(Box::new(e)))?;
Url::parse(s).map_err(|e| FromSqlError::Other(Box::new(e)))
Self::parse(s).map_err(|e| FromSqlError::Other(Box::new(e)))
}
_ => Err(FromSqlError::InvalidType),
}

View File

@ -21,22 +21,22 @@ pub enum Value {
impl From<Null> for Value {
#[inline]
fn from(_: Null) -> Value {
Value::Null
fn from(_: Null) -> Self {
Self::Null
}
}
impl From<bool> for Value {
#[inline]
fn from(i: bool) -> Value {
Value::Integer(i as i64)
fn from(i: bool) -> Self {
Self::Integer(i as i64)
}
}
impl From<isize> for Value {
#[inline]
fn from(i: isize) -> Value {
Value::Integer(i as i64)
fn from(i: isize) -> Self {
Self::Integer(i as i64)
}
}
@ -44,10 +44,10 @@ impl From<isize> for Value {
#[cfg_attr(docsrs, doc(cfg(feature = "i128_blob")))]
impl From<i128> for Value {
#[inline]
fn from(i: i128) -> Value {
fn from(i: i128) -> Self {
// We store these biased (e.g. with the most significant bit flipped)
// so that comparisons with negative numbers work properly.
Value::Blob(i128::to_be_bytes(i ^ (1_i128 << 127)).to_vec())
Self::Blob(i128::to_be_bytes(i ^ (1_i128 << 127)).to_vec())
}
}
@ -55,8 +55,8 @@ impl From<i128> for Value {
#[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
impl From<uuid::Uuid> for Value {
#[inline]
fn from(id: uuid::Uuid) -> Value {
Value::Blob(id.as_bytes().to_vec())
fn from(id: uuid::Uuid) -> Self {
Self::Blob(id.as_bytes().to_vec())
}
}
@ -80,48 +80,48 @@ from_i64!(u32);
impl From<i64> for Value {
#[inline]
fn from(i: i64) -> Value {
Value::Integer(i)
fn from(i: i64) -> Self {
Self::Integer(i)
}
}
impl From<f32> for Value {
#[inline]
fn from(f: f32) -> Value {
Value::Real(f.into())
fn from(f: f32) -> Self {
Self::Real(f.into())
}
}
impl From<f64> for Value {
#[inline]
fn from(f: f64) -> Value {
Value::Real(f)
fn from(f: f64) -> Self {
Self::Real(f)
}
}
impl From<String> for Value {
#[inline]
fn from(s: String) -> Value {
Value::Text(s)
fn from(s: String) -> Self {
Self::Text(s)
}
}
impl From<Vec<u8>> for Value {
#[inline]
fn from(v: Vec<u8>) -> Value {
Value::Blob(v)
fn from(v: Vec<u8>) -> Self {
Self::Blob(v)
}
}
impl<T> From<Option<T>> for Value
where
T: Into<Value>,
T: Into<Self>,
{
#[inline]
fn from(v: Option<T>) -> Value {
fn from(v: Option<T>) -> Self {
match v {
Some(x) => x.into(),
None => Value::Null,
None => Self::Null,
}
}
}
@ -132,11 +132,11 @@ impl Value {
#[must_use]
pub fn data_type(&self) -> Type {
match *self {
Value::Null => Type::Null,
Value::Integer(_) => Type::Integer,
Value::Real(_) => Type::Real,
Value::Text(_) => Type::Text,
Value::Blob(_) => Type::Blob,
Self::Null => Type::Null,
Self::Integer(_) => Type::Integer,
Self::Real(_) => Type::Real,
Self::Text(_) => Type::Text,
Self::Blob(_) => Type::Blob,
}
}
}
@ -158,7 +158,7 @@ mod test {
assert_eq!(Value::Null.data_type(), Type::Null);
assert_eq!(Value::Integer(0).data_type(), Type::Integer);
assert_eq!(Value::Real(0.).data_type(), Type::Real);
assert_eq!(Value::Text("".to_owned()).data_type(), Type::Text);
assert_eq!(Value::Text(String::new()).data_type(), Type::Text);
assert_eq!(Value::Blob(vec![]).data_type(), Type::Blob);
}
}

View File

@ -153,16 +153,16 @@ impl<'a> ValueRef<'a> {
impl From<ValueRef<'_>> for Value {
#[inline]
#[track_caller]
fn from(borrowed: ValueRef<'_>) -> Value {
fn from(borrowed: ValueRef<'_>) -> Self {
match borrowed {
ValueRef::Null => Value::Null,
ValueRef::Integer(i) => Value::Integer(i),
ValueRef::Real(r) => Value::Real(r),
ValueRef::Null => Self::Null,
ValueRef::Integer(i) => Self::Integer(i),
ValueRef::Real(r) => Self::Real(r),
ValueRef::Text(s) => {
let s = std::str::from_utf8(s).expect("invalid UTF-8");
Value::Text(s.to_string())
Self::Text(s.to_string())
}
ValueRef::Blob(b) => Value::Blob(b.to_vec()),
ValueRef::Blob(b) => Self::Blob(b.to_vec()),
}
}
}
@ -183,7 +183,7 @@ impl<'a> From<&'a [u8]> for ValueRef<'a> {
impl<'a> From<&'a Value> for ValueRef<'a> {
#[inline]
fn from(value: &'a Value) -> ValueRef<'a> {
fn from(value: &'a Value) -> Self {
match *value {
Value::Null => ValueRef::Null,
Value::Integer(i) => ValueRef::Integer(i),
@ -196,10 +196,10 @@ impl<'a> From<&'a Value> for ValueRef<'a> {
impl<'a, T> From<Option<T>> for ValueRef<'a>
where
T: Into<ValueRef<'a>>,
T: Into<Self>,
{
#[inline]
fn from(s: Option<T>) -> ValueRef<'a> {
fn from(s: Option<T>) -> Self {
match s {
Some(x) => x.into(),
None => ValueRef::Null,
@ -214,7 +214,7 @@ where
feature = "preupdate_hook"
))]
impl<'a> ValueRef<'a> {
pub(crate) unsafe fn from_value(value: *mut crate::ffi::sqlite3_value) -> ValueRef<'a> {
pub(crate) unsafe fn from_value(value: *mut crate::ffi::sqlite3_value) -> Self {
use crate::ffi;
use std::slice::from_raw_parts;

View File

@ -14,8 +14,8 @@ struct UnlockNotification {
#[allow(clippy::mutex_atomic)]
impl UnlockNotification {
fn new() -> UnlockNotification {
UnlockNotification {
fn new() -> Self {
Self {
cond: Condvar::new(),
mutex: Mutex::new(false),
}

View File

@ -81,8 +81,8 @@ unsafe impl<'vtab> VTab<'vtab> for ArrayTab {
_: &mut VTabConnection,
_aux: Option<&()>,
_args: &[&[u8]],
) -> Result<(String, ArrayTab)> {
let vtab = ArrayTab {
) -> Result<(String, Self)> {
let vtab = Self {
base: ffi::sqlite3_vtab::default(),
};
Ok(("CREATE TABLE x(value,pointer hidden)".to_owned(), vtab))

View File

@ -91,14 +91,14 @@ unsafe impl<'vtab> VTab<'vtab> for CsvTab {
db: &mut VTabConnection,
_aux: Option<&()>,
args: &[&[u8]],
) -> Result<(String, CsvTab)> {
) -> Result<(String, Self)> {
if args.len() < 4 {
return Err(Error::ModuleError("no CSV file specified".to_owned()));
}
let mut vtab = CsvTab {
let mut vtab = Self {
base: ffi::sqlite3_vtab::default(),
filename: "".to_owned(),
filename: String::new(),
has_headers: false,
delimiter: b',',
quote: b'"',
@ -148,7 +148,7 @@ unsafe impl<'vtab> VTab<'vtab> for CsvTab {
}
}
"delimiter" => {
if let Some(b) = CsvTab::parse_byte(value) {
if let Some(b) = Self::parse_byte(value) {
vtab.delimiter = b;
} else {
return Err(Error::ModuleError(format!(
@ -157,7 +157,7 @@ unsafe impl<'vtab> VTab<'vtab> for CsvTab {
}
}
"quote" => {
if let Some(b) = CsvTab::parse_byte(value) {
if let Some(b) = Self::parse_byte(value) {
if b == b'0' {
vtab.quote = 0;
} else {
@ -335,8 +335,8 @@ unsafe impl VTabCursor for CsvTabCursor<'_> {
impl From<csv::Error> for Error {
#[cold]
fn from(err: csv::Error) -> Error {
Error::ModuleError(err.to_string())
fn from(err: csv::Error) -> Self {
Self::ModuleError(err.to_string())
}
}

View File

@ -189,13 +189,13 @@ pub fn eponymous_only_module<'vtab, T: VTab<'vtab>>() -> &'static Module<'vtab,
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum VTabConfig {
/// Equivalent to SQLITE_VTAB_CONSTRAINT_SUPPORT
/// Equivalent to `SQLITE_VTAB_CONSTRAINT_SUPPORT`
ConstraintSupport = 1,
/// Equivalent to SQLITE_VTAB_INNOCUOUS
/// Equivalent to `SQLITE_VTAB_INNOCUOUS`
Innocuous = 2,
/// Equivalent to SQLITE_VTAB_DIRECTONLY
/// Equivalent to `SQLITE_VTAB_DIRECTONLY`
DirectOnly = 3,
/// Equivalent to SQLITE_VTAB_USES_ALL_SCHEMAS
/// Equivalent to `SQLITE_VTAB_USES_ALL_SCHEMAS`
UsesAllSchemas = 4,
}
@ -345,25 +345,25 @@ pub enum IndexConstraintOp {
}
impl From<u8> for IndexConstraintOp {
fn from(code: u8) -> IndexConstraintOp {
fn from(code: u8) -> Self {
match code {
2 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_EQ,
4 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_GT,
8 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_LE,
16 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_LT,
32 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_GE,
64 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_MATCH,
65 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_LIKE,
66 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_GLOB,
67 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_REGEXP,
68 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_NE,
69 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_ISNOT,
70 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_ISNOTNULL,
71 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_ISNULL,
72 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_IS,
73 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_LIMIT,
74 => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_OFFSET,
v => IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_FUNCTION(v),
2 => Self::SQLITE_INDEX_CONSTRAINT_EQ,
4 => Self::SQLITE_INDEX_CONSTRAINT_GT,
8 => Self::SQLITE_INDEX_CONSTRAINT_LE,
16 => Self::SQLITE_INDEX_CONSTRAINT_LT,
32 => Self::SQLITE_INDEX_CONSTRAINT_GE,
64 => Self::SQLITE_INDEX_CONSTRAINT_MATCH,
65 => Self::SQLITE_INDEX_CONSTRAINT_LIKE,
66 => Self::SQLITE_INDEX_CONSTRAINT_GLOB,
67 => Self::SQLITE_INDEX_CONSTRAINT_REGEXP,
68 => Self::SQLITE_INDEX_CONSTRAINT_NE,
69 => Self::SQLITE_INDEX_CONSTRAINT_ISNOT,
70 => Self::SQLITE_INDEX_CONSTRAINT_ISNOTNULL,
71 => Self::SQLITE_INDEX_CONSTRAINT_ISNULL,
72 => Self::SQLITE_INDEX_CONSTRAINT_IS,
73 => Self::SQLITE_INDEX_CONSTRAINT_LIMIT,
74 => Self::SQLITE_INDEX_CONSTRAINT_OFFSET,
v => Self::SQLITE_INDEX_CONSTRAINT_FUNCTION(v),
}
}
}
@ -480,7 +480,7 @@ impl IndexInfo {
}
}
/// Mask of SQLITE_INDEX_SCAN_* flags.
/// Mask of `SQLITE_INDEX_SCAN_*` flags.
#[inline]
pub fn set_idx_flags(&mut self, flags: IndexFlags) {
unsafe { (*self.0).idxFlags = flags.bits() };

View File

@ -14,7 +14,7 @@ use crate::vtab::{
};
use crate::{Connection, Error, Result};
/// Register the "generate_series" module.
/// Register the `generate_series` module.
pub fn load_module(conn: &Connection) -> Result<()> {
let aux: Option<()> = None;
conn.create_module("generate_series", eponymous_only_module::<SeriesTab>(), aux)
@ -60,8 +60,8 @@ unsafe impl<'vtab> VTab<'vtab> for SeriesTab {
db: &mut VTabConnection,
_aux: Option<&()>,
_args: &[&[u8]],
) -> Result<(String, SeriesTab)> {
let vtab = SeriesTab {
) -> Result<(String, Self)> {
let vtab = Self {
base: ffi::sqlite3_vtab::default(),
};
db.config(VTabConfig::Innocuous)?;

View File

@ -36,7 +36,7 @@ impl VTabLog {
_: Option<&()>,
args: &[&[u8]],
is_create: bool,
) -> Result<(String, VTabLog)> {
) -> Result<(String, Self)> {
static N_INST: AtomicUsize = AtomicUsize::new(1);
let i_inst = N_INST.fetch_add(1, Ordering::SeqCst);
println!(
@ -80,7 +80,7 @@ impl VTabLog {
if schema.is_none() {
return Err(Error::ModuleError("no schema defined".to_owned()));
}
let vtab = VTabLog {
let vtab = Self {
base: ffi::sqlite3_vtab::default(),
n_row: n_row.unwrap_or(10),
i_inst,
@ -105,7 +105,7 @@ unsafe impl<'vtab> VTab<'vtab> for VTabLog {
aux: Option<&Self::Aux>,
args: &[&[u8]],
) -> Result<(String, Self)> {
VTabLog::connect_create(db, aux, args, false)
Self::connect_create(db, aux, args, false)
}
fn best_index(&self, info: &mut IndexInfo) -> Result<()> {
@ -138,7 +138,7 @@ impl<'vtab> CreateVTab<'vtab> for VTabLog {
aux: Option<&Self::Aux>,
args: &[&[u8]],
) -> Result<(String, Self)> {
VTabLog::connect_create(db, aux, args, true)
Self::connect_create(db, aux, args, true)
}
fn destroy(&self) -> Result<()> {

View File

@ -27,8 +27,8 @@ fn test_dummy_module() -> rusqlite::Result<()> {
_: &mut VTabConnection,
_aux: Option<&()>,
_args: &[&[u8]],
) -> Result<(String, DummyTab)> {
let vtab = DummyTab {
) -> Result<(String, Self)> {
let vtab = Self {
base: sqlite3_vtab::default(),
};
Ok(("CREATE TABLE x(value)".to_owned(), vtab))