Skip to main content

risingwave_expr_impl/scalar/
variant.rs

1// Copyright 2026 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::{ScalarRefImpl, VariantPath, VariantRef, VariantVal};
16use risingwave_expr::expr::Context;
17use risingwave_expr::{ExprError, Result, function};
18use thiserror_ext::AsReport;
19
20#[function("to_variant(any) -> variant")]
21fn to_variant(input: Option<ScalarRefImpl<'_>>, ctx: &Context) -> Result<VariantVal> {
22    VariantVal::try_from_scalar_ref(input, &ctx.arg_types[0]).map_err(|e| ExprError::InvalidParam {
23        name: "to_variant",
24        reason: e.to_report_string().into(),
25    })
26}
27
28#[function(
29    "variant_get(variant, varchar) -> variant",
30    prebuild = "PrebuiltVariantPath::parse($1)"
31)]
32fn variant_get(value: VariantRef<'_>, path: &PrebuiltVariantPath) -> Result<Option<VariantVal>> {
33    let path = path.0.as_ref().map_err(variant_get_error)?;
34    value
35        .access_path_parsed(path)
36        .map_err(|e| variant_get_error(&e))
37}
38
39fn variant_get_error(e: &anyhow::Error) -> ExprError {
40    ExprError::InvalidParam {
41        name: "variant_get",
42        reason: e.to_report_string().into(),
43    }
44}
45
46#[derive(Debug)]
47struct PrebuiltVariantPath(anyhow::Result<VariantPath>);
48
49impl PrebuiltVariantPath {
50    fn parse(path: &str) -> Self {
51        Self(VariantPath::parse(path))
52    }
53}
54
55#[function(
56    "try_variant_get(variant, varchar) -> variant",
57    prebuild = "PrebuiltVariantPath::parse($1)"
58)]
59fn try_variant_get(value: VariantRef<'_>, path: &PrebuiltVariantPath) -> Option<VariantVal> {
60    path.0
61        .as_ref()
62        .ok()
63        .and_then(|path| value.access_path_parsed(path).ok().flatten())
64}
65
66#[function("variant_typeof(variant) -> varchar")]
67fn variant_typeof(value: VariantRef<'_>, writer: &mut impl std::fmt::Write) {
68    writer.write_str(value.type_name()).unwrap();
69}