servers/postgres/
fixtures.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::collections::HashMap;
16use std::sync::Arc;
17
18use futures::stream;
19use once_cell::sync::Lazy;
20use pgwire::api::Type;
21use pgwire::api::results::{DataRowEncoder, FieldFormat, FieldInfo, QueryResponse, Response, Tag};
22use pgwire::error::PgWireResult;
23use pgwire::messages::data::DataRow;
24use regex::Regex;
25use session::context::{QueryContext, QueryContextRef};
26
27fn build_string_data_rows(
28    schema: Arc<Vec<FieldInfo>>,
29    rows: Vec<Vec<String>>,
30) -> Vec<PgWireResult<DataRow>> {
31    rows.iter()
32        .map(|row| {
33            let mut encoder = DataRowEncoder::new(schema.clone());
34            for value in row {
35                encoder.encode_field(&Some(value))?;
36            }
37            encoder.finish()
38        })
39        .collect()
40}
41
42static VAR_VALUES: Lazy<HashMap<&str, &str>> = Lazy::new(|| {
43    HashMap::from([
44        ("default_transaction_isolation", "read committed"),
45        ("transaction isolation level", "read committed"),
46        ("standard_conforming_strings", "on"),
47        ("client_encoding", "UTF8"),
48    ])
49});
50
51static SHOW_PATTERN: Lazy<Regex> = Lazy::new(|| Regex::new("(?i)^SHOW (.*?);?$").unwrap());
52static SET_TRANSACTION_PATTERN: Lazy<Regex> =
53    Lazy::new(|| Regex::new("(?i)^SET TRANSACTION (.*?);?$").unwrap());
54static START_TRANSACTION_PATTERN: Lazy<Regex> =
55    Lazy::new(|| Regex::new("(?i)^(START TRANSACTION.*|BEGIN);?").unwrap());
56static COMMIT_TRANSACTION_PATTERN: Lazy<Regex> =
57    Lazy::new(|| Regex::new("(?i)^(COMMIT TRANSACTION|COMMIT);?").unwrap());
58static ABORT_TRANSACTION_PATTERN: Lazy<Regex> =
59    Lazy::new(|| Regex::new("(?i)^(ABORT TRANSACTION|ROLLBACK);?").unwrap());
60
61/// Test if given query statement matches the patterns
62pub(crate) fn matches(query: &str) -> bool {
63    process(query, QueryContext::arc()).is_some()
64}
65
66fn set_transaction_warning(query_ctx: QueryContextRef) {
67    query_ctx.set_warning("Please note transaction is not supported in GreptimeDB.".to_string());
68}
69
70/// Process unsupported SQL and return fixed result as a compatibility solution
71pub(crate) fn process(query: &str, query_ctx: QueryContextRef) -> Option<Vec<Response>> {
72    // Transaction directives:
73    if START_TRANSACTION_PATTERN.is_match(query) {
74        set_transaction_warning(query_ctx);
75        if query.to_lowercase().starts_with("begin") {
76            Some(vec![Response::TransactionStart(Tag::new("BEGIN"))])
77        } else {
78            Some(vec![Response::TransactionStart(Tag::new(
79                "START TRANSACTION",
80            ))])
81        }
82    } else if ABORT_TRANSACTION_PATTERN.is_match(query) {
83        Some(vec![Response::TransactionEnd(Tag::new("ROLLBACK"))])
84    } else if COMMIT_TRANSACTION_PATTERN.is_match(query) {
85        Some(vec![Response::TransactionEnd(Tag::new("COMMIT"))])
86    } else if let Some(show_var) = SHOW_PATTERN.captures(query) {
87        let show_var = show_var[1].to_lowercase();
88        if let Some(value) = VAR_VALUES.get(&show_var.as_ref()) {
89            let f1 = FieldInfo::new(
90                show_var.clone(),
91                None,
92                None,
93                Type::VARCHAR,
94                FieldFormat::Text,
95            );
96            let schema = Arc::new(vec![f1]);
97            let data = stream::iter(build_string_data_rows(
98                schema.clone(),
99                vec![vec![value.to_string()]],
100            ));
101
102            Some(vec![Response::Query(QueryResponse::new(schema, data))])
103        } else {
104            None
105        }
106    } else if SET_TRANSACTION_PATTERN.is_match(query) {
107        Some(vec![Response::Execution(Tag::new("SET"))])
108    } else {
109        None
110    }
111}
112
113#[cfg(test)]
114mod test {
115    use session::context::{QueryContext, QueryContextRef};
116
117    use super::*;
118
119    fn assert_tag(q: &str, t: &str, query_context: QueryContextRef) {
120        if let Response::Execution(tag)
121        | Response::TransactionStart(tag)
122        | Response::TransactionEnd(tag) = process(q, query_context.clone())
123            .unwrap_or_else(|| panic!("fail to match {}", q))
124            .remove(0)
125        {
126            assert_eq!(Tag::new(t), tag);
127        } else {
128            panic!("Invalid response");
129        }
130    }
131
132    fn get_data(q: &str, query_context: QueryContextRef) -> QueryResponse {
133        if let Response::Query(resp) = process(q, query_context.clone())
134            .unwrap_or_else(|| panic!("fail to match {}", q))
135            .remove(0)
136        {
137            resp
138        } else {
139            panic!("Invalid response");
140        }
141    }
142
143    #[test]
144    fn test_process() {
145        let query_context = QueryContext::arc();
146
147        assert_tag("BEGIN", "BEGIN", query_context.clone());
148        assert_tag("BEGIN;", "BEGIN", query_context.clone());
149        assert_tag("begin;", "BEGIN", query_context.clone());
150        assert_tag("ROLLBACK", "ROLLBACK", query_context.clone());
151        assert_tag("ROLLBACK;", "ROLLBACK", query_context.clone());
152        assert_tag("rollback;", "ROLLBACK", query_context.clone());
153        assert_tag("COMMIT", "COMMIT", query_context.clone());
154        assert_tag("COMMIT;", "COMMIT", query_context.clone());
155        assert_tag("commit;", "COMMIT", query_context.clone());
156        assert_tag(
157            "SET TRANSACTION ISOLATION LEVEL READ COMMITTED",
158            "SET",
159            query_context.clone(),
160        );
161        assert_tag(
162            "SET TRANSACTION ISOLATION LEVEL READ COMMITTED;",
163            "SET",
164            query_context.clone(),
165        );
166        assert_tag(
167            "SET transaction isolation level READ COMMITTED;",
168            "SET",
169            query_context.clone(),
170        );
171        assert_tag(
172            "START TRANSACTION isolation level READ COMMITTED;",
173            "START TRANSACTION",
174            query_context.clone(),
175        );
176        assert_tag(
177            "start transaction isolation level READ COMMITTED;",
178            "START TRANSACTION",
179            query_context.clone(),
180        );
181        assert_tag("abort transaction;", "ROLLBACK", query_context.clone());
182        assert_tag("commit transaction;", "COMMIT", query_context.clone());
183        assert_tag("COMMIT transaction;", "COMMIT", query_context.clone());
184
185        let resp = get_data("SHOW transaction isolation level", query_context.clone());
186        assert_eq!(1, resp.row_schema().len());
187        let resp = get_data("show client_encoding;", query_context.clone());
188        assert_eq!(1, resp.row_schema().len());
189        let resp = get_data("show standard_conforming_strings;", query_context.clone());
190        assert_eq!(1, resp.row_schema().len());
191        let resp = get_data("show default_transaction_isolation", query_context.clone());
192        assert_eq!(1, resp.row_schema().len());
193
194        assert!(process("SELECT 1", query_context.clone()).is_none());
195        assert!(process("SHOW TABLES ", query_context.clone()).is_none());
196        assert!(process("SET TIME_ZONE=utc ", query_context.clone()).is_none());
197    }
198}