risingwave_expr_impl/scalar/jsonb_info.rs
1// Copyright 2025 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::JsonbRef;
16use risingwave_expr::{ExprError, Result, function};
17
18#[function("jsonb_typeof(jsonb) -> varchar")]
19pub fn jsonb_typeof(v: JsonbRef<'_>, writer: &mut impl std::fmt::Write) {
20 writer.write_str(v.type_name()).unwrap()
21}
22
23#[function("jsonb_array_length(jsonb) -> int4")]
24pub fn jsonb_array_length(v: JsonbRef<'_>) -> Result<i32> {
25 v.array_len()
26 .map(|n| n as i32)
27 .map_err(|e| ExprError::InvalidParam {
28 name: "",
29 reason: e.into(),
30 })
31}
32
33#[function("is_json(varchar) -> boolean")]
34pub fn is_json_value(s: &str) -> bool {
35 serde_json::from_str::<serde::de::IgnoredAny>(s).is_ok()
36}
37
38#[function("is_json(varchar, varchar) -> boolean")]
39pub fn is_json_type(s: &str, t: &str) -> bool {
40 serde_json::from_str::<serde::de::IgnoredAny>(s).is_ok_and(|_| {
41 let s = s.trim_start();
42 match t {
43 "ARRAY" => s.starts_with('['),
44 "OBJECT" => s.starts_with('{'),
45 "SCALAR" => !s.starts_with('[') && !s.starts_with('{'),
46 // forward compatible in case we always pass the default later
47 "VALUE" => true,
48 // After #11134, validate during expr build and pass enum to avoid this
49 _ => unreachable!(),
50 }
51 })
52}
53
54/// Converts the given JSON value to pretty-printed, indented text.
55///
56/// # Examples
57// TODO: enable docslt after sqllogictest supports multiline output
58/// ```text
59/// query T
60/// select jsonb_pretty('[{"f1":1,"f2":null}, 2]');
61/// ----
62/// [
63/// {
64/// "f1": 1,
65/// "f2": null
66/// },
67/// 2
68/// ]
69/// ```
70#[function("jsonb_pretty(jsonb) -> varchar")]
71pub fn jsonb_pretty(v: JsonbRef<'_>, writer: &mut impl std::fmt::Write) {
72 v.pretty(writer).unwrap()
73}