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