Skip to main content

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    let mut encoder = DataRowEncoder::new(schema.clone());
32    rows.iter()
33        .map(|row| {
34            for value in row {
35                encoder.encode_field(&Some(value))?;
36            }
37            Ok(encoder.take_row())
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
51// Patterns match a whole command; a prefix match would answer `BEGIN; <stmt>`
52// or `ROLLBACK TO SAVEPOINT s` and drop or fake the rest.
53static SHOW_PATTERN: Lazy<Regex> =
54    Lazy::new(|| Regex::new(r"(?i)^SHOW ([^;]*?)\s*;?\s*$").unwrap());
55static SET_TRANSACTION_PATTERN: Lazy<Regex> =
56    Lazy::new(|| Regex::new(r"(?i)^SET TRANSACTION [^;]*;?\s*$").unwrap());
57static START_TRANSACTION_PATTERN: Lazy<Regex> =
58    Lazy::new(|| Regex::new(r"(?i)^(START TRANSACTION|BEGIN)\b[^;]*;?\s*$").unwrap());
59static COMMIT_TRANSACTION_PATTERN: Lazy<Regex> = Lazy::new(|| {
60    Regex::new(r"(?i)^(COMMIT TRANSACTION|COMMIT)(\s+AND\s+(NO\s+)?CHAIN)?\s*;?\s*$").unwrap()
61});
62static ABORT_TRANSACTION_PATTERN: Lazy<Regex> = Lazy::new(|| {
63    Regex::new(r"(?i)^(ABORT TRANSACTION|ROLLBACK)(\s+AND\s+(NO\s+)?CHAIN)?\s*;?\s*$").unwrap()
64});
65
66/// Test if given query statement matches the patterns
67pub(crate) fn matches(query: &str) -> bool {
68    process(query, QueryContext::arc()).is_some()
69}
70
71fn set_transaction_warning(query_ctx: QueryContextRef) {
72    query_ctx.set_warning("Please note transaction is not supported in GreptimeDB.".to_string());
73}
74
75/// Process unsupported SQL and return fixed result as a compatibility solution
76pub(crate) fn process(query: &str, query_ctx: QueryContextRef) -> Option<Vec<Response>> {
77    // Transaction directives:
78    if START_TRANSACTION_PATTERN.is_match(query) {
79        set_transaction_warning(query_ctx);
80        if query.to_lowercase().starts_with("begin") {
81            Some(vec![Response::TransactionStart(Tag::new("BEGIN"))])
82        } else {
83            Some(vec![Response::TransactionStart(Tag::new(
84                "START TRANSACTION",
85            ))])
86        }
87    } else if ABORT_TRANSACTION_PATTERN.is_match(query) {
88        Some(vec![Response::TransactionEnd(Tag::new("ROLLBACK"))])
89    } else if COMMIT_TRANSACTION_PATTERN.is_match(query) {
90        Some(vec![Response::TransactionEnd(Tag::new("COMMIT"))])
91    } else if let Some(show_var) = SHOW_PATTERN.captures(query) {
92        let show_var = show_var[1].to_lowercase();
93        if let Some(value) = VAR_VALUES.get(&show_var.as_ref()) {
94            let f1 = FieldInfo::new(
95                show_var.clone(),
96                None,
97                None,
98                Type::VARCHAR,
99                FieldFormat::Text,
100            );
101            let schema = Arc::new(vec![f1]);
102            let data = stream::iter(build_string_data_rows(
103                schema.clone(),
104                vec![vec![value.to_string()]],
105            ));
106
107            Some(vec![Response::Query(QueryResponse::new(schema, data))])
108        } else {
109            None
110        }
111    } else if SET_TRANSACTION_PATTERN.is_match(query) {
112        Some(vec![Response::Execution(Tag::new("SET"))])
113    } else {
114        None
115    }
116}
117
118#[cfg(test)]
119mod test {
120    use session::context::{QueryContext, QueryContextRef};
121
122    use super::*;
123
124    fn assert_tag(q: &str, t: &str, query_context: QueryContextRef) {
125        if let Response::Execution(tag)
126        | Response::TransactionStart(tag)
127        | Response::TransactionEnd(tag) = process(q, query_context.clone())
128            .unwrap_or_else(|| panic!("fail to match {}", q))
129            .remove(0)
130        {
131            assert_eq!(Tag::new(t), tag);
132        } else {
133            panic!("Invalid response");
134        }
135    }
136
137    fn get_data(q: &str, query_context: QueryContextRef) -> QueryResponse {
138        if let Response::Query(resp) = process(q, query_context.clone())
139            .unwrap_or_else(|| panic!("fail to match {}", q))
140            .remove(0)
141        {
142            resp
143        } else {
144            panic!("Invalid response");
145        }
146    }
147
148    #[test]
149    fn test_process() {
150        let query_context = QueryContext::arc();
151
152        assert_tag("BEGIN", "BEGIN", query_context.clone());
153        assert_tag("BEGIN;", "BEGIN", query_context.clone());
154        assert_tag("begin;", "BEGIN", query_context.clone());
155        assert_tag("ROLLBACK", "ROLLBACK", query_context.clone());
156        assert_tag("ROLLBACK;", "ROLLBACK", query_context.clone());
157        assert_tag("rollback;", "ROLLBACK", query_context.clone());
158        assert_tag("COMMIT", "COMMIT", query_context.clone());
159        assert_tag("COMMIT;", "COMMIT", query_context.clone());
160        assert_tag("commit;", "COMMIT", query_context.clone());
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            "SET transaction isolation level READ COMMITTED;",
173            "SET",
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(
182            "start transaction isolation level READ COMMITTED;",
183            "START TRANSACTION",
184            query_context.clone(),
185        );
186        assert_tag("abort transaction;", "ROLLBACK", query_context.clone());
187        assert_tag("commit transaction;", "COMMIT", query_context.clone());
188        assert_tag("COMMIT transaction;", "COMMIT", query_context.clone());
189        assert_tag("ROLLBACK AND CHAIN", "ROLLBACK", query_context.clone());
190
191        let resp = get_data("SHOW transaction isolation level", query_context.clone());
192        assert_eq!(1, resp.row_schema().len());
193        let resp = get_data("show client_encoding;", query_context.clone());
194        assert_eq!(1, resp.row_schema().len());
195        let resp = get_data("show standard_conforming_strings;", query_context.clone());
196        assert_eq!(1, resp.row_schema().len());
197        let resp = get_data("show default_transaction_isolation", query_context.clone());
198        assert_eq!(1, resp.row_schema().len());
199
200        for query in [
201            "BEGIN; SELECT 1",
202            "COMMIT; SELECT 1",
203            "ROLLBACK TO SAVEPOINT s",
204            "SET TRANSACTION ISOLATION LEVEL READ COMMITTED; SELECT 1",
205            "SHOW client_encoding; SELECT 1",
206        ] {
207            assert!(process(query, query_context.clone()).is_none(), "{query}");
208        }
209        assert!(process("SELECT 1", query_context.clone()).is_none());
210        assert!(process("SHOW TABLES ", query_context.clone()).is_none());
211        assert!(process("SET TIME_ZONE=utc ", query_context.clone()).is_none());
212    }
213}