2015-12-12 05:27:39 +08:00
|
|
|
//! Create or redefine SQL functions.
|
|
|
|
//!
|
|
|
|
//! # Example
|
|
|
|
//!
|
|
|
|
//! Adding a `regexp` function to a connection in which compiled regular expressions
|
|
|
|
//! are cached in a `HashMap`. For an alternative implementation that uses SQLite's
|
|
|
|
//! [Function Auxilliary Data](https://www.sqlite.org/c3ref/get_auxdata.html) interface
|
|
|
|
//! to avoid recompiling regular expressions, see the unit tests for this module.
|
|
|
|
//!
|
|
|
|
//! ```rust
|
|
|
|
//! extern crate libsqlite3_sys;
|
|
|
|
//! extern crate rusqlite;
|
|
|
|
//! extern crate regex;
|
|
|
|
//!
|
2015-12-13 03:06:03 +08:00
|
|
|
//! use rusqlite::{Connection, Error, Result};
|
2015-12-12 05:27:39 +08:00
|
|
|
//! use std::collections::HashMap;
|
|
|
|
//! use regex::Regex;
|
|
|
|
//!
|
2015-12-13 03:06:03 +08:00
|
|
|
//! fn add_regexp_function(db: &Connection) -> Result<()> {
|
2015-12-12 05:27:39 +08:00
|
|
|
//! let mut cached_regexes = HashMap::new();
|
|
|
|
//! db.create_scalar_function("regexp", 2, true, move |ctx| {
|
|
|
|
//! let regex_s = try!(ctx.get::<String>(0));
|
|
|
|
//! let entry = cached_regexes.entry(regex_s.clone());
|
|
|
|
//! let regex = {
|
|
|
|
//! use std::collections::hash_map::Entry::{Occupied, Vacant};
|
|
|
|
//! match entry {
|
|
|
|
//! Occupied(occ) => occ.into_mut(),
|
|
|
|
//! Vacant(vac) => {
|
2015-12-13 13:54:08 +08:00
|
|
|
//! match Regex::new(®ex_s) {
|
|
|
|
//! Ok(r) => vac.insert(r),
|
|
|
|
//! Err(err) => return Err(Error::UserFunctionError(Box::new(err))),
|
|
|
|
//! }
|
2015-12-12 05:27:39 +08:00
|
|
|
//! }
|
|
|
|
//! }
|
|
|
|
//! };
|
|
|
|
//!
|
|
|
|
//! let text = try!(ctx.get::<String>(1));
|
|
|
|
//! Ok(regex.is_match(&text))
|
|
|
|
//! })
|
|
|
|
//! }
|
|
|
|
//!
|
|
|
|
//! fn main() {
|
2015-12-13 02:50:12 +08:00
|
|
|
//! let db = Connection::open_in_memory().unwrap();
|
2015-12-12 05:27:39 +08:00
|
|
|
//! add_regexp_function(&db).unwrap();
|
|
|
|
//!
|
2016-01-02 19:13:37 +08:00
|
|
|
//! let is_match: bool = db.query_row("SELECT regexp('[aeiou]*', 'aaaaeeeiii')", &[],
|
|
|
|
//! |row| row.get(0)).unwrap();
|
2015-12-12 05:27:39 +08:00
|
|
|
//!
|
|
|
|
//! assert!(is_match);
|
|
|
|
//! }
|
|
|
|
//! ```
|
2015-12-13 13:54:08 +08:00
|
|
|
use std::error::Error as StdError;
|
2015-12-12 00:41:40 +08:00
|
|
|
use std::ffi::CStr;
|
2015-08-09 15:52:53 +08:00
|
|
|
use std::mem;
|
2015-12-12 04:47:52 +08:00
|
|
|
use std::ptr;
|
2015-12-12 03:46:28 +08:00
|
|
|
use std::slice;
|
2017-02-17 00:17:24 +08:00
|
|
|
use std::os::raw::{c_int, c_char, c_void};
|
2015-08-09 15:52:53 +08:00
|
|
|
|
|
|
|
use ffi;
|
2016-05-26 12:09:58 +08:00
|
|
|
use ffi::sqlite3_context;
|
|
|
|
use ffi::sqlite3_value;
|
2015-08-09 15:52:53 +08:00
|
|
|
|
2016-12-31 13:35:47 +08:00
|
|
|
use types::{ToSql, ToSqlOutput, FromSql, FromSqlError, ValueRef};
|
2015-08-09 15:52:53 +08:00
|
|
|
|
2015-12-13 03:06:03 +08:00
|
|
|
use {Result, Error, Connection, str_to_cstring, InnerConnection};
|
2015-08-09 15:52:53 +08:00
|
|
|
|
2016-05-26 12:06:53 +08:00
|
|
|
fn set_result<'a>(ctx: *mut sqlite3_context, result: &ToSqlOutput<'a>) {
|
|
|
|
let value = match *result {
|
|
|
|
ToSqlOutput::Borrowed(v) => v,
|
|
|
|
ToSqlOutput::Owned(ref v) => ValueRef::from(v),
|
2015-08-09 15:52:53 +08:00
|
|
|
|
2016-05-26 12:06:53 +08:00
|
|
|
#[cfg(feature = "blob")]
|
|
|
|
ToSqlOutput::ZeroBlob(len) => {
|
|
|
|
return unsafe { ffi::sqlite3_result_zeroblob(ctx, len) };
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
2016-05-26 12:06:53 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
match value {
|
|
|
|
ValueRef::Null => unsafe { ffi::sqlite3_result_null(ctx) },
|
|
|
|
ValueRef::Integer(i) => unsafe { ffi::sqlite3_result_int64(ctx, i) },
|
|
|
|
ValueRef::Real(r) => unsafe { ffi::sqlite3_result_double(ctx, r) },
|
2017-02-25 03:10:51 +08:00
|
|
|
ValueRef::Text(s) => unsafe {
|
2016-05-26 12:06:53 +08:00
|
|
|
let length = s.len();
|
|
|
|
if length > ::std::i32::MAX as usize {
|
|
|
|
ffi::sqlite3_result_error_toobig(ctx);
|
|
|
|
} else {
|
|
|
|
let c_str = match str_to_cstring(s) {
|
|
|
|
Ok(c_str) => c_str,
|
|
|
|
// TODO sqlite3_result_error
|
|
|
|
Err(_) => return ffi::sqlite3_result_error_code(ctx, ffi::SQLITE_MISUSE),
|
|
|
|
};
|
|
|
|
let destructor = if length > 0 {
|
|
|
|
ffi::SQLITE_TRANSIENT()
|
|
|
|
} else {
|
|
|
|
ffi::SQLITE_STATIC()
|
|
|
|
};
|
|
|
|
ffi::sqlite3_result_text(ctx, c_str.as_ptr(), length as c_int, destructor);
|
2015-12-12 00:41:40 +08:00
|
|
|
}
|
2016-05-26 12:06:53 +08:00
|
|
|
},
|
2017-02-25 03:10:51 +08:00
|
|
|
ValueRef::Blob(b) => unsafe {
|
2016-05-26 12:06:53 +08:00
|
|
|
let length = b.len();
|
|
|
|
if length > ::std::i32::MAX as usize {
|
|
|
|
ffi::sqlite3_result_error_toobig(ctx);
|
|
|
|
} else if length == 0 {
|
|
|
|
ffi::sqlite3_result_zeroblob(ctx, 0)
|
|
|
|
} else {
|
2016-05-26 12:28:18 +08:00
|
|
|
ffi::sqlite3_result_blob(ctx,
|
|
|
|
b.as_ptr() as *const c_void,
|
2015-12-12 00:41:40 +08:00
|
|
|
length as c_int,
|
2016-05-26 12:28:18 +08:00
|
|
|
ffi::SQLITE_TRANSIENT());
|
2015-12-12 00:41:40 +08:00
|
|
|
}
|
2016-05-26 12:06:53 +08:00
|
|
|
},
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-05-26 12:06:53 +08:00
|
|
|
unsafe fn report_error(ctx: *mut sqlite3_context, err: &Error) {
|
2017-04-06 01:22:55 +08:00
|
|
|
// Extended constraint error codes were added in SQLite 3.7.16. We don't have an explicit
|
|
|
|
// feature check for that, and this doesn't really warrant one. We'll use the extended code
|
|
|
|
// if we're on the bundled version (since it's at least 3.17.0) and the normal constraint
|
|
|
|
// error code if not.
|
|
|
|
#[cfg(feature = "bundled")]
|
2017-04-08 01:43:24 +08:00
|
|
|
fn constraint_error_code() -> i32 {
|
|
|
|
ffi::SQLITE_CONSTRAINT_FUNCTION
|
|
|
|
}
|
2017-04-06 01:22:55 +08:00
|
|
|
#[cfg(not(feature = "bundled"))]
|
2017-04-08 01:43:24 +08:00
|
|
|
fn constraint_error_code() -> i32 {
|
|
|
|
ffi::SQLITE_CONSTRAINT
|
|
|
|
}
|
2017-04-06 01:22:55 +08:00
|
|
|
|
2017-02-25 03:10:51 +08:00
|
|
|
match *err {
|
|
|
|
Error::SqliteFailure(ref err, ref s) => {
|
2016-05-26 12:06:53 +08:00
|
|
|
ffi::sqlite3_result_error_code(ctx, err.extended_code);
|
|
|
|
if let Some(Ok(cstr)) = s.as_ref().map(|s| str_to_cstring(s)) {
|
|
|
|
ffi::sqlite3_result_error(ctx, cstr.as_ptr(), -1);
|
|
|
|
}
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
2016-05-26 12:06:53 +08:00
|
|
|
_ => {
|
2017-04-06 01:22:55 +08:00
|
|
|
ffi::sqlite3_result_error_code(ctx, constraint_error_code());
|
2016-05-26 12:06:53 +08:00
|
|
|
if let Ok(cstr) = str_to_cstring(err.description()) {
|
|
|
|
ffi::sqlite3_result_error(ctx, cstr.as_ptr(), -1);
|
|
|
|
}
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-05-25 09:34:18 +08:00
|
|
|
impl<'a> ValueRef<'a> {
|
|
|
|
unsafe fn from_value(value: *mut sqlite3_value) -> ValueRef<'a> {
|
2015-08-09 15:52:53 +08:00
|
|
|
use std::slice::from_raw_parts;
|
|
|
|
|
2016-05-25 08:08:12 +08:00
|
|
|
match ffi::sqlite3_value_type(value) {
|
2016-05-25 09:34:18 +08:00
|
|
|
ffi::SQLITE_NULL => ValueRef::Null,
|
|
|
|
ffi::SQLITE_INTEGER => ValueRef::Integer(ffi::sqlite3_value_int64(value)),
|
|
|
|
ffi::SQLITE_FLOAT => ValueRef::Real(ffi::sqlite3_value_double(value)),
|
2016-05-25 08:08:12 +08:00
|
|
|
ffi::SQLITE_TEXT => {
|
|
|
|
let text = ffi::sqlite3_value_text(value);
|
2016-05-26 12:28:18 +08:00
|
|
|
assert!(!text.is_null(),
|
|
|
|
"unexpected SQLITE_TEXT value type with NULL data");
|
2016-05-25 08:08:12 +08:00
|
|
|
let s = CStr::from_ptr(text as *const c_char);
|
|
|
|
|
|
|
|
// sqlite3_value_text returns UTF8 data, so our unwrap here should be fine.
|
2017-04-08 01:43:24 +08:00
|
|
|
let s = s.to_str()
|
|
|
|
.expect("sqlite3_value_text returned invalid UTF-8");
|
2016-05-25 09:34:18 +08:00
|
|
|
ValueRef::Text(s)
|
2016-05-25 08:08:12 +08:00
|
|
|
}
|
|
|
|
ffi::SQLITE_BLOB => {
|
2017-04-16 23:49:28 +08:00
|
|
|
let (blob, len) = (ffi::sqlite3_value_blob(value), ffi::sqlite3_value_bytes(value));
|
2015-08-09 15:52:53 +08:00
|
|
|
|
2016-05-26 12:28:18 +08:00
|
|
|
assert!(len >= 0,
|
|
|
|
"unexpected negative return from sqlite3_value_bytes");
|
2017-04-16 23:49:28 +08:00
|
|
|
if len > 0 {
|
|
|
|
assert!(!blob.is_null(),
|
|
|
|
"unexpected SQLITE_BLOB value type with NULL data");
|
|
|
|
ValueRef::Blob(from_raw_parts(blob as *const u8, len as usize))
|
|
|
|
} else {
|
|
|
|
// The return value from sqlite3_value_blob() for a zero-length BLOB
|
|
|
|
// is a NULL pointer.
|
|
|
|
ValueRef::Blob(&[])
|
|
|
|
}
|
2016-05-25 08:08:12 +08:00
|
|
|
}
|
2016-05-27 03:03:05 +08:00
|
|
|
_ => unreachable!("sqlite3_value_type returned invalid value"),
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-12 02:54:08 +08:00
|
|
|
unsafe extern "C" fn free_boxed_value<T>(p: *mut c_void) {
|
|
|
|
let _: Box<T> = Box::from_raw(mem::transmute(p));
|
|
|
|
}
|
|
|
|
|
2015-12-12 05:27:39 +08:00
|
|
|
/// Context is a wrapper for the SQLite function evaluation context.
|
2015-12-12 03:46:28 +08:00
|
|
|
pub struct Context<'a> {
|
2015-12-12 04:08:40 +08:00
|
|
|
ctx: *mut sqlite3_context,
|
2015-12-12 03:46:28 +08:00
|
|
|
args: &'a [*mut sqlite3_value],
|
2015-12-12 02:54:08 +08:00
|
|
|
}
|
|
|
|
|
2015-12-12 03:46:28 +08:00
|
|
|
impl<'a> Context<'a> {
|
2015-12-12 05:27:39 +08:00
|
|
|
/// Returns the number of arguments to the function.
|
2015-12-12 03:46:28 +08:00
|
|
|
pub fn len(&self) -> usize {
|
|
|
|
self.args.len()
|
|
|
|
}
|
2016-02-14 23:11:59 +08:00
|
|
|
/// Returns `true` when there is no argument.
|
|
|
|
pub fn is_empty(&self) -> bool {
|
|
|
|
self.args.is_empty()
|
|
|
|
}
|
2015-12-12 03:46:28 +08:00
|
|
|
|
2015-12-12 05:27:39 +08:00
|
|
|
/// Returns the `idx`th argument as a `T`.
|
|
|
|
///
|
|
|
|
/// # Failure
|
|
|
|
///
|
|
|
|
/// Will panic if `idx` is greater than or equal to `self.len()`.
|
|
|
|
///
|
|
|
|
/// Will return Err if the underlying SQLite type cannot be converted to a `T`.
|
2016-05-25 08:08:12 +08:00
|
|
|
pub fn get<T: FromSql>(&self, idx: usize) -> Result<T> {
|
2015-12-12 03:46:28 +08:00
|
|
|
let arg = self.args[idx];
|
2016-05-25 09:34:18 +08:00
|
|
|
let value = unsafe { ValueRef::from_value(arg) };
|
2016-05-31 02:35:56 +08:00
|
|
|
FromSql::column_result(value).map_err(|err| match err {
|
2017-04-08 01:43:24 +08:00
|
|
|
FromSqlError::InvalidType => {
|
2016-06-03 03:03:25 +08:00
|
|
|
Error::InvalidFunctionParameterType(idx, value.data_type())
|
|
|
|
}
|
2017-04-08 01:43:24 +08:00
|
|
|
FromSqlError::OutOfRange(i) => {
|
|
|
|
Error::IntegralValueOutOfRange(idx as c_int,
|
|
|
|
i)
|
|
|
|
}
|
|
|
|
FromSqlError::Other(err) => {
|
2016-06-03 03:03:25 +08:00
|
|
|
Error::FromSqlConversionFailure(idx, value.data_type(), err)
|
|
|
|
}
|
2017-04-08 01:43:24 +08:00
|
|
|
})
|
2015-12-12 03:46:28 +08:00
|
|
|
}
|
|
|
|
|
2015-12-12 05:27:39 +08:00
|
|
|
/// Sets the auxilliary data associated with a particular parameter. See
|
|
|
|
/// https://www.sqlite.org/c3ref/get_auxdata.html for a discussion of
|
|
|
|
/// this feature, or the unit tests of this module for an example.
|
2015-12-12 02:54:08 +08:00
|
|
|
pub fn set_aux<T>(&self, arg: c_int, value: T) {
|
|
|
|
let boxed = Box::into_raw(Box::new(value));
|
|
|
|
unsafe {
|
|
|
|
ffi::sqlite3_set_auxdata(self.ctx,
|
|
|
|
arg,
|
|
|
|
mem::transmute(boxed),
|
2016-03-30 02:18:56 +08:00
|
|
|
Some(free_boxed_value::<T>))
|
2015-12-12 02:54:08 +08:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2015-12-12 05:27:39 +08:00
|
|
|
/// Gets the auxilliary data that was associated with a given parameter
|
|
|
|
/// via `set_aux`. Returns `None` if no data has been associated.
|
|
|
|
///
|
|
|
|
/// # Unsafety
|
|
|
|
///
|
|
|
|
/// This function is unsafe as there is no guarantee that the type `T`
|
|
|
|
/// requested matches the type `T` that was provided to `set_aux`. The
|
|
|
|
/// types must be identical.
|
2015-12-12 02:54:08 +08:00
|
|
|
pub unsafe fn get_aux<T>(&self, arg: c_int) -> Option<&T> {
|
|
|
|
let p = ffi::sqlite3_get_auxdata(self.ctx, arg) as *mut T;
|
2017-02-09 04:11:15 +08:00
|
|
|
if p.is_null() { None } else { Some(&*p) }
|
2015-12-12 02:54:08 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-21 02:27:28 +08:00
|
|
|
/// Aggregate is the callback interface for user-defined aggregate function.
|
|
|
|
///
|
|
|
|
/// `A` is the type of the aggregation context and `T` is the type of the final result.
|
|
|
|
/// Implementations should be stateless.
|
2016-05-17 01:52:17 +08:00
|
|
|
pub trait Aggregate<A, T>
|
2016-05-26 12:06:53 +08:00
|
|
|
where T: ToSql
|
2016-05-17 01:52:17 +08:00
|
|
|
{
|
2016-01-08 04:14:24 +08:00
|
|
|
/// Initializes the aggregation context. Will be called prior to the first call
|
|
|
|
/// to `step()` to set up the context for an invocation of the function. (Note:
|
|
|
|
/// `init()` will not be called if the there are no rows.)
|
2015-12-21 02:27:28 +08:00
|
|
|
fn init(&self) -> A;
|
2016-01-08 01:33:32 +08:00
|
|
|
|
|
|
|
/// "step" function called once for each row in an aggregate group. May be called
|
|
|
|
/// 0 times if there are no rows.
|
2015-12-21 02:27:28 +08:00
|
|
|
fn step(&self, &mut Context, &mut A) -> Result<()>;
|
2016-01-08 01:33:32 +08:00
|
|
|
|
|
|
|
/// Computes and returns the final result. Will be called exactly once for each
|
2016-01-08 04:14:24 +08:00
|
|
|
/// invocation of the function. If `step()` was called at least once, will be given
|
|
|
|
/// `Some(A)` (the same `A` as was created by `init` and given to `step`); if `step()`
|
|
|
|
/// was not called (because the function is running against 0 rows), will be given
|
|
|
|
/// `None`.
|
|
|
|
fn finalize(&self, Option<A>) -> Result<T>;
|
2015-12-16 03:54:23 +08:00
|
|
|
}
|
|
|
|
|
2015-12-13 02:50:12 +08:00
|
|
|
impl Connection {
|
2015-12-12 05:27:39 +08:00
|
|
|
/// Attach a user-defined scalar function to this database connection.
|
|
|
|
///
|
|
|
|
/// `fn_name` is the name the function will be accessible from SQL.
|
|
|
|
/// `n_arg` is the number of arguments to the function. Use `-1` for a variable
|
|
|
|
/// number. If the function always returns the same value given the same
|
|
|
|
/// input, `deterministic` should be `true`.
|
|
|
|
///
|
|
|
|
/// The function will remain available until the connection is closed or
|
|
|
|
/// until it is explicitly removed via `remove_function`.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
2015-12-13 03:06:03 +08:00
|
|
|
/// # use rusqlite::{Connection, Result};
|
|
|
|
/// fn scalar_function_example(db: Connection) -> Result<()> {
|
2015-12-12 05:27:39 +08:00
|
|
|
/// try!(db.create_scalar_function("halve", 1, true, |ctx| {
|
2016-08-15 18:41:15 +08:00
|
|
|
/// let value = try!(ctx.get::<f64>(0));
|
2015-12-12 05:27:39 +08:00
|
|
|
/// Ok(value / 2f64)
|
|
|
|
/// }));
|
|
|
|
///
|
2016-01-02 19:13:37 +08:00
|
|
|
/// let six_halved: f64 = try!(db.query_row("SELECT halve(6)", &[], |r| r.get(0)));
|
2015-12-12 05:27:39 +08:00
|
|
|
/// assert_eq!(six_halved, 3f64);
|
|
|
|
/// Ok(())
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// # Failure
|
|
|
|
///
|
|
|
|
/// Will return Err if the function could not be attached to the connection.
|
2015-12-12 04:08:40 +08:00
|
|
|
pub fn create_scalar_function<F, T>(&self,
|
|
|
|
fn_name: &str,
|
|
|
|
n_arg: c_int,
|
|
|
|
deterministic: bool,
|
|
|
|
x_func: F)
|
2015-12-13 03:06:03 +08:00
|
|
|
-> Result<()>
|
|
|
|
where F: FnMut(&Context) -> Result<T>,
|
2016-05-26 12:06:53 +08:00
|
|
|
T: ToSql
|
2015-12-12 01:01:05 +08:00
|
|
|
{
|
2017-04-08 01:43:24 +08:00
|
|
|
self.db
|
|
|
|
.borrow_mut()
|
|
|
|
.create_scalar_function(fn_name, n_arg, deterministic, x_func)
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
2015-12-12 04:47:52 +08:00
|
|
|
|
2015-12-21 02:27:28 +08:00
|
|
|
/// Attach a user-defined aggregate function to this database connection.
|
|
|
|
///
|
|
|
|
/// # Failure
|
|
|
|
///
|
|
|
|
/// Will return Err if the function could not be attached to the connection.
|
2015-12-16 03:54:23 +08:00
|
|
|
pub fn create_aggregate_function<A, D, T>(&self,
|
|
|
|
fn_name: &str,
|
|
|
|
n_arg: c_int,
|
|
|
|
deterministic: bool,
|
|
|
|
aggr: D)
|
|
|
|
-> Result<()>
|
2015-12-16 03:57:32 +08:00
|
|
|
where D: Aggregate<A, T>,
|
2016-05-26 12:06:53 +08:00
|
|
|
T: ToSql
|
2015-12-16 03:54:23 +08:00
|
|
|
{
|
|
|
|
self.db
|
|
|
|
.borrow_mut()
|
|
|
|
.create_aggregate_function(fn_name, n_arg, deterministic, aggr)
|
|
|
|
}
|
|
|
|
|
2015-12-12 05:27:39 +08:00
|
|
|
/// Removes a user-defined function from this database connection.
|
|
|
|
///
|
|
|
|
/// `fn_name` and `n_arg` should match the name and number of arguments
|
2015-12-21 02:27:28 +08:00
|
|
|
/// given to `create_scalar_function` or `create_aggregate_function`.
|
2015-12-12 05:27:39 +08:00
|
|
|
///
|
|
|
|
/// # Failure
|
|
|
|
///
|
|
|
|
/// Will return Err if the function could not be removed.
|
2015-12-13 03:06:03 +08:00
|
|
|
pub fn remove_function(&self, fn_name: &str, n_arg: c_int) -> Result<()> {
|
2015-12-12 04:47:52 +08:00
|
|
|
self.db.borrow_mut().remove_function(fn_name, n_arg)
|
|
|
|
}
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
|
2015-12-13 02:50:12 +08:00
|
|
|
impl InnerConnection {
|
2015-12-12 04:08:40 +08:00
|
|
|
fn create_scalar_function<F, T>(&mut self,
|
|
|
|
fn_name: &str,
|
|
|
|
n_arg: c_int,
|
|
|
|
deterministic: bool,
|
|
|
|
x_func: F)
|
2015-12-13 03:06:03 +08:00
|
|
|
-> Result<()>
|
|
|
|
where F: FnMut(&Context) -> Result<T>,
|
2016-05-26 12:06:53 +08:00
|
|
|
T: ToSql
|
2015-12-12 01:01:05 +08:00
|
|
|
{
|
2015-12-13 21:40:51 +08:00
|
|
|
unsafe extern "C" fn call_boxed_closure<F, T>(ctx: *mut sqlite3_context,
|
|
|
|
argc: c_int,
|
|
|
|
argv: *mut *mut sqlite3_value)
|
2015-12-13 03:06:03 +08:00
|
|
|
where F: FnMut(&Context) -> Result<T>,
|
2016-05-26 12:06:53 +08:00
|
|
|
T: ToSql
|
2015-12-12 01:01:05 +08:00
|
|
|
{
|
2015-12-13 21:40:51 +08:00
|
|
|
let ctx = Context {
|
|
|
|
ctx: ctx,
|
|
|
|
args: slice::from_raw_parts(argv, argc as usize),
|
|
|
|
};
|
|
|
|
let boxed_f: *mut F = mem::transmute(ffi::sqlite3_user_data(ctx.ctx));
|
|
|
|
assert!(!boxed_f.is_null(), "Internal error - null function pointer");
|
2016-05-26 12:06:53 +08:00
|
|
|
|
|
|
|
let t = (*boxed_f)(&ctx);
|
|
|
|
let t = t.as_ref().map(|t| ToSql::to_sql(t));
|
|
|
|
|
|
|
|
match t {
|
|
|
|
Ok(Ok(ref value)) => set_result(ctx.ctx, value),
|
|
|
|
Ok(Err(err)) => report_error(ctx.ctx, &err),
|
|
|
|
Err(err) => report_error(ctx.ctx, err),
|
2015-12-12 01:01:05 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let boxed_f: *mut F = Box::into_raw(Box::new(x_func));
|
2015-08-09 15:52:53 +08:00
|
|
|
let c_name = try!(str_to_cstring(fn_name));
|
|
|
|
let mut flags = ffi::SQLITE_UTF8;
|
|
|
|
if deterministic {
|
|
|
|
flags |= ffi::SQLITE_DETERMINISTIC;
|
|
|
|
}
|
|
|
|
let r = unsafe {
|
2015-12-12 00:41:40 +08:00
|
|
|
ffi::sqlite3_create_function_v2(self.db(),
|
|
|
|
c_name.as_ptr(),
|
|
|
|
n_arg,
|
|
|
|
flags,
|
2015-12-12 01:01:05 +08:00
|
|
|
mem::transmute(boxed_f),
|
2015-12-12 04:08:40 +08:00
|
|
|
Some(call_boxed_closure::<F, T>),
|
2015-12-12 00:41:40 +08:00
|
|
|
None,
|
|
|
|
None,
|
2016-03-30 02:18:56 +08:00
|
|
|
Some(free_boxed_value::<F>))
|
2015-08-09 15:52:53 +08:00
|
|
|
};
|
|
|
|
self.decode_result(r)
|
|
|
|
}
|
2015-12-12 04:47:52 +08:00
|
|
|
|
2015-12-16 03:54:23 +08:00
|
|
|
fn create_aggregate_function<A, D, T>(&mut self,
|
|
|
|
fn_name: &str,
|
|
|
|
n_arg: c_int,
|
|
|
|
deterministic: bool,
|
|
|
|
aggr: D)
|
|
|
|
-> Result<()>
|
2015-12-16 03:57:32 +08:00
|
|
|
where D: Aggregate<A, T>,
|
2016-05-26 12:06:53 +08:00
|
|
|
T: ToSql
|
2015-12-16 03:54:23 +08:00
|
|
|
{
|
2016-02-01 23:48:30 +08:00
|
|
|
unsafe fn aggregate_context<A>(ctx: *mut sqlite3_context,
|
|
|
|
bytes: usize)
|
|
|
|
-> Option<*mut *mut A> {
|
|
|
|
let pac = ffi::sqlite3_aggregate_context(ctx, bytes as c_int) as *mut *mut A;
|
2016-01-08 01:33:32 +08:00
|
|
|
if pac.is_null() {
|
2016-01-08 04:14:24 +08:00
|
|
|
return None;
|
2016-01-08 01:33:32 +08:00
|
|
|
}
|
2016-01-08 04:14:24 +08:00
|
|
|
Some(pac)
|
2016-01-08 01:33:32 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
unsafe extern "C" fn call_boxed_step<A, D, T>(ctx: *mut sqlite3_context,
|
|
|
|
argc: c_int,
|
|
|
|
argv: *mut *mut sqlite3_value)
|
2015-12-16 03:57:32 +08:00
|
|
|
where D: Aggregate<A, T>,
|
2016-05-26 12:06:53 +08:00
|
|
|
T: ToSql
|
2015-12-16 03:54:23 +08:00
|
|
|
{
|
|
|
|
let boxed_aggr: *mut D = mem::transmute(ffi::sqlite3_user_data(ctx));
|
2015-12-16 03:57:32 +08:00
|
|
|
assert!(!boxed_aggr.is_null(),
|
|
|
|
"Internal error - null aggregate pointer");
|
2015-12-16 03:54:23 +08:00
|
|
|
|
2016-01-29 01:12:23 +08:00
|
|
|
let pac = match aggregate_context(ctx, ::std::mem::size_of::<*mut A>()) {
|
2016-01-08 04:14:24 +08:00
|
|
|
Some(pac) => pac,
|
|
|
|
None => {
|
2016-01-08 01:33:32 +08:00
|
|
|
ffi::sqlite3_result_error_nomem(ctx);
|
|
|
|
return;
|
|
|
|
}
|
2015-12-16 03:54:23 +08:00
|
|
|
};
|
|
|
|
|
2016-01-08 04:14:24 +08:00
|
|
|
if (*pac).is_null() {
|
|
|
|
*pac = Box::into_raw(Box::new((*boxed_aggr).init()));
|
|
|
|
}
|
|
|
|
|
2015-12-16 03:54:23 +08:00
|
|
|
let mut ctx = Context {
|
|
|
|
ctx: ctx,
|
|
|
|
args: slice::from_raw_parts(argv, argc as usize),
|
|
|
|
};
|
|
|
|
|
2016-01-08 04:14:24 +08:00
|
|
|
match (*boxed_aggr).step(&mut ctx, &mut **pac) {
|
|
|
|
Ok(_) => {}
|
2016-05-26 12:06:53 +08:00
|
|
|
Err(err) => report_error(ctx.ctx, &err),
|
2015-12-20 19:23:51 +08:00
|
|
|
};
|
2015-12-16 03:54:23 +08:00
|
|
|
}
|
2016-01-08 01:33:32 +08:00
|
|
|
|
2015-12-16 03:54:23 +08:00
|
|
|
unsafe extern "C" fn call_boxed_final<A, D, T>(ctx: *mut sqlite3_context)
|
2015-12-16 03:57:32 +08:00
|
|
|
where D: Aggregate<A, T>,
|
2016-05-26 12:06:53 +08:00
|
|
|
T: ToSql
|
2015-12-16 03:54:23 +08:00
|
|
|
{
|
|
|
|
let boxed_aggr: *mut D = mem::transmute(ffi::sqlite3_user_data(ctx));
|
2015-12-16 03:57:32 +08:00
|
|
|
assert!(!boxed_aggr.is_null(),
|
|
|
|
"Internal error - null aggregate pointer");
|
2015-12-16 03:54:23 +08:00
|
|
|
|
2016-01-29 01:12:23 +08:00
|
|
|
// Within the xFinal callback, it is customary to set N=0 in calls to
|
|
|
|
// sqlite3_aggregate_context(C,N) so that no pointless memory allocations occur.
|
|
|
|
let a: Option<A> = match aggregate_context(ctx, 0) {
|
2016-02-01 23:48:30 +08:00
|
|
|
Some(pac) => {
|
|
|
|
if (*pac).is_null() {
|
|
|
|
None
|
|
|
|
} else {
|
|
|
|
let a = Box::from_raw(*pac);
|
|
|
|
Some(*a)
|
|
|
|
}
|
|
|
|
}
|
2016-01-29 01:12:23 +08:00
|
|
|
None => None,
|
2016-01-08 04:14:24 +08:00
|
|
|
};
|
2015-12-16 03:54:23 +08:00
|
|
|
|
2016-05-26 12:06:53 +08:00
|
|
|
let t = (*boxed_aggr).finalize(a);
|
|
|
|
let t = t.as_ref().map(|t| ToSql::to_sql(t));
|
|
|
|
match t {
|
|
|
|
Ok(Ok(ref value)) => set_result(ctx, value),
|
|
|
|
Ok(Err(err)) => report_error(ctx, &err),
|
|
|
|
Err(err) => report_error(ctx, err),
|
|
|
|
}
|
2015-12-16 03:54:23 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
let boxed_aggr: *mut D = Box::into_raw(Box::new(aggr));
|
|
|
|
let c_name = try!(str_to_cstring(fn_name));
|
|
|
|
let mut flags = ffi::SQLITE_UTF8;
|
|
|
|
if deterministic {
|
|
|
|
flags |= ffi::SQLITE_DETERMINISTIC;
|
|
|
|
}
|
|
|
|
let r = unsafe {
|
|
|
|
ffi::sqlite3_create_function_v2(self.db(),
|
|
|
|
c_name.as_ptr(),
|
|
|
|
n_arg,
|
|
|
|
flags,
|
|
|
|
mem::transmute(boxed_aggr),
|
|
|
|
None,
|
2016-01-08 01:33:32 +08:00
|
|
|
Some(call_boxed_step::<A, D, T>),
|
2015-12-16 03:54:23 +08:00
|
|
|
Some(call_boxed_final::<A, D, T>),
|
2016-03-30 02:18:56 +08:00
|
|
|
Some(free_boxed_value::<D>))
|
2015-12-16 03:54:23 +08:00
|
|
|
};
|
|
|
|
self.decode_result(r)
|
|
|
|
}
|
|
|
|
|
2015-12-13 03:06:03 +08:00
|
|
|
fn remove_function(&mut self, fn_name: &str, n_arg: c_int) -> Result<()> {
|
2015-12-12 04:47:52 +08:00
|
|
|
let c_name = try!(str_to_cstring(fn_name));
|
|
|
|
let r = unsafe {
|
|
|
|
ffi::sqlite3_create_function_v2(self.db(),
|
|
|
|
c_name.as_ptr(),
|
|
|
|
n_arg,
|
|
|
|
ffi::SQLITE_UTF8,
|
|
|
|
ptr::null_mut(),
|
|
|
|
None,
|
|
|
|
None,
|
|
|
|
None,
|
|
|
|
None)
|
|
|
|
};
|
|
|
|
self.decode_result(r)
|
|
|
|
}
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
2015-08-09 19:06:23 +08:00
|
|
|
extern crate regex;
|
|
|
|
|
2015-12-12 04:35:59 +08:00
|
|
|
use std::collections::HashMap;
|
2017-02-17 00:17:24 +08:00
|
|
|
use std::os::raw::c_double;
|
2015-08-09 19:06:23 +08:00
|
|
|
use self::regex::Regex;
|
2016-03-30 02:18:56 +08:00
|
|
|
use std::f64::EPSILON;
|
2015-08-09 19:06:23 +08:00
|
|
|
|
2015-12-13 03:06:03 +08:00
|
|
|
use {Connection, Error, Result};
|
2015-12-20 19:23:51 +08:00
|
|
|
use functions::{Aggregate, Context};
|
2015-08-09 15:52:53 +08:00
|
|
|
|
2015-12-13 03:06:03 +08:00
|
|
|
fn half(ctx: &Context) -> Result<c_double> {
|
2015-12-12 03:46:28 +08:00
|
|
|
assert!(ctx.len() == 1, "called with unexpected number of arguments");
|
2015-12-12 04:08:40 +08:00
|
|
|
let value = try!(ctx.get::<c_double>(0));
|
|
|
|
Ok(value / 2f64)
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2015-12-12 01:01:05 +08:00
|
|
|
fn test_function_half() {
|
2015-12-13 02:50:12 +08:00
|
|
|
let db = Connection::open_in_memory().unwrap();
|
2015-12-12 01:01:05 +08:00
|
|
|
db.create_scalar_function("half", 1, true, half).unwrap();
|
2016-01-02 19:13:37 +08:00
|
|
|
let result: Result<f64> = db.query_row("SELECT half(6)", &[], |r| r.get(0));
|
2015-08-09 15:52:53 +08:00
|
|
|
|
2016-03-30 02:18:56 +08:00
|
|
|
assert!((3f64 - result.unwrap()).abs() < EPSILON);
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
2015-08-09 19:06:23 +08:00
|
|
|
|
2015-12-12 04:47:52 +08:00
|
|
|
#[test]
|
|
|
|
fn test_remove_function() {
|
2015-12-13 02:50:12 +08:00
|
|
|
let db = Connection::open_in_memory().unwrap();
|
2015-12-12 04:47:52 +08:00
|
|
|
db.create_scalar_function("half", 1, true, half).unwrap();
|
2016-01-02 19:13:37 +08:00
|
|
|
let result: Result<f64> = db.query_row("SELECT half(6)", &[], |r| r.get(0));
|
2016-03-30 02:18:56 +08:00
|
|
|
assert!((3f64 - result.unwrap()).abs() < EPSILON);
|
2015-12-12 04:47:52 +08:00
|
|
|
|
|
|
|
db.remove_function("half", 1).unwrap();
|
2016-01-02 19:13:37 +08:00
|
|
|
let result: Result<f64> = db.query_row("SELECT half(6)", &[], |r| r.get(0));
|
2015-12-12 04:47:52 +08:00
|
|
|
assert!(result.is_err());
|
|
|
|
}
|
|
|
|
|
2015-12-12 04:35:59 +08:00
|
|
|
// This implementation of a regexp scalar function uses SQLite's auxilliary data
|
|
|
|
// (https://www.sqlite.org/c3ref/get_auxdata.html) to avoid recompiling the regular
|
|
|
|
// expression multiple times within one query.
|
2015-12-13 03:06:03 +08:00
|
|
|
fn regexp_with_auxilliary(ctx: &Context) -> Result<bool> {
|
2015-12-12 03:46:28 +08:00
|
|
|
assert!(ctx.len() == 2, "called with unexpected number of arguments");
|
|
|
|
|
2015-12-12 02:54:08 +08:00
|
|
|
let saved_re: Option<&Regex> = unsafe { ctx.get_aux(0) };
|
|
|
|
let new_re = match saved_re {
|
2015-12-12 04:08:40 +08:00
|
|
|
None => {
|
|
|
|
let s = try!(ctx.get::<String>(0));
|
2015-12-13 13:54:08 +08:00
|
|
|
match Regex::new(&s) {
|
|
|
|
Ok(r) => Some(r),
|
|
|
|
Err(err) => return Err(Error::UserFunctionError(Box::new(err))),
|
|
|
|
}
|
2015-12-12 04:35:59 +08:00
|
|
|
}
|
2015-12-12 02:54:08 +08:00
|
|
|
Some(_) => None,
|
|
|
|
};
|
2015-08-09 19:06:23 +08:00
|
|
|
|
2015-12-12 04:08:40 +08:00
|
|
|
let is_match = {
|
2015-12-12 02:54:08 +08:00
|
|
|
let re = saved_re.unwrap_or_else(|| new_re.as_ref().unwrap());
|
|
|
|
|
2015-12-12 04:08:40 +08:00
|
|
|
let text = try!(ctx.get::<String>(1));
|
|
|
|
re.is_match(&text)
|
|
|
|
};
|
2015-08-09 19:06:23 +08:00
|
|
|
|
2015-12-12 02:54:08 +08:00
|
|
|
if let Some(re) = new_re {
|
|
|
|
ctx.set_aux(0, re);
|
2015-08-09 19:06:23 +08:00
|
|
|
}
|
2015-12-12 04:08:40 +08:00
|
|
|
|
|
|
|
Ok(is_match)
|
2015-08-09 19:06:23 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2015-12-12 03:46:28 +08:00
|
|
|
#[cfg_attr(rustfmt, rustfmt_skip)]
|
2015-12-12 04:35:59 +08:00
|
|
|
fn test_function_regexp_with_auxilliary() {
|
2015-12-13 02:50:12 +08:00
|
|
|
let db = Connection::open_in_memory().unwrap();
|
2015-12-12 04:35:59 +08:00
|
|
|
db.execute_batch("BEGIN;
|
|
|
|
CREATE TABLE foo (x string);
|
|
|
|
INSERT INTO foo VALUES ('lisa');
|
|
|
|
INSERT INTO foo VALUES ('lXsi');
|
|
|
|
INSERT INTO foo VALUES ('lisX');
|
|
|
|
END;").unwrap();
|
|
|
|
db.create_scalar_function("regexp", 2, true, regexp_with_auxilliary).unwrap();
|
|
|
|
|
2016-01-02 19:13:37 +08:00
|
|
|
let result: Result<bool> = db.query_row("SELECT regexp('l.s[aeiouy]', 'lisa')",
|
2015-12-12 04:35:59 +08:00
|
|
|
&[],
|
2016-01-02 19:13:37 +08:00
|
|
|
|r| r.get(0));
|
2015-12-12 04:35:59 +08:00
|
|
|
|
|
|
|
assert_eq!(true, result.unwrap());
|
|
|
|
|
2016-05-20 09:09:40 +08:00
|
|
|
let result: Result<i64> =
|
|
|
|
db.query_row("SELECT COUNT(*) FROM foo WHERE regexp('l.s[aeiouy]', x) == 1",
|
|
|
|
&[],
|
|
|
|
|r| r.get(0));
|
2015-12-12 04:35:59 +08:00
|
|
|
|
|
|
|
assert_eq!(2, result.unwrap());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
#[cfg_attr(rustfmt, rustfmt_skip)]
|
|
|
|
fn test_function_regexp_with_hashmap_cache() {
|
2015-12-13 02:50:12 +08:00
|
|
|
let db = Connection::open_in_memory().unwrap();
|
2015-12-12 03:46:28 +08:00
|
|
|
db.execute_batch("BEGIN;
|
|
|
|
CREATE TABLE foo (x string);
|
|
|
|
INSERT INTO foo VALUES ('lisa');
|
|
|
|
INSERT INTO foo VALUES ('lXsi');
|
|
|
|
INSERT INTO foo VALUES ('lisX');
|
|
|
|
END;").unwrap();
|
2015-12-12 04:35:59 +08:00
|
|
|
|
|
|
|
// This implementation of a regexp scalar function uses a captured HashMap
|
|
|
|
// to keep cached regular expressions around (even across multiple queries)
|
|
|
|
// until the function is removed.
|
|
|
|
let mut cached_regexes = HashMap::new();
|
|
|
|
db.create_scalar_function("regexp", 2, true, move |ctx| {
|
|
|
|
assert!(ctx.len() == 2, "called with unexpected number of arguments");
|
|
|
|
|
|
|
|
let regex_s = try!(ctx.get::<String>(0));
|
|
|
|
let entry = cached_regexes.entry(regex_s.clone());
|
|
|
|
let regex = {
|
|
|
|
use std::collections::hash_map::Entry::{Occupied, Vacant};
|
|
|
|
match entry {
|
|
|
|
Occupied(occ) => occ.into_mut(),
|
|
|
|
Vacant(vac) => {
|
2015-12-13 13:54:08 +08:00
|
|
|
match Regex::new(®ex_s) {
|
|
|
|
Ok(r) => vac.insert(r),
|
|
|
|
Err(err) => return Err(Error::UserFunctionError(Box::new(err))),
|
|
|
|
}
|
2015-12-12 04:35:59 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let text = try!(ctx.get::<String>(1));
|
|
|
|
Ok(regex.is_match(&text))
|
|
|
|
}).unwrap();
|
2015-12-12 03:46:28 +08:00
|
|
|
|
2016-01-02 19:13:37 +08:00
|
|
|
let result: Result<bool> = db.query_row("SELECT regexp('l.s[aeiouy]', 'lisa')",
|
2015-12-12 00:41:40 +08:00
|
|
|
&[],
|
2016-01-02 19:13:37 +08:00
|
|
|
|r| r.get(0));
|
2015-08-09 19:06:23 +08:00
|
|
|
|
|
|
|
assert_eq!(true, result.unwrap());
|
2015-12-12 03:46:28 +08:00
|
|
|
|
2016-05-20 09:09:40 +08:00
|
|
|
let result: Result<i64> =
|
|
|
|
db.query_row("SELECT COUNT(*) FROM foo WHERE regexp('l.s[aeiouy]', x) == 1",
|
|
|
|
&[],
|
|
|
|
|r| r.get(0));
|
2015-12-12 03:46:28 +08:00
|
|
|
|
|
|
|
assert_eq!(2, result.unwrap());
|
2015-08-09 19:06:23 +08:00
|
|
|
}
|
2015-12-12 23:44:08 +08:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_varargs_function() {
|
2015-12-13 02:50:12 +08:00
|
|
|
let db = Connection::open_in_memory().unwrap();
|
2015-12-12 23:44:08 +08:00
|
|
|
db.create_scalar_function("my_concat", -1, true, |ctx| {
|
2016-05-17 01:52:17 +08:00
|
|
|
let mut ret = String::new();
|
2015-12-12 23:44:08 +08:00
|
|
|
|
2016-05-17 01:52:17 +08:00
|
|
|
for idx in 0..ctx.len() {
|
|
|
|
let s = try!(ctx.get::<String>(idx));
|
|
|
|
ret.push_str(&s);
|
|
|
|
}
|
2015-12-12 23:44:08 +08:00
|
|
|
|
2016-05-17 01:52:17 +08:00
|
|
|
Ok(ret)
|
|
|
|
})
|
|
|
|
.unwrap();
|
2015-12-12 23:44:08 +08:00
|
|
|
|
2017-02-09 04:11:15 +08:00
|
|
|
for &(expected, query) in
|
|
|
|
&[("", "SELECT my_concat()"),
|
|
|
|
("onetwo", "SELECT my_concat('one', 'two')"),
|
|
|
|
("abc", "SELECT my_concat('a', 'b', 'c')")] {
|
2015-12-12 23:44:08 +08:00
|
|
|
let result: String = db.query_row(query, &[], |r| r.get(0)).unwrap();
|
|
|
|
assert_eq!(expected, result);
|
|
|
|
}
|
|
|
|
}
|
2015-12-20 19:23:51 +08:00
|
|
|
|
|
|
|
struct Sum;
|
2016-01-08 01:33:32 +08:00
|
|
|
struct Count;
|
|
|
|
|
2016-01-08 04:14:24 +08:00
|
|
|
impl Aggregate<i64, Option<i64>> for Sum {
|
|
|
|
fn init(&self) -> i64 {
|
|
|
|
0
|
2016-01-08 01:33:32 +08:00
|
|
|
}
|
|
|
|
|
2016-01-08 04:14:24 +08:00
|
|
|
fn step(&self, ctx: &mut Context, sum: &mut i64) -> Result<()> {
|
|
|
|
*sum += try!(ctx.get::<i64>(0));
|
2016-01-08 01:33:32 +08:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn finalize(&self, sum: Option<i64>) -> Result<Option<i64>> {
|
|
|
|
Ok(sum)
|
|
|
|
}
|
|
|
|
}
|
2015-12-20 19:23:51 +08:00
|
|
|
|
2016-01-08 01:33:32 +08:00
|
|
|
impl Aggregate<i64, i64> for Count {
|
2015-12-20 19:23:51 +08:00
|
|
|
fn init(&self) -> i64 {
|
|
|
|
0
|
|
|
|
}
|
|
|
|
|
2016-01-08 01:33:32 +08:00
|
|
|
fn step(&self, _ctx: &mut Context, sum: &mut i64) -> Result<()> {
|
|
|
|
*sum += 1;
|
2015-12-20 19:23:51 +08:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2016-01-08 04:14:24 +08:00
|
|
|
fn finalize(&self, sum: Option<i64>) -> Result<i64> {
|
|
|
|
Ok(sum.unwrap_or(0))
|
2015-12-20 19:23:51 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_sum() {
|
|
|
|
let db = Connection::open_in_memory().unwrap();
|
2017-04-08 01:43:24 +08:00
|
|
|
db.create_aggregate_function("my_sum", 1, true, Sum)
|
|
|
|
.unwrap();
|
2016-01-08 01:33:32 +08:00
|
|
|
|
|
|
|
// sum should return NULL when given no columns (contrast with count below)
|
2015-12-20 19:23:51 +08:00
|
|
|
let no_result = "SELECT my_sum(i) FROM (SELECT 2 AS i WHERE 1 <> 1)";
|
2017-04-08 01:43:24 +08:00
|
|
|
let result: Option<i64> = db.query_row(no_result, &[], |r| r.get(0)).unwrap();
|
2015-12-20 19:23:51 +08:00
|
|
|
assert!(result.is_none());
|
|
|
|
|
|
|
|
let single_sum = "SELECT my_sum(i) FROM (SELECT 2 AS i UNION ALL SELECT 2)";
|
2017-04-08 01:43:24 +08:00
|
|
|
let result: i64 = db.query_row(single_sum, &[], |r| r.get(0)).unwrap();
|
2015-12-20 19:23:51 +08:00
|
|
|
assert_eq!(4, result);
|
|
|
|
|
2015-12-21 02:27:28 +08:00
|
|
|
let dual_sum = "SELECT my_sum(i), my_sum(j) FROM (SELECT 2 AS i, 1 AS j UNION ALL SELECT \
|
|
|
|
2, 1)";
|
|
|
|
let result: (i64, i64) = db.query_row(dual_sum, &[], |r| (r.get(0), r.get(1)))
|
2016-05-17 01:52:17 +08:00
|
|
|
.unwrap();
|
2015-12-20 19:23:51 +08:00
|
|
|
assert_eq!((4, 2), result);
|
|
|
|
}
|
2016-01-08 01:33:32 +08:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_count() {
|
|
|
|
let db = Connection::open_in_memory().unwrap();
|
2017-04-08 01:43:24 +08:00
|
|
|
db.create_aggregate_function("my_count", -1, true, Count)
|
|
|
|
.unwrap();
|
2016-01-08 01:33:32 +08:00
|
|
|
|
|
|
|
// count should return 0 when given no columns (contrast with sum above)
|
|
|
|
let no_result = "SELECT my_count(i) FROM (SELECT 2 AS i WHERE 1 <> 1)";
|
|
|
|
let result: i64 = db.query_row(no_result, &[], |r| r.get(0)).unwrap();
|
|
|
|
assert_eq!(result, 0);
|
|
|
|
|
|
|
|
let single_sum = "SELECT my_count(i) FROM (SELECT 2 AS i UNION ALL SELECT 2)";
|
2017-04-08 01:43:24 +08:00
|
|
|
let result: i64 = db.query_row(single_sum, &[], |r| r.get(0)).unwrap();
|
2016-01-08 01:33:32 +08:00
|
|
|
assert_eq!(2, result);
|
|
|
|
}
|
2015-12-07 04:33:21 +08:00
|
|
|
}
|