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
//! # General-Purpose file loader
//!
//! This is the original entry point to the FDB loading API. A [`SchemaLoader`] wraps
//! an implementation of [`BufRead`] and loads the data from the file into an
//! instance of [`Schema`].
//!
//! This uses the methods defined in the `reader` module and produces the data
//! structure defined in the `core` module.

use super::*;
use crate::io::read::{DatabaseBufReader, DatabaseBuilder, DatabaseReader};
use assembly_core::reader::{FileError, FileResult};
use assembly_fdb_core::file::{
    FDBBucketHeader, FDBColumnHeader, FDBRowHeader, FDBTableDataHeader, FDBTableDefHeader,
    FDBTableHeader,
};
use std::convert::TryFrom;
use std::fs;
use std::io::{BufRead, BufReader, Seek};

/// Configuration for the [`SchemaLoader`]
pub trait LoaderConfig {
    /// Whether to process to table specified by `def`
    fn load_table_data(&self, def: &TableDef) -> bool;
}

/// Configuration for SchemaLoader
pub struct LoaderConfigImpl<P>
where
    P: Fn(&TableDef) -> bool,
{
    /// The policy for tables
    pub table_data_policy: P,
}

impl<P> LoaderConfig for LoaderConfigImpl<P>
where
    P: Fn(&TableDef) -> bool,
{
    fn load_table_data(&self, def: &TableDef) -> bool {
        (self.table_data_policy)(def)
    }
}

/// Structure to load a schema from some encapsulated stream
pub struct SchemaLoader<'a, T, C> {
    inner: &'a mut T,
    config: C,
}

impl TryFrom<&str> for Schema {
    type Error = FileError;

    fn try_from(filename: &str) -> FileResult<Schema> {
        let file = fs::File::open(filename)?;
        Schema::try_from(file)
    }
}

impl TryFrom<fs::File> for Schema {
    type Error = FileError;

    fn try_from(file: fs::File) -> FileResult<Schema> {
        let mut reader = BufReader::new(file);
        let config = LoaderConfigImpl {
            table_data_policy: |_| true,
        };
        let mut loader = SchemaLoader::open(&mut reader, config);
        loader.try_load_schema()
    }
}

impl<'a, T, C> SchemaLoader<'a, T, C>
where
    T: BufRead + Seek,
    C: LoaderConfig,
{
    /// Create a new loader from the given reader
    pub fn open(inner: &'a mut T, config: C) -> Self {
        Self { inner, config }
    }

    /// Try to load a row
    pub fn try_load_row(&mut self, header: FDBRowHeader) -> FileResult<Row> {
        let a = &mut self.inner;
        let field_list = a.get_field_data_list(header)?;
        let mut fields: Vec<Field> = Vec::with_capacity(field_list.len());
        for field in field_list {
            match self.inner.try_load_field(&field) {
                Ok(value) => fields.push(value),
                Err(e) => println!("{:?}", e),
            }
        }
        Ok(Row::from(fields))
    }

    /// Try to load a bucket
    pub fn try_load_bucket(&mut self, header: FDBBucketHeader) -> FileResult<Bucket> {
        let row_header_addr_it = self
            .inner
            .get_row_header_addr_iterator(header.row_header_list_head_addr);
        let row_header_addr_list = row_header_addr_it.collect::<Result<Vec<_>, _>>()?;
        let mut rows: Vec<Row> = Vec::with_capacity(row_header_addr_list.len());
        for row_header_addr in row_header_addr_list {
            let row_header = self.inner.get_row_header(row_header_addr)?;
            let row = self.try_load_row(row_header)?;
            rows.push(row);
        }
        Ok(Bucket(rows))
    }

    /// Try to load a column
    pub fn try_load_column(&mut self, header: FDBColumnHeader) -> FileResult<Column> {
        // FIXME: remove unwrap
        let col_type = ValueType::try_from(header.column_data_type).unwrap();
        let col_name = self.inner.get_string(header.column_name_addr)?;
        Ok(Column::from((col_name.as_ref(), col_type)))
    }

    /// Try to load a table definition
    pub fn try_load_table_def(&mut self, header: FDBTableDefHeader) -> FileResult<TableDef> {
        let name = self.inner.get_string(header.table_name_addr)?;
        let column_header_list: Vec<FDBColumnHeader> =
            self.inner.get_column_header_list(&header)?;

        let columns: Vec<Column> = column_header_list
            .iter()
            .map(|column_header| self.try_load_column(*column_header))
            .collect::<Result<Vec<_>, _>>()?;

        Ok(TableDef { columns, name })
    }

    /// Try to load table data
    pub fn try_load_table_data(&mut self, header: FDBTableDataHeader) -> FileResult<TableData> {
        let bucket_header_list: Vec<FDBBucketHeader> =
            self.inner.get_bucket_header_list(&header)?;

        let buckets: Vec<Bucket> = bucket_header_list
            .iter()
            .map(|bucket_header| self.try_load_bucket(*bucket_header))
            .collect::<Result<Vec<_>, _>>()?;

        Ok(TableData { buckets })
    }

    /// Try to load a table
    pub fn try_load_table(&mut self, header: FDBTableHeader) -> FileResult<Table> {
        let def_header = self
            .inner
            .get_table_def_header(header.table_def_header_addr)?;
        let definition = self.try_load_table_def(def_header)?;
        if self.config.load_table_data(&definition) {
            let data_header = self
                .inner
                .get_table_data_header(header.table_data_header_addr)?;
            let data = self.try_load_table_data(data_header)?;
            Ok(Table::from(definition, data))
        } else {
            Ok(Table::new(definition))
        }
    }

    /// Try to load a schema
    pub fn try_load_schema(&mut self) -> FileResult<Schema> {
        let header = self.inner.get_header()?;
        let table_header_list: Vec<FDBTableHeader> = self.inner.get_table_header_list(header)?;
        let tables: Vec<Table> = table_header_list
            .iter()
            .map(|table_header| self.try_load_table(*table_header))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Schema::from(tables))
    }
}