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
//! The analyzer should check that tables and columns exist before allowing a query to proceed.
//! More features will come I'm sure
mod definition_lookup;
use definition_lookup::{DefinitionLookup, DefinitionLookupError};

use crate::constants::{BuiltinSqlTypes, Nullable, SqlTypeError};
use crate::engine::objects::{JoinType, SqlTuple};

use super::io::VisibleRowManager;
use super::objects::types::{BaseSqlTypes, BaseSqlTypesError, SqlTypeDefinition};
use super::objects::{
    Attribute, CommandType, ParseExpression, ParseTree, QueryTree, RangeRelation,
    RangeRelationTable, RawInsertCommand, RawSelectCommand, Table,
};
use super::transactions::TransactionId;
use std::collections::HashMap;
use std::sync::Arc;
use thiserror::Error;

#[derive(Clone, Debug)]
pub struct Analyzer {
    dl: DefinitionLookup,
}

impl Analyzer {
    pub fn new(vis_row_man: VisibleRowManager) -> Analyzer {
        Analyzer {
            dl: DefinitionLookup::new(vis_row_man),
        }
    }

    pub async fn analyze(
        &self,
        tran_id: TransactionId,
        parse_tree: ParseTree,
    ) -> Result<QueryTree, AnalyzerError> {
        match parse_tree {
            ParseTree::Insert(i) => {
                return self.insert_processing(tran_id, i).await;
            }
            ParseTree::Select(i) => {
                return self.select_processing(tran_id, i).await;
            }
            _ => return Err(AnalyzerError::NotImplemented()),
        }
    }

    async fn insert_processing(
        &self,
        tran_id: TransactionId,
        raw_insert: RawInsertCommand,
    ) -> Result<QueryTree, AnalyzerError> {
        let definition = self
            .dl
            .get_definition(tran_id, raw_insert.table_name)
            .await?;

        let (output_type, val_cols) = Analyzer::validate_columns(
            definition.clone(),
            raw_insert.provided_columns,
            raw_insert.provided_values,
        )?;

        let anon_tbl = RangeRelation::AnonymousTable(Arc::new(vec![val_cols]));
        let target_tbl = RangeRelation::Table(RangeRelationTable {
            alias: None,
            table: definition.clone(),
        });

        //We should be good to build the query tree if we got here
        Ok(QueryTree {
            command_type: CommandType::Insert,
            //Insert columns will be the target
            targets: Arc::new(output_type),
            range_tables: vec![target_tbl.clone(), anon_tbl.clone()],
            joins: vec![((JoinType::Inner, target_tbl, anon_tbl))],
        })
    }

    async fn select_processing(
        &self,
        tran_id: TransactionId,
        raw_select: RawSelectCommand,
    ) -> Result<QueryTree, AnalyzerError> {
        let definition = self.dl.get_definition(tran_id, raw_select.table).await?;

        //Need to valid the columns asked for exist
        let mut targets = vec![];
        'outer: for rcol in raw_select.columns {
            for c in definition.attributes.as_slice() {
                if rcol == c.name {
                    targets.push((c.name.clone(), c.sql_type.clone()));
                    continue 'outer;
                }
            }
            return Err(AnalyzerError::UnknownColumn(rcol));
        }

        //We should be good to build the query tree if we got here
        Ok(QueryTree {
            command_type: CommandType::Select,
            targets: Arc::new(SqlTypeDefinition(targets)),
            range_tables: vec![RangeRelation::Table(RangeRelationTable {
                table: definition,
                alias: None,
            })],
            joins: vec![],
        })
    }

    /// This function will sort the columns and values and convert them
    fn validate_columns(
        table: Arc<Table>,
        provided_columns: Option<Vec<String>>,
        provided_values: Vec<ParseExpression>,
    ) -> Result<(SqlTypeDefinition, SqlTuple), AnalyzerError> {
        let columns = match provided_columns {
            Some(pc) => {
                //Can't assume we got the columns in order so we'll have to reorder to match the table
                let mut provided_pair: HashMap<String, ParseExpression> =
                    pc.into_iter().zip(provided_values).collect();
                let mut result = vec![];
                for a in table.attributes.clone() {
                    match provided_pair.get(&a.name) {
                        Some(ppv) => {
                            result.push((a.clone(), Some(ppv.clone())));
                            provided_pair.remove(&a.name);
                        }
                        None => match a.nullable {
                            Nullable::NotNull => return Err(AnalyzerError::MissingColumn(a)),
                            Nullable::Null => result.push((a, None)),
                        },
                    }
                }

                if !provided_pair.is_empty() {
                    return Err(AnalyzerError::UnknownColumns(
                        provided_pair.keys().map(|s| s.clone()).collect(),
                    ));
                }

                result
            }
            None => {
                //Assume we are in order of the table columns
                table
                    .attributes
                    .clone()
                    .into_iter()
                    .zip(provided_values)
                    .map(|(a, s)| (a, Some(s)))
                    .collect()
            }
        };

        Analyzer::convert_into_types(columns)
    }

    fn convert_into_types(
        provided: Vec<(Attribute, Option<ParseExpression>)>,
    ) -> Result<(SqlTypeDefinition, SqlTuple), AnalyzerError> {
        let mut tbl_cols = vec![];
        let mut val_cols = vec![];
        for (a, s) in provided {
            match s {
                Some(s2) => match s2 {
                    ParseExpression::String(s3) => {
                        tbl_cols.push((a.name, a.sql_type.clone()));
                        val_cols.push(Some(BaseSqlTypes::parse(a.sql_type, &s3)?));
                    }
                    ParseExpression::Null() => {
                        tbl_cols.push((a.name, a.sql_type));
                        val_cols.push(None);
                    }
                },
                None => {
                    tbl_cols.push((a.name, a.sql_type));
                    val_cols.push(None);
                }
            }
        }
        Ok((SqlTypeDefinition(tbl_cols), SqlTuple(val_cols)))
    }
}

#[derive(Debug, Error)]
pub enum AnalyzerError {
    #[error(transparent)]
    DefinitionLookupError(#[from] DefinitionLookupError),
    #[error(transparent)]
    BaseSqlTypesError(#[from] BaseSqlTypesError),
    #[error("Provided columns {0:?} does not match the underlying table columns {1:?}")]
    ColumnVsColumnMismatch(Vec<String>, Vec<String>),
    #[error("Provided value count {0} does not match the underlying table column count {1}")]
    ValueVsColumnMismatch(usize, usize),
    #[error("Missing required column {0}")]
    MissingColumn(Attribute),
    #[error("Unknown column received {0}")]
    UnknownColumn(String),
    #[error("Unknown columns received {0:?}")]
    UnknownColumns(Vec<String>),
    #[error("Not implemented")]
    NotImplemented(),
}