Module rusqlite::functions [] [src]

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 interface to avoid recompiling regular expressions, see the unit tests for this module.

extern crate libsqlite3_sys;
extern crate rusqlite;
extern crate regex;

use rusqlite::{Connection, Error, Result};
use std::collections::HashMap;
use regex::Regex;

fn add_regexp_function(db: &Connection) -> Result<()> {
    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) => {
                    match Regex::new(&regex_s) {
                        Ok(r) => vac.insert(r),
                        Err(err) => return Err(Error::UserFunctionError(Box::new(err))),
                    }
                }
            }
        };

        let text = try!(ctx.get::<String>(1));
        Ok(regex.is_match(&text))
    })
}

fn main() {
    let db = Connection::open_in_memory().unwrap();
    add_regexp_function(&db).unwrap();

    let is_match: bool = db.query_row("SELECT regexp('[aeiou]*', 'aaaaeeeiii')", &[],
                                |row| row.get(0)).unwrap();

    assert!(is_match);
}

Structs

Context

Context is a wrapper for the SQLite function evaluation context.

Traits

Aggregate

Aggregate is the callback interface for user-defined aggregate function.