-
Notifications
You must be signed in to change notification settings - Fork 47
/
postgres_extended.rs
361 lines (340 loc) · 12.2 KB
/
postgres_extended.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
use std::fmt::Write;
use std::sync::Arc;
use anyhow::Context;
use async_trait::async_trait;
use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime};
use pg_interval::Interval;
use postgres_types::Type;
use rust_decimal::Decimal;
use sqllogictest::{ColumnType, DBOutput};
use tokio::task::JoinHandle;
use crate::{DBConfig, Result};
pub struct PostgresExtended {
client: Arc<tokio_postgres::Client>,
join_handle: JoinHandle<()>,
}
impl PostgresExtended {
pub(super) async fn connect(config: &DBConfig) -> Result<Self> {
let (host, port) = config.random_addr();
let (client, connection) = tokio_postgres::Config::new()
.host(host)
.port(port)
.dbname(&config.db)
.user(&config.user)
.password(&config.pass)
.connect(tokio_postgres::NoTls)
.await
.context(format!("failed to connect to postgres at {host}:{port}"))?;
let join_handle = tokio::spawn(async move {
if let Err(e) = connection.await {
log::error!("PostgresExtended connection error: {:?}", e);
}
});
Ok(Self {
client: Arc::new(client),
join_handle,
})
}
}
impl Drop for PostgresExtended {
fn drop(&mut self) {
self.join_handle.abort()
}
}
macro_rules! array_process {
($row:ident, $row_vec:ident, $idx:ident, $t:ty) => {
let value: Option<Vec<Option<$t>>> = $row.get($idx);
match value {
Some(value) => {
let mut output = String::new();
write!(output, "{{").unwrap();
for (i, v) in value.iter().enumerate() {
match v {
Some(v) => {
write!(output, "{}", v).unwrap();
}
None => {
write!(output, "NULL").unwrap();
}
}
if i < value.len() - 1 {
write!(output, ",").unwrap();
}
}
write!(output, "}}").unwrap();
$row_vec.push(output);
}
None => {
$row_vec.push("NULL".to_string());
}
}
};
($row:ident, $row_vec:ident, $idx:ident, $t:ty, $convert:ident) => {
let value: Option<Vec<Option<$t>>> = $row.get($idx);
match value {
Some(value) => {
let mut output = String::new();
write!(output, "{{").unwrap();
for (i, v) in value.iter().enumerate() {
match v {
Some(v) => {
write!(output, "{}", $convert(v)).unwrap();
}
None => {
write!(output, "NULL").unwrap();
}
}
if i < value.len() - 1 {
write!(output, ",").unwrap();
}
}
write!(output, "}}").unwrap();
$row_vec.push(output);
}
None => {
$row_vec.push("NULL".to_string());
}
}
};
($self:ident, $row:ident, $row_vec:ident, $idx:ident, $t:ty, $ty_name:expr) => {
let value: Option<Vec<Option<$t>>> = $row.get($idx);
match value {
Some(value) => {
let mut output = String::new();
write!(output, "{{").unwrap();
for (i, v) in value.iter().enumerate() {
match v {
Some(v) => {
let sql = format!("select ($1::{})::varchar", stringify!($ty_name));
let tmp_rows = $self.client.query(&sql, &[&v]).await.unwrap();
let value: &str = tmp_rows.get(0).unwrap().get(0);
assert!(value.len() > 0);
write!(output, "{}", value).unwrap();
}
None => {
write!(output, "NULL").unwrap();
}
}
if i < value.len() - 1 {
write!(output, ",").unwrap();
}
}
write!(output, "}}").unwrap();
$row_vec.push(output);
}
None => {
$row_vec.push("NULL".to_string());
}
}
};
}
macro_rules! single_process {
($row:ident, $row_vec:ident, $idx:ident, $t:ty) => {
let value: Option<$t> = $row.get($idx);
match value {
Some(value) => {
$row_vec.push(value.to_string());
}
None => {
$row_vec.push("NULL".to_string());
}
}
};
($row:ident, $row_vec:ident, $idx:ident, $t:ty, $convert:ident) => {
let value: Option<$t> = $row.get($idx);
match value {
Some(value) => {
$row_vec.push($convert(&value).to_string());
}
None => {
$row_vec.push("NULL".to_string());
}
}
};
($self:ident, $row:ident, $row_vec:ident, $idx:ident, $t:ty, $ty_name:expr) => {
let value: Option<$t> = $row.get($idx);
match value {
Some(value) => {
let sql = format!("select ($1::{})::varchar", stringify!($ty_name));
let tmp_rows = $self.client.query(&sql, &[&value]).await.unwrap();
let value: &str = tmp_rows.get(0).unwrap().get(0);
assert!(value.len() > 0);
$row_vec.push(value.to_string());
}
None => {
$row_vec.push("NULL".to_string());
}
}
};
}
fn bool_to_str(value: &bool) -> &'static str {
if *value {
"t"
} else {
"f"
}
}
fn varchar_to_str(value: &str) -> String {
if value.is_empty() {
"(empty)".to_string()
} else {
value.to_string()
}
}
fn float4_to_str(value: &f32) -> String {
if value.is_nan() {
"NaN".to_string()
} else if *value == f32::INFINITY {
"Infinity".to_string()
} else if *value == f32::NEG_INFINITY {
"-Infinity".to_string()
} else {
value.to_string()
}
}
fn float8_to_str(value: &f64) -> String {
if value.is_nan() {
"NaN".to_string()
} else if *value == f64::INFINITY {
"Infinity".to_string()
} else if *value == f64::NEG_INFINITY {
"-Infinity".to_string()
} else {
value.to_string()
}
}
#[async_trait]
impl sqllogictest::AsyncDB for PostgresExtended {
type Error = tokio_postgres::error::Error;
async fn run(&mut self, sql: &str) -> Result<DBOutput, Self::Error> {
let mut output = vec![];
let is_query_sql = {
let lower_sql = sql.trim_start().to_ascii_lowercase();
lower_sql.starts_with("select")
|| lower_sql.starts_with("values")
|| lower_sql.starts_with("show")
|| lower_sql.starts_with("with")
|| lower_sql.starts_with("describe")
|| ((lower_sql.starts_with("insert")
|| lower_sql.starts_with("update")
|| lower_sql.starts_with("delete"))
&& lower_sql.contains("returning"))
};
if !is_query_sql {
self.client.execute(sql, &[]).await?;
return Ok(DBOutput::StatementComplete(0));
}
let rows = self.client.query(sql, &[]).await?;
for row in rows {
let mut row_vec = vec![];
for (idx, column) in row.columns().iter().enumerate() {
match column.type_().clone() {
Type::INT2 => {
single_process!(row, row_vec, idx, i16);
}
Type::INT4 => {
single_process!(row, row_vec, idx, i32);
}
Type::INT8 => {
single_process!(row, row_vec, idx, i64);
}
Type::NUMERIC => {
single_process!(row, row_vec, idx, Decimal);
}
Type::DATE => {
single_process!(row, row_vec, idx, NaiveDate);
}
Type::TIME => {
single_process!(row, row_vec, idx, NaiveTime);
}
Type::TIMESTAMP => {
single_process!(row, row_vec, idx, NaiveDateTime);
}
Type::BOOL => {
single_process!(row, row_vec, idx, bool, bool_to_str);
}
Type::INT2_ARRAY => {
array_process!(row, row_vec, idx, i16);
}
Type::INT4_ARRAY => {
array_process!(row, row_vec, idx, i32);
}
Type::INT8_ARRAY => {
array_process!(row, row_vec, idx, i64);
}
Type::BOOL_ARRAY => {
array_process!(row, row_vec, idx, bool, bool_to_str);
}
Type::FLOAT4_ARRAY => {
array_process!(row, row_vec, idx, f32, float4_to_str);
}
Type::FLOAT8_ARRAY => {
array_process!(row, row_vec, idx, f64, float8_to_str);
}
Type::NUMERIC_ARRAY => {
array_process!(row, row_vec, idx, Decimal);
}
Type::DATE_ARRAY => {
array_process!(row, row_vec, idx, NaiveDate);
}
Type::TIME_ARRAY => {
array_process!(row, row_vec, idx, NaiveTime);
}
Type::TIMESTAMP_ARRAY => {
array_process!(row, row_vec, idx, NaiveDateTime);
}
Type::VARCHAR_ARRAY | Type::TEXT_ARRAY => {
array_process!(row, row_vec, idx, String, varchar_to_str);
}
Type::VARCHAR | Type::TEXT => {
single_process!(row, row_vec, idx, String, varchar_to_str);
}
Type::FLOAT4 => {
single_process!(row, row_vec, idx, f32, float4_to_str);
}
Type::FLOAT8 => {
single_process!(row, row_vec, idx, f64, float8_to_str);
}
Type::INTERVAL => {
single_process!(self, row, row_vec, idx, Interval, INTERVAL);
}
Type::TIMESTAMPTZ => {
single_process!(
self,
row,
row_vec,
idx,
DateTime<chrono::Utc>,
TIMESTAMPTZ
);
}
Type::INTERVAL_ARRAY => {
array_process!(self, row, row_vec, idx, Interval, INTERVAL);
}
Type::TIMESTAMPTZ_ARRAY => {
array_process!(self, row, row_vec, idx, DateTime<chrono::Utc>, TIMESTAMPTZ);
}
_ => {
todo!("Don't support {} type now.", column.type_().name())
}
}
}
output.push(row_vec);
}
if output.is_empty() {
let stmt = self.client.prepare(sql).await?;
Ok(DBOutput::Rows {
types: vec![ColumnType::Any; stmt.columns().len()],
rows: vec![],
})
} else {
Ok(DBOutput::Rows {
types: vec![ColumnType::Any; output[0].len()],
rows: output,
})
}
}
fn engine_name(&self) -> &str {
"postgres-extended"
}
}