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