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_expr_derive::sqlfunc;
13use mz_lowertest::MzReflect;
14use mz_repr::adt::char::{Char, CharLength, format_str_pad};
15use mz_repr::{SqlColumnType, SqlScalarType};
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(Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash, MzReflect)]
24pub struct PadChar {
25    pub length: Option<CharLength>,
26}
27
28impl<'a> EagerUnaryFunc<'a> for PadChar {
29    type Input = &'a str;
30    type Output = Char<String>;
31
32    fn call(&self, a: &'a str) -> Char<String> {
33        Char(format_str_pad(a, self.length))
34    }
35
36    fn output_type(&self, input: SqlColumnType) -> SqlColumnType {
37        SqlScalarType::Char {
38            length: self.length,
39        }
40        .nullable(input.nullable)
41    }
42}
43
44impl fmt::Display for PadChar {
45    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
46        f.write_str("padchar")
47    }
48}
49
50// This function simply allows the expression of changing a's type from char to
51// string
52#[sqlfunc(
53    sqlname = "char_to_text",
54    preserves_uniqueness = true,
55    inverse = to_unary!(super::CastStringToChar{
56        length: None,
57        fail_on_len: false,
58    })
59)]
60fn cast_char_to_string<'a>(a: Char<&'a str>) -> &'a str {
61    a.0
62}