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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
use query::Query;
use table::{Table, Column, Foreign};
use dao::Dao;

use postgres::Connection;
use regex::Regex;
use dao::Value;
use database::{Database, DatabaseDev, DatabaseDDL, DbError};
use postgres::types::Type;
use postgres::types::ToSql;
use writer::SqlFrag;
use postgres::rows::Row;
use database::SqlOption;
use r2d2::PooledConnection;
use r2d2_postgres::PostgresConnectionManager;
use std::collections::BTreeMap;

pub struct Postgres{
    /// a connection pool is provided
    pub pool: Option<PooledConnection<PostgresConnectionManager>>,
}

/// Build the Query into a SQL statements that is a valid
/// PostgreSQL sql query,
/// TODO: support version SqlOptions/specific syntax

impl Postgres{

    /// create an instance, but without a connection yet,
    /// useful when just building sql queries specific to this platform
    /// inexpensive operation, so can have multiple instances
    pub fn new()->Self{
        Postgres{pool: None}
    }


    pub fn with_pooled_connection(pool: PooledConnection<PostgresConnectionManager>)->Self{
        Postgres{pool: Some(pool)}
    }



    pub fn get_connection(&self)->&Connection{
        if self.pool.is_some(){
            &self.pool.as_ref().unwrap()
        }
        else{
            panic!("No connection for this database")
        }
    }

