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
/// StmtData, this contains both statement and the data
use crate::{
    ast::{Statement, TableLookup},
    parser::utils::bytes_to_chars,
    CsvRows,
};
pub use parser::parse_select_chars;
use parser::parse_statement_chars;
use std::io::{BufRead, BufReader, Read};

mod parser;

/// Contains both the statement commands and the data
pub struct StmtData<R>
where
    R: Read + Send + Sync,
{
    pub header: Statement,
    pub body: BufReader<R>,
}

impl<R> StmtData<R>
where
    R: Read + Send + Sync,
{
    pub fn from_reader(reader: R) -> Result<Self, crate::Error> {
        let mut bufread = BufReader::new(reader);
        let mut first_line = vec![];
        let _header_len = bufread.read_until(b'\n', &mut first_line)?;

        let header_input = bytes_to_chars(&first_line);
        let statement = parse_statement_chars(&header_input)?;

        Ok(StmtData {
            header: statement,
            body: bufread,
        })
    }

    pub fn statement(&self) -> Statement {
        self.header.clone()
    }

    /// consume self and return as csv rows iterator
    pub fn rows_iter(
        self,
        table_lookup: Option<&TableLookup>,
    ) -> Option<CsvRows<R>> {
        match self.header {
            Statement::Create(table_def) => {
                Some(CsvRows::new(self.body, table_def.columns))
            }
            Statement::Insert(insert) => {
                let table_def = table_lookup
                    .expect("need table lookup")
                    .get_table_def(&insert.into.name)
                    .expect("must have table lookup");
                Some(CsvRows::new(
                    self.body,
                    table_def.matching_column_def(&insert.columns),
                ))
            }
            Statement::Select(_) => None,
            Statement::Delete(_) => None,
            Statement::BulkDelete(delete) => {
                let table_def = table_lookup
                    .expect("need table lookup")
                    .get_table_def(&delete.from.name)
                    .expect("must have table lookup");
                Some(CsvRows::new(
                    self.body,
                    table_def.matching_column_def(&delete.columns),
                ))
            }
            Statement::BulkUpdate(update) => {
                let table_def = table_lookup
                    .expect("need table lookup")
                    .get_table_def(&update.table.name)
                    .expect("must have table lookup");
                Some(CsvRows::new(
                    self.body,
                    table_def.matching_column_def(&update.columns),
                ))
            }
            _ => todo!("rows_iter for {:?}.. not yet", self.header),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data_value::DataValue;

    #[test]
    fn test_csv_data() {
        let data = "PUT /product(*product_id:s32,@name:text,description:text,updated:utc,created_by(users):u32,@is_active:bool)\n\
            1,go pro,a slightly used go pro, 2019-10-31 10:10:10\n\
            2,shovel,a slightly used shovel, 2019-11-11 11:11:11\n\
            ";

        let csv_data =
            StmtData::from_reader(data.as_bytes()).expect("must be valid");

        let rows: Vec<Vec<DataValue>> = csv_data
            .rows_iter(None)
            .expect("must have iterator")
            .collect();
        println!("rows: {:#?}", rows);
        assert_eq!(rows.len(), 2);
    }
}