Skip to main content

risingwave_expr_impl/scalar/
jsonb_object.rs

1// Copyright 2023 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use risingwave_common::types::ListRef;
16use risingwave_common::util::iter_util::ZipEqFast;
17use risingwave_expr::{ExprError, Result, function};
18
19/// Builds a JSON object out of a text array.
20///
21/// The array must have either exactly one dimension with an even number of members,
22/// in which case they are taken as alternating key/value pairs, or two dimensions
23/// such that each inner array has exactly two elements, which are taken as a key/value pair.
24/// All values are converted to JSON strings.
25///
26/// # Examples
27///
28/// ```slt
29/// query T
30/// select jsonb_object('{a, 1, b, def, c, 3.5}' :: text[]);
31/// ----
32/// {"a": "1", "b": "def", "c": "3.5"}
33///
34/// query error array must have even number of elements
35/// select jsonb_object('{a, 1, b, "def", c}' :: text[]);
36///
37/// query error null value not allowed for object key
38/// select jsonb_object(array[null, 'b']);
39///
40/// query T
41/// select jsonb_object(array['a', null]);
42/// ----
43/// {"a": null}
44/// ```
45#[function("jsonb_object(varchar[]) -> jsonb")]
46fn jsonb_object_1d(array: ListRef<'_>, writer: &mut jsonbb::Builder) -> Result<()> {
47    if array.len() % 2 == 1 {
48        return Err(ExprError::InvalidParam {
49            name: "array",
50            reason: "array must have even number of elements".into(),
51        });
52    }
53    writer.begin_object();
54    for [key, value] in array.iter().array_chunks() {
55        match key {
56            Some(s) => writer.add_string(s.into_utf8()),
57            None => {
58                return Err(ExprError::InvalidParam {
59                    name: "array",
60                    reason: "null value not allowed for object key".into(),
61                });
62            }
63        }
64        match value {
65            Some(s) => writer.add_string(s.into_utf8()),
66            None => writer.add_null(),
67        }
68    }
69    writer.end_object();
70    Ok(())
71}
72
73/// Builds a JSON object out of a text array.
74///
75/// The array must have either exactly one dimension with an even number of members,
76/// in which case they are taken as alternating key/value pairs, or two dimensions
77/// such that each inner array has exactly two elements, which are taken as a key/value pair.
78/// All values are converted to JSON strings.
79///
80/// # Examples
81///
82/// ```slt
83/// query T
84/// select jsonb_object('{{a, 1}, {b, def}, {c, 3.5}}' :: text[][]);
85/// ----
86/// {"a": "1", "b": "def", "c": "3.5"}
87///
88/// query error null value not allowed for object key
89/// select jsonb_object('{{a, 1}, {null, "def"}, {c, 3.5}}' :: text[][]);
90///
91/// query error array must have two columns
92/// select jsonb_object('{{a, 1, 2}, {b, "def"}, {c, 3.5}}' :: text[][]);
93/// ```
94#[function("jsonb_object(varchar[][]) -> jsonb")]
95fn jsonb_object_2d(array: ListRef<'_>, writer: &mut jsonbb::Builder) -> Result<()> {
96    writer.begin_object();
97    for kv in array.iter() {
98        let Some(kv) = kv else {
99            return Err(ExprError::InvalidParam {
100                name: "array",
101                reason: "Unexpected array element.".into(),
102            });
103        };
104        let kv = kv.into_list();
105        if kv.len() != 2 {
106            return Err(ExprError::InvalidParam {
107                name: "array",
108                reason: "array must have two columns".into(),
109            });
110        }
111        match kv.get(0).unwrap() {
112            Some(s) => writer.add_string(s.into_utf8()),
113            None => {
114                return Err(ExprError::InvalidParam {
115                    name: "array",
116                    reason: "null value not allowed for object key".into(),
117                });
118            }
119        }
120        match kv.get(1).unwrap() {
121            Some(s) => writer.add_string(s.into_utf8()),
122            None => writer.add_null(),
123        }
124    }
125    writer.end_object();
126    Ok(())
127}
128
129/// This form of `jsonb_object` takes keys and values pairwise from separate text arrays.
130/// Otherwise it is identical to the one-argument form.
131///
132/// # Examples
133///
134/// ```slt
135/// query T
136/// select jsonb_object('{a,b}', '{1,2}');
137/// ----
138/// {"a": "1", "b": "2"}
139///
140/// query error mismatched array dimensions
141/// select jsonb_object('{a,b}', '{1,2,3}');
142///
143/// query error null value not allowed for object key
144/// select jsonb_object('{a,null}', '{1,2}');
145/// ```
146#[function("jsonb_object(varchar[], varchar[]) -> jsonb")]
147fn jsonb_object_kv(
148    keys: ListRef<'_>,
149    values: ListRef<'_>,
150    writer: &mut jsonbb::Builder,
151) -> Result<()> {
152    if keys.len() != values.len() {
153        return Err(ExprError::InvalidParam {
154            name: "values",
155            reason: "mismatched array dimensions".into(),
156        });
157    }
158    writer.begin_object();
159    for (key, value) in keys.iter().zip_eq_fast(values.iter()) {
160        match key {
161            Some(s) => writer.add_string(s.into_utf8()),
162            None => {
163                return Err(ExprError::InvalidParam {
164                    name: "keys",
165                    reason: "null value not allowed for object key".into(),
166                });
167            }
168        }
169        match value {
170            Some(s) => writer.add_string(s.into_utf8()),
171            None => writer.add_null(),
172        }
173    }
174    writer.end_object();
175    Ok(())
176}