Skip to main content

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