    /// convert Type to ToSql (postgresql native types)
    /// This is used when inserting records to the database
    /// TODO: put this somewhere organized
    /// TODO: match all the other filter types
    /// TODO: need to have a container for PgType contained before being borrowed to actual postgres type
    fn from_rust_type_tosql<'b>(&self, types: &'b Vec<Value>)->Vec<&'b ToSql>{
        let mut params:Vec<&ToSql> = vec![];
        for t in types{
            match *t {
                Value::Bool(ref x) => params.push(x),
                Value::I8(ref x) => params.push(x),
                Value::I16(ref x) => params.push(x),
                Value::I32(ref x) => params.push(x),
                Value::I64(ref x) => params.push(x),
                Value::U8(_) => panic!("unsupported/unexpected type! {:?}", t),
                Value::U16(_) => panic!("unsupported/unexpected type! {:?}", t),
                Value::U32(ref x) => params.push(x),
                Value::U64(_) => panic!("unsupported/unexpected type! {:?}", t),
                Value::F32(ref x) => params.push(x),
                Value::F64(ref x) => params.push(x),
                Value::String(ref x) => params.push(x),
                Value::VecU8(ref x) => params.push(x),
                Value::Uuid(ref x) => params.push(x),
                Value::DateTime(ref x) => params.push(x),
                Value::NaiveDate(ref x) => params.push(x),
                Value::NaiveTime(ref x) => params.push(x),
                Value::NaiveDateTime(ref x) => params.push(x),
                Value::Null => panic!("unsupported/unexpected type! {:?}", t),
                _ => panic!("not yet here {:?}", t),
            };
        }
        params
    }

    /// convert a record of a row into rust type
    fn from_sql_to_rust_type(&self, dtype:&Type, row: &Row, index:usize)->Value{
        match *dtype{
            Type::Uuid => {
                let value = row.get_opt(index);
                match value{
                    Ok(value) => Value::Uuid(value),
                    Err(_) => Value::Null,
                }
            },
            Type::Varchar | Type::Text | Type::Bpchar => {
                let value = row.get_opt(index);
                match value{
                    Ok(value) => Value::String(value),
                    Err(_) => Value::Null,
                }
            },
            Type::TimestampTZ | Type::Timestamp => {
                let value = row.get_opt(index);
                match value{
                    Ok(value) => Value::NaiveDateTime(value),
                    Err(_) => Value::Null,
                }
            },
            Type::Float4 => {
                let value = row.get_opt(index);
                match value{
                    Ok(value) => Value::F32(value),
                    Err(_) => Value::Null,
                }
            },
            Type::Numeric | Type::Float8 => {
                let value = row.get_opt(index);
                match value{
                    Ok(value) => Value::F64(value),
                    Err(_) => Value::Null,
                }
            },
            Type::Bool => {
                let value = row.get_opt(index);
                match value{
                    Ok(value) => Value::Bool(value),
                    Err(_) => Value::Null,
                }
            },
            Type::Json => {
                let value = row.get_opt(index);
                match value{
                    Ok(value) => Value::String(value),
                    Err(_) => Value::Null,
                }
            },
            Type::Int2 => {
                let value = row.get_opt(index);
                match value{
                    Ok(value) => Value::I16(value),
                    Err(_) => Value::Null,
                }
            },
            Type::Int4 => {
                let value = row.get_opt(index);
                match value{
                    Ok(value) => Value::I32(value),
                    Err(_) => Value::Null,
                }
            },
            Type::Int8 => {
                let value = row.get_opt(index);
                match value{
                    Ok(value) => Value::I64(value),
                    Err(_) => Value::Null,
                }
            },
            Type::Timetz => {
                let value = row.get_opt(index);
                match value{
                    Ok(value) => Value::DateTime(value),
                    Err(_) => Value::Null,
                }
            },
            Type::Date => {
                let value = row.get_opt(index);
                match value{
                    Ok(value) => Value::DateTime(value),
                    Err(_) => Value::Null,
                }
            },
            Type::Bytea => {
                let value = row.get_opt(index);
                match value{
                    Ok(value) => Value::VecU8(value),
                    Err(_) => Value::Null,
                }
            },
            Type::Inet => {
                let value = row.get_opt(index);
                match value{
                    Ok(value) => Value::String(value),
                    Err(_) => Value::Null,
                }
            },
            Type::Tsvector => {
                let value = row.get_opt(index);
                match value{
                    Ok(value) => Value::String(value),
                    Err(_) => Value::Null,
                }
            },
            _ => panic!("Type {:?} is not covered!", dtype)
        }
    }


    ///
    /// http://stackoverflow.com/questions/109325/postgresql-describe-table
    ///
    fn get_table_columns(&self, schema:&str, table:&str)->Vec<Column>{
        let sql = "
            SELECT
                pg_attribute.attnum AS number,
                pg_attribute.attname AS name,
                pg_attribute.attnotnull AS notnull,
                pg_catalog.format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS data_type,
                CASE
                WHEN pg_constraint.contype = 'p' THEN true
                ELSE false
                END AS is_primary,
                CASE
                WHEN pg_constraint.contype = 'u' THEN true
                ELSE false
                END AS is_unique,
                CASE
                WHEN pg_constraint.contype = 'f' THEN g.relname
                END AS foreign_table,
                CASE
                WHEN pg_attribute.atthasdef = true THEN pg_attrdef.adsrc
                END as default
                ,pg_description.description as comment
                ,(SELECT nspname FROM pg_namespace WHERE oid=g.relnamespace) AS foreign_schema
                ,(SELECT pg_attribute.attname FROM pg_attribute
                WHERE pg_attribute.attrelid = pg_constraint.confrelid
                AND pg_attribute.attnum = pg_constraint.confkey[1]
                AND pg_attribute.attisdropped = false) AS foreign_column
                ,pg_constraint.conname

            FROM pg_attribute
                JOIN pg_class
                    ON pg_class.oid = pg_attribute.attrelid
                JOIN pg_type
                    ON pg_type.oid = pg_attribute.atttypid
                LEFT JOIN pg_attrdef
                    ON pg_attrdef.adrelid = pg_class.oid
                    AND pg_attrdef.adnum = pg_attribute.attnum
                LEFT JOIN pg_namespace
                    ON pg_namespace.oid = pg_class.relnamespace
                LEFT JOIN pg_constraint
                    ON pg_constraint.conrelid = pg_class.oid
                    AND pg_attribute.attnum = ANY (pg_constraint.conkey)
                LEFT JOIN pg_class AS g
                    ON pg_constraint.confrelid = g.oid
                LEFT JOIN pg_description
                    ON pg_description.objoid = pg_class.oid
                    AND pg_description.objsubid = pg_attribute.attnum
            WHERE pg_class.relkind IN ('r','v')
                AND pg_namespace.nspname = $1
                AND pg_class.relname = $2
                AND pg_attribute.attnum > 0
                ORDER BY number
            ";
        let conn = self.get_connection();
        let stmt = conn.prepare(&sql).unwrap();
        let mut columns = Vec::new();
        for row in stmt.query(&[&schema, &table]).unwrap() {
            let name:String = row.get("name");
            let not_null:bool = row.get("notnull");
            let db_data_type:String = row.get("data_type");
            //TODO: temporarily regex the data type to extract the size as well
            let re = match Regex::new("(.+)\\((.+)\\)") {
                Ok(re) => re,
                Err(err) => panic!("{}", err),
            };

            let db_data_type = if re.is_match(&db_data_type){
                let cap = re.captures(&db_data_type).unwrap();
                let data_type = cap.at(1).unwrap().to_owned();
                //let size = cap.at(2).unwrap().to_owned();//TODO::can be use in the later future
                data_type
            }else{
                db_data_type
            };

            let is_primary:bool = row.get("is_primary");
            let is_unique:bool = row.get("is_unique");

            let default:Option<String> = match row.get_opt("default"){
                Ok(x) => Some(x),
                Err(_) => None
            };
            let comment:Option<String> = match row.get_opt("comment"){
                Ok(x) => Some(x),
                Err(_) => None
            };

            let foreign_schema:Option<String> = match row.get_opt("foreign_schema"){
                Ok(x) => Some(x),
                Err(_) => None
            };
            let foreign_column:Option<String> = match row.get_opt("foreign_column"){
                Ok(x) => Some(x),
                Err(_) => None
            };
            let foreign_table:Option<String> = match row.get_opt("foreign_table"){
                Ok(x) => Some(x),
                Err(_) => None
            };


            let foreign = if foreign_table.is_some() &&
                foreign_column.is_some() &&
                foreign_schema.is_some(){
                    Some(
                        Foreign{
                            schema:foreign_schema.unwrap(),
                            table:foreign_table.unwrap(),
                            column:foreign_column.unwrap()
                        })

                }else{
                    None
                };
            let (_, data_type) = self.dbtype_to_rust_type(&db_data_type);
            let column = Column{
                name:name,
                data_type:data_type,
                db_data_type:db_data_type,
                comment:comment,
                is_primary:is_primary,
                is_unique:is_unique,
                default:default,
                not_null:not_null,
                foreign:foreign,
                is_inherited:false,//will be corrected later in the get_meta_data
            };
            columns.push(column);
        }
        //unify due to the fact that postgresql return a separate row for
        // both primary and foreign columns
        self.unify_primary_and_foreign_column(&columns)
    }

    fn get_table_comment(&self, schema:&str, table:&str)->Option<String>{
        let sql ="
                SELECT
                    pg_class.relname AS table,
                    pg_namespace.nspname AS schema,
                    obj_description(pg_class.oid) AS comment
                FROM pg_class
                    LEFT JOIN pg_namespace
                        ON pg_namespace.oid = pg_class.relnamespace
                WHERE
                    pg_class.relkind IN ('r','v')
                    AND pg_namespace.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND nspname = $1
                    AND relname = $2
                ";
        let conn = self.get_connection();
        let stmt = conn.prepare(&sql).unwrap();
        for row in stmt.query(&[&schema, &table]).unwrap() {
            let comment:Option<String> = match row.get_opt("comment"){
                Ok(x) => Some(x),
                Err(_) => None
            };
            return comment;
        }
        None
    }

    /// column that is both primary and foreign should be unified
    fn unify_primary_and_foreign_column(&self, columns:&Vec<Column>)->Vec<Column>{
        let mut unified_columns = Vec::new();
        let mut primary_columns = Vec::new();
        let mut foreign_columns = Vec::new();
        let mut column_names = BTreeMap::new();
        for c in columns{
            if c.is_primary{
                primary_columns.push(c.name.clone());
            }
            if c.foreign.is_some(){
                foreign_columns.push(c.name.clone());
            }
        }
        //if both primary and foreign, push only the modified foreign
        for c in columns{
            let mut inserted = false;
            if primary_columns.contains(&c.name) && foreign_columns.contains(&c.name){
                if c.foreign.is_some(){
                    let mut clone_column = c.clone();
                    clone_column.is_primary = true;
                    unified_columns.push(clone_column);
                    inserted = true;
                }
            }
            else {
                match column_names.get(&c.name) {
                    Some(index) => {
                        let ref mut ucol: Column = unified_columns[*index];
                        ucol.is_primary = ucol.is_primary || c.is_primary;
                        ucol.is_unique = ucol.is_unique || c.is_unique;
                        ucol.not_null = ucol.not_null || c.not_null;
                    },
                    None => {
                        unified_columns.push(c.clone());
                        inserted = true;
                    }
                }
            }
            if inserted {
                column_names.insert(c.name.clone(), unified_columns.len() - 1);
            }
        }
        unified_columns

    }

}


