sqlfuncs 0.6.0

Scalar functions for use in SQLite through rusqlite.
Documentation
//! Functions for transcoding data.

use rusqlite::{Connection, Error, functions::FunctionFlags};

/// Decode a hex encoded string
///
/// The SQL function `dehex()` takes a single argument:
/// 1. The input hex string.
///
/// Its output will be a blob of the decoded data.
///
/// ```
/// use rusqlite::Connection;
/// use sqlfuncs::transcode::dehex;
///
/// let conn = Connection::open_in_memory().unwrap();
/// dehex(&conn).unwrap();
/// let instr = "48656c6c6f20776f726c6421";
/// let buf: Vec<u8> = conn.query_row_and_then(
///   "SELECT dehex(?);", [instr], |row| {
///     row.get(0)
///   }).unwrap();
/// assert_eq!(buf, "Hello world!".to_owned().into_bytes());
/// ```
///
/// ## SQLite function properties
/// - Deterministic
/// - Innocuous
/// - UTF8
#[allow(clippy::missing_errors_doc)]
pub fn dehex(db: &Connection) -> Result<(), Error> {
  db.create_scalar_function(
    "dehex",
    1,
    FunctionFlags::SQLITE_UTF8
      | FunctionFlags::SQLITE_INNOCUOUS
      | FunctionFlags::SQLITE_DETERMINISTIC,
    move |ctx| {
      let hex_input = ctx.get::<String>(0)?;
      let buf = hex::decode(hex_input)
        .map_err(|_| Error::UserFunctionError("Invalid hex".into()))?;
      Ok(buf)
    }
  )
}

// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :