Skip to content

Commit 6e9b678

Browse files
feat: implement json_get_array udf v2 (#87)
Co-authored-by: David Hewitt <[email protected]>
1 parent 14a4bba commit 6e9b678

File tree

4 files changed

+203
-1
lines changed

4 files changed

+203
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ SELECT id, json_col->'a' as json_col_a FROM test_table
6262
* [x] `json_get_float(json: str, *keys: str | int) -> float` - Get a float value from a JSON string by its "path"
6363
* [x] `json_get_bool(json: str, *keys: str | int) -> bool` - Get a boolean value from a JSON string by its "path"
6464
* [x] `json_get_json(json: str, *keys: str | int) -> str` - Get a nested raw JSON string from a JSON string by its "path"
65+
* [x] `json_get_array(json: str, *keys: str | int) -> array` - Get an arrow array from a JSON string by its "path"
6566
* [x] `json_as_text(json: str, *keys: str | int) -> str` - Get any value from a JSON string by its "path", represented as a string (used for the `->>` operator)
6667
* [x] `json_length(json: str, *keys: str | int) -> int` - get the length of a JSON string or array
6768

src/json_get_array.rs

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
use std::any::Any;
2+
use std::sync::Arc;
3+
4+
use datafusion::arrow::array::{ArrayRef, ListBuilder, StringBuilder};
5+
use datafusion::arrow::datatypes::DataType;
6+
use datafusion::common::{Result as DataFusionResult, ScalarValue};
7+
use datafusion::logical_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility};
8+
use jiter::Peek;
9+
10+
use crate::common::{get_err, invoke, jiter_json_find, return_type_check, GetError, InvokeResult, JsonPath};
11+
use crate::common_macros::make_udf_function;
12+
13+
make_udf_function!(
14+
JsonGetArray,
15+
json_get_array,
16+
json_data path,
17+
r#"Get an arrow array from a JSON string by its "path""#
18+
);
19+
20+
#[derive(Debug)]
21+
pub(super) struct JsonGetArray {
22+
signature: Signature,
23+
aliases: [String; 1],
24+
}
25+
26+
impl Default for JsonGetArray {
27+
fn default() -> Self {
28+
Self {
29+
signature: Signature::variadic_any(Volatility::Immutable),
30+
aliases: ["json_get_array".to_string()],
31+
}
32+
}
33+
}
34+
35+
impl ScalarUDFImpl for JsonGetArray {
36+
fn as_any(&self) -> &dyn Any {
37+
self
38+
}
39+
40+
fn name(&self) -> &str {
41+
self.aliases[0].as_str()
42+
}
43+
44+
fn signature(&self) -> &Signature {
45+
&self.signature
46+
}
47+
48+
fn return_type(&self, arg_types: &[DataType]) -> DataFusionResult<DataType> {
49+
return_type_check(
50+
arg_types,
51+
self.name(),
52+
DataType::List(Arc::new(datafusion::arrow::datatypes::Field::new(
53+
"item",
54+
DataType::Utf8,
55+
true,
56+
))),
57+
)
58+
}
59+
60+
fn invoke_with_args(&self, args: ScalarFunctionArgs) -> DataFusionResult<ColumnarValue> {
61+
invoke::<BuildArrayList>(&args.args, jiter_json_get_array)
62+
}
63+
64+
fn aliases(&self) -> &[String] {
65+
&self.aliases
66+
}
67+
}
68+
69+
#[derive(Debug)]
70+
struct BuildArrayList;
71+
72+
impl InvokeResult for BuildArrayList {
73+
type Item = Vec<String>;
74+
75+
type Builder = ListBuilder<StringBuilder>;
76+
77+
const ACCEPT_DICT_RETURN: bool = false;
78+
79+
fn builder(capacity: usize) -> Self::Builder {
80+
let values_builder = StringBuilder::new();
81+
ListBuilder::with_capacity(values_builder, capacity)
82+
}
83+
84+
fn append_value(builder: &mut Self::Builder, value: Option<Self::Item>) {
85+
builder.append_option(value.map(|v| v.into_iter().map(Some)));
86+
}
87+
88+
fn finish(mut builder: Self::Builder) -> DataFusionResult<ArrayRef> {
89+
Ok(Arc::new(builder.finish()))
90+
}
91+
92+
fn scalar(value: Option<Self::Item>) -> ScalarValue {
93+
let mut builder = ListBuilder::new(StringBuilder::new());
94+
95+
if let Some(array_items) = value {
96+
for item in array_items {
97+
builder.values().append_value(item);
98+
}
99+
100+
builder.append(true);
101+
} else {
102+
builder.append(false);
103+
}
104+
let array = builder.finish();
105+
ScalarValue::List(Arc::new(array))
106+
}
107+
}
108+
109+
fn jiter_json_get_array(opt_json: Option<&str>, path: &[JsonPath]) -> Result<Vec<String>, GetError> {
110+
if let Some((mut jiter, peek)) = jiter_json_find(opt_json, path) {
111+
match peek {
112+
Peek::Array => {
113+
let mut peek_opt = jiter.known_array()?;
114+
let mut array_items: Vec<String> = Vec::new();
115+
116+
while let Some(element_peek) = peek_opt {
117+
// Get the raw JSON slice for each array element
118+
let start = jiter.current_index();
119+
jiter.known_skip(element_peek)?;
120+
let slice = jiter.slice_to_current(start);
121+
let element_str = std::str::from_utf8(slice)?.to_string();
122+
123+
array_items.push(element_str);
124+
peek_opt = jiter.array_step()?;
125+
}
126+
127+
Ok(array_items)
128+
}
129+
_ => get_err!(),
130+
}
131+
} else {
132+
get_err!()
133+
}
134+
}