impl Database for Postgres{

    fn version(&self)->String{
        let sql = "SHOW server_version";
        let dao = self.execute_sql_with_one_return(sql, &vec![]);
        match dao{
            Ok(dao) => {
                dao.get("server_version")
            },
            Err(_) => panic!("unable to get database version")
        }

    }
    fn begin(&self){}
    fn commit(&self){}
    fn rollback(&self){}
    fn is_transacted(&self)->bool{false}
    fn is_closed(&self)->bool{false}
    fn is_connected(&self)->bool{false}
    fn close(&self){}
    fn is_valid(&self)->bool{false}
    fn reset(&self){}

    /// return this list of options, supported features in the database
    /// TODO: make this features version specific
    /// http://www.postgresql.org/about/featurematrix/
    /// writer CTE  >= 9.1
    /// Inheritance  >= 9.0
    /// JSON >= 9.2
    /// JSONB >= 9.4
    /// Returning >= 8.2
    fn sql_options(&self)->Vec<SqlOption>{
        vec![
            SqlOption::UsesNumberedParam,  // uses numbered parameters
            SqlOption::SupportsReturningClause, // supports returning clause, feature
            SqlOption::SupportsCTE,
            SqlOption::SupportsInheritance,
            SqlOption::UsesSchema,
            SqlOption::ReturnMetaColumns,// whether to use the column names returned in a statement
            ]
    }


