sql/statements/
comment.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::{self, Display, Formatter};
16
17use serde::Serialize;
18use sqlparser_derive::{Visit, VisitMut};
19
20use crate::ast::{Ident, ObjectName};
21
22/// Represents a SQL COMMENT statement for adding or removing comments on database objects.
23///
24/// # Examples
25///
26/// ```sql
27/// COMMENT ON TABLE my_table IS 'This is a table comment';
28/// COMMENT ON COLUMN my_table.my_column IS 'This is a column comment';
29/// COMMENT ON FLOW my_flow IS NULL;
30/// ```
31#[derive(Debug, Clone, PartialEq, Eq, Visit, VisitMut, Serialize)]
32pub struct Comment {
33    pub object: CommentObject,
34    pub comment: Option<String>,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Visit, VisitMut, Serialize)]
38pub enum CommentObject {
39    Table(ObjectName),
40    Column { table: ObjectName, column: Ident },
41    Flow(ObjectName),
42}
43
44impl Display for Comment {
45    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
46        write!(f, "COMMENT ON {} IS ", self.object)?;
47        match &self.comment {
48            Some(comment) => {
49                let escaped = comment.replace('\'', "''");
50                write!(f, "'{}'", escaped)
51            }
52            None => f.write_str("NULL"),
53        }
54    }
55}
56
57impl Display for CommentObject {
58    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
59        match self {
60            CommentObject::Table(name) => write!(f, "TABLE {}", name),
61            CommentObject::Column { table, column } => {
62                write!(f, "COLUMN {}.{}", table, column)
63            }
64            CommentObject::Flow(name) => write!(f, "FLOW {}", name),
65        }
66    }
67}