mz_expr/scalar/func/impls/
char.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 mz_lowertest::MzReflect;
13use mz_repr::adt::char::{Char, CharLength, format_str_pad};
14use mz_repr::{ColumnType, ScalarType};
15use proptest_derive::Arbitrary;
16use serde::{Deserialize, Serialize};
17
18use crate::scalar::func::EagerUnaryFunc;
19
20/// All Char data is stored in Datum::String with its blank padding removed
21/// (i.e. trimmed), so this function provides a means of restoring any
22/// removed padding.
23#[derive(
24    Arbitrary, Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash, MzReflect,
25)]
26pub struct PadChar {
27    pub length: Option<CharLength>,
28}
29
30impl<'a> EagerUnaryFunc<'a> for PadChar {
31    type Input = &'a str;
32    type Output = Char<String>;
33
34    fn call(&self, a: &'a str) -> Char<String> {
35        Char(format_str_pad(a, self.length))
36    }
37
38    fn output_type(&self, input: ColumnType) -> ColumnType {
39        ScalarType::Char {
40            length: self.length,
41        }
42        .nullable(input.nullable)
43    }
44}
45
46impl fmt::Display for PadChar {
47    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
48        f.write_str("padchar")
49    }
50}
51
52// This function simply allows the expression of changing a's type from char to
53// string
54sqlfunc!(
55    #[sqlname = "char_to_text"]
56    #[preserves_uniqueness = true]
57    #[inverse = to_unary!(super::CastStringToChar{
58        length: None,
59        fail_on_len: false,
60    })]
61    fn cast_char_to_string<'a>(a: Char<&'a str>) -> &'a str {
62        a.0
63    }
64);