[][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};
use std::sync::Arc;
type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;

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 regexp: Arc<Regex> = ctx
                .get_or_create_aux(0, |vr| -> Result<_, BoxError> {
                    Ok(Regex::new(vr.as_str()?)?)
                })?;
            let is_match = {
                let text = ctx
                    .get_raw(1)
                    .as_str()
                    .map_err(|e| Error::UserFunctionError(e.into()))?;

                regexp.is_match(text)
            };

            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 and Function Flags 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.