Skip to main content

mz_expr/scalar/func/impls/
map.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::fmt;
11
12use itertools::Itertools;
13use mz_expr_derive::sqlfunc;
14use mz_lowertest::MzReflect;
15use mz_repr::{Datum, DatumMap, RowArena, SqlColumnType, SqlScalarType};
16use serde::{Deserialize, Serialize};
17
18use crate::scalar::func::{LazyUnaryFunc, stringify_datum};
19use crate::{EvalError, MirScalarExpr};
20
21#[derive(
22    Ord,
23    PartialOrd,
24    Clone,
25    Debug,
26    Eq,
27    PartialEq,
28    Serialize,
29    Deserialize,
30    Hash,
31    MzReflect
32)]
33pub struct CastMapToString {
34    pub ty: SqlScalarType,
35}
36
37impl LazyUnaryFunc for CastMapToString {
38    fn eval<'a>(
39        &'a self,
40        datums: &[Datum<'a>],
41        temp_storage: &'a RowArena,
42        a: &'a MirScalarExpr,
43    ) -> Result<Datum<'a>, EvalError> {
44        let a = a.eval(datums, temp_storage)?;
45        if a.is_null() {
46            return Ok(Datum::Null);
47        }
48        let mut buf = String::new();
49        stringify_datum(&mut buf, a, &self.ty)?;
50        Ok(Datum::String(temp_storage.push_string(buf)))
51    }
52
53    fn output_type(&self, input_type: SqlColumnType) -> SqlColumnType {
54        SqlScalarType::String.nullable(input_type.nullable)
55    }
56
57    fn propagates_nulls(&self) -> bool {
58        true
59    }
60
61    fn introduces_nulls(&self) -> bool {
62        false
63    }
64
65    fn preserves_uniqueness(&self) -> bool {
66        true
67    }
68
69    fn inverse(&self) -> Option<crate::UnaryFunc> {
70        // TODO? If we moved typeconv into expr, we could evaluate this
71        None
72    }
73
74    fn is_monotone(&self) -> bool {
75        false
76    }
77}
78
79impl fmt::Display for CastMapToString {
80    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
81        f.write_str("maptostr")
82    }
83}
84
85#[sqlfunc(sqlname = "map_length")]
86fn map_length<'a>(a: DatumMap<'a>) -> Result<i32, EvalError> {
87    let count = a.iter().count();
88    count
89        .try_into()
90        .map_err(|_| EvalError::Int32OutOfRange(count.to_string().into()))
91}
92
93#[derive(
94    Ord,
95    PartialOrd,
96    Clone,
97    Debug,
98    Eq,
99    PartialEq,
100    Serialize,
101    Deserialize,
102    Hash,
103    MzReflect
104)]
105pub struct MapBuildFromRecordList {
106    pub value_type: SqlScalarType,
107}
108
109impl LazyUnaryFunc for MapBuildFromRecordList {
110    fn eval<'a>(
111        &'a self,
112        datums: &[Datum<'a>],
113        temp_storage: &'a RowArena,
114        a: &'a MirScalarExpr,
115    ) -> Result<Datum<'a>, EvalError> {
116        let a = a.eval(datums, temp_storage)?;
117        if a.is_null() {
118            return Ok(Datum::Null);
119        }
120        let list = a.unwrap_list();
121        let mut map = std::collections::BTreeMap::new();
122
123        for i in list.iter() {
124            if i.is_null() {
125                continue;
126            }
127
128            for (k, v) in i.unwrap_list().iter().tuples() {
129                if k.is_null() {
130                    continue;
131                }
132                map.insert(k.unwrap_str(), v);
133            }
134        }
135
136        let map = temp_storage.make_datum(|packer| packer.push_dict(map));
137        Ok(map)
138    }
139
140    fn output_type(&self, _input_type: SqlColumnType) -> SqlColumnType {
141        SqlScalarType::Map {
142            value_type: Box::new(self.value_type.clone()),
143            custom_id: None,
144        }
145        .nullable(true)
146    }
147
148    fn propagates_nulls(&self) -> bool {
149        true
150    }
151
152    fn introduces_nulls(&self) -> bool {
153        true
154    }
155
156    fn preserves_uniqueness(&self) -> bool {
157        false
158    }
159
160    fn inverse(&self) -> Option<crate::UnaryFunc> {
161        None
162    }
163
164    fn is_monotone(&self) -> bool {
165        false
166    }
167}
168
169impl fmt::Display for MapBuildFromRecordList {
170    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171        f.write_str("map_build")
172    }
173}