src/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ mod common_union;
1111
mod json_as_text;
1212
mod json_contains;
1313
mod json_get;
14+
mod json_get_array;
1415
mod json_get_bool;
1516
mod json_get_float;
1617
mod json_get_int;
@@ -26,6 +27,7 @@ pub mod functions {
2627
pub use crate::json_as_text::json_as_text;
2728
pub use crate::json_contains::json_contains;
2829
pub use crate::json_get::json_get;
30+
pub use crate::json_get_array::json_get_array;
2931
pub use crate::json_get_bool::json_get_bool;
3032
pub use crate::json_get_float::json_get_float;
3133
pub use crate::json_get_int::json_get_int;
@@ -39,6 +41,7 @@ pub mod udfs {
3941
pub use crate::json_as_text::json_as_text_udf;
4042
pub use crate::json_contains::json_contains_udf;
4143
pub use crate::json_get::json_get_udf;
44+
pub use crate::json_get_array::json_get_array_udf;
4245
pub use crate::json_get_bool::json_get_bool_udf;
4346
pub use crate::json_get_float::json_get_float_udf;
4447
pub use crate::json_get_int::json_get_int_udf;
@@ -64,6 +67,7 @@ pub fn register_all(registry: &mut dyn FunctionRegistry) -> Result<()> {
6467
json_get_float::json_get_float_udf(),
6568
json_get_int::json_get_int_udf(),
6669
json_get_json::json_get_json_udf(),
70+
json_get_array::json_get_array_udf(),
6771
json_as_text::json_as_text_udf(),
6872
json_get_str::json_get_str_udf(),
6973
json_contains::json_contains_udf(),

tests/main.rs

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,14 +84,77 @@ async fn test_json_get_union() {
8484
}
8585

8686
#[tokio::test]
87-
async fn test_json_get_array() {
87+
async fn test_json_get_array_elem() {
8888
let sql = "select json_get('[1, 2, 3]', 2)";
8989
let batches = run_query(sql).await.unwrap();
9090
let (value_type, value_repr) = display_val(batches).await;
9191
assert!(matches!(value_type, DataType::Union(_, _)));
9292
assert_eq!(value_repr, "{int=3}");
9393
}
9494

95+
#[tokio::test]
96+
async fn test_json_get_array_basic_numbers() {
97+
let sql = "select json_get_array('[1, 2, 3]')";
98+
let batches = run_query(sql).await.unwrap();
99+
let (value_type, value_repr) = display_val(batches).await;
100+
assert!(matches!(value_type, DataType::List(_)));
101+
assert_eq!(value_repr, "[1, 2, 3]");
102+
}
103+
104+
#[tokio::test]
105+
async fn test_json_get_array_mixed_types() {
106+
let sql = r#"select json_get_array('["hello", 42, true, null, 3.14]')"#;
107+
let batches = run_query(sql).await.unwrap();
108+
let (value_type, value_repr) = display_val(batches).await;
109+
assert!(matches!(value_type, DataType::List(_)));
110+
assert_eq!(value_repr, r#"["hello", 42, true, null, 3.14]"#);
111+
}
112+
113+
#[tokio::test]
114+
async fn test_json_get_array_nested_objects() {
115+
let sql = r#"select json_get_array('[{"name": "John"}, {"age": 30}]')"#;
116+
let batches = run_query(sql).await.unwrap();
117+
let (value_type, value_repr) = display_val(batches).await;
118+
assert!(matches!(value_type, DataType::List(_)));
119+
assert_eq!(value_repr, r#"[{"name": "John"}, {"age": 30}]"#);
120+
}
121+
122+
#[tokio::test]
123+
async fn test_json_get_array_nested_arrays() {
124+
let sql = r#"select json_get_array('[[1, 2], [3, 4]]')"#;
125+
let batches = run_query(sql).await.unwrap();
126+
let (value_type, value_repr) = display_val(batches).await;
127+
assert!(matches!(value_type, DataType::List(_)));
128+
assert_eq!(value_repr, "[[1, 2], [3, 4]]");
129+
}
130+
131+
#[tokio::test]
132+
async fn test_json_get_array_empty() {
133+
let sql = "select json_get_array('[]')";
134+
let batches = run_query(sql).await.unwrap();
135+
let (value_type, value_repr) = display_val(batches).await;
136+
assert!(matches!(value_type, DataType::List(_)));
137+
assert_eq!(value_repr, "[]");
138+
}
139+
140+
#[tokio::test]
141+
async fn test_json_get_array_invalid_json() {
142+
let sql = "select json_get_array('')";
143+
let batches = run_query(sql).await.unwrap();
144+
let (value_type, value_repr) = display_val(batches).await;
145+
assert!(matches!(value_type, DataType::List(_)));
146+
assert_eq!(value_repr, "");
147+
}
148+
149+
#[tokio::test]
150+
async fn test_json_get_array_with_path() {
151+
let sql = r#"select json_get_array('{"items": [1, 2, 3]}', 'items')"#;
152+
let batches = run_query(sql).await.unwrap();
153+
let (value_type, value_repr) = display_val(batches).await;
154+
assert!(matches!(value_type, DataType::List(_)));
155+
assert_eq!(value_repr, "[1, 2, 3]");
156+
}
157+
95158
#[tokio::test]
96159
async fn test_json_get_equals() {
97160
let e = run_query(r"select name, json_get(json_data, 'foo')='abc' from test")

0 commit comments

Comments
 (0)