#[cfg(not(all(target_family = "wasm", target_os = "unknown")))] extern crate libsqlite3_sys as ffi; #[cfg(all(target_family = "wasm", target_os = "unknown"))] use sqlite_wasm_rs as ffi; use super::raw::RawConnection; use super::{Sqlite, SqliteAggregateFunction, SqliteBindValue}; use crate::backend::Backend; use crate::deserialize::{FromSqlRow, StaticallySizedRow}; use crate::result::{DatabaseErrorKind, Error, QueryResult}; use crate::row::{Field, PartialRow, Row, RowIndex, RowSealed}; use crate::serialize::{IsNull, Output, ToSql}; use crate::sql_types::HasSqlType; use crate::sqlite::connection::bind_collector::InternalSqliteBindValue; use crate::sqlite::connection::sqlite_value::OwnedSqliteValue; use crate::sqlite::SqliteValue; pub(super) fn register( conn: &RawConnection, fn_name: &str, deterministic: bool, mut f: F, ) -> QueryResult<()> where F: FnMut(&RawConnection, Args) -> Ret + std::panic::UnwindSafe + Send + 'static, Args: FromSqlRow + StaticallySizedRow, Ret: ToSql, Sqlite: HasSqlType, { let fields_needed = Args::FIELD_COUNT; if fields_needed > 127 { return Err(Error::DatabaseError( DatabaseErrorKind::UnableToSendCommand, Box::new("SQLite functions cannot take more than 127 parameters".to_string()), )); } conn.register_sql_function(fn_name, fields_needed, deterministic, move |conn, args| { let args = build_sql_function_args::(args)?; Ok(f(conn, args)) })?; Ok(()) } pub(super) fn register_noargs( conn: &RawConnection, fn_name: &str, deterministic: bool, mut f: F, ) -> QueryResult<()> where F: FnMut() -> Ret + std::panic::UnwindSafe + Send + 'static, Ret: ToSql, Sqlite: HasSqlType, { conn.register_sql_function(fn_name, 0, deterministic, move |_, _| Ok(f()))?; Ok(()) } pub(super) fn register_aggregate( conn: &RawConnection, fn_name: &str, ) -> QueryResult<()> where A: SqliteAggregateFunction + 'static + Send + std::panic::UnwindSafe, Args: FromSqlRow + StaticallySizedRow, Ret: ToSql, Sqlite: HasSqlType, { let fields_needed = Args::FIELD_COUNT; if fields_needed > 127 { return Err(Error::DatabaseError( DatabaseErrorKind::UnableToSendCommand, Box::new("SQLite functions cannot take more than 127 parameters".to_string()), )); } conn.register_aggregate_function::( fn_name, fields_needed, )?; Ok(()) } pub(super) fn build_sql_function_args( args: &mut [*mut ffi::sqlite3_value], ) -> Result where Args: FromSqlRow, { let row = FunctionRow::new(args); Args::build_from_row(&row).map_err(Error::DeserializationError) } // clippy is wrong here, the let binding is required // for lifetime reasons #[allow(clippy::let_unit_value)] pub(super) fn process_sql_function_result( result: &'_ Ret, ) -> QueryResult> where Ret: ToSql, Sqlite: HasSqlType, { let mut metadata_lookup = (); let value = SqliteBindValue { inner: InternalSqliteBindValue::Null, }; let mut buf = Output::new(value, &mut metadata_lookup); let is_null = result.to_sql(&mut buf).map_err(Error::SerializationError)?; if let IsNull::Yes = is_null { Ok(InternalSqliteBindValue::Null) } else { Ok(buf.into_inner().inner) } } struct FunctionRow<'a> { args: &'a [Option], field_count: usize, } impl FunctionRow<'_> { #[allow(unsafe_code)] // complicated ptr cast fn new(args: &mut [*mut ffi::sqlite3_value]) -> Self { let lengths = args.len(); let args = unsafe { core::slice::from_raw_parts( // This cast is safe because: // * Casting from a pointer to an array to a pointer to the first array // element is safe // * Casting from a raw pointer to `NonNull` is safe, // because `NonNull` is #[repr(transparent)] // * Casting from `NonNull` to `OwnedSqliteValue` is safe, // as the struct is `#[repr(transparent)] // * Casting from `NonNull` to `Option>` as the documentation // states: "This is so that enums may use this forbidden value as a discriminant – // Option> has the same size as *mut T" // * The last point remains true for `OwnedSqliteValue` as `#[repr(transparent)] // guarantees the same layout as the inner type args as *mut [*mut ffi::sqlite3_value] as *mut ffi::sqlite3_value as *mut Option, lengths, ) }; Self { field_count: lengths, args, } } } impl RowSealed for FunctionRow<'_> {} impl<'a> Row<'a, Sqlite> for FunctionRow<'a> { type Field<'f> = FunctionArgument<'f> where 'a: 'f, Self: 'f; type InnerPartialRow = Self; fn field_count(&self) -> usize { self.field_count } fn get<'b, I>(&'b self, idx: I) -> Option> where 'a: 'b, Self: crate::row::RowIndex, { let col_idx = self.idx(idx)?; Some(FunctionArgument { args: self.args, col_idx, }) } fn partial_row(&self, range: std::ops::Range) -> PartialRow<'_, Self::InnerPartialRow> { PartialRow::new(self, range) } } impl RowIndex for FunctionRow<'_> { fn idx(&self, idx: usize) -> Option { if idx < self.field_count() { Some(idx) } else { None } } } impl<'a> RowIndex<&'a str> for FunctionRow<'_> { fn idx(&self, _idx: &'a str) -> Option { None } } struct FunctionArgument<'a> { args: &'a [Option], col_idx: usize, } impl<'a> Field<'a, Sqlite> for FunctionArgument<'a> { fn field_name(&self) -> Option<&str> { None } fn is_null(&self) -> bool { self.value().is_none() } fn value(&self) -> Option<::RawValue<'_>> { SqliteValue::from_function_row(self.args, self.col_idx) } }