Skip to content

Commit

Permalink
add user defined functions: md5, sqrt and stddev
Browse files Browse the repository at this point in the history
  • Loading branch information
hderms committed Apr 27, 2021
1 parent 5db9c4c commit 424a987
Show file tree
Hide file tree
Showing 6 changed files with 316 additions and 6 deletions.
218 changes: 215 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ edition = "2018"
debug = true

[dependencies]
rusqlite = "0.25.1"
rusqlite = {version = "0.25.1", features = ["functions"]}
csv="1.1"
sqlparser = "0.9.0"
uuid={version = "0.8", features = ["v4"]}
log = "0.4.14"
simple_logger="1.11.0"
clap = "3.0.0-beta.2"
md5 = "0.7.0"
statistical = "1.0.0"

[dev-dependencies]
assert_cmd="0.10"
Expand Down
42 changes: 42 additions & 0 deletions src/db/functions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use rusqlite::functions::{Context, Aggregate};
use rusqlite::Result;
use statistical::population_standard_deviation;

pub(crate) fn calculate_md5(ctx: &Context) -> Result<String> {
assert_eq!(ctx.len(), 1, "called with unexpected number of arguments");
let str = ctx.get_raw(0).as_str()?;
let hash = md5::compute(str);
Ok(format!("{:x}", hash))
}

pub(crate) fn calculate_sqrt(ctx: &Context) -> Result<f64> {
assert_eq!(ctx.len(), 1, "called with unexpected number of arguments");
let arg = ctx.get_raw(0);
if let Ok(f64) = arg.as_f64() {
Ok(f64.sqrt())
} else {
let i64 = arg.as_i64()?;
Ok((i64 as f64).sqrt())
}
}
pub struct Stddev;

impl Aggregate<Vec<f64>, Option<f64>> for Stddev {
fn init(&self, _: &mut Context<'_>) -> Result<Vec<f64>> {
Ok(vec!())
}

fn step(&self, ctx: &mut Context<'_>, stdev: &mut Vec<f64>) -> Result<()> {
let next = ctx.get::<f64>(0)?;
stdev.push(next);
Ok(())
}

fn finalize(&self, _: &mut Context<'_>, numbers: Option<Vec<f64>>) -> Result<Option<f64>> {
println!("{:?}", &numbers);
let stddev = numbers.map(|n| population_standard_deviation(&n, None));
println!("{:?}", stddev);
Ok(stddev)
}
}

Loading

0 comments on commit 424a987

Please sign in to comment.