diff --git a/sqlx-core/src/any/arguments.rs b/sqlx-core/src/any/arguments.rs index 2c05e3fd5b..28dadaa757 100644 --- a/sqlx-core/src/any/arguments.rs +++ b/sqlx-core/src/any/arguments.rs @@ -4,13 +4,15 @@ use crate::arguments::Arguments; use crate::encode::{Encode, IsNull}; use crate::error::BoxDynError; use crate::types::Type; +use std::sync::Arc; -pub struct AnyArguments<'q> { +#[derive(Default)] +pub struct AnyArguments { #[doc(hidden)] - pub values: AnyArgumentBuffer<'q>, + pub values: AnyArgumentBuffer, } -impl<'q> Arguments<'q> for AnyArguments<'q> { +impl<'q> Arguments<'q> for AnyArguments { type Database = Any; fn reserve(&mut self, additional: usize, _size: usize) { @@ -30,21 +32,13 @@ impl<'q> Arguments<'q> for AnyArguments<'q> { } } -pub struct AnyArgumentBuffer<'q>(#[doc(hidden)] pub Vec>); +#[derive(Default)] +pub struct AnyArgumentBuffer(#[doc(hidden)] pub Vec); -impl Default for AnyArguments<'_> { - fn default() -> Self { - AnyArguments { - values: AnyArgumentBuffer(vec![]), - } - } -} - -impl<'q> AnyArguments<'q> { +impl AnyArguments { #[doc(hidden)] - pub fn convert_to<'a, A: Arguments<'a>>(&'a self) -> Result + pub fn convert_into<'a, A: Arguments<'a>>(self) -> Result where - 'q: 'a, Option: Type + Encode<'a, A::Database>, Option: Type + Encode<'a, A::Database>, Option: Type + Encode<'a, A::Database>, @@ -60,12 +54,13 @@ impl<'q> AnyArguments<'q> { i64: Type + Encode<'a, A::Database>, f32: Type + Encode<'a, A::Database>, f64: Type + Encode<'a, A::Database>, - &'a str: Type + Encode<'a, A::Database>, - &'a [u8]: Type + Encode<'a, A::Database>, + Arc: Type + Encode<'a, A::Database>, + Arc: Type + Encode<'a, A::Database>, + Arc>: Type + Encode<'a, A::Database>, { let mut out = A::default(); - for arg in &self.values.0 { + for arg in self.values.0 { match arg { AnyValueKind::Null(AnyTypeInfoKind::Null) => out.add(Option::::None), AnyValueKind::Null(AnyTypeInfoKind::Bool) => out.add(Option::::None), @@ -82,8 +77,9 @@ impl<'q> AnyArguments<'q> { AnyValueKind::BigInt(i) => out.add(i), AnyValueKind::Real(r) => out.add(r), AnyValueKind::Double(d) => out.add(d), - AnyValueKind::Text(t) => out.add(&**t), - AnyValueKind::Blob(b) => out.add(&**b), + AnyValueKind::Text(t) => out.add(t), + AnyValueKind::TextSlice(t) => out.add(t), + AnyValueKind::Blob(b) => out.add(b), }? } Ok(out) diff --git a/sqlx-core/src/any/connection/backend.rs b/sqlx-core/src/any/connection/backend.rs index e59b345ed9..5b3ea7bf2d 100644 --- a/sqlx-core/src/any/connection/backend.rs +++ b/sqlx-core/src/any/connection/backend.rs @@ -94,19 +94,19 @@ pub trait AnyConnectionBackend: std::any::Any + Debug + Send + 'static { )) } - fn fetch_many<'q>( - &'q mut self, + fn fetch_many( + &mut self, query: SqlStr, persistent: bool, - arguments: Option>, - ) -> BoxStream<'q, crate::Result>>; + arguments: Option, + ) -> BoxStream<'_, crate::Result>>; - fn fetch_optional<'q>( - &'q mut self, + fn fetch_optional( + &mut self, query: SqlStr, persistent: bool, - arguments: Option>, - ) -> BoxFuture<'q, crate::Result>>; + arguments: Option, + ) -> BoxFuture<'_, crate::Result>>; fn prepare_with<'c, 'q: 'c>( &'c mut self, diff --git a/sqlx-core/src/any/database.rs b/sqlx-core/src/any/database.rs index 6e8343e928..6e7a5f5ea8 100644 --- a/sqlx-core/src/any/database.rs +++ b/sqlx-core/src/any/database.rs @@ -25,8 +25,8 @@ impl Database for Any { type Value = AnyValue; type ValueRef<'r> = AnyValueRef<'r>; - type Arguments<'q> = AnyArguments<'q>; - type ArgumentBuffer<'q> = AnyArgumentBuffer<'q>; + type Arguments<'q> = AnyArguments; + type ArgumentBuffer<'q> = AnyArgumentBuffer; type Statement = AnyStatement; diff --git a/sqlx-core/src/any/mod.rs b/sqlx-core/src/any/mod.rs index 032f4dda03..9d37bbf5ab 100644 --- a/sqlx-core/src/any/mod.rs +++ b/sqlx-core/src/any/mod.rs @@ -56,7 +56,7 @@ pub trait AnyExecutor<'c>: Executor<'c, Database = Any> {} impl<'c, T: Executor<'c, Database = Any>> AnyExecutor<'c> for T {} // NOTE: required due to the lack of lazy normalization -impl_into_arguments_for_arguments!(AnyArguments<'q>); +impl_into_arguments_for_arguments!(AnyArguments); // impl_executor_for_pool_connection!(Any, AnyConnection, AnyRow); // impl_executor_for_transaction!(Any, AnyRow); impl_acquire!(Any, AnyConnection); @@ -71,7 +71,7 @@ where { fn encode_by_ref( &self, - buf: &mut AnyArgumentBuffer<'q>, + buf: &mut AnyArgumentBuffer, ) -> Result { if let Some(value) = self { value.encode_by_ref(buf) diff --git a/sqlx-core/src/any/statement.rs b/sqlx-core/src/any/statement.rs index 98b28c2c32..42c7255736 100644 --- a/sqlx-core/src/any/statement.rs +++ b/sqlx-core/src/any/statement.rs @@ -44,7 +44,7 @@ impl Statement for AnyStatement { &self.columns } - impl_statement_query!(AnyArguments<'_>); + impl_statement_query!(AnyArguments); } impl ColumnIndex for &'_ str { diff --git a/sqlx-core/src/any/types/blob.rs b/sqlx-core/src/any/types/blob.rs index 851c93bf5a..21379a6429 100644 --- a/sqlx-core/src/any/types/blob.rs +++ b/sqlx-core/src/any/types/blob.rs @@ -4,7 +4,7 @@ use crate::decode::Decode; use crate::encode::{Encode, IsNull}; use crate::error::BoxDynError; use crate::types::Type; -use std::borrow::Cow; +use std::sync::Arc; impl Type for [u8] { fn type_info() -> AnyTypeInfo { @@ -19,7 +19,7 @@ impl<'q> Encode<'q, Any> for &'q [u8] { &self, buf: &mut ::ArgumentBuffer<'q>, ) -> Result { - buf.0.push(AnyValueKind::Blob((*self).into())); + buf.0.push(AnyValueKind::Blob(Arc::new(self.to_vec()))); Ok(IsNull::No) } } @@ -27,12 +27,7 @@ impl<'q> Encode<'q, Any> for &'q [u8] { impl<'r> Decode<'r, Any> for &'r [u8] { fn decode(value: ::ValueRef<'r>) -> Result { match value.kind { - AnyValueKind::Blob(Cow::Borrowed(blob)) => Ok(blob), - // This shouldn't happen in practice, it means the user got an `AnyValueRef` - // constructed from an owned `Vec` which shouldn't be allowed by the API. - AnyValueKind::Blob(Cow::Owned(_text)) => { - panic!("attempting to return a borrow that outlives its buffer") - } + AnyValueKind::Blob(blob) => Ok(blob.as_slice()), other => other.unexpected(), } } @@ -49,7 +44,7 @@ impl<'q> Encode<'q, Any> for Vec { &self, buf: &mut ::ArgumentBuffer<'q>, ) -> Result { - buf.0.push(AnyValueKind::Blob(Cow::Owned(self.clone()))); + buf.0.push(AnyValueKind::Blob(Arc::new(self.clone()))); Ok(IsNull::No) } } @@ -57,7 +52,7 @@ impl<'q> Encode<'q, Any> for Vec { impl<'r> Decode<'r, Any> for Vec { fn decode(value: ::ValueRef<'r>) -> Result { match value.kind { - AnyValueKind::Blob(blob) => Ok(blob.into_owned()), + AnyValueKind::Blob(blob) => Ok(blob.as_ref().clone()), other => other.unexpected(), } } diff --git a/sqlx-core/src/any/types/bool.rs b/sqlx-core/src/any/types/bool.rs index fb7ee9d5dd..ff915c5bfd 100644 --- a/sqlx-core/src/any/types/bool.rs +++ b/sqlx-core/src/any/types/bool.rs @@ -26,7 +26,7 @@ impl<'q> Encode<'q, Any> for bool { impl<'r> Decode<'r, Any> for bool { fn decode(value: ::ValueRef<'r>) -> Result { match value.kind { - AnyValueKind::Bool(b) => Ok(b), + AnyValueKind::Bool(b) => Ok(*b), other => other.unexpected(), } } diff --git a/sqlx-core/src/any/types/float.rs b/sqlx-core/src/any/types/float.rs index 01d6073a2f..36ee38a05f 100644 --- a/sqlx-core/src/any/types/float.rs +++ b/sqlx-core/src/any/types/float.rs @@ -13,8 +13,8 @@ impl Type for f32 { } } -impl<'q> Encode<'q, Any> for f32 { - fn encode_by_ref(&self, buf: &mut AnyArgumentBuffer<'q>) -> Result { +impl Encode<'_, Any> for f32 { + fn encode_by_ref(&self, buf: &mut AnyArgumentBuffer) -> Result { buf.0.push(AnyValueKind::Real(*self)); Ok(IsNull::No) } @@ -23,7 +23,7 @@ impl<'q> Encode<'q, Any> for f32 { impl<'r> Decode<'r, Any> for f32 { fn decode(value: AnyValueRef<'r>) -> Result { match value.kind { - AnyValueKind::Real(r) => Ok(r), + AnyValueKind::Real(r) => Ok(*r), other => other.unexpected(), } } @@ -51,8 +51,8 @@ impl<'r> Decode<'r, Any> for f64 { fn decode(value: ::ValueRef<'r>) -> Result { match value.kind { // Widening is safe - AnyValueKind::Real(r) => Ok(r as f64), - AnyValueKind::Double(d) => Ok(d), + AnyValueKind::Real(r) => Ok(*r as f64), + AnyValueKind::Double(d) => Ok(*d), other => other.unexpected(), } } diff --git a/sqlx-core/src/any/types/str.rs b/sqlx-core/src/any/types/str.rs index 4c00832690..3faf6a1708 100644 --- a/sqlx-core/src/any/types/str.rs +++ b/sqlx-core/src/any/types/str.rs @@ -5,7 +5,7 @@ use crate::decode::Decode; use crate::encode::{Encode, IsNull}; use crate::error::BoxDynError; use crate::types::Type; -use std::borrow::Cow; +use std::sync::Arc; impl Type for str { fn type_info() -> AnyTypeInfo { @@ -20,7 +20,7 @@ impl<'a> Encode<'a, Any> for &'a str { where Self: Sized, { - buf.0.push(AnyValueKind::Text(self.into())); + buf.0.push(AnyValueKind::Text(Arc::new(self.into()))); Ok(IsNull::No) } @@ -35,12 +35,7 @@ impl<'a> Encode<'a, Any> for &'a str { impl<'a> Decode<'a, Any> for &'a str { fn decode(value: ::ValueRef<'a>) -> Result { match value.kind { - AnyValueKind::Text(Cow::Borrowed(text)) => Ok(text), - // This shouldn't happen in practice, it means the user got an `AnyValueRef` - // constructed from an owned `String` which shouldn't be allowed by the API. - AnyValueKind::Text(Cow::Owned(_text)) => { - panic!("attempting to return a borrow that outlives its buffer") - } + AnyValueKind::Text(text) => Ok(text.as_str()), other => other.unexpected(), } } @@ -53,11 +48,19 @@ impl Type for String { } impl<'q> Encode<'q, Any> for String { + fn encode( + self, + buf: &mut ::ArgumentBuffer<'q>, + ) -> Result { + buf.0.push(AnyValueKind::Text(Arc::new(self))); + Ok(IsNull::No) + } + fn encode_by_ref( &self, buf: &mut ::ArgumentBuffer<'q>, ) -> Result { - buf.0.push(AnyValueKind::Text(Cow::Owned(self.clone()))); + buf.0.push(AnyValueKind::Text(Arc::new(self.clone()))); Ok(IsNull::No) } } @@ -65,7 +68,7 @@ impl<'q> Encode<'q, Any> for String { impl<'r> Decode<'r, Any> for String { fn decode(value: ::ValueRef<'r>) -> Result { match value.kind { - AnyValueKind::Text(text) => Ok(text.into_owned()), + AnyValueKind::Text(text) => Ok(text.to_string()), other => other.unexpected(), } } diff --git a/sqlx-core/src/any/value.rs b/sqlx-core/src/any/value.rs index 9917b39f4f..a85c1dc69c 100644 --- a/sqlx-core/src/any/value.rs +++ b/sqlx-core/src/any/value.rs @@ -1,14 +1,14 @@ -use std::borrow::Cow; - use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind}; use crate::database::Database; use crate::error::BoxDynError; use crate::types::Type; use crate::value::{Value, ValueRef}; +use std::borrow::Cow; +use std::sync::Arc; #[derive(Clone, Debug)] #[non_exhaustive] -pub enum AnyValueKind<'a> { +pub enum AnyValueKind { Null(AnyTypeInfoKind), Bool(bool), SmallInt(i16), @@ -16,11 +16,12 @@ pub enum AnyValueKind<'a> { BigInt(i64), Real(f32), Double(f64), - Text(Cow<'a, str>), - Blob(Cow<'a, [u8]>), + Text(Arc), + TextSlice(Arc), + Blob(Arc>), } -impl AnyValueKind<'_> { +impl AnyValueKind { fn type_info(&self) -> AnyTypeInfo { AnyTypeInfo { kind: match self { @@ -32,6 +33,7 @@ impl AnyValueKind<'_> { AnyValueKind::Real(_) => AnyTypeInfoKind::Real, AnyValueKind::Double(_) => AnyTypeInfoKind::Double, AnyValueKind::Text(_) => AnyTypeInfoKind::Text, + AnyValueKind::TextSlice(_) => AnyTypeInfoKind::Text, AnyValueKind::Blob(_) => AnyTypeInfoKind::Blob, }, } @@ -60,31 +62,19 @@ impl AnyValueKind<'_> { #[derive(Clone, Debug)] pub struct AnyValue { #[doc(hidden)] - pub kind: AnyValueKind<'static>, + pub kind: AnyValueKind, } #[derive(Clone, Debug)] pub struct AnyValueRef<'a> { - pub(crate) kind: AnyValueKind<'a>, + pub(crate) kind: &'a AnyValueKind, } impl Value for AnyValue { type Database = Any; fn as_ref(&self) -> ::ValueRef<'_> { - AnyValueRef { - kind: match &self.kind { - AnyValueKind::Null(k) => AnyValueKind::Null(*k), - AnyValueKind::Bool(b) => AnyValueKind::Bool(*b), - AnyValueKind::SmallInt(i) => AnyValueKind::SmallInt(*i), - AnyValueKind::Integer(i) => AnyValueKind::Integer(*i), - AnyValueKind::BigInt(i) => AnyValueKind::BigInt(*i), - AnyValueKind::Real(r) => AnyValueKind::Real(*r), - AnyValueKind::Double(d) => AnyValueKind::Double(*d), - AnyValueKind::Text(t) => AnyValueKind::Text(Cow::Borrowed(t)), - AnyValueKind::Blob(b) => AnyValueKind::Blob(Cow::Borrowed(b)), - }, - } + AnyValueRef { kind: &self.kind } } fn type_info(&self) -> Cow<'_, ::TypeInfo> { @@ -101,17 +91,7 @@ impl<'a> ValueRef<'a> for AnyValueRef<'a> { fn to_owned(&self) -> ::Value { AnyValue { - kind: match &self.kind { - AnyValueKind::Null(k) => AnyValueKind::Null(*k), - AnyValueKind::Bool(b) => AnyValueKind::Bool(*b), - AnyValueKind::SmallInt(i) => AnyValueKind::SmallInt(*i), - AnyValueKind::Integer(i) => AnyValueKind::Integer(*i), - AnyValueKind::BigInt(i) => AnyValueKind::BigInt(*i), - AnyValueKind::Real(r) => AnyValueKind::Real(*r), - AnyValueKind::Double(d) => AnyValueKind::Double(*d), - AnyValueKind::Text(t) => AnyValueKind::Text(Cow::Owned(t.to_string())), - AnyValueKind::Blob(b) => AnyValueKind::Blob(Cow::Owned(b.to_vec())), - }, + kind: self.kind.clone(), } } diff --git a/sqlx-mysql/src/any.rs b/sqlx-mysql/src/any.rs index 028b6c55b8..241900560e 100644 --- a/sqlx-mysql/src/any.rs +++ b/sqlx-mysql/src/any.rs @@ -77,14 +77,14 @@ impl AnyConnectionBackend for MySqlConnection { Ok(self) } - fn fetch_many<'q>( - &'q mut self, + fn fetch_many( + &mut self, query: SqlStr, persistent: bool, - arguments: Option>, - ) -> BoxStream<'q, sqlx_core::Result>> { + arguments: Option, + ) -> BoxStream<'_, sqlx_core::Result>> { let persistent = persistent && arguments.is_some(); - let arguments = match arguments.as_ref().map(AnyArguments::convert_to).transpose() { + let arguments = match arguments.map(AnyArguments::convert_into).transpose() { Ok(arguments) => arguments, Err(error) => { return stream::once(future::ready(Err(sqlx_core::Error::Encode(error)))).boxed() @@ -103,16 +103,15 @@ impl AnyConnectionBackend for MySqlConnection { ) } - fn fetch_optional<'q>( - &'q mut self, + fn fetch_optional( + &mut self, query: SqlStr, persistent: bool, - arguments: Option>, - ) -> BoxFuture<'q, sqlx_core::Result>> { + arguments: Option, + ) -> BoxFuture<'_, sqlx_core::Result>> { let persistent = persistent && arguments.is_some(); let arguments = arguments - .as_ref() - .map(AnyArguments::convert_to) + .map(AnyArguments::convert_into) .transpose() .map_err(sqlx_core::Error::Encode); diff --git a/sqlx-postgres/src/any.rs b/sqlx-postgres/src/any.rs index 75ee0d73df..51eb15d2a7 100644 --- a/sqlx-postgres/src/any.rs +++ b/sqlx-postgres/src/any.rs @@ -79,14 +79,14 @@ impl AnyConnectionBackend for PgConnection { Ok(self) } - fn fetch_many<'q>( - &'q mut self, + fn fetch_many( + &mut self, query: SqlStr, persistent: bool, - arguments: Option>, - ) -> BoxStream<'q, sqlx_core::Result>> { + arguments: Option, + ) -> BoxStream>> { let persistent = persistent && arguments.is_some(); - let arguments = match arguments.as_ref().map(AnyArguments::convert_to).transpose() { + let arguments = match arguments.map(AnyArguments::convert_into).transpose() { Ok(arguments) => arguments, Err(error) => { return stream::once(future::ready(Err(sqlx_core::Error::Encode(error)))).boxed() @@ -105,16 +105,15 @@ impl AnyConnectionBackend for PgConnection { ) } - fn fetch_optional<'q>( - &'q mut self, + fn fetch_optional( + &mut self, query: SqlStr, persistent: bool, - arguments: Option>, - ) -> BoxFuture<'q, sqlx_core::Result>> { + arguments: Option, + ) -> BoxFuture>> { let persistent = persistent && arguments.is_some(); let arguments = arguments - .as_ref() - .map(AnyArguments::convert_to) + .map(AnyArguments::convert_into) .transpose() .map_err(sqlx_core::Error::Encode); diff --git a/sqlx-sqlite/src/any.rs b/sqlx-sqlite/src/any.rs index d33677c64e..83b141decd 100644 --- a/sqlx-sqlite/src/any.rs +++ b/sqlx-sqlite/src/any.rs @@ -12,6 +12,7 @@ use sqlx_core::any::{ }; use sqlx_core::sql_str::SqlStr; +use crate::arguments::SqliteArgumentsBuffer; use crate::type_info::DataType; use sqlx_core::connection::{ConnectOptions, Connection}; use sqlx_core::database::Database; @@ -19,6 +20,7 @@ use sqlx_core::describe::Describe; use sqlx_core::executor::Executor; use sqlx_core::transaction::TransactionManager; use std::pin::pin; +use std::sync::Arc; sqlx_core::declare_driver_with_optional_migrate!(DRIVER = Sqlite); @@ -78,12 +80,12 @@ impl AnyConnectionBackend for SqliteConnection { Ok(self) } - fn fetch_many<'q>( - &'q mut self, + fn fetch_many( + &mut self, query: SqlStr, persistent: bool, - arguments: Option>, - ) -> BoxStream<'q, sqlx_core::Result>> { + arguments: Option, + ) -> BoxStream<'_, sqlx_core::Result>> { let persistent = persistent && arguments.is_some(); let args = arguments.map(map_arguments); @@ -101,12 +103,12 @@ impl AnyConnectionBackend for SqliteConnection { ) } - fn fetch_optional<'q>( - &'q mut self, + fn fetch_optional( + &mut self, query: SqlStr, persistent: bool, - arguments: Option>, - ) -> BoxFuture<'q, sqlx_core::Result>> { + arguments: Option, + ) -> BoxFuture<'_, sqlx_core::Result>> { let persistent = persistent && arguments.is_some(); let args = arguments.map(map_arguments); @@ -203,27 +205,29 @@ impl<'a> TryFrom<&'a AnyConnectOptions> for SqliteConnectOptions { } } -/// Instead of `AnyArguments::convert_into()`, we can do a direct mapping and preserve the lifetime. -fn map_arguments(args: AnyArguments<'_>) -> SqliteArguments<'_> { +// Infallible alternative to AnyArguments::convert_into() +fn map_arguments(args: AnyArguments) -> SqliteArguments { + let values = args + .values + .0 + .into_iter() + .map(|val| match val { + AnyValueKind::Null(_) => SqliteArgumentValue::Null, + AnyValueKind::Bool(b) => SqliteArgumentValue::Int(b as i32), + AnyValueKind::SmallInt(i) => SqliteArgumentValue::Int(i as i32), + AnyValueKind::Integer(i) => SqliteArgumentValue::Int(i), + AnyValueKind::BigInt(i) => SqliteArgumentValue::Int64(i), + AnyValueKind::Real(r) => SqliteArgumentValue::Double(r as f64), + AnyValueKind::Double(d) => SqliteArgumentValue::Double(d), + AnyValueKind::Text(t) => SqliteArgumentValue::Text(Arc::new(t.to_string())), + AnyValueKind::Blob(b) => SqliteArgumentValue::Blob(Arc::new(b.to_vec())), + // AnyValueKind is `#[non_exhaustive]` but we should have covered everything + _ => unreachable!("BUG: missing mapping for {val:?}"), + }) + .collect(); + SqliteArguments { - values: args - .values - .0 - .into_iter() - .map(|val| match val { - AnyValueKind::Null(_) => SqliteArgumentValue::Null, - AnyValueKind::Bool(b) => SqliteArgumentValue::Int(b as i32), - AnyValueKind::SmallInt(i) => SqliteArgumentValue::Int(i as i32), - AnyValueKind::Integer(i) => SqliteArgumentValue::Int(i), - AnyValueKind::BigInt(i) => SqliteArgumentValue::Int64(i), - AnyValueKind::Real(r) => SqliteArgumentValue::Double(r as f64), - AnyValueKind::Double(d) => SqliteArgumentValue::Double(d), - AnyValueKind::Text(t) => SqliteArgumentValue::Text(t), - AnyValueKind::Blob(b) => SqliteArgumentValue::Blob(b), - // AnyValueKind is `#[non_exhaustive]` but we should have covered everything - _ => unreachable!("BUG: missing mapping for {val:?}"), - }) - .collect(), + values: SqliteArgumentsBuffer::new(values), } } diff --git a/sqlx-sqlite/src/arguments.rs b/sqlx-sqlite/src/arguments.rs index 410b4caa99..6354cbebc9 100644 --- a/sqlx-sqlite/src/arguments.rs +++ b/sqlx-sqlite/src/arguments.rs @@ -4,62 +4,56 @@ use crate::statement::StatementHandle; use crate::Sqlite; use atoi::atoi; use libsqlite3_sys::SQLITE_OK; -use std::borrow::Cow; +use std::sync::Arc; pub(crate) use sqlx_core::arguments::*; use sqlx_core::error::BoxDynError; #[derive(Debug, Clone)] -pub enum SqliteArgumentValue<'q> { +pub enum SqliteArgumentValue { Null, - Text(Cow<'q, str>), - Blob(Cow<'q, [u8]>), + Text(Arc), + TextSlice(Arc), + Blob(Arc>), Double(f64), Int(i32), Int64(i64), } #[derive(Default, Debug, Clone)] -pub struct SqliteArguments<'q> { - pub(crate) values: Vec>, +pub struct SqliteArguments { + pub(crate) values: SqliteArgumentsBuffer, } -impl<'q> SqliteArguments<'q> { +#[derive(Default, Debug, Clone)] +pub struct SqliteArgumentsBuffer(Vec); + +impl<'q> SqliteArguments { pub(crate) fn add(&mut self, value: T) -> Result<(), BoxDynError> where T: Encode<'q, Sqlite>, { - let value_length_before_encoding = self.values.len(); + let value_length_before_encoding = self.values.0.len(); match value.encode(&mut self.values) { - Ok(IsNull::Yes) => self.values.push(SqliteArgumentValue::Null), + Ok(IsNull::Yes) => self.values.0.push(SqliteArgumentValue::Null), Ok(IsNull::No) => {} Err(error) => { // reset the value buffer to its previous value if encoding failed so we don't leave a half-encoded value behind - self.values.truncate(value_length_before_encoding); + self.values.0.truncate(value_length_before_encoding); return Err(error); } }; Ok(()) } - - pub(crate) fn into_static(self) -> SqliteArguments<'static> { - SqliteArguments { - values: self - .values - .into_iter() - .map(SqliteArgumentValue::into_static) - .collect(), - } - } } -impl<'q> Arguments<'q> for SqliteArguments<'q> { +impl<'q> Arguments<'q> for SqliteArguments { type Database = Sqlite; fn reserve(&mut self, len: usize, _size_hint: usize) { - self.values.reserve(len); + self.values.0.reserve(len); } fn add(&mut self, value: T) -> Result<(), BoxDynError> @@ -70,11 +64,11 @@ impl<'q> Arguments<'q> for SqliteArguments<'q> { } fn len(&self) -> usize { - self.values.len() + self.values.0.len() } } -impl SqliteArguments<'_> { +impl SqliteArguments { pub(super) fn bind(&self, handle: &mut StatementHandle, offset: usize) -> Result { let mut arg_i = offset; // for handle in &statement.handles { @@ -103,7 +97,7 @@ impl SqliteArguments<'_> { arg_i }; - if n > self.values.len() { + if n > self.values.0.len() { // SQLite treats unbound variables as NULL // we reproduce this here // If you are reading this and think this should be an error, open an issue and we can @@ -113,32 +107,31 @@ impl SqliteArguments<'_> { break; } - self.values[n - 1].bind(handle, param_i)?; + self.values.0[n - 1].bind(handle, param_i)?; } Ok(arg_i - offset) } } -impl SqliteArgumentValue<'_> { - fn into_static(self) -> SqliteArgumentValue<'static> { - use SqliteArgumentValue::*; +impl SqliteArgumentsBuffer { + #[allow(dead_code)] // clippy incorrectly reports this as unused + pub(crate) fn new(values: Vec) -> SqliteArgumentsBuffer { + Self(values) + } - match self { - Null => Null, - Text(text) => Text(text.into_owned().into()), - Blob(blob) => Blob(blob.into_owned().into()), - Int(v) => Int(v), - Int64(v) => Int64(v), - Double(v) => Double(v), - } + pub(crate) fn push(&mut self, value: SqliteArgumentValue) { + self.0.push(value); } +} +impl SqliteArgumentValue { fn bind(&self, handle: &mut StatementHandle, i: usize) -> Result<(), Error> { use SqliteArgumentValue::*; let status = match self { Text(v) => handle.bind_text(i, v), + TextSlice(v) => handle.bind_text(i, v), Blob(v) => handle.bind_blob(i, v), Int(v) => handle.bind_int(i, *v), Int64(v) => handle.bind_int64(i, *v), diff --git a/sqlx-sqlite/src/connection/execute.rs b/sqlx-sqlite/src/connection/execute.rs index 7acbc91ff8..733a1abbe6 100644 --- a/sqlx-sqlite/src/connection/execute.rs +++ b/sqlx-sqlite/src/connection/execute.rs @@ -10,7 +10,7 @@ pub struct ExecuteIter<'a> { handle: &'a mut ConnectionHandle, statement: &'a mut VirtualStatement, logger: QueryLogger, - args: Option>, + args: Option, /// since a `VirtualStatement` can encompass multiple actual statements, /// this keeps track of the number of arguments so far @@ -19,12 +19,12 @@ pub struct ExecuteIter<'a> { goto_next: bool, } -pub(crate) fn iter<'a>( - conn: &'a mut ConnectionState, +pub(crate) fn iter( + conn: &mut ConnectionState, query: impl SqlSafeStr, - args: Option>, + args: Option, persistent: bool, -) -> Result, Error> { +) -> Result, Error> { let query = query.into_sql_str(); // fetch the cached statement or allocate a new one let statement = conn.statements.get(query.as_str(), persistent)?; @@ -43,7 +43,7 @@ pub(crate) fn iter<'a>( fn bind( statement: &mut StatementHandle, - arguments: &Option>, + arguments: &Option, offset: usize, ) -> Result { let mut n = 0; @@ -56,7 +56,7 @@ fn bind( } impl ExecuteIter<'_> { - pub fn finish(&mut self) -> Result<(), Error> { + pub fn finish(self) -> Result<(), Error> { for res in self { let _ = res?; } diff --git a/sqlx-sqlite/src/connection/worker.rs b/sqlx-sqlite/src/connection/worker.rs index ae50f3e896..f1dbea3682 100644 --- a/sqlx-sqlite/src/connection/worker.rs +++ b/sqlx-sqlite/src/connection/worker.rs @@ -63,7 +63,7 @@ enum Command { }, Execute { query: SqlStr, - arguments: Option>, + arguments: Option, persistent: bool, tx: flume::Sender, Error>>, limit: Option, @@ -353,7 +353,7 @@ impl ConnectionWorker { pub(crate) async fn execute( &mut self, query: SqlStr, - args: Option>, + args: Option, chan_size: usize, persistent: bool, limit: Option, @@ -364,7 +364,7 @@ impl ConnectionWorker { .send_async(( Command::Execute { query, - arguments: args.map(SqliteArguments::into_static), + arguments: args, persistent, tx, limit, diff --git a/sqlx-sqlite/src/database.rs b/sqlx-sqlite/src/database.rs index d34d8eb8c3..2e83880544 100644 --- a/sqlx-sqlite/src/database.rs +++ b/sqlx-sqlite/src/database.rs @@ -1,9 +1,9 @@ pub(crate) use sqlx_core::database::{Database, HasStatementCache}; +use crate::arguments::SqliteArgumentsBuffer; use crate::{ - SqliteArgumentValue, SqliteArguments, SqliteColumn, SqliteConnection, SqliteQueryResult, - SqliteRow, SqliteStatement, SqliteTransactionManager, SqliteTypeInfo, SqliteValue, - SqliteValueRef, + SqliteArguments, SqliteColumn, SqliteConnection, SqliteQueryResult, SqliteRow, SqliteStatement, + SqliteTransactionManager, SqliteTypeInfo, SqliteValue, SqliteValueRef, }; /// Sqlite database driver. @@ -26,8 +26,8 @@ impl Database for Sqlite { type Value = SqliteValue; type ValueRef<'r> = SqliteValueRef<'r>; - type Arguments<'q> = SqliteArguments<'q>; - type ArgumentBuffer<'q> = Vec>; + type Arguments<'q> = SqliteArguments; + type ArgumentBuffer<'q> = SqliteArgumentsBuffer; type Statement = SqliteStatement; diff --git a/sqlx-sqlite/src/lib.rs b/sqlx-sqlite/src/lib.rs index 36d3ee7e69..17b4bed1ca 100644 --- a/sqlx-sqlite/src/lib.rs +++ b/sqlx-sqlite/src/lib.rs @@ -74,7 +74,7 @@ extern crate sqlx_core; use std::sync::atomic::AtomicBool; -pub use arguments::{SqliteArgumentValue, SqliteArguments}; +pub use arguments::{SqliteArgumentValue, SqliteArguments, SqliteArgumentsBuffer}; pub use column::SqliteColumn; #[cfg(feature = "deserialize")] #[cfg_attr(docsrs, doc(cfg(feature = "deserialize")))] @@ -147,7 +147,7 @@ impl<'c, T: Executor<'c, Database = Sqlite>> SqliteExecutor<'c> for T {} pub type SqliteTransaction<'c> = sqlx_core::transaction::Transaction<'c, Sqlite>; // NOTE: required due to the lack of lazy normalization -impl_into_arguments_for_arguments!(SqliteArguments<'q>); +impl_into_arguments_for_arguments!(SqliteArguments); impl_column_index_for_row!(SqliteRow); impl_column_index_for_statement!(SqliteStatement); impl_acquire!(Sqlite, SqliteConnection); diff --git a/sqlx-sqlite/src/statement/mod.rs b/sqlx-sqlite/src/statement/mod.rs index 407c567045..93485397d3 100644 --- a/sqlx-sqlite/src/statement/mod.rs +++ b/sqlx-sqlite/src/statement/mod.rs @@ -45,7 +45,7 @@ impl Statement for SqliteStatement { &self.columns } - impl_statement_query!(SqliteArguments<'_>); + impl_statement_query!(SqliteArguments); } impl ColumnIndex for &'_ str { @@ -57,20 +57,3 @@ impl ColumnIndex for &'_ str { .copied() } } - -// #[cfg(feature = "any")] -// impl<'q> From> for crate::any::AnyStatement<'q> { -// #[inline] -// fn from(statement: SqliteStatement<'q>) -> Self { -// crate::any::AnyStatement::<'q> { -// columns: statement -// .columns -// .iter() -// .map(|col| col.clone().into()) -// .collect(), -// column_names: statement.column_names, -// parameters: Some(Either::Right(statement.parameters)), -// sql: statement.sql, -// } -// } -// } diff --git a/sqlx-sqlite/src/types/bool.rs b/sqlx-sqlite/src/types/bool.rs index a229298ff9..9228eef236 100644 --- a/sqlx-sqlite/src/types/bool.rs +++ b/sqlx-sqlite/src/types/bool.rs @@ -1,3 +1,4 @@ +use crate::arguments::SqliteArgumentsBuffer; use crate::decode::Decode; use crate::encode::{Encode, IsNull}; use crate::error::BoxDynError; @@ -15,11 +16,8 @@ impl Type for bool { } } -impl<'q> Encode<'q, Sqlite> for bool { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { +impl Encode<'_, Sqlite> for bool { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { args.push(SqliteArgumentValue::Int((*self).into())); Ok(IsNull::No) diff --git a/sqlx-sqlite/src/types/bytes.rs b/sqlx-sqlite/src/types/bytes.rs index 2d67335a52..6453007bc9 100644 --- a/sqlx-sqlite/src/types/bytes.rs +++ b/sqlx-sqlite/src/types/bytes.rs @@ -2,6 +2,7 @@ use std::borrow::Cow; use std::rc::Rc; use std::sync::Arc; +use crate::arguments::SqliteArgumentsBuffer; use crate::decode::Decode; use crate::encode::{Encode, IsNull}; use crate::error::BoxDynError; @@ -19,12 +20,9 @@ impl Type for [u8] { } } -impl<'q> Encode<'q, Sqlite> for &'q [u8] { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { - args.push(SqliteArgumentValue::Blob(Cow::Borrowed(self))); +impl Encode<'_, Sqlite> for &'_ [u8] { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new(self.to_vec()))); Ok(IsNull::No) } @@ -37,19 +35,14 @@ impl<'r> Decode<'r, Sqlite> for &'r [u8] { } impl Encode<'_, Sqlite> for Box<[u8]> { - fn encode(self, args: &mut Vec>) -> Result { - args.push(SqliteArgumentValue::Blob(Cow::Owned(self.into_vec()))); + fn encode(self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new(self.into_vec()))); Ok(IsNull::No) } - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { - args.push(SqliteArgumentValue::Blob(Cow::Owned( - self.clone().into_vec(), - ))); + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new(self.clone().into_vec()))); Ok(IsNull::No) } @@ -65,18 +58,15 @@ impl Type for Vec { } } -impl<'q> Encode<'q, Sqlite> for Vec { - fn encode(self, args: &mut Vec>) -> Result { - args.push(SqliteArgumentValue::Blob(Cow::Owned(self))); +impl Encode<'_, Sqlite> for Vec { + fn encode(self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new(self))); Ok(IsNull::No) } - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { - args.push(SqliteArgumentValue::Blob(Cow::Owned(self.clone()))); + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new(self.clone()))); Ok(IsNull::No) } @@ -88,37 +78,28 @@ impl<'r> Decode<'r, Sqlite> for Vec { } } -impl<'q> Encode<'q, Sqlite> for Cow<'q, [u8]> { - fn encode(self, args: &mut Vec>) -> Result { - args.push(SqliteArgumentValue::Blob(self)); +impl Encode<'_, Sqlite> for Cow<'_, [u8]> { + fn encode(self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new(self.into()))); Ok(IsNull::No) } - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { - args.push(SqliteArgumentValue::Blob(self.clone())); + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new(self.to_vec()))); Ok(IsNull::No) } } -impl<'q> Encode<'q, Sqlite> for Arc<[u8]> { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { +impl Encode<'_, Sqlite> for Arc<[u8]> { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { as Encode<'_, Sqlite>>::encode(self.to_vec(), args) } } -impl<'q> Encode<'q, Sqlite> for Rc<[u8]> { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { +impl Encode<'_, Sqlite> for Rc<[u8]> { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { as Encode<'_, Sqlite>>::encode(self.to_vec(), args) } } diff --git a/sqlx-sqlite/src/types/chrono.rs b/sqlx-sqlite/src/types/chrono.rs index 5c4a41caff..8d987538d0 100644 --- a/sqlx-sqlite/src/types/chrono.rs +++ b/sqlx-sqlite/src/types/chrono.rs @@ -7,7 +7,7 @@ use crate::{ error::BoxDynError, type_info::DataType, types::Type, - Sqlite, SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef, + Sqlite, SqliteArgumentsBuffer, SqliteTypeInfo, SqliteValueRef, }; use chrono::FixedOffset; use chrono::{ @@ -65,25 +65,25 @@ impl Encode<'_, Sqlite> for DateTime where Tz::Offset: Display, { - fn encode_by_ref(&self, buf: &mut Vec>) -> Result { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { Encode::::encode(self.to_rfc3339_opts(SecondsFormat::AutoSi, false), buf) } } impl Encode<'_, Sqlite> for NaiveDateTime { - fn encode_by_ref(&self, buf: &mut Vec>) -> Result { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { Encode::::encode(self.format("%F %T%.f").to_string(), buf) } } impl Encode<'_, Sqlite> for NaiveDate { - fn encode_by_ref(&self, buf: &mut Vec>) -> Result { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { Encode::::encode(self.format("%F").to_string(), buf) } } impl Encode<'_, Sqlite> for NaiveTime { - fn encode_by_ref(&self, buf: &mut Vec>) -> Result { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { Encode::::encode(self.format("%T%.f").to_string(), buf) } } diff --git a/sqlx-sqlite/src/types/float.rs b/sqlx-sqlite/src/types/float.rs index c6e105d783..d23b3f3a08 100644 --- a/sqlx-sqlite/src/types/float.rs +++ b/sqlx-sqlite/src/types/float.rs @@ -1,3 +1,4 @@ +use crate::arguments::SqliteArgumentsBuffer; use crate::decode::Decode; use crate::encode::{Encode, IsNull}; use crate::error::BoxDynError; @@ -11,11 +12,8 @@ impl Type for f32 { } } -impl<'q> Encode<'q, Sqlite> for f32 { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { +impl Encode<'_, Sqlite> for f32 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { args.push(SqliteArgumentValue::Double((*self).into())); Ok(IsNull::No) @@ -36,11 +34,8 @@ impl Type for f64 { } } -impl<'q> Encode<'q, Sqlite> for f64 { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { +impl Encode<'_, Sqlite> for f64 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { args.push(SqliteArgumentValue::Double(*self)); Ok(IsNull::No) diff --git a/sqlx-sqlite/src/types/int.rs b/sqlx-sqlite/src/types/int.rs index e87025e2fb..2cf4209ad6 100644 --- a/sqlx-sqlite/src/types/int.rs +++ b/sqlx-sqlite/src/types/int.rs @@ -1,3 +1,4 @@ +use crate::arguments::SqliteArgumentsBuffer; use crate::decode::Decode; use crate::encode::{Encode, IsNull}; use crate::error::BoxDynError; @@ -15,11 +16,8 @@ impl Type for i8 { } } -impl<'q> Encode<'q, Sqlite> for i8 { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { +impl Encode<'_, Sqlite> for i8 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { args.push(SqliteArgumentValue::Int(*self as i32)); Ok(IsNull::No) @@ -46,11 +44,8 @@ impl Type for i16 { } } -impl<'q> Encode<'q, Sqlite> for i16 { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { +impl Encode<'_, Sqlite> for i16 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { args.push(SqliteArgumentValue::Int(*self as i32)); Ok(IsNull::No) @@ -73,11 +68,8 @@ impl Type for i32 { } } -impl<'q> Encode<'q, Sqlite> for i32 { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { +impl Encode<'_, Sqlite> for i32 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { args.push(SqliteArgumentValue::Int(*self)); Ok(IsNull::No) @@ -100,11 +92,8 @@ impl Type for i64 { } } -impl<'q> Encode<'q, Sqlite> for i64 { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { +impl Encode<'_, Sqlite> for i64 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { args.push(SqliteArgumentValue::Int64(*self)); Ok(IsNull::No) diff --git a/sqlx-sqlite/src/types/json.rs b/sqlx-sqlite/src/types/json.rs index b8b665c4d3..dafd483658 100644 --- a/sqlx-sqlite/src/types/json.rs +++ b/sqlx-sqlite/src/types/json.rs @@ -1,10 +1,11 @@ use serde::{Deserialize, Serialize}; +use crate::arguments::SqliteArgumentsBuffer; use crate::decode::Decode; use crate::encode::{Encode, IsNull}; use crate::error::BoxDynError; use crate::types::{Json, Type}; -use crate::{type_info::DataType, Sqlite, SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef}; +use crate::{type_info::DataType, Sqlite, SqliteTypeInfo, SqliteValueRef}; impl Type for Json { fn type_info() -> SqliteTypeInfo { @@ -20,7 +21,7 @@ impl Encode<'_, Sqlite> for Json where T: Serialize, { - fn encode_by_ref(&self, buf: &mut Vec>) -> Result { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { Encode::::encode(self.encode_to_string()?, buf) } } diff --git a/sqlx-sqlite/src/types/str.rs b/sqlx-sqlite/src/types/str.rs index 5392f6401a..c90f9bba55 100644 --- a/sqlx-sqlite/src/types/str.rs +++ b/sqlx-sqlite/src/types/str.rs @@ -2,6 +2,7 @@ use std::borrow::Cow; use std::rc::Rc; use std::sync::Arc; +use crate::arguments::SqliteArgumentsBuffer; use crate::decode::Decode; use crate::encode::{Encode, IsNull}; use crate::error::BoxDynError; @@ -15,12 +16,9 @@ impl Type for str { } } -impl<'q> Encode<'q, Sqlite> for &'q str { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { - args.push(SqliteArgumentValue::Text(Cow::Borrowed(*self))); +impl Encode<'_, Sqlite> for &'_ str { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self.to_string()))); Ok(IsNull::No) } @@ -33,19 +31,14 @@ impl<'r> Decode<'r, Sqlite> for &'r str { } impl Encode<'_, Sqlite> for Box { - fn encode(self, args: &mut Vec>) -> Result { - args.push(SqliteArgumentValue::Text(Cow::Owned(self.into_string()))); + fn encode(self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(String::from(self)))); Ok(IsNull::No) } - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { - args.push(SqliteArgumentValue::Text(Cow::Owned( - self.clone().into_string(), - ))); + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self.to_string()))); Ok(IsNull::No) } @@ -57,18 +50,15 @@ impl Type for String { } } -impl<'q> Encode<'q, Sqlite> for String { - fn encode(self, args: &mut Vec>) -> Result { - args.push(SqliteArgumentValue::Text(Cow::Owned(self))); +impl Encode<'_, Sqlite> for String { + fn encode(self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self))); Ok(IsNull::No) } - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { - args.push(SqliteArgumentValue::Text(Cow::Owned(self.clone()))); + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self.clone()))); Ok(IsNull::No) } @@ -80,37 +70,28 @@ impl<'r> Decode<'r, Sqlite> for String { } } -impl<'q> Encode<'q, Sqlite> for Cow<'q, str> { - fn encode(self, args: &mut Vec>) -> Result { - args.push(SqliteArgumentValue::Text(self)); +impl Encode<'_, Sqlite> for Cow<'_, str> { + fn encode(self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self.into()))); Ok(IsNull::No) } - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { - args.push(SqliteArgumentValue::Text(self.clone())); + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self.to_string()))); Ok(IsNull::No) } } -impl<'q> Encode<'q, Sqlite> for Arc { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { +impl Encode<'_, Sqlite> for Arc { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { >::encode(self.to_string(), args) } } -impl<'q> Encode<'q, Sqlite> for Rc { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { +impl Encode<'_, Sqlite> for Rc { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { >::encode(self.to_string(), args) } } diff --git a/sqlx-sqlite/src/types/text.rs b/sqlx-sqlite/src/types/text.rs index 80aab0d4ba..ef03caf5a0 100644 --- a/sqlx-sqlite/src/types/text.rs +++ b/sqlx-sqlite/src/types/text.rs @@ -1,4 +1,5 @@ -use crate::{Sqlite, SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef}; +use crate::arguments::SqliteArgumentsBuffer; +use crate::{Sqlite, SqliteTypeInfo, SqliteValueRef}; use sqlx_core::decode::Decode; use sqlx_core::encode::{Encode, IsNull}; use sqlx_core::error::BoxDynError; @@ -16,11 +17,11 @@ impl Type for Text { } } -impl<'q, T> Encode<'q, Sqlite> for Text +impl Encode<'_, Sqlite> for Text where T: Display, { - fn encode_by_ref(&self, buf: &mut Vec>) -> Result { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { Encode::::encode(self.0.to_string(), buf) } } diff --git a/sqlx-sqlite/src/types/time.rs b/sqlx-sqlite/src/types/time.rs index c7ad3b3d05..0e0027882d 100644 --- a/sqlx-sqlite/src/types/time.rs +++ b/sqlx-sqlite/src/types/time.rs @@ -1,3 +1,4 @@ +use crate::arguments::SqliteArgumentsBuffer; use crate::value::ValueRef; use crate::{ decode::Decode, @@ -5,7 +6,7 @@ use crate::{ error::BoxDynError, type_info::DataType, types::Type, - Sqlite, SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef, + Sqlite, SqliteTypeInfo, SqliteValueRef, }; use time::format_description::{well_known::Rfc3339, BorrowedFormatItem}; use time::macros::format_description as fd; @@ -55,27 +56,27 @@ impl Type for Time { } impl Encode<'_, Sqlite> for OffsetDateTime { - fn encode_by_ref(&self, buf: &mut Vec>) -> Result { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { Encode::::encode(self.format(&Rfc3339)?, buf) } } impl Encode<'_, Sqlite> for PrimitiveDateTime { - fn encode_by_ref(&self, buf: &mut Vec>) -> Result { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { let format = fd!("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond]"); Encode::::encode(self.format(&format)?, buf) } } impl Encode<'_, Sqlite> for Date { - fn encode_by_ref(&self, buf: &mut Vec>) -> Result { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { let format = fd!("[year]-[month]-[day]"); Encode::::encode(self.format(&format)?, buf) } } impl Encode<'_, Sqlite> for Time { - fn encode_by_ref(&self, buf: &mut Vec>) -> Result { + fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result { let format = fd!("[hour]:[minute]:[second].[subsecond]"); Encode::::encode(self.format(&format)?, buf) } diff --git a/sqlx-sqlite/src/types/uint.rs b/sqlx-sqlite/src/types/uint.rs index f3d7da8c2f..1e8b1c5392 100644 --- a/sqlx-sqlite/src/types/uint.rs +++ b/sqlx-sqlite/src/types/uint.rs @@ -1,3 +1,4 @@ +use crate::arguments::SqliteArgumentsBuffer; use crate::decode::Decode; use crate::encode::{Encode, IsNull}; use crate::error::BoxDynError; @@ -15,11 +16,8 @@ impl Type for u8 { } } -impl<'q> Encode<'q, Sqlite> for u8 { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { +impl Encode<'_, Sqlite> for u8 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { args.push(SqliteArgumentValue::Int(*self as i32)); Ok(IsNull::No) @@ -46,11 +44,8 @@ impl Type for u16 { } } -impl<'q> Encode<'q, Sqlite> for u16 { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { +impl Encode<'_, Sqlite> for u16 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { args.push(SqliteArgumentValue::Int(*self as i32)); Ok(IsNull::No) @@ -73,11 +68,8 @@ impl Type for u32 { } } -impl<'q> Encode<'q, Sqlite> for u32 { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { +impl Encode<'_, Sqlite> for u32 { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { args.push(SqliteArgumentValue::Int64(*self as i64)); Ok(IsNull::No) diff --git a/sqlx-sqlite/src/types/uuid.rs b/sqlx-sqlite/src/types/uuid.rs index 99291be86e..718ca5fb5d 100644 --- a/sqlx-sqlite/src/types/uuid.rs +++ b/sqlx-sqlite/src/types/uuid.rs @@ -1,10 +1,11 @@ +use crate::arguments::SqliteArgumentsBuffer; use crate::decode::Decode; use crate::encode::{Encode, IsNull}; use crate::error::BoxDynError; use crate::type_info::DataType; use crate::types::Type; use crate::{Sqlite, SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef}; -use std::borrow::Cow; +use std::sync::Arc; use uuid::{ fmt::{Hyphenated, Simple}, Uuid, @@ -20,12 +21,9 @@ impl Type for Uuid { } } -impl<'q> Encode<'q, Sqlite> for Uuid { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { - args.push(SqliteArgumentValue::Blob(Cow::Owned( +impl Encode<'_, Sqlite> for Uuid { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Blob(Arc::new( self.as_bytes().to_vec(), ))); @@ -46,12 +44,9 @@ impl Type for Hyphenated { } } -impl<'q> Encode<'q, Sqlite> for Hyphenated { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { - args.push(SqliteArgumentValue::Text(Cow::Owned(self.to_string()))); +impl Encode<'_, Sqlite> for Hyphenated { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self.to_string()))); Ok(IsNull::No) } @@ -72,12 +67,9 @@ impl Type for Simple { } } -impl<'q> Encode<'q, Sqlite> for Simple { - fn encode_by_ref( - &self, - args: &mut Vec>, - ) -> Result { - args.push(SqliteArgumentValue::Text(Cow::Owned(self.to_string()))); +impl Encode<'_, Sqlite> for Simple { + fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result { + args.push(SqliteArgumentValue::Text(Arc::new(self.to_string()))); Ok(IsNull::No) } diff --git a/tests/sqlite/macros.rs b/tests/sqlite/macros.rs index 74e689260a..0ab4dd56bf 100644 --- a/tests/sqlite/macros.rs +++ b/tests/sqlite/macros.rs @@ -175,6 +175,31 @@ async fn test_query_scalar() -> anyhow::Result<()> { Ok(()) } +#[sqlx_macros::test] +async fn query_by_string() -> anyhow::Result<()> { + let mut conn = new::().await?; + + let string = "Hello, world!".to_string(); + let ref tuple = ("Hello, world!".to_string(),); + + let result = sqlx::query!( + "SELECT 'Hello, world!' as string where 'Hello, world!' in (?, ?, ?, ?, ?, ?, ?)", + string, // make sure we don't actually take ownership here + &string[..], + Some(&string), + Some(&string[..]), + Option::::None, + string.clone(), + tuple.0 // make sure we're not trying to move out of a field expression + ) + .fetch_one(&mut conn) + .await?; + + assert_eq!(result.string, string); + + Ok(()) +} + #[sqlx_macros::test] async fn macro_select_from_view() -> anyhow::Result<()> { let mut conn = new::().await?;