micromegas_datafusion_extensions/jsonb/
extract.rs1use datafusion::common::Result;
11use datafusion::error::DataFusionError;
12use jsonb::RawJsonb;
13use jsonb::jsonpath::JsonPath;
14
15pub type EntryList = Vec<(String, Vec<u8>)>;
17
18pub fn object_or_array_entries(jsonb_bytes: &[u8]) -> Result<Option<EntryList>> {
21 let jsonb = RawJsonb::new(jsonb_bytes);
22 match jsonb.object_each() {
23 Ok(Some(entries)) => {
24 return Ok(Some(
25 entries
26 .into_iter()
27 .map(|(k, v)| (k, v.as_ref().to_vec()))
28 .collect(),
29 ));
30 }
31 Ok(None) => {}
32 Err(e) => return Err(DataFusionError::External(e.into())),
33 }
34 match jsonb.array_values() {
35 Ok(Some(values)) => Ok(Some(
36 values
37 .into_iter()
38 .enumerate()
39 .map(|(i, v)| (i.to_string(), v.as_ref().to_vec()))
40 .collect(),
41 )),
42 Ok(None) => Ok(None),
43 Err(e) => Err(DataFusionError::External(e.into())),
44 }
45}
46
47pub fn array_elements(jsonb_bytes: &[u8]) -> Result<Option<Vec<Vec<u8>>>> {
49 let jsonb = RawJsonb::new(jsonb_bytes);
50 match jsonb.array_values() {
51 Ok(Some(values)) => Ok(Some(
52 values.into_iter().map(|v| v.as_ref().to_vec()).collect(),
53 )),
54 Ok(None) => Ok(None),
55 Err(e) => Err(DataFusionError::External(e.into())),
56 }
57}
58
59pub fn path_select_all<'a>(jsonb_bytes: &[u8], path: &'a JsonPath<'a>) -> Result<Vec<Vec<u8>>> {
63 let jsonb = RawJsonb::new(jsonb_bytes);
64 match jsonb.select_by_path(path) {
65 Ok(values) => Ok(values.into_iter().map(|v| v.as_ref().to_vec()).collect()),
66 Err(e) => Err(DataFusionError::External(e.into())),
67 }
68}