clickhouse_client/query/fmt/tab/
mod.rs

1//! TabSeparated format
2
3#[cfg(test)]
4mod tests;
5
6use std::{collections::HashMap, str::FromStr};
7
8use ethnum::{I256, U256};
9use time::{Date, OffsetDateTime};
10use uuid::Uuid;
11
12use crate::{
13    error::Error,
14    query::QueryData,
15    value::{
16        time::{DateExt, DateTimeExt},
17        Type, Value,
18    },
19};
20
21use super::Formatter;
22
23/// TabSeparated formatter
24#[derive(Debug, Default)]
25pub struct TsvFormatter {
26    /// Raw
27    raw: bool,
28    /// With column names
29    with_names: bool,
30    /// With column types
31    with_types: bool,
32}
33
34impl TsvFormatter {
35    /// Use the default variant
36    pub fn new() -> Self {
37        Self::default()
38    }
39
40    /// Use the variant with names
41    pub fn with_names() -> Self {
42        Self {
43            raw: false,
44            with_names: true,
45            with_types: false,
46        }
47    }
48
49    /// Use the variant with names and types
50    pub fn with_names_and_types() -> Self {
51        Self {
52            raw: false,
53            with_names: true,
54            with_types: true,
55        }
56    }
57
58    /// Use the raw variant
59    pub fn raw() -> Self {
60        Self {
61            raw: true,
62            with_names: false,
63            with_types: false,
64        }
65    }
66
67    /// Use the raw variant with names
68    pub fn raw_with_names() -> Self {
69        Self {
70            raw: true,
71            with_names: true,
72            with_types: false,
73        }
74    }
75
76    /// Use the raw variant with names and types
77    pub fn raw_with_names_and_types() -> Self {
78        Self {
79            raw: true,
80            with_names: true,
81            with_types: true,
82        }
83    }
84}
85
86impl Formatter for TsvFormatter {
87    fn serialize_value(&self, value: Value) -> Vec<u8> {
88        self.format_value(value).into_bytes()
89    }
90
91    fn serialize_query_data(&self, data: QueryData) -> Result<Vec<u8>, Error> {
92        self.format_data(data).map(|s| s.into_bytes())
93    }
94
95    fn deserialize_value(&self, bytes: &[u8], ty: Type) -> Result<Value, Error> {
96        let value = String::from_utf8(bytes.to_vec())?;
97        self.parse_value(&value, ty)
98    }
99
100    fn deserialize_query_data(
101        &self,
102        bytes: &[u8],
103        mapping: Option<&[(&str, Type)]>,
104    ) -> Result<QueryData, Error> {
105        let value = String::from_utf8(bytes.to_vec())?;
106        self.parse_data(&value, mapping)
107    }
108}
109
110/// NULL value
111const NULL: &str = r"\N";
112
113impl TsvFormatter {
114    /// Formats a [Value]
115    pub fn format_value(&self, value: Value) -> String {
116        self.format_value_iter(value, false)
117    }
118
119    /// Formats a [Value] recursively
120    fn format_value_iter(&self, value: Value, is_within_array: bool) -> String {
121        /// Implements the nullable variant for formatting
122        macro_rules! impl_nullable {
123            ($VAL:tt, $VAR:ident) => {
124                match $VAL {
125                    Some(v) => self.format_value_iter(Value::$VAR(v), is_within_array),
126                    None => NULL.to_string(),
127                }
128            };
129        }
130
131        match value {
132            Value::UInt8(v) => v.to_string(),
133            Value::UInt16(v) => v.to_string(),
134            Value::UInt32(v) => v.to_string(),
135            Value::UInt64(v) => v.to_string(),
136            Value::UInt128(v) => v.to_string(),
137            Value::UInt256(_) => {
138                let u256: U256 = value.try_into().unwrap();
139                u256.to_string()
140            }
141            Value::Int8(v) => v.to_string(),
142            Value::Int16(v) => v.to_string(),
143            Value::Int32(v) => v.to_string(),
144            Value::Int64(v) => v.to_string(),
145            Value::Int128(v) => v.to_string(),
146            Value::Int256(_) => {
147                let i256: I256 = value.try_into().unwrap();
148                i256.to_string()
149            }
150            Value::Float32(v) => v.to_string(),
151            Value::Float64(v) => v.to_string(),
152            Value::Bool(v) => v.to_string(),
153            Value::String(v) => {
154                let s = if self.raw { v } else { v.escape() };
155                if is_within_array {
156                    s.enclose()
157                } else {
158                    s
159                }
160            }
161            Value::UUID(_) => {
162                let uuid: Uuid = value.try_into().unwrap();
163                uuid.as_hyphenated().to_string()
164            }
165            Value::Date(_) | Value::Date32(_) => {
166                let date: Date = value.try_into().unwrap();
167                let s = date.format_yyyy_mm_dd();
168                if is_within_array {
169                    s.enclose()
170                } else {
171                    s
172                }
173            }
174            Value::DateTime(_) => {
175                let dt: OffsetDateTime = value.try_into().unwrap();
176                let s = dt.format_yyyy_mm_dd_hh_mm_ss();
177                if is_within_array {
178                    s.enclose()
179                } else {
180                    s
181                }
182            }
183            Value::DateTime64(_) => {
184                let dt: OffsetDateTime = value.try_into().unwrap();
185                let s = dt.format_yyyy_mm_dd_hh_mm_ss_ns();
186                if is_within_array {
187                    s.enclose()
188                } else {
189                    s
190                }
191            }
192            Value::Enum8(v) => v.to_string(),
193            Value::Enum16(v) => v.to_string(),
194            Value::Array(v) => {
195                format!(
196                    "[{}]",
197                    v.into_iter()
198                        .map(|v| self.format_value_iter(v, true))
199                        .collect::<Vec<_>>()
200                        .join(", ")
201                )
202            }
203            Value::Tuple(v) => {
204                format!(
205                    "({})",
206                    v.into_iter()
207                        .map(|v| self.format_value_iter(v, true))
208                        .collect::<Vec<_>>()
209                        .join(", ")
210                )
211            }
212            Value::Map(v) => {
213                let mut kv = v
214                    .into_iter()
215                    .map(|(k, v)| format!("'{}': {}", k, self.format_value_iter(v, true)))
216                    .collect::<Vec<_>>();
217                kv.sort();
218                format!("{{{}}}", kv.join(", "))
219            }
220            Value::Nested(fields) => {
221                let values = fields.into_values().collect::<Vec<_>>();
222                let value = Value::Array(values);
223                self.format_value_iter(value, false)
224            }
225            Value::NullableUInt8(v) => impl_nullable!(v, UInt8),
226            Value::NullableUInt16(v) => impl_nullable!(v, UInt16),
227            Value::NullableUInt32(v) => impl_nullable!(v, UInt32),
228            Value::NullableUInt64(v) => impl_nullable!(v, UInt64),
229            Value::NullableUInt128(v) => impl_nullable!(v, UInt128),
230            Value::NullableUInt256(v) => impl_nullable!(v, UInt256),
231            Value::NullableInt8(v) => impl_nullable!(v, Int8),
232            Value::NullableInt16(v) => impl_nullable!(v, Int16),
233            Value::NullableInt32(v) => impl_nullable!(v, Int32),
234            Value::NullableInt64(v) => impl_nullable!(v, Int64),
235            Value::NullableInt128(v) => impl_nullable!(v, Int128),
236            Value::NullableInt256(v) => impl_nullable!(v, Int256),
237            Value::NullableFloat32(v) => impl_nullable!(v, Float32),
238            Value::NullableFloat64(v) => impl_nullable!(v, Float64),
239            Value::NullableBool(v) => impl_nullable!(v, Bool),
240            Value::NullableString(v) => impl_nullable!(v, String),
241            Value::NullableUUID(v) => impl_nullable!(v, UUID),
242            Value::NullableDate(v) => impl_nullable!(v, Date),
243            Value::NullableDate32(v) => impl_nullable!(v, Date32),
244            Value::NullableDateTime(v) => impl_nullable!(v, DateTime),
245            Value::NullableDateTime64(v) => impl_nullable!(v, DateTime64),
246            Value::NullableEnum8(v) => impl_nullable!(v, Enum8),
247            Value::NullableEnum16(v) => impl_nullable!(v, Enum16),
248        }
249    }
250
251    /// Formats a [QueryTable]
252    pub fn format_data(&self, data: QueryData) -> Result<String, Error> {
253        // each value is followed by a tab (except the last value in a row)
254        // the last value is followed by a newline (inc. last row)
255        let mut buf = String::new();
256        let parts = data.into_parts();
257        if self.with_names {
258            if let Some(names) = parts.names {
259                let row = self.format_table_row(names)?;
260                buf.push_str(row.as_str());
261            } else {
262                return Err(Error::new("Table is missing the column names"));
263            }
264        }
265
266        if self.with_types {
267            if let Some(types) = parts.types {
268                let types = types.into_iter().map(|t| t.to_string()).collect();
269                let row = self.format_table_row(types)?;
270                buf.push_str(row.as_str());
271            } else {
272                return Err(Error::new("Table is missing the column types"));
273            }
274        }
275
276        for row in parts.rows {
277            let values = row
278                .into_iter()
279                .map(|value| self.format_value(value))
280                .collect::<Vec<_>>();
281            let row = self.format_table_row(values)?;
282            buf.push_str(row.as_str());
283        }
284
285        Ok(buf)
286    }
287
288    /// Formats a table row
289    fn format_table_row(&self, values: Vec<String>) -> Result<String, Error> {
290        let mut buf = String::new();
291        let n = values.len();
292        for (i, value) in values.iter().enumerate() {
293            buf.push_str(value);
294            if i < n - 1 {
295                buf.push('\t');
296            } else {
297                buf.push('\n');
298            }
299        }
300        Ok(buf)
301    }
302
303    /// Parses a [Value]
304    fn parse_value(&self, value: &str, ty: Type) -> Result<Value, Error> {
305        self.parse_value_iter(value, ty, false)
306    }
307
308    /// Parses a [Value] recursively
309    #[allow(clippy::only_used_in_recursion)]
310    fn parse_value_iter(
311        &self,
312        value: &str,
313        ty: Type,
314        is_within_array: bool,
315    ) -> Result<Value, Error> {
316        match ty {
317            Type::UInt8 => {
318                let v = value.parse::<u8>()?;
319                Ok(v.into())
320            }
321            Type::UInt16 => {
322                let v = value.parse::<u16>()?;
323                Ok(v.into())
324            }
325            Type::UInt32 => {
326                let v = value.parse::<u32>()?;
327                Ok(v.into())
328            }
329            Type::UInt64 => {
330                let v = value.parse::<u64>()?;
331                Ok(v.into())
332            }
333            Type::UInt128 => {
334                let v = value.parse::<u128>()?;
335                Ok(v.into())
336            }
337            Type::UInt256 => {
338                let v = value.parse::<U256>()?;
339                Ok(v.into())
340            }
341            Type::Int8 => {
342                let v = value.parse::<i8>()?;
343                Ok(v.into())
344            }
345            Type::Int16 => {
346                let v = value.parse::<i16>()?;
347                Ok(v.into())
348            }
349            Type::Int32 => {
350                let v = value.parse::<i32>()?;
351                Ok(v.into())
352            }
353            Type::Int64 => {
354                let v = value.parse::<i64>()?;
355                Ok(v.into())
356            }
357            Type::Int128 => {
358                let v = value.parse::<i128>()?;
359                Ok(v.into())
360            }
361            Type::Int256 => {
362                let v: I256 = value.parse::<I256>()?;
363                Ok(v.into())
364            }
365            Type::Float32 => {
366                let v = value.parse::<f32>()?;
367                Ok(v.into())
368            }
369            Type::Float64 => {
370                let v = value.parse::<f64>()?;
371                Ok(v.into())
372            }
373            Type::Decimal(_, _)
374            | Type::Decimal32(_)
375            | Type::Decimal64(_)
376            | Type::Decimal128(_)
377            | Type::Decimal256(_) => {
378                let v = value.parse::<f64>()?;
379                Ok(v.into())
380            }
381            Type::Bool => {
382                let v = value.parse::<bool>()?;
383                Ok(v.into())
384            }
385            Type::String => {
386                let v = value.unescape();
387                let v = if is_within_array { v.unenclose() } else { v };
388                Ok(v.into())
389            }
390            Type::FixedString(_) => {
391                let v = value.unescape();
392                let v = if is_within_array { v.unenclose() } else { v };
393                Ok(v.into())
394            }
395            Type::UUID => {
396                let v = value.parse::<Uuid>()?;
397                Ok(v.into())
398            }
399            Type::Date | Type::Date32 => {
400                let v = value.to_string();
401                let v = if is_within_array { v.unenclose() } else { v };
402                let date = Date::parse_yyyy_mm_dd(&v)?;
403                Ok(date.into())
404            }
405            Type::DateTime => {
406                let v = value.to_string();
407                let v = if is_within_array { v.unenclose() } else { v };
408                let dt = OffsetDateTime::parse_yyyy_mm_dd_hh_mm_ss(&v)?;
409                Ok(dt.into())
410            }
411            Type::DateTime64(_) => {
412                let v = value.to_string();
413                let v = if is_within_array { v.unenclose() } else { v };
414                let dt = OffsetDateTime::parse_yyyy_mm_dd_hh_mm_ss_ns(&v)?;
415                Ok(dt.into())
416            }
417            Type::Enum8(variants) => match variants.get(value) {
418                Some(i) => Ok(Value::Enum8(*i)),
419                None => Err(Error::new(
420                    format!("Invalid enum variant: {value}").as_str(),
421                )),
422            },
423            Type::Enum16(variants) => match variants.get(value) {
424                Some(i) => Ok(Value::Enum16(*i)),
425                None => Err(Error::new(
426                    format!("Invalid enum variant: {value}").as_str(),
427                )),
428            },
429            Type::Array(ty) => {
430                if let Some(s) = value.trim().strip_prefix('[') {
431                    if let Some(s) = s.strip_suffix(']') {
432                        let parts = s.trim().split(',').collect::<Vec<_>>();
433                        let mut values = vec![];
434                        for part in parts {
435                            let value = self.parse_value_iter(part.trim(), *ty.clone(), true)?;
436                            values.push(value);
437                        }
438                        Ok(Value::Array(values))
439                    } else {
440                        Err(Error::new("Invalid array"))
441                    }
442                } else {
443                    Err(Error::new("Invalid array"))
444                }
445            }
446            Type::Tuple(types) => {
447                if let Some(s) = value.trim().strip_prefix('(') {
448                    if let Some(s) = s.strip_suffix(')') {
449                        let parts = s.trim().split(',').collect::<Vec<_>>();
450                        if parts.len() != types.len() {
451                            return Err(Error::new("Invalid tuple"));
452                        }
453                        let mut values = vec![];
454                        for (i, part) in parts.into_iter().enumerate() {
455                            let value =
456                                self.parse_value_iter(part.trim(), types[i].clone(), true)?;
457                            values.push(value);
458                        }
459                        Ok(Value::Tuple(values))
460                    } else {
461                        Err(Error::new("Invalid tuple"))
462                    }
463                } else {
464                    Err(Error::new("Invalid tuple"))
465                }
466            }
467            Type::Map(_ty_key, ty_val) => {
468                if let Some(s) = value.trim().strip_prefix('{') {
469                    if let Some(s) = s.strip_suffix('}') {
470                        let mut map = HashMap::new();
471                        let kv_pairs = s.trim().split(',').collect::<Vec<_>>();
472                        for kv in kv_pairs {
473                            let parts = kv.trim().split(':').collect::<Vec<_>>();
474                            if parts.len() != 2 {
475                                return Err(Error::new("Invalid map"));
476                            }
477                            let key = parts[0].trim().unenclose();
478                            let value_str = parts[1].trim();
479                            let value = self.parse_value_iter(value_str, *ty_val.clone(), true)?;
480                            map.insert(key, value);
481                        }
482                        Ok(Value::Map(map))
483                    } else {
484                        Err(Error::new("Invalid map"))
485                    }
486                } else {
487                    Err(Error::new("Invalid map"))
488                }
489            }
490            Type::Nested(fields) => {
491                if let Some(s) = value.trim().strip_prefix('[') {
492                    if let Some(s) = s.strip_suffix(']') {
493                        let parts = s.trim().split(',').collect::<Vec<_>>();
494                        let mut map = HashMap::new();
495                        for (i, part) in parts.into_iter().enumerate() {
496                            let (key, ty) =
497                                fields.get(i).ok_or(Error::new("Invalid nested value"))?;
498                            let value = self.parse_value_iter(part.trim(), ty.clone(), true)?;
499                            map.insert(key.to_string(), value);
500                        }
501                        Ok(Value::Nested(map))
502                    } else {
503                        Err(Error::new("Invalid array"))
504                    }
505                } else {
506                    Err(Error::new("Invalid array"))
507                }
508            }
509            Type::NullableUInt8 => match value {
510                NULL => Ok(Value::NullableUInt8(None)),
511                _ => {
512                    let v = self.parse_value_iter(value, Type::UInt8, false)?;
513                    Ok(v.into_nullable().unwrap())
514                }
515            },
516            Type::NullableUInt16 => match value {
517                NULL => Ok(Value::NullableUInt16(None)),
518                _ => {
519                    let v = self.parse_value_iter(value, Type::UInt16, false)?;
520                    Ok(v.into_nullable().unwrap())
521                }
522            },
523            Type::NullableUInt32 => match value {
524                NULL => Ok(Value::NullableUInt32(None)),
525                _ => {
526                    let v = self.parse_value_iter(value, Type::UInt32, false)?;
527                    Ok(v.into_nullable().unwrap())
528                }
529            },
530            Type::NullableUInt64 => match value {
531                NULL => Ok(Value::NullableUInt64(None)),
532                _ => {
533                    let v = self.parse_value_iter(value, Type::UInt64, false)?;
534                    Ok(v.into_nullable().unwrap())
535                }
536            },
537            Type::NullableUInt128 => match value {
538                NULL => Ok(Value::NullableUInt128(None)),
539                _ => {
540                    let v = self.parse_value_iter(value, Type::UInt128, false)?;
541                    Ok(v.into_nullable().unwrap())
542                }
543            },
544            Type::NullableUInt256 => match value {
545                NULL => Ok(Value::NullableUInt256(None)),
546                _ => {
547                    let v = self.parse_value_iter(value, Type::UInt256, false)?;
548                    Ok(v.into_nullable().unwrap())
549                }
550            },
551            Type::NullableInt8 => match value {
552                NULL => Ok(Value::NullableInt8(None)),
553                _ => {
554                    let v = self.parse_value_iter(value, Type::Int8, false)?;
555                    Ok(v.into_nullable().unwrap())
556                }
557            },
558            Type::NullableInt16 => match value {
559                NULL => Ok(Value::NullableInt16(None)),
560                _ => {
561                    let v = self.parse_value_iter(value, Type::Int16, false)?;
562                    Ok(v.into_nullable().unwrap())
563                }
564            },
565            Type::NullableInt32 => match value {
566                NULL => Ok(Value::NullableInt32(None)),
567                _ => {
568                    let v = self.parse_value_iter(value, Type::Int32, false)?;
569                    Ok(v.into_nullable().unwrap())
570                }
571            },
572            Type::NullableInt64 => match value {
573                NULL => Ok(Value::NullableInt64(None)),
574                _ => {
575                    let v = self.parse_value_iter(value, Type::Int64, false)?;
576                    Ok(v.into_nullable().unwrap())
577                }
578            },
579            Type::NullableInt128 => match value {
580                NULL => Ok(Value::NullableInt128(None)),
581                _ => {
582                    let v = self.parse_value_iter(value, Type::Int128, false)?;
583                    Ok(v.into_nullable().unwrap())
584                }
585            },
586            Type::NullableInt256 => match value {
587                NULL => Ok(Value::NullableInt256(None)),
588                _ => {
589                    let v = self.parse_value_iter(value, Type::Int256, false)?;
590                    Ok(v.into_nullable().unwrap())
591                }
592            },
593            Type::NullableFloat32 => match value {
594                NULL => Ok(Value::NullableFloat32(None)),
595                _ => {
596                    let v = self.parse_value_iter(value, Type::Float32, false)?;
597                    Ok(v.into_nullable().unwrap())
598                }
599            },
600            Type::NullableFloat64 => match value {
601                NULL => Ok(Value::NullableFloat64(None)),
602                _ => {
603                    let v = self.parse_value_iter(value, Type::Float64, false)?;
604                    Ok(v.into_nullable().unwrap())
605                }
606            },
607            Type::NullableDecimal(p, s) => match value {
608                NULL => Ok(Value::NullableFloat64(None)),
609                _ => {
610                    let v = self.parse_value_iter(value, Type::Decimal(p, s), false)?;
611                    Ok(v.into_nullable().unwrap())
612                }
613            },
614            Type::NullableDecimal32(s) => match value {
615                NULL => Ok(Value::NullableFloat64(None)),
616                _ => {
617                    let v = self.parse_value_iter(value, Type::Decimal32(s), false)?;
618                    Ok(v.into_nullable().unwrap())
619                }
620            },
621            Type::NullableDecimal64(s) => match value {
622                NULL => Ok(Value::NullableFloat64(None)),
623                _ => {
624                    let v = self.parse_value_iter(value, Type::Decimal64(s), false)?;
625                    Ok(v.into_nullable().unwrap())
626                }
627            },
628            Type::NullableDecimal128(s) => match value {
629                NULL => Ok(Value::NullableFloat64(None)),
630                _ => {
631                    let v = self.parse_value_iter(value, Type::Decimal128(s), false)?;
632                    Ok(v.into_nullable().unwrap())
633                }
634            },
635            Type::NullableDecimal256(s) => match value {
636                NULL => Ok(Value::NullableFloat64(None)),
637                _ => {
638                    let v = self.parse_value_iter(value, Type::Decimal256(s), false)?;
639                    Ok(v.into_nullable().unwrap())
640                }
641            },
642            Type::NullableBool => match value {
643                NULL => Ok(Value::NullableBool(None)),
644                _ => {
645                    let v = self.parse_value_iter(value, Type::Bool, false)?;
646                    Ok(v.into_nullable().unwrap())
647                }
648            },
649            Type::NullableString => match value {
650                NULL => Ok(Value::NullableString(None)),
651                _ => {
652                    let v = self.parse_value_iter(value, Type::String, false)?;
653                    Ok(v.into_nullable().unwrap())
654                }
655            },
656            Type::NullableFixedString(n) => match value {
657                NULL => Ok(Value::NullableString(None)),
658                _ => {
659                    let v = self.parse_value_iter(value, Type::FixedString(n), false)?;
660                    Ok(v.into_nullable().unwrap())
661                }
662            },
663            Type::NullableUUID => match value {
664                NULL => Ok(Value::NullableUUID(None)),
665                _ => {
666                    let v = self.parse_value_iter(value, Type::UUID, false)?;
667                    Ok(v.into_nullable().unwrap())
668                }
669            },
670            Type::NullableDate => match value {
671                NULL => Ok(Value::NullableDate(None)),
672                _ => {
673                    let v = self.parse_value_iter(value, Type::Date, false)?;
674                    Ok(v.into_nullable().unwrap())
675                }
676            },
677            Type::NullableDate32 => match value {
678                NULL => Ok(Value::NullableDate32(None)),
679                _ => {
680                    let v = self.parse_value_iter(value, Type::Date32, false)?;
681                    Ok(v.into_nullable().unwrap())
682                }
683            },
684            Type::NullableDateTime => match value {
685                NULL => Ok(Value::NullableDateTime(None)),
686                _ => {
687                    let v = self.parse_value_iter(value, Type::DateTime, false)?;
688                    Ok(v.into_nullable().unwrap())
689                }
690            },
691            Type::NullableDateTime64(p) => match value {
692                NULL => Ok(Value::NullableDateTime64(None)),
693                _ => {
694                    let v = self.parse_value_iter(value, Type::DateTime64(p), false)?;
695                    Ok(v.into_nullable().unwrap())
696                }
697            },
698            Type::NullableEnum8(variants) => match value {
699                NULL => Ok(Value::NullableEnum8(None)),
700                _ => {
701                    let v = self.parse_value_iter(value, Type::Enum8(variants.clone()), false)?;
702                    Ok(v.into_nullable().unwrap())
703                }
704            },
705            Type::NullableEnum16(variants) => match value {
706                NULL => Ok(Value::NullableEnum16(None)),
707                _ => {
708                    let v = self.parse_value_iter(value, Type::Enum16(variants.clone()), false)?;
709                    Ok(v.into_nullable().unwrap())
710                }
711            },
712        }
713    }
714
715    /// Parses a [QueryTable]
716    pub fn parse_data(
717        &self,
718        value: &str,
719        mapping: Option<&[(&str, Type)]>,
720    ) -> Result<QueryData, Error> {
721        // split rows
722        let mut rows = value.split('\n').collect::<Vec<_>>();
723
724        // parse names and types from the buffer
725        let mut data = if self.with_names {
726            if rows.is_empty() {
727                return Err(Error::new("Table is missing the row with names"));
728            }
729            let row = rows.remove(0);
730            let names = row.split('\t').collect::<Vec<_>>();
731
732            if self.with_types {
733                if rows.is_empty() {
734                    return Err(Error::new("Table is missing the row with types"));
735                }
736                let row = rows.remove(0);
737                let types = row
738                    .split('\t')
739                    .map(Type::from_str)
740                    .collect::<Result<Vec<Type>, Error>>()?;
741                let names_and_types = names
742                    .into_iter()
743                    .enumerate()
744                    .map(|(i, n)| (n, types[i].clone()))
745                    .collect();
746
747                QueryData::with_names_and_types(names_and_types)
748            } else {
749                QueryData::with_names(names)
750            }
751        } else {
752            QueryData::no_headers()
753        };
754
755        // parse rows from the buffer
756        let types = if let Some(types) = data.get_types() {
757            types
758        } else if let Some(mapping) = mapping {
759            mapping.iter().map(|(_, t)| t.clone()).collect()
760        } else {
761            return Err(Error::new("Deserializing data requires a mapping table"));
762        };
763
764        for row_str in rows {
765            if row_str.is_empty() {
766                break;
767            }
768
769            let mut row = vec![];
770            for (i, value) in row_str.split('\t').enumerate() {
771                let ty = types
772                    .get(i)
773                    .ok_or(Error(format!("No type for value at index {i}")))?
774                    .clone();
775                row.push(self.parse_value(value, ty)?);
776            }
777            data.add_row(row);
778        }
779
780        Ok(data)
781    }
782}
783
784/// Extension trait for strings
785trait StringExt {
786    /// Escapes a string
787    fn escape(&self) -> String;
788
789    /// Unescapes a string
790    fn unescape(&self) -> String;
791
792    /// Encloses a string
793    fn enclose(&self) -> String;
794
795    /// Unencloses a string
796    fn unenclose(&self) -> String;
797}
798
799impl StringExt for &str {
800    fn escape(&self) -> String {
801        self.replace('\\', r"\b")
802            .replace(' ', r"\n")
803            .replace('\t', r"\t")
804            .replace('\'', r"\'")
805    }
806
807    fn unescape(&self) -> String {
808        self.replace(r"\b", "\\")
809            .replace(r"\n", " ")
810            .replace(r"\t", "\t")
811            .replace(r"\'", "\'")
812    }
813
814    fn enclose(&self) -> String {
815        format!("'{self}'")
816    }
817
818    fn unenclose(&self) -> String {
819        self.trim_start_matches('\'')
820            .trim_end_matches('\'')
821            .to_string()
822    }
823}
824
825impl StringExt for String {
826    fn escape(&self) -> String {
827        self.as_str().escape()
828    }
829
830    fn unescape(&self) -> String {
831        self.as_str().unescape()
832    }
833
834    fn enclose(&self) -> String {
835        self.as_str().enclose()
836    }
837
838    fn unenclose(&self) -> String {
839        self.as_str().unenclose()
840    }
841}