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
// MIT License
//
// Copyright (c) 2018 Hans-Martin Will
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use std::fs;
use std::io;
use std::collections::BTreeMap;
use std::path::PathBuf;

use csv;

use super::Error;
use super::types;

/// the logical database, which is a collection of schemata
#[derive(Serialize, Deserialize, Debug)]
pub struct Database {
    pub schemata: BTreeMap<String, Schema>,
}

impl Database {
    pub fn new() -> Database {
        Database { schemata: BTreeMap::new() }
    }

    pub fn create_schema(&mut self, schema_name: &str) -> Result<(), Error> {
        if self.schemata.contains_key(schema_name) {
            return Err(Error::from(
                format!("Schema '{}' is already defined", schema_name),
            ));
        }

        let old_value = self.schemata.insert(
            String::from(schema_name),
            Schema::new(schema_name),
        );
        assert!(old_value.is_none());
        Ok(())
    }

    pub fn attach_file(
        &mut self,
        schema_name: &str,
        object_name: &str,
        path: &str,
    ) -> Result<(), Error> {
        // validate that the schema name is valid
        let ref mut schema = self.schemata.get_mut(schema_name).ok_or(
            Error::from(format!(
                "Schema '{}' not found",
                schema_name
            )),
        )?;

        // validate that the name is not already in use in the schema
        if schema.objects.contains_key(object_name) {
            return Err(Error::from(format!(
                "Object '{}' already defined in schema '{}'",
                object_name,
                schema_name
            )));
        }

        // Retrieve column information from actual data
        let file_object = File::from_data_file(object_name, path)?;
        schema.objects.insert(
            String::from(object_name),
            SchemaObject::File(file_object),
        );
        Ok(())
    }

    pub fn describe(&self, schema_name: &str, object_name: &str) -> Result<RowSet, Error> {
        // validate that the schema name is valid
        let schema = self.schemata.get(schema_name).ok_or(Error::from(format!(
            "Schema '{}' not found",
            schema_name
        )))?;

        let object = schema.objects.get(object_name).ok_or(Error::from(format!(
            "Object '{}' not found in schema {}",
            object_name,
            schema_name
        )))?;

        match object {
            &SchemaObject::File(ref file) => Ok(file.rows.clone()),
            &SchemaObject::Table(ref table) => Ok(table.rows.clone()),
            &SchemaObject::View(ref view) => Ok(view.rows.clone()),
        }
    }
}

/// description of a schema within the database
#[derive(Serialize, Deserialize, Debug)]
pub struct Schema {
    /// the schema name
    pub name: String,

    /// the collection of tables making up the database
    pub objects: BTreeMap<String, SchemaObject>,
}

impl Schema {
    fn new(name: &str) -> Self {
        Schema {
            name: String::from(name),
            objects: BTreeMap::new(),
        }
    }
}

/// currently, the only schema object types we support are tables and views
#[derive(Serialize, Deserialize, Debug)]
pub enum SchemaObject {
    /// an external CSV file
    File(File),

    /// a table object (in-memory B-Tree)
    Table(Table),

    /// a view object (query short-cut)
    View(View),
}

/// Description of a table within the database
#[derive(Serialize, Deserialize, Debug)]
pub struct Table {
    /// the name of the table
    pub name: String,

    /// description of the data rows that are stored in this table
    pub rows: RowSet,

    /// the names of the columns that are part of the primary key
    pub primary_key: Vec<String>,
}

/// An external CSV data file that can be accessed by the engine.
#[derive(Serialize, Deserialize, Debug)]
pub struct File {
    /// the name of the schema object
    pub name: String,

    /// description of the data rows that are stored in this data file
    pub rows: RowSet,

    /// the file system path to the data file
    path: PathBuf,
}

impl File {
    fn from_data_file(object_name: &str, path: &str) -> Result<File, Error> {
        // ensure that the path refers to an existing file; determine column set
        let reader_result = csv::Reader::from_path(path);

        if let Err(nested) = reader_result {
            return Err(Error::new(
                &format!("Could not open file '{}'", path),
                Box::new(nested),
            ));
        };

        let mut reader = reader_result.unwrap();
        let headers = reader.headers();

        if let Err(nested) = headers {
            return Err(Error::new(
                &format!("Could not read headers in file '{}'", path),
                Box::new(nested),
            ));
        }

        let columns: Vec<Column> = headers
            .unwrap()
            .iter()
            .map(|c| {
                Column {
                    name: String::from(c),
                    not_null: false,
                    primary_key: false,
                    data_type: types::DataType::Generic,
                }
            })
            .collect();

        // create a schema object and register it
        Ok(File {
            name: String::from(object_name),
            rows: RowSet { columns },
            path: PathBuf::from(path),
        })
    }
}

/// Various options for the CSV library; ideally, this collection of parameters would reside within the
/// CSV library and could be passed directly to the csv::ReaderBuilder constructor.
pub struct CsvOptions {
    pub delimiter: u8,
    pub has_headers: bool,
    pub flexible: bool,
    pub terminator: csv::Terminator,
    pub quote: u8,
    pub escape: Option<u8>,
    pub double_quote: bool,
    pub quoting: bool,
    pub comment: Option<u8>,
    pub buffer_capacity: usize,
}

/// Description of a table within the database
#[derive(Serialize, Deserialize, Debug)]
pub struct View {
    /// the name of the view
    pub name: String,

    /// description of the data rows that are stored in this table
    pub rows: RowSet,

    /// description of the query used to generate the view (ultimately, this should be an AST)
    pub query: String,
}

/// Description of a collection of rows of the database
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RowSet {
    /// the ordered list of columns in the database
    pub columns: Vec<Column>,
}

impl RowSet {
    pub fn empty() -> Self {
        RowSet { columns: vec![] }
    }

    pub fn meta_data() -> Self {
        RowSet {
            columns: vec![
                Column {
                    name: String::from("name"),
                    not_null: true,
                    primary_key: true,
                    data_type: types::DataType::Varchar,
                },
                Column {
                    name: String::from("not_null"),
                    not_null: true,
                    primary_key: false,
                    data_type: types::DataType::Numeric,
                },
                Column {
                    name: String::from("primary_key"),
                    not_null: true,
                    primary_key: false,
                    data_type: types::DataType::Numeric,
                },
                Column {
                    name: String::from("datatype"),
                    not_null: true,
                    primary_key: false,
                    data_type: types::DataType::Varchar,
                },
            ],
        }
    }
}

/// Description of a column with a data set
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Column {
    /// the name of the column
    pub name: String,

    /// if true, the value is required
    pub not_null: bool,

    /// if true, the column is part of the primary key
    pub primary_key: bool,

    /// the type of the column
    pub data_type: types::DataType,
}