risingwave_expr_impl/scalar/
jsonb_build.rs1use itertools::Either;
16use jsonbb::Builder;
17use risingwave_common::row::Row;
18use risingwave_common::types::{JsonbVal, ScalarRefImpl};
19use risingwave_common::util::iter_util::ZipEqDebug;
20use risingwave_expr::expr::Context;
21use risingwave_expr::{ExprError, Result, function};
22
23use super::{ToJsonb, ToTextDisplay};
24
25#[function("jsonb_build_array(variadic anyarray) -> jsonb")]
42fn jsonb_build_array(args: impl Row, ctx: &Context) -> Result<JsonbVal> {
43 let mut builder = Builder::<Vec<u8>>::new();
44 builder.begin_array();
45 if ctx.variadic {
46 for (value, ty) in args.iter().zip_eq_debug(&ctx.arg_types) {
47 value.add_to(ty, &mut builder)?;
48 }
49 } else {
50 let ty = ctx.arg_types[0].as_list();
51 for value in args.iter() {
52 value.add_to(ty, &mut builder)?;
53 }
54 }
55 builder.end_array();
56 Ok(builder.finish().into())
57}
58
59#[function("jsonb_build_object(variadic anyarray) -> jsonb")]
77fn jsonb_build_object(args: impl Row, ctx: &Context) -> Result<JsonbVal> {
78 if args.len() % 2 == 1 {
79 return Err(ExprError::InvalidParam {
80 name: "args",
81 reason: "argument list must have even number of elements".into(),
82 });
83 }
84 let mut builder = Builder::<Vec<u8>>::new();
85 builder.begin_object();
86 let arg_types = match ctx.variadic {
87 true => Either::Left(ctx.arg_types.iter()),
88 false => Either::Right(itertools::repeat_n(ctx.arg_types[0].as_list(), args.len())),
89 };
90 for (i, [(key, _), (value, value_type)]) in args
91 .iter()
92 .zip_eq_debug(arg_types)
93 .array_chunks()
94 .enumerate()
95 {
96 match key {
97 Some(ScalarRefImpl::List(_) | ScalarRefImpl::Struct(_) | ScalarRefImpl::Jsonb(_)) => {
98 return Err(ExprError::InvalidParam {
99 name: "args",
100 reason: "key value must be scalar, not array, composite, or json".into(),
101 });
102 }
103 Some(ScalarRefImpl::Bool(b)) => builder.display(b),
105 Some(s) => builder.display(ToTextDisplay(s)),
106 None => {
107 return Err(ExprError::InvalidParam {
108 name: "args",
109 reason: format!("argument {}: key must not be null", i * 2 + 1).into(),
110 });
111 }
112 }
113 value.add_to(value_type, &mut builder)?;
114 }
115 builder.end_object();
116 Ok(builder.finish().into())
117}