[][src]Module rusqlite::functions

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.

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

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 = 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 = ctx.get::<String>(1)?;
        Ok(regex.is_match(&text))
    })
}

fn main() -> Result<()> {
    let db = Connection::open_in_memory()?;
    add_regexp_function(&db)?;

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

    assert!(is_match);
    Ok(())
}

Structs

Context

Context is a wrapper for the SQLite function evaluation context.

Traits

Aggregate

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