Module rusqlite::functions

source ·
Available on crate feature functions only.
Expand description

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 Auxiliary 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};
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')", [], |row| {
            row.get(0)
        })?;

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

Structs

Traits

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