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
use std::{
    collections::VecDeque,
    io::{self, Write},
};

use crate::{byte_generator::bytes::generate_bytes, configuration::config_model::GenericConfiguration, datastores::{datastore::DataGeneration, generic::common_models::{CdDt, ForeignKeyRel, TableFields, TempKeys}, postgres::{
            const_types::const_types,
            discover, insert,
            random_values::{generate_date_time, generate_numeric},
        }}, name_generator::{
        loader::{loader, name_generator_exists},
        name::generate_name,
    }, number_generator::number::{generate_int_number, int_generator_exists}, random_number, string_generator::strings::generate_alphas};

use super::datastore_models::Postgres;
use postgres::{Client, NoTls};

impl DataGeneration<Client> for Postgres {
    fn spawn(&mut self, config: &GenericConfiguration, no_of_record: i32) {
        let db_configuration = match &config.postgres_configuration {
            Some(config) => config,
            None => {
                println!("Configuration not found skipping postgres data generator");
                return;
            }
        };

        let connection_string = format!(
            "host={} user={} password={} port={}",
            &db_configuration.address,
            &db_configuration.user,
            &db_configuration.password,
            &db_configuration.port,
        );

        let mut client = match Client::connect(connection_string.as_str(), NoTls) {
            Ok(data) => data,
            Err(why) => {
                panic!("{}", why);
            }
        };

        <Postgres as DataGeneration<Client>>::set_schema(
            self,
            &mut client,
            &db_configuration.schema,
        );

        let mut temp_keys: Vec<TempKeys> = vec![];
        for table in &self.schema {
            println!("");
            println!("* Generating records for {:?}", &table.table_name);

            let mut columns: Vec<CdDt> = table
                .clone()
                .fields
                .into_iter()
                .filter(|a| a.key != "PRI")
                .map(|f| {
                    let fk_exists = table
                        .clone()
                        .rel
                        .into_iter()
                        .any(|r| r.column_name == f.field);

                    let dep = table
                        .clone()
                        .rel
                        .into_iter()
                        .find(|r| r.column_name == f.field);

                    return CdDt {
                        name: f.field,
                        data_type: f.data_type,
                        fk: fk_exists,
                        non_generated: false,
                        dep: dep,
                        nullable: if f.null == "YES" { true } else { false }
                    };
                })
                .collect();

            columns.sort_by(|a, b| a.fk.cmp(&b.fk));
            let mut fk_keys: Vec<String> = vec![];
            for _i in 0..no_of_record {
                print!("*");
                io::stdout().flush();

                let mut values: Vec<String> = vec![];
                let mut fk_table_data;
                for cd in &columns {
                    if cd.clone().fk == false {
                        let end_bytes = cd.data_type.find("(").unwrap_or(cd.data_type.len());

                        match &cd.data_type[0..end_bytes] {
                            const_types::VARCHAR | const_types::CHAR | const_types::TEXT => {
                                if name_generator_exists(&config, &cd.name)
                                    && cd.data_type.contains(const_types::VARCHAR)
                                {
                                    values.push(format!(
                                        "'{}'",
                                        generate_name(&loader(&config, &cd.name))
                                    ));
                                } else {
                                    values.push(format!("'{}'", generate_alphas(&cd.data_type)));
                                }
                            }
                            const_types::BYTE => {
                                values.push(format!("'\\x{}'", generate_bytes(&cd.data_type)));
                            }
                            const_types::INT
                            | const_types::SMALLINT
                            | const_types::BIGINT
                            | const_types::DECIMAL
                            | const_types::DOUBLE
                            | const_types::REAL => {
                                if int_generator_exists(&config, &cd.name)
                                    && cd.data_type.eq(const_types::INT)
                                {
                                    values.push(format!(
                                        "'{}'",
                                        generate_int_number(&config, &cd.name).to_string()
                                    ));
                                } else {
                                    values.push(format!(
                                        "'{}'",
                                        generate_numeric(&cd.data_type).unwrap_or("0".to_string())
                                    ));
                                }
                            }
                            const_types::DATE
                            | const_types::TIMESTAMP
                            | const_types::TIME
                            | const_types::INTERVAL => {
                                values.push(format!(
                                    "'{}'",
                                    generate_date_time(&cd.data_type).unwrap()
                                ));
                            }
                            const_types::BOOLEAN => {
                                let value = random_number!(i8)(0, 2);
                                let output = if value == 0 { "true" } else { "false" };
                                values.push(format!("{}", output));
                            }
                            _ => println!("type {} not currently supported", cd.data_type),
                        }
                    } else {
                        let fk_table = cd.clone().dep.unwrap().referenced_table_name;
                        fk_table_data = temp_keys
                            .clone()
                            .into_iter()
                            .find(|f| f.table_name == fk_table)
                            .unwrap();
                        let fk_index = random_number!(i32)(0, fk_table_data.id.len() as i32);
                        values.push(format!(
                            "'{}'",
                            fk_table_data.id.get(fk_index as usize).unwrap()
                        ));
                    }
                }

                let key = insert::insert_record(
                    &mut client,
                    table.table_name.to_owned(),
                    columns // TODO: change this to supported types only
                        .clone()
                        .into_iter()
                        .map(|f| f.name)
                        .collect::<Vec<String>>()
                        .join(","),
                    values.join(","),
                );
                
                fk_keys.push(key.unwrap().to_string());
            }

            temp_keys.push(TempKeys {
                id: fk_keys,
                table_name: table.clone().table_name,
            });
        }
    }

    fn set_schema(&mut self, client: &mut Client, schema: &String) {
        let tables = discover::get_tables(client, schema.clone());
        for t in tables.unwrap() {
            let fields = discover::get_columns(client, t.to_string(), schema.to_string());
            let get_foreign_keys =
                discover::get_foreign_keys(client, t.to_string(), schema.clone());

            self.schema.push(TableFields {
                table_name: t.clone(),
                fields: fields.unwrap(),
                rel: get_foreign_keys.unwrap_or(vec![]),
            })
        }
    }

    fn new() -> Self {
        let table_fields: Vec<TableFields> = vec![];
        Self {
            schema: table_fields,
        }
    }

    fn build_depedency_tree(
        &mut self,
        safe_tf: &mut VecDeque<TableFields>,
        unsafe_tf: &mut VecDeque<TableFields>,
        cyclic_dependency_check: bool
    ) -> (VecDeque<TableFields>, VecDeque<TableFields>) {
        todo!()
    }
}