-
Notifications
You must be signed in to change notification settings - Fork 752
/
clickhouse_handler.rs
268 lines (233 loc) · 7.43 KB
/
clickhouse_handler.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_base::tokio;
use databend_query::servers::http::middleware::HTTPSessionEndpoint;
use databend_query::servers::http::middleware::HTTPSessionMiddleware;
use databend_query::servers::http::v1::clickhouse_router;
use http::Uri;
use poem::error::Result as PoemResult;
use poem::http::Method;
use poem::http::StatusCode;
use poem::Body;
use poem::Endpoint;
use poem::EndpointExt;
use poem::Request;
use poem::Route;
use pretty_assertions::assert_eq;
use crate::tests::SessionManagerBuilder;
macro_rules! assert_error {
($body:expr, $msg:expr$(,)?) => {{
assert!($body.contains($msg), "{}", $body);
}};
}
macro_rules! assert_ok {
($status:expr, $body:expr) => {{
assert_eq!($status, StatusCode::OK, "{}: {}", $status, $body);
}};
}
#[tokio::test]
async fn test_select() -> PoemResult<()> {
let server = Server::new();
{
let (status, body) = server.get("").await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_error!(body, "Empty query");
}
{
let (status, body) = server.get("bad sql").await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_error!(body, "sql parser error");
}
{
let (status, body) = server.post("sel", "ect 1").await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_error!(body, "sql parser error");
}
{
let (status, body) = server.post("", "bad sql").await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_error!(body, "sql parser error");
}
{
let (status, body) = server.get("select 1").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(&body, "1\n");
}
{
let (status, body) = server.post("", "select 1").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(&body, "1\n");
}
{
let (status, body) = server.post("select ", "1").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(&body, "1\n");
}
{
// basic tsv format
let (status, body) = server
.get(r#"select number, 'a' from numbers(2) order by number"#)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(&body, "0\ta\n1\ta\n");
}
Ok(())
}
#[tokio::test]
async fn test_insert_values() -> PoemResult<()> {
let server = Server::new();
{
let (status, body) = server.post("create table t1(a int, b string)", "").await;
assert_eq!(status, StatusCode::OK);
assert_error!(body, "");
}
{
let (status, body) = server
.post("insert into table t1 values (0, 'a'), (1, 'b')", "")
.await;
assert_eq!(status, StatusCode::OK);
assert_error!(body, "");
}
{
// basic tsv format
let (status, body) = server.get(r#"select * from t1"#).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(&body, "0\ta\n1\tb\n");
}
Ok(())
}
#[tokio::test]
async fn test_insert_format_values() -> PoemResult<()> {
let server = Server::new();
{
let (status, body) = server.post("create table t1(a int, b string)", "").await;
assert_eq!(status, StatusCode::OK);
assert_error!(body, "");
}
{
let (status, body) = server
.post("insert into table t1 values", "(0, 'a'), (1, 'b')")
.await;
assert_ok!(status, body);
assert_error!(body, "");
}
{
// basic tsv format
let (status, body) = server.get(r#"select * from t1"#).await;
assert_eq!(status, StatusCode::OK, "{} {}", status, body);
assert_eq!(&body, "0\ta\n1\tb\n");
}
Ok(())
}
#[tokio::test]
async fn test_insert_format_ndjson() -> PoemResult<()> {
let server = Server::new();
{
let (status, body) = server
.post("create table t1(a int, b string null)", "")
.await;
assert_ok!(status, body);
}
{
let jsons = vec![r#"{"a": 0, "b": "a"}"#, r#"{"a": 1, "b": "b"}"#];
let body = jsons.join("\n");
let (status, body) = server
.post("insert into table t1 format JSONEachRow", &body)
.await;
assert_ok!(status, body);
}
{
let (status, body) = server.get(r#"select * from t1 order by a"#).await;
assert_ok!(status, body);
assert_eq!(&body, "0\ta\n1\tb\n");
}
{
let jsons = vec![r#"{"a": 2}"#];
let body = jsons.join("\n");
let (status, body) = server
.post("insert into table t1 format JSONEachRow", &body)
.await;
assert_ok!(status, body);
}
{
let (status, body) = server.get(r#"select * from t1 order by a"#).await;
assert_ok!(status, body);
assert_eq!(&body, "0\ta\n1\tb\n2\tNULL\n");
}
{
let jsons = vec![r#"{"b": 0}"#];
let body = jsons.join("\n");
let (status, body) = server
.post("insert into table t1 format JSONEachRow", &body)
.await;
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
assert_error!(body, "column a");
}
Ok(())
}
struct QueryBuilder {
sql: String,
body: Option<Body>,
}
impl QueryBuilder {
pub fn new(sql: &str) -> Self {
QueryBuilder {
sql: sql.to_string(),
body: None,
}
}
pub fn body(self, body: impl Into<Body>) -> Self {
Self {
body: Some(body.into()),
..self
}
}
pub fn build(self) -> Request {
let uri = url::form_urlencoded::Serializer::new(String::new())
.append_pair("query", &self.sql)
.finish();
let uri = "/?".to_string() + &uri;
let uri = uri.parse::<Uri>().unwrap();
let (method, body) = match self.body {
None => (Method::GET, Body::empty()),
Some(body) => (Method::POST, body),
};
Request::builder().uri(uri).method(method).body(body)
}
}
struct Server {
endpoint: HTTPSessionEndpoint<Route>,
}
impl Server {
pub fn new() -> Self {
let session_manager = SessionManagerBuilder::create().build().unwrap();
let endpoint = Route::new()
.nest("/", clickhouse_router())
.with(HTTPSessionMiddleware { session_manager });
Server { endpoint }
}
pub async fn get_response(&self, req: Request) -> (StatusCode, String) {
let response = self.endpoint.get_response(req).await;
let status = response.status();
let body = response.into_body().into_string().await.unwrap();
(status, body)
}
pub async fn get(&self, sql: &str) -> (StatusCode, String) {
self.get_response(QueryBuilder::new(sql).build()).await
}
pub async fn post(&self, sql: &str, body: &str) -> (StatusCode, String) {
self.get_response(QueryBuilder::new(sql).body(body.to_string()).build())
.await
}
}