[][src]Module rusqlite::functions

feature = "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::functions::FunctionFlags;
use rusqlite::{Connection, Error, Result, NO_PARAMS};

fn add_regexp_function(db: &Connection) -> Result<()> {
    db.create_scalar_function(
        "regexp",
        2,
        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,
        move |ctx| {
            assert_eq!(ctx.len(), 2, "called with unexpected number of arguments");

            let saved_re: Option<&Regex> = ctx.get_aux(0)?;
            let new_re = match saved_re {
                None => {
                    let s = ctx.get::<String>(0)?;
                    match Regex::new(&s) {
                        Ok(r) => Some(r),
                        Err(err) => return Err(Error::UserFunctionError(Box::new(err))),
                    }
                }
                Some(_) => None,
            };

            let is_match = {
                let re = saved_re.unwrap_or_else(|| new_re.as_ref().unwrap());

                let text = ctx
                    .get_raw(1)
                    .as_str()
                    .map_err(|e| Error::UserFunctionError(e.into()))?;

                re.is_match(text)
            };

            if let Some(re) = new_re {
                ctx.set_aux(0, re);
            }

            Ok(is_match)
        },
    )
}

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

feature = "functions" Context is a wrapper for the SQLite function evaluation context.

FunctionFlags

Function Flags. See sqlite3_create_function for details.

Traits

Aggregate

feature = "functions" Aggregate is the callback interface for user-defined aggregate function.

WindowAggregate

feature = "window" WindowAggregate is the callback interface for user-defined aggregate window function.