Skip to main content

risingwave_sqlparser/ast/
data_type.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12
13use std::fmt;
14
15use crate::ast::{Ident, ObjectName, display_comma_separated};
16
17/// SQL data types
18#[derive(Debug, Clone, PartialEq, Eq, Hash)]
19pub enum DataType {
20    /// Fixed-length character type e.g. CHAR(10)
21    Char(Option<u64>),
22    /// Variable-length character type.
23    /// We diverge from postgres by disallowing Varchar(n).
24    Varchar,
25    /// Uuid type
26    Uuid,
27    /// Decimal type with optional precision and scale e.g. DECIMAL(10,2)
28    Decimal(Option<u64>, Option<u64>),
29    /// Floating point with optional precision e.g. FLOAT(8)
30    Float(Option<u64>),
31    /// SMALLINT (int2)
32    SmallInt,
33    /// INTEGER (int4)
34    Int,
35    /// BIGINT (int8)
36    BigInt,
37    /// Floating point e.g. REAL
38    Real,
39    /// Double e.g. DOUBLE PRECISION
40    Double,
41    /// Boolean
42    Boolean,
43    /// Date
44    Date,
45    /// Time with optional time zone
46    Time(bool),
47    /// Timestamp with optional time zone
48    Timestamp(bool),
49    /// Interval
50    Interval,
51    /// Regclass used in postgresql serial
52    Regclass,
53    /// Regproc used in postgresql function
54    Regproc,
55    /// Text
56    Text,
57    /// Bytea
58    Bytea,
59    /// JSONB
60    Jsonb,
61    /// VARIANT
62    Variant,
63    /// Custom type such as enums
64    Custom(ObjectName),
65    /// Arrays
66    Array(Box<DataType>),
67    /// Structs
68    Struct(Vec<StructField>),
69    /// Map(key_type, value_type)
70    Map(Box<(DataType, DataType)>),
71    /// Vector of f32, fixed-length
72    Vector(u64),
73}
74
75impl fmt::Display for DataType {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        match self {
78            DataType::Char(size) => format_type_with_optional_length(f, "CHAR", size),
79            DataType::Varchar => write!(f, "CHARACTER VARYING"),
80            DataType::Uuid => write!(f, "UUID"),
81            DataType::Decimal(precision, scale) => {
82                if let Some(scale) = scale {
83                    write!(f, "NUMERIC({},{})", precision.unwrap(), scale)
84                } else {
85                    format_type_with_optional_length(f, "NUMERIC", precision)
86                }
87            }
88            DataType::Float(size) => format_type_with_optional_length(f, "FLOAT", size),
89            DataType::SmallInt => {
90                write!(f, "SMALLINT")
91            }
92            DataType::Int => write!(f, "INT"),
93            DataType::BigInt => write!(f, "BIGINT"),
94            DataType::Real => write!(f, "REAL"),
95            DataType::Double => write!(f, "DOUBLE"),
96            DataType::Boolean => write!(f, "BOOLEAN"),
97            DataType::Date => write!(f, "DATE"),
98            DataType::Time(tz) => write!(f, "TIME{}", if *tz { " WITH TIME ZONE" } else { "" }),
99            DataType::Timestamp(tz) => {
100                write!(f, "TIMESTAMP{}", if *tz { " WITH TIME ZONE" } else { "" })
101            }
102            DataType::Interval => write!(f, "INTERVAL"),
103            DataType::Regclass => write!(f, "REGCLASS"),
104            DataType::Regproc => write!(f, "REGPROC"),
105            DataType::Text => write!(f, "TEXT"),
106            DataType::Bytea => write!(f, "BYTEA"),
107            DataType::Jsonb => write!(f, "JSONB"),
108            DataType::Variant => write!(f, "VARIANT"),
109            DataType::Array(ty) => write!(f, "{}[]", ty),
110            DataType::Custom(ty) => write!(f, "{}", ty),
111            DataType::Struct(defs) => {
112                write!(f, "STRUCT<")?;
113                if defs.is_empty() {
114                    // We require a whitespace for empty(zero-field) struct to prevent `<>` from
115                    // being tokenized as a single token `Neq`.
116                    write!(f, " ")?;
117                } else {
118                    write!(f, "{}", display_comma_separated(defs))?;
119                }
120                write!(f, ">")
121            }
122            DataType::Map(kv) => {
123                write!(f, "MAP({},{})", kv.0, kv.1)
124            }
125            DataType::Vector(size) => {
126                write!(f, "VECTOR({})", size)
127            }
128        }
129    }
130}
131
132fn format_type_with_optional_length(
133    f: &mut fmt::Formatter<'_>,
134    sql_type: &'static str,
135    len: &Option<u64>,
136) -> fmt::Result {
137    write!(f, "{}", sql_type)?;
138    if let Some(len) = len {
139        write!(f, "({})", len)?;
140    }
141    Ok(())
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Hash)]
145pub struct StructField {
146    pub name: Ident,
147    pub data_type: DataType,
148}
149
150impl fmt::Display for StructField {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        write!(f, "{} {}", self.name, self.data_type)
153    }
154}