From fb2356b17a38f2d6ac575600745327edcfc07230 Mon Sep 17 00:00:00 2001 From: Tobie Morgan Hitchcock Date: Sun, 26 Mar 2023 08:53:19 +0100 Subject: [PATCH] Add SQL `array::add()` function for adding unique items Related to #1690 --- lib/src/fnc/array.rs | 20 ++++++++++++++++++++ lib/src/fnc/mod.rs | 1 + lib/src/sql/function.rs | 1 + 3 files changed, 22 insertions(+) diff --git a/lib/src/fnc/array.rs b/lib/src/fnc/array.rs index 8d68d79f..0b2ead0d 100644 --- a/lib/src/fnc/array.rs +++ b/lib/src/fnc/array.rs @@ -9,6 +9,26 @@ use crate::sql::array::Union; use crate::sql::array::Uniq; use crate::sql::value::Value; +pub fn add((array, value): (Value, Value)) -> Result { + match (array, value) { + (Value::Array(mut arr), Value::Array(other)) => { + for v in other.0 { + if !arr.0.iter().any(|x| *x == v) { + arr.0.push(v) + } + } + Ok(arr.into()) + } + (Value::Array(mut arr), value) => { + if !arr.0.iter().any(|x| *x == value) { + arr.0.push(value) + } + Ok(arr.into()) + } + _ => Ok(Value::None), + } +} + pub fn all((arg,): (Value,)) -> Result { match arg { Value::Array(v) => Ok(v.iter().all(Value::is_truthy).into()), diff --git a/lib/src/fnc/mod.rs b/lib/src/fnc/mod.rs index ea8ec2af..0fdd6160 100644 --- a/lib/src/fnc/mod.rs +++ b/lib/src/fnc/mod.rs @@ -66,6 +66,7 @@ pub fn synchronous(ctx: &Context<'_>, name: &str, args: Vec) -> Result array::add, "array::all" => array::all, "array::any" => array::any, "array::append" => array::append, diff --git a/lib/src/sql/function.rs b/lib/src/sql/function.rs index 7965a765..4cdfe86f 100644 --- a/lib/src/sql/function.rs +++ b/lib/src/sql/function.rs @@ -303,6 +303,7 @@ fn function_names(i: &str) -> IResult<&str, &str> { fn function_array(i: &str) -> IResult<&str, &str> { alt(( alt(( + tag("array::add"), tag("array::all"), tag("array::any"), tag("array::append"),