    fn update(&self, _query:&Query)->Dao{unimplemented!()}
    fn delete(&self, _query:&Query)->Result<usize, String>{unimplemented!();}

    fn execute_sql_with_return(&self, sql:&str, params:&Vec<Value>)->Result<Vec<Dao>, DbError>{
        let conn = self.get_connection();
        let stmt = match conn.prepare(sql){
            Ok(stmt) => stmt,
            Err(e) => panic!("Something is wrong, when preparing statements: {:?}",e),
        };
        let mut daos = vec![];
        let param = self.from_rust_type_tosql(params);
        let rows = try!(stmt.query(&param));
        for row in rows {
            let columns = row.columns();
            let mut index = 0;
            let mut dao = Dao::new();
            for c in columns{
                let column_name = c.name();
                let dtype = c.type_();
                let rtype = self.from_sql_to_rust_type(&dtype, &row, index);
                dao.set_value(column_name, rtype);
                index += 1;
            }
            daos.push(dao);
        }
        Ok(daos)
    }

    /// generic execute sql which returns not much information,
    /// returns only the number of affected records or errors
    /// can be used with DDL operations (CREATE, DELETE, ALTER, DROP)
    fn execute_sql(&self, sql:&str, params:&Vec<Value>)->Result<usize, DbError>{
        let to_sql_types = self.from_rust_type_tosql(params);
        let conn = self.get_connection();
        let result = conn.execute(sql, &to_sql_types);
        Ok(try!(result) as usize)
    }

}

impl DatabaseDDL for Postgres{

    fn create_schema(&self, _schema:&str){unimplemented!()}
    fn drop_schema(&self, _schema:&str){unimplemented!()}
    fn create_table(&self, _model:&Table){unimplemented!()}
    fn build_create_table(&self, _table:&Table)->SqlFrag{unimplemented!()}
    fn rename_table(&self, _table:&Table, _new_tablename:String){unimplemented!()}
    fn drop_table(&self, _table:&Table){unimplemented!()}
    fn set_foreign_constraint(&self, _model:&Table){unimplemented!()}
    fn set_primary_constraint(&self, _model:&Table){unimplemented!()}

}

/// this can be condensed with using just extracting the table definition
impl DatabaseDev for Postgres{

    fn get_parent_table(&self, schema:&str, table:&str)->Option<String>{
        let sql ="
            SELECT
                relname as table,
                pg_namespace.nspname as schema,
                ( SELECT relname FROM pg_class WHERE oid = pg_inherits.inhparent ) AS parent_table
             FROM pg_class
             INNER JOIN pg_namespace
                ON pg_class.relnamespace = pg_namespace.oid
             LEFT JOIN pg_inherits
                 ON pg_class.oid = pg_inherits.inhrelid
             WHERE pg_namespace.nspname = $1
                 AND relname = $2
                ";
        let conn = self.get_connection();
        let stmt = conn.prepare(&sql).unwrap();
        for row in stmt.query(&[&schema, &table]).unwrap() {
            let parent_table:Option<String> = match row.get_opt("parent_table"){
                Ok(x) => Some(x),
                Err(_) => None
            };
            return parent_table;
        }
        None
    }

