2015-08-09 15:52:53 +08:00
|
|
|
//! Create or redefine SQL functions
|
2015-12-12 00:41:40 +08:00
|
|
|
use std::ffi::CStr;
|
2015-08-09 15:52:53 +08:00
|
|
|
use std::mem;
|
|
|
|
use std::str;
|
2015-12-12 01:01:05 +08:00
|
|
|
use libc::{c_int, c_double, c_char, c_void};
|
2015-08-09 15:52:53 +08:00
|
|
|
|
|
|
|
use ffi;
|
2015-12-12 00:41:40 +08:00
|
|
|
pub use ffi::sqlite3_context;
|
|
|
|
pub use ffi::sqlite3_value;
|
|
|
|
pub use ffi::sqlite3_value_type;
|
|
|
|
pub use ffi::sqlite3_value_numeric_type;
|
2015-08-09 15:52:53 +08:00
|
|
|
|
|
|
|
use types::Null;
|
|
|
|
|
|
|
|
use {SqliteResult, SqliteError, SqliteConnection, str_to_cstring, InnerSqliteConnection};
|
|
|
|
|
|
|
|
/// A trait for types that can be converted into the result of an SQL function.
|
|
|
|
pub trait ToResult {
|
2015-08-09 19:06:23 +08:00
|
|
|
unsafe fn set_result(&self, ctx: *mut sqlite3_context);
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
macro_rules! raw_to_impl(
|
|
|
|
($t:ty, $f:ident) => (
|
|
|
|
impl ToResult for $t {
|
2015-08-09 19:06:23 +08:00
|
|
|
unsafe fn set_result(&self, ctx: *mut sqlite3_context) {
|
2015-08-09 15:52:53 +08:00
|
|
|
ffi::$f(ctx, *self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
);
|
|
|
|
|
|
|
|
raw_to_impl!(c_int, sqlite3_result_int);
|
|
|
|
raw_to_impl!(i64, sqlite3_result_int64);
|
|
|
|
raw_to_impl!(c_double, sqlite3_result_double);
|
|
|
|
|
2015-08-09 19:06:23 +08:00
|
|
|
impl<'a> ToResult for bool {
|
|
|
|
unsafe fn set_result(&self, ctx: *mut sqlite3_context) {
|
|
|
|
match *self {
|
|
|
|
true => ffi::sqlite3_result_int(ctx, 1),
|
|
|
|
_ => ffi::sqlite3_result_int(ctx, 0),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-08-09 15:52:53 +08:00
|
|
|
|
|
|
|
impl<'a> ToResult for &'a str {
|
2015-08-09 19:06:23 +08:00
|
|
|
unsafe fn set_result(&self, ctx: *mut sqlite3_context) {
|
2015-08-09 15:52:53 +08:00
|
|
|
let length = self.len();
|
|
|
|
if length > ::std::i32::MAX as usize {
|
|
|
|
ffi::sqlite3_result_error_toobig(ctx);
|
2015-12-12 00:41:40 +08:00
|
|
|
return;
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
match str_to_cstring(self) {
|
2015-12-12 00:41:40 +08:00
|
|
|
Ok(c_str) => {
|
|
|
|
ffi::sqlite3_result_text(ctx,
|
|
|
|
c_str.as_ptr(),
|
|
|
|
length as c_int,
|
|
|
|
ffi::SQLITE_TRANSIENT())
|
|
|
|
}
|
|
|
|
Err(_) => ffi::sqlite3_result_error_code(ctx, ffi::SQLITE_MISUSE), // TODO sqlite3_result_error
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ToResult for String {
|
2015-08-09 19:06:23 +08:00
|
|
|
unsafe fn set_result(&self, ctx: *mut sqlite3_context) {
|
|
|
|
(&self[..]).set_result(ctx)
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> ToResult for &'a [u8] {
|
2015-08-09 19:06:23 +08:00
|
|
|
unsafe fn set_result(&self, ctx: *mut sqlite3_context) {
|
2015-08-09 15:52:53 +08:00
|
|
|
if self.len() > ::std::i32::MAX as usize {
|
|
|
|
ffi::sqlite3_result_error_toobig(ctx);
|
2015-12-12 00:41:40 +08:00
|
|
|
return;
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
2015-12-12 00:41:40 +08:00
|
|
|
ffi::sqlite3_result_blob(ctx,
|
|
|
|
mem::transmute(self.as_ptr()),
|
|
|
|
self.len() as c_int,
|
|
|
|
ffi::SQLITE_TRANSIENT())
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ToResult for Vec<u8> {
|
2015-08-09 19:06:23 +08:00
|
|
|
unsafe fn set_result(&self, ctx: *mut sqlite3_context) {
|
|
|
|
(&self[..]).set_result(ctx)
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: ToResult> ToResult for Option<T> {
|
2015-08-09 19:06:23 +08:00
|
|
|
unsafe fn set_result(&self, ctx: *mut sqlite3_context) {
|
2015-08-09 15:52:53 +08:00
|
|
|
match *self {
|
|
|
|
None => ffi::sqlite3_result_null(ctx),
|
2015-08-09 19:06:23 +08:00
|
|
|
Some(ref t) => t.set_result(ctx),
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ToResult for Null {
|
2015-08-09 19:06:23 +08:00
|
|
|
unsafe fn set_result(&self, ctx: *mut sqlite3_context) {
|
2015-08-09 15:52:53 +08:00
|
|
|
ffi::sqlite3_result_null(ctx)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// sqlite3_result_error_code, c_int
|
|
|
|
// sqlite3_result_error_nomem
|
|
|
|
// sqlite3_result_error_toobig
|
|
|
|
// sqlite3_result_error, *const c_char, c_int
|
|
|
|
// sqlite3_result_zeroblob
|
|
|
|
// sqlite3_result_value
|
|
|
|
|
|
|
|
/// A trait for types that can be created from a SQLite function parameter value.
|
2015-12-07 04:33:21 +08:00
|
|
|
pub trait FromValue: Sized {
|
2015-08-09 15:52:53 +08:00
|
|
|
unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult<Self>;
|
|
|
|
|
|
|
|
/// FromValue types can implement this method and use sqlite3_value_type to check that
|
|
|
|
/// the type reported by SQLite matches a type suitable for Self. This method is used
|
|
|
|
/// by `???` to confirm that the parameter contains a valid type before
|
|
|
|
/// attempting to retrieve the value.
|
|
|
|
unsafe fn parameter_has_valid_sqlite_type(_: *mut sqlite3_value) -> bool {
|
|
|
|
true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
macro_rules! raw_from_impl(
|
|
|
|
($t:ty, $f:ident, $c:expr) => (
|
|
|
|
impl FromValue for $t {
|
|
|
|
unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult<$t> {
|
|
|
|
Ok(ffi::$f(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
unsafe fn parameter_has_valid_sqlite_type(v: *mut sqlite3_value) -> bool {
|
|
|
|
sqlite3_value_numeric_type(v) == $c
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
);
|
|
|
|
|
|
|
|
raw_from_impl!(c_int, sqlite3_value_int, ffi::SQLITE_INTEGER);
|
|
|
|
raw_from_impl!(i64, sqlite3_value_int64, ffi::SQLITE_INTEGER);
|
|
|
|
|
2015-08-09 19:06:23 +08:00
|
|
|
impl FromValue for bool {
|
|
|
|
unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult<bool> {
|
|
|
|
match ffi::sqlite3_value_int(v) {
|
|
|
|
0 => Ok(false),
|
|
|
|
_ => Ok(true),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
unsafe fn parameter_has_valid_sqlite_type(v: *mut sqlite3_value) -> bool {
|
|
|
|
sqlite3_value_numeric_type(v) == ffi::SQLITE_INTEGER
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-08-09 15:52:53 +08:00
|
|
|
impl FromValue for c_double {
|
|
|
|
unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult<c_double> {
|
|
|
|
Ok(ffi::sqlite3_value_double(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
unsafe fn parameter_has_valid_sqlite_type(v: *mut sqlite3_value) -> bool {
|
2015-12-12 00:41:40 +08:00
|
|
|
sqlite3_value_numeric_type(v) == ffi::SQLITE_FLOAT ||
|
|
|
|
sqlite3_value_numeric_type(v) == ffi::SQLITE_INTEGER
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FromValue for String {
|
|
|
|
unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult<String> {
|
|
|
|
let c_text = ffi::sqlite3_value_text(v);
|
|
|
|
if c_text.is_null() {
|
|
|
|
Ok("".to_string())
|
|
|
|
} else {
|
|
|
|
let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes();
|
|
|
|
let utf8_str = str::from_utf8(c_slice);
|
2015-12-12 00:41:40 +08:00
|
|
|
utf8_str.map(|s| s.to_string())
|
|
|
|
.map_err(|e| {
|
|
|
|
SqliteError {
|
|
|
|
code: 0,
|
|
|
|
message: e.to_string(),
|
|
|
|
}
|
|
|
|
})
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
unsafe fn parameter_has_valid_sqlite_type(v: *mut sqlite3_value) -> bool {
|
|
|
|
sqlite3_value_type(v) == ffi::SQLITE_TEXT
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FromValue for Vec<u8> {
|
|
|
|
unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult<Vec<u8>> {
|
|
|
|
use std::slice::from_raw_parts;
|
|
|
|
let c_blob = ffi::sqlite3_value_blob(v);
|
|
|
|
let len = ffi::sqlite3_value_bytes(v);
|
|
|
|
|
2015-12-12 00:41:40 +08:00
|
|
|
assert!(len >= 0,
|
|
|
|
"unexpected negative return from sqlite3_value_bytes");
|
2015-08-09 15:52:53 +08:00
|
|
|
let len = len as usize;
|
|
|
|
|
|
|
|
Ok(from_raw_parts(mem::transmute(c_blob), len).to_vec())
|
|
|
|
}
|
|
|
|
|
|
|
|
unsafe fn parameter_has_valid_sqlite_type(v: *mut sqlite3_value) -> bool {
|
|
|
|
sqlite3_value_type(v) == ffi::SQLITE_BLOB
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: FromValue> FromValue for Option<T> {
|
|
|
|
unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult<Option<T>> {
|
|
|
|
if sqlite3_value_type(v) == ffi::SQLITE_NULL {
|
|
|
|
Ok(None)
|
|
|
|
} else {
|
|
|
|
FromValue::parameter_value(v).map(|t| Some(t))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
unsafe fn parameter_has_valid_sqlite_type(v: *mut sqlite3_value) -> bool {
|
2015-12-12 00:41:40 +08:00
|
|
|
sqlite3_value_type(v) == ffi::SQLITE_NULL || T::parameter_has_valid_sqlite_type(v)
|
2015-08-09 15:52:53 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// sqlite3_user_data
|
|
|
|
// sqlite3_get_auxdata
|
|
|
|
// sqlite3_set_auxdata
|
|
|
|
|
2015-12-12 01:01:05 +08:00
|
|
|
pub trait ScalarFunction: FnMut(*mut sqlite3_context, c_int, *mut *mut sqlite3_value) {}
|
|
|
|
impl<F: FnMut(*mut sqlite3_context, c_int, *mut *mut sqlite3_value)> ScalarFunction for F {}
|
2015-08-09 15:52:53 +08:00
|
|
|
|
|
|
|
impl SqliteConnection {
|
2015-12-12 01:01:05 +08:00
|
|
|
pub fn create_scalar_function<F>(&self,
|
|
|
|
fn_name: &str,
|
|
|
|
n_arg: c_int,
|
|
|
|
deterministic: bool,
|
|
|
|
x_func: F)
|
|
|
|
-> SqliteResult<()>
|
|
|
|
where F: ScalarFunction
|
|
|
|
{
|
2015-08-09 15:52:53 +08:00
|
|
|
self.db.borrow_mut().create_scalar_function(fn_name, n_arg, deterministic, x_func)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl InnerSqliteConnection {
|
2015-12-12 01:01:05 +08:00
|
|
|
pub fn create_scalar_function<F>(&mut self,
|
|
|
|
fn_name: &str,
|
|
|
|
n_arg: c_int,
|
|
|
|
deterministic: bool,
|
|
|
|
x_func: F)
|
|
|
|
-> SqliteResult<()>
|
|
|
|
where F: ScalarFunction
|
|
|
|
{
|
|
|
|
extern "C" fn free_boxed_closure<F>(p: *mut c_void)
|
|
|
|
where F: ScalarFunction
|
|
|
|
{
|
|
|
|
let _: Box<F> = unsafe { Box::from_raw(mem::transmute(p)) };
|
|
|
|
}
|
|
|
|
|
|
|
|
extern "C" fn call_boxed_closure<F>(ctx: *mut sqlite3_context,
|
|
|
|
argc: c_int,
|
|
|
|
argv: *mut *mut sqlite3_value)
|
|
|
|
where F: ScalarFunction
|
|
|
|
{
|
|
|
|
unsafe {
|
|
|
|
let boxed_f: *mut F = mem::transmute(ffi::sqlite3_user_data(ctx));
|
|
|
|
assert!(!boxed_f.is_null(), "Internal error - null function pointer");
|
|
|
|
(*boxed_f)(ctx, argc, argv);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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),
|
|
|
|
Some(call_boxed_closure::<F>),
|
2015-12-12 00:41:40 +08:00
|
|
|
None,
|
|
|
|
None,
|
2015-12-12 01:01:05 +08:00
|
|
|
Some(free_boxed_closure::<F>))
|
2015-08-09 15:52:53 +08:00
|
|
|
};
|
|
|
|
self.decode_result(r)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
2015-08-09 19:06:23 +08:00
|
|
|
extern crate regex;
|
|
|
|
|
|
|
|
use std::boxed::Box;
|
2015-12-12 00:41:40 +08:00
|
|
|
use std::ffi::CString;
|
2015-08-09 19:06:23 +08:00
|
|
|
use std::mem;
|
|
|
|
use libc::{c_int, c_double, c_void};
|
|
|
|
use self::regex::Regex;
|
|
|
|
|
2015-08-09 15:52:53 +08:00
|
|
|
use SqliteConnection;
|
|
|
|
use ffi;
|
2015-12-12 00:41:40 +08:00
|
|
|
use ffi::sqlite3_context;
|
|
|
|
use ffi::sqlite3_value;
|
|
|
|
use functions::{FromValue, ToResult};
|
2015-08-09 15:52:53 +08:00
|
|
|
|
2015-12-12 01:01:05 +08:00
|
|
|
fn half(ctx: *mut sqlite3_context, _: c_int, argv: *mut *mut sqlite3_value) {
|
2015-08-09 15:52:53 +08:00
|
|
|
unsafe {
|
|
|
|
let arg = *argv.offset(0);
|
|
|
|
if c_double::parameter_has_valid_sqlite_type(arg) {
|
|
|
|
let value = c_double::parameter_value(arg).unwrap() / 2f64;
|
2015-08-09 19:06:23 +08:00
|
|
|
value.set_result(ctx);
|
2015-08-09 15:52:53 +08:00
|
|
|
} else {
|
|
|
|
ffi::sqlite3_result_error_code(ctx, ffi::SQLITE_MISMATCH);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2015-12-12 01:01:05 +08:00
|
|
|
fn test_function_half() {
|
2015-08-09 15:52:53 +08:00
|
|
|
let db = SqliteConnection::open_in_memory().unwrap();
|
2015-12-12 01:01:05 +08:00
|
|
|
db.create_scalar_function("half", 1, true, half).unwrap();
|
2015-12-12 00:41:40 +08:00
|
|
|
let result = db.query_row("SELECT half(6)", &[], |r| r.get::<f64>(0));
|
2015-08-09 15:52:53 +08:00
|
|
|
|
|
|
|
assert_eq!(3f64, result.unwrap());
|
|
|
|
}
|
2015-08-09 19:06:23 +08:00
|
|
|
|
|
|
|
extern "C" fn regexp_free(raw: *mut c_void) {
|
2015-12-12 00:41:40 +08:00
|
|
|
let _: Box<Regex> = unsafe { Box::from_raw(mem::transmute(raw)) };
|
2015-08-09 19:06:23 +08:00
|
|
|
}
|
|
|
|
|
2015-12-12 01:01:05 +08:00
|
|
|
fn regexp(ctx: *mut sqlite3_context, _: c_int, argv: *mut *mut sqlite3_value) {
|
2015-08-09 19:06:23 +08:00
|
|
|
unsafe {
|
|
|
|
let mut re_ptr = ffi::sqlite3_get_auxdata(ctx, 0) as *const Regex;
|
2015-12-12 00:40:53 +08:00
|
|
|
let need_re = re_ptr.is_null();
|
|
|
|
if need_re {
|
2015-08-09 19:06:23 +08:00
|
|
|
let raw = String::parameter_value(*argv.offset(0));
|
|
|
|
if raw.is_err() {
|
|
|
|
let msg = CString::new(format!("{}", raw.unwrap_err())).unwrap();
|
|
|
|
ffi::sqlite3_result_error(ctx, msg.as_ptr(), -1);
|
2015-12-12 00:41:40 +08:00
|
|
|
return;
|
2015-08-09 19:06:23 +08:00
|
|
|
}
|
|
|
|
let comp = Regex::new(raw.unwrap().as_ref());
|
|
|
|
if comp.is_err() {
|
|
|
|
let msg = CString::new(format!("{}", comp.unwrap_err())).unwrap();
|
|
|
|
ffi::sqlite3_result_error(ctx, msg.as_ptr(), -1);
|
2015-12-12 00:41:40 +08:00
|
|
|
return;
|
2015-08-09 19:06:23 +08:00
|
|
|
}
|
2015-12-12 00:40:53 +08:00
|
|
|
let re = Box::new(comp.unwrap());
|
|
|
|
re_ptr = Box::into_raw(re);
|
2015-08-09 19:06:23 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
let text = String::parameter_value(*argv.offset(1));
|
|
|
|
if text.is_ok() {
|
|
|
|
let text = text.unwrap();
|
|
|
|
(*re_ptr).is_match(text.as_ref()).set_result(ctx);
|
|
|
|
}
|
|
|
|
|
2015-12-12 00:40:53 +08:00
|
|
|
if need_re {
|
|
|
|
ffi::sqlite3_set_auxdata(ctx, 0, mem::transmute(re_ptr), Some(regexp_free));
|
2015-08-09 19:06:23 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2015-12-12 01:01:05 +08:00
|
|
|
fn test_function_regexp() {
|
2015-08-09 19:06:23 +08:00
|
|
|
let db = SqliteConnection::open_in_memory().unwrap();
|
2015-12-12 01:01:05 +08:00
|
|
|
db.create_scalar_function("regexp", 2, true, regexp).unwrap();
|
2015-08-09 19:06:23 +08:00
|
|
|
let result = db.query_row("SELECT regexp('l.s[aeiouy]', 'lisa')",
|
2015-12-12 00:41:40 +08:00
|
|
|
&[],
|
|
|
|
|r| r.get::<bool>(0));
|
2015-08-09 19:06:23 +08:00
|
|
|
|
|
|
|
assert_eq!(true, result.unwrap());
|
|
|
|
}
|
2015-12-07 04:33:21 +08:00
|
|
|
}
|