    fn get_table_sub_class(&self, schema:&str, table:&str)->Vec<String>{
        let sql ="
            SELECT
                relname AS base_table,
                ( SELECT relname FROM pg_class WHERE oid = pg_inherits.inhrelid ) AS sub_class
             FROM pg_inherits
             LEFT JOIN pg_class
                ON pg_class.oid = pg_inherits.inhparent
             INNER JOIN pg_namespace
                ON pg_class.relnamespace = pg_namespace.oid
             WHERE pg_namespace.nspname = $1
             AND relname = $2
             ORDER BY relname
            ";
        let conn = self.get_connection();
        let stmt = conn.prepare(&sql).unwrap();
        let mut sub_classes:Vec<String> = vec![];
        for row in stmt.query(&[&schema, &table]).unwrap() {
            match row.get_opt("sub_class"){
                Ok(x) => sub_classes.push(x),
                Err(_) => (),
            };
        }
        sub_classes
    }



    fn get_table_metadata(&self, schema:&str, table:&str, is_view: bool)->Table{

        let mut columns = self.get_table_columns(schema, table);
        let comment = self.get_table_comment(schema, table);
        let parent = self.get_parent_table(schema, table);
        let subclass = self.get_table_sub_class(schema, table);

        //mutate columns to mark those which are inherited
        if parent.is_some(){
            let inherited_columns = self.get_inherited_columns(schema, table);
            for i in inherited_columns{
                for c in &mut columns{
                    if i == c.name{
                        c.is_inherited = true;
                    }
                }
            }
        }

        Table{
            schema:schema.to_owned(),
            name:table.to_owned(),
            parent_table:parent,
            sub_table:subclass,
            comment:comment,
            columns:columns,
            is_view: is_view
        }
    }

    fn get_all_tables(&self)->Vec<(String, String, bool)>{
        let sql ="
                SELECT
                    pg_class.relname AS table,
                    pg_namespace.nspname AS schema,
                    obj_description(pg_class.oid) AS comment,
                    CASE
                        WHEN pg_class.relkind = 'r' THEN false
                        WHEN pg_class.relkind = 'v' THEN true
                    END AS is_view
                FROM pg_class
                    LEFT JOIN pg_namespace
                        ON pg_namespace.oid = pg_class.relnamespace
                WHERE
                    pg_class.relkind IN ('r','v')
                    AND pg_namespace.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                ORDER BY relname, nspname

                ";
        let conn = self.get_connection();
        let stmt = conn.prepare(&sql).unwrap();
        let mut tables:Vec<(String, String, bool)> = Vec::new();
        for row in stmt.query(&[]).unwrap() {
            let table:String = row.get("table");
            let schema:String = row.get("schema");
            let is_view:bool = row.get("is_view");
            tables.push((schema, table, is_view));
        }
        tables
    }



    fn get_inherited_columns(&self, schema:&str, table:&str)->Vec<String>{
        let sql = "
                SELECT nmsp_parent.nspname    AS parent_schema,
                    parent.relname         AS parent_table,
                    nmsp_child.nspname     AS child_schema,
                       child.relname          AS child_table,
                       column_parent.attname  AS column_parent_name
                FROM pg_inherits
                    JOIN pg_class parent
                        ON pg_inherits.inhparent  = parent.oid
                    JOIN pg_class child
                        ON pg_inherits.inhrelid   = child.oid
                    JOIN pg_namespace nmsp_parent
                        ON nmsp_parent.oid        = parent.relnamespace
                    JOIN pg_namespace nmsp_child
                        ON nmsp_child.oid         = child.relnamespace
                    JOIN pg_attribute column_parent
                        ON column_parent.attrelid = parent.oid
                    WHERE column_parent.attnum > 0
                    AND nmsp_child.nspname = $1
                    AND child.relname = $2
                    ORDER BY column_parent.attname
                ";
        let conn = self.get_connection();
        let stmt = conn.prepare(&sql).unwrap();
        let mut inherited_columns = Vec::new();
        for row in stmt.query(&[&schema, &table]).unwrap() {
            let column:String = row.get("column_parent_name");
            inherited_columns.push(column);
        }
        inherited_columns
    }


    /// get the rust data type names from database data type names
    /// will be used in source code generation
    fn dbtype_to_rust_type(&self, db_type: &str)->(Vec<String>, String){
        let db_type = match db_type{
            "boolean" => {
                (vec![], "bool".to_owned() )
            },
            "char" => {
                (vec![], "i8".to_owned() )
            },
            "smallint" | "smallserial" => {
                (vec![], "i16".to_owned() )
            },
            "integer" | "int" | "serial"  => {
                (vec![], "i32".to_owned() )
            },
            "oid"  => {
                (vec![], "u32".to_owned() )
            },
            "bigint" | "bigserial"  => {
                (vec![], "i64".to_owned() )
            },
            "real" => {
                (vec![], "f32".to_owned() )
            },
            "double precision" | "numeric" => {
                (vec![], "f64".to_owned() )
            },
            "name" | "character" | "character varying" | "text" | "citext" | "bpchar" =>{
                ( vec![], "String".to_owned() )
            },
            "bytea" =>{
                ( vec![], "Vec<u8>".to_owned() )
            },
            //"json" | "jsonb" => {
            //    ((Some(vec!["rustc_serialize::json::Json".to_owned()]), "Json".to_owned()))
            // },
            "json" | "jsonb" => {//FIXME :String for now, since Json itself is not encodable
                ((vec![], "String".to_owned()))
            },
            "uuid" => {
                (vec!["uuid::Uuid".to_owned()], "Uuid".to_owned() )
            },
            "timestamp" => {
                (vec!["chrono::naive::datetime::NaiveDateTime".to_owned()], "NaiveDateTime".to_owned() )
            },
            "timestamp without time zone" => {
                (vec!["chrono::naive::datetime::NaiveDateTime".to_owned()], "NaiveDateTime".to_owned() )
            },
            "timestamp with time zone" => {
                (vec!["chrono::datetime::DateTime".to_owned(),
                      "chrono::offset::utc::UTC".to_owned()], "DateTime<UTC>".to_owned() )
            },
            "time with time zone" => {
                (vec!["chrono::naive::time::NaiveTime".to_owned(),
                      "chrono::offset::utc::UTC".to_owned()], "NaiveTime".to_owned() )
            },
            "date" => {
                (vec!["chrono::naive::date::NaiveDate".to_owned()], "NaiveDate".to_owned() )
            },
            "time" => {
                (vec!["chrono::naive::time::NaiveTime".to_owned()], "NaiveTime".to_owned() )
            },
            "hstore" => {
                (vec!["std::collections::HashMap".to_owned()], "HashMap<String, Option<String>>".to_owned())
            },
            "interval" => {
                (vec![], "u32".to_owned() )
            },
            "inet[]" => {
                (vec![], "String".to_owned() )
            },
            "tsvector" | "inet" => {
                (vec![], "String".to_owned() )
            },//or everything else should be string
            _ => panic!("Unable to get the equivalent data type for {}", db_type),
        };
        db_type
    }

    ///
    /// convert rust data type names to database data type names
    /// will be used in generating SQL for table creation
    /// FIXME, need to restore the exact data type as before
    fn rust_type_to_dbtype(&self, rust_type: &str)->String{

        let rust_type = match rust_type{
            "bool" => {
                "boolean".to_owned()
            },
            "i8" => {
                "char".to_owned()
            },
            "i16" => {
                "smallint".to_owned()
            },
            "i32"  => {
                "integer".to_owned()
            },
            "u32"  => {
                "oid".to_owned()
            },
            "i64"  => {
                "bigint".to_owned()
            },
            "f32" => {
                "real".to_owned()
            },
            "f64" => {
                "numeric".to_owned()
            },
            "String" =>{
                "character varying".to_owned()
            },
            "Vec<u8>" =>{
                "bytea".to_owned()
            },
            "Json" => {
                "json".to_owned()
            },
            "Uuid" => {
                "uuid".to_owned()
            },
            "NaiveDateTime" => {
                "timestamp".to_owned()
            },
            "DateTime<UTC>" => {
                "timestamp with time zone".to_owned()
            },
            "NaiveDate" => {
                "date".to_owned()
            },
            "NaiveTime" => {
                "time".to_owned()
            },
            "HashMap<String, Option<String>>" => {
                "hstore".to_owned()
            },
            _ => panic!("Unable to get the equivalent database data type for {}", rust_type),
        };
        rust_type

    }

}