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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
use anyhow::{anyhow, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::path::Path;
use std::{fmt, fs};

pub use super::connection::{Connection, ConnectionType};
pub use super::User;
pub use super::{Role, RoleLevelType};

/// Configuration contains all the information needed to connect to a database, the roles and
/// users.
///  - `connection`: the connection to the database, including the type of connection and the URL.
///  - `roles`: the roles of the users. The roles are used to determine the permissions of the
///  users. A role can be a [RoleDatabaseLevel], [RoleSchemaLevel] or [RoleTableLevel].
///  - `users`: the users.
///
/// [RoleDatabaseLevel]: crate::config::role::RoleDatabaseLevel
/// [RoleSchemaLevel]: crate::config::role::RoleSchemaLevel
/// [RoleTableLevel]: crate::config::role::RoleTableLevel
///
/// For example:
///
/// ```yaml
/// connection:
///   type: postgres
///   url: postgres://user:password@host:port/database
///
/// roles:
///   - name: role_database_level
///     type: databases
///     grants:
///     - CREATE
///     - TEMP
///     databases:
///     - db1
///     - db2
///     - db3
///  users:
///  - name: user1
///    password: password1
///    roles:
///    - role_database_level
///    - role_schema_level
///    - role_table_level
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct Config {
    pub connection: Connection,
    pub roles: Vec<Role>,
    pub users: Vec<User>,
}

impl fmt::Display for Config {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", serde_yaml::to_string(&self).unwrap())
    }
}

impl std::str::FromStr for Config {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        let config: Config = serde_yaml::from_str(s)?;

        // Validate
        config.validate()?;

        Ok(config)
    }
}

impl Config {
    pub fn new(config_path: &Path) -> Result<Self> {
        let config_path = config_path.to_path_buf();
        let config_str = fs::read_to_string(&config_path).context("failed to read config file")?;
        let config: Config = serde_yaml::from_str(&config_str)?;

        config.validate()?;

        // expand env variables
        let config = config.expand_env_vars()?;

        Ok(config)
    }

    pub fn validate(&self) -> Result<()> {
        // Validate connection
        self.connection.validate()?;

        // Validate roles
        for role in &self.roles {
            role.validate()?;
        }
        // Validate role name are unique by name
        let mut role_names = HashSet::new();
        for role in &self.roles {
            if role_names.contains(&role.get_name()) {
                return Err(anyhow!("duplicated role name: {}", role.get_name()));
            }
            role_names.insert(role.get_name());
        }

        // Validate users
        for user in &self.users {
            user.validate()?;
        }
        // Validate users are unique by name
        let mut user_names: HashSet<String> = HashSet::new();
        for user in &self.users {
            if user_names.contains(&user.name) {
                return Err(anyhow!("duplicated user: {}", user.name));
            }
            user_names.insert(user.name.clone());
        }
        // Validate users roles are available in roles
        for user in &self.users {
            for role in &user.roles {
                // role name can contain '-' at the first position
                let role_name = if let Some(without_sign) = role.strip_prefix('-') {
                    without_sign
                } else {
                    role
                };

                if !self.roles.iter().any(|r| r.get_name() == role_name) {
                    return Err(anyhow!("user role {} is not available", role));
                }
            }
        }

        Ok(())
    }

    // Expand env variables in config
    fn expand_env_vars(&self) -> Result<Self> {
        let mut config = self.clone();

        // expand connection
        config.connection = config.connection.expand_env_vars()?;

        Ok(config)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use indoc::indoc;
    use std::io::Write;
    use std::path::PathBuf;
    use std::str::FromStr;
    use tempfile::NamedTempFile;

    #[test]
    #[should_panic(expected = "failed to get content: invalid type: string")]
    fn test_with_basic_config() {
        let _text = "bad yaml content";
        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        Config::new(&path).expect("failed to get content");
    }

    // Test config with minimum valid YAML
    #[test]
    fn test_read_config_basic_config() {
        let _text = indoc! {"
                 connection:
                   type: postgres
                   url: postgres://localhost:5432/postgres
                 roles: []
                 users: []
             "};

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        Config::new(&path).expect("failed to get content");
    }

    // Test Config::from_str
    #[test]
    fn test_read_config_from_str() {
        let _text = indoc! {"
                 connection:
                   type: postgres
                   url: postgres://localhost:5432/postgres
                 roles: []
                 users: []
             "};

        Config::from_str(_text).expect("failed to get content");
    }

    // Config::from_str and Config::new should return the same result
    #[test]
    fn test_read_config_from_str_and_new() {
        let _text = indoc! {"
             connection:
               type: postgres
               url: postgres://localhost:5432/postgres
             roles: []
             users: []
        "};

        let config_1 = Config::from_str(_text).expect("failed to get content");

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());
        let config_2 = Config::new(&path).expect("failed to get content");

        assert_eq!(config_1, config_2);
    }

    // Test config with url contains environement variable
    #[test]
    fn test_read_config_with_env_var() {
        envmnt::set("POSTGRES_HOST", "duyet");

        let _text = indoc! {"
                 connection:
                   type: postgres
                   url: postgres://${POSTGRES_HOST}:5432/postgres
                 roles: []
                 users: []
             "};

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        let config = Config::new(&path).expect("failed to get content");

        assert_eq!(config.connection.url, "postgres://duyet:5432/postgres");

        envmnt::remove("POSTGRES_HOST");
    }

    // Test expand environement variables but not available
    #[test]
    fn test_read_config_with_env_var_not_available() {
        let _text = indoc! {"
                 connection:
                   type: postgres
                   url: postgres://${POSTGRES_HOST:duyet}:5432/${POSTGRES_ABC}
                 roles: []
                 users: []
             "};

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        let config = Config::new(&path).expect("failed to get content");

        assert_eq!(
            config.connection.url,
            "postgres://duyet:5432/${POSTGRES_ABC}"
        );
    }

    // Test config with invalid connection type
    #[test]
    #[should_panic(expected = "connection.type: unknown variant `invalid`")]
    fn test_read_config_invalid_connection_type() {
        let _text = indoc! {"
                 connection:
                   type: invalid
                   url: postgres://postgres@localhost:5432/postgres
                 roles: []
                 users: []
             "};

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        Config::new(&path).expect("failed to parse config");
    }

    // Test config with role database level
    #[test]
    fn test_read_config_one_role_database_level() {
        let _text = indoc! {"
                 connection:
                   type: postgres
                   url: postgres://localhost:5432/postgres
                 roles:
                 - type: database
                   name: role_database_level_1
                   grants:
                   - CREATE
                   - TEMP
                   databases:
                   - db1
                   - db2
                   - db3
                 - type: database
                   name: role_database_level_2
                   grants:
                   - ALL
                   databases:
                   - db1
                   - db2
                   - db3
                 users: []
             "};

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        let config = Config::new(&path).expect("failed to parse config");
        assert_eq!(config.roles.len(), 2);

        // Test role 1
        assert_eq!(config.roles[0].get_name(), "role_database_level_1");
        assert_eq!(config.roles[0].get_level(), RoleLevelType::Database);
        assert_eq!(config.roles[0].get_grants().len(), 2);
        assert_eq!(config.roles[0].get_grants()[0], "CREATE");
        assert_eq!(config.roles[0].get_grants()[1], "TEMP");
        assert_eq!(config.roles[0].get_databases().len(), 3);
        assert_eq!(config.roles[0].get_databases()[0], "db1");
        assert_eq!(config.roles[0].get_databases()[1], "db2");
        assert_eq!(config.roles[0].get_databases()[2], "db3");
        assert_eq!(
            config.roles[0].to_sql("duyet"),
            "GRANT CREATE, TEMP ON DATABASE db1, db2, db3 TO duyet;".to_string()
        );

        // Test role 2
        assert_eq!(config.roles[1].get_name(), "role_database_level_2");
        assert_eq!(config.roles[1].get_level(), RoleLevelType::Database);
        assert_eq!(config.roles[1].get_grants().len(), 1);
        assert_eq!(config.roles[1].get_grants()[0], "ALL");
        assert_eq!(config.roles[1].get_databases().len(), 3);
        assert_eq!(config.roles[1].get_databases()[0], "db1");
        assert_eq!(config.roles[1].get_databases()[1], "db2");
        assert_eq!(config.roles[1].get_databases()[2], "db3");
        assert_eq!(
            config.roles[1].to_sql("duyet"),
            "GRANT ALL PRIVILEGES ON DATABASE db1, db2, db3 TO duyet;".to_string()
        );
    }

    // Test config role type database level with invalid grants
    #[test]
    #[should_panic(expected = "invalid grant: invalid")]
    fn test_read_config_role_type_database_level_invalid_grants() {
        let _text = indoc! {"
                 connection:
                   type: postgres
                   url: postgres://localhost:5432/postgres
                 roles:
                 - type: database
                   name: role_database_level
                   grants:
                   - invalid
                   databases:
                   - db1
                   - db2
                   - db3
                 users: []
             "};

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        Config::new(&path).expect("failed to parse config");
    }

    // Test config with role schema level
    #[test]
    fn test_read_config_one_role_schema_level() {
        let _text = indoc! {"
                 connection:
                   type: postgres
                   url: postgres://localhost:5432/postgres
                 roles:
                 - type: schema
                   name: role_schema_level_1
                   grants:
                   - CREATE
                   - USAGE
                   schemas:
                   - schema1
                   - schema2
                   - schema3
                 - type: schema
                   name: role_schema_level_2
                   grants:
                   - ALL
                   schemas:
                   - schema1
                   - schema2
                   - schema3
                 users: []
             "};

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        let config = Config::new(&path).expect("failed to parse config");
        assert_eq!(config.roles.len(), 2);

        // Test role 1
        assert_eq!(config.roles[0].get_name(), "role_schema_level_1");
        assert_eq!(config.roles[0].get_level(), RoleLevelType::Schema);
        assert_eq!(config.roles[0].get_grants().len(), 2);
        assert_eq!(config.roles[0].get_grants()[0], "CREATE");
        assert_eq!(config.roles[0].get_grants()[1], "USAGE");
        assert_eq!(config.roles[0].get_schemas().len(), 3);
        assert_eq!(config.roles[0].get_schemas()[0], "schema1");
        assert_eq!(config.roles[0].get_schemas()[1], "schema2");
        assert_eq!(config.roles[0].get_schemas()[2], "schema3");
        assert_eq!(
            config.roles[0].to_sql("duyet"),
            "GRANT CREATE, USAGE ON SCHEMA schema1, schema2, schema3 TO duyet;".to_string()
        );

        // Test role 2
        assert_eq!(config.roles[1].get_name(), "role_schema_level_2");
        assert_eq!(config.roles[1].get_level(), RoleLevelType::Schema);
        assert_eq!(config.roles[1].get_grants().len(), 1);
        assert_eq!(config.roles[1].get_grants()[0], "ALL");
        assert_eq!(config.roles[1].get_schemas().len(), 3);
        assert_eq!(config.roles[1].get_schemas()[0], "schema1");
        assert_eq!(config.roles[1].get_schemas()[1], "schema2");
        assert_eq!(config.roles[1].get_schemas()[2], "schema3");
        assert_eq!(
            config.roles[1].to_sql("duyet"),
            "GRANT ALL PRIVILEGES ON SCHEMA schema1, schema2, schema3 TO duyet;".to_string()
        );
    }

    // Test config role type schema level with invalid grants
    #[test]
    #[should_panic(expected = "invalid grant: invalid")]
    fn test_read_config_role_type_schema_level_invalid_grants() {
        let _text = indoc! {"
                 connection:
                   type: postgres
                   url: postgres://localhost:5432/postgres
                 roles:
                 - type: schema
                   name: role_schema_level
                   grants:
                   - invalid
                   schemas:
                   - schema1
                   - schema2
                   - schema3
                 users: []
             "};

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        Config::new(&path).expect("failed to parse config");
    }

    // Test config with one role table level
    #[test]
    fn test_read_config_one_role_table_level() {
        let _text = indoc! {"
                 connection:
                   type: postgres
                   url: postgres://localhost:5432/postgres
                 roles:
                 - type: table
                   name: role_table_level_1
                   grants:
                     - SELECT
                     - INSERT
                   schemas:
                     - schema1
                   tables:
                     - table1
                     - table2
                     - table3
                 - type: table
                   name: role_table_level_2
                   grants:
                     - ALL
                   schemas:
                     - schema1
                   tables:
                     - table1
                     - table2
                     - table3
                 users: []
             "};

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        let config = Config::new(&path).expect("failed to parse config");
        assert_eq!(config.roles.len(), 2);

        // Test role 1
        assert_eq!(config.roles[0].get_name(), "role_table_level_1");
        assert_eq!(config.roles[0].get_level(), RoleLevelType::Table);
        assert_eq!(config.roles[0].get_grants().len(), 2);
        assert_eq!(config.roles[0].get_grants()[0], "SELECT");
        assert_eq!(config.roles[0].get_grants()[1], "INSERT");
        assert_eq!(config.roles[0].get_schemas().len(), 1);
        assert_eq!(config.roles[0].get_schemas()[0], "schema1");
        assert_eq!(config.roles[0].get_tables().len(), 3);
        assert_eq!(config.roles[0].get_tables()[0], "table1");
        assert_eq!(config.roles[0].get_tables()[1], "table2");
        assert_eq!(config.roles[0].get_tables()[2], "table3");
        assert_eq!(
            config.roles[0].to_sql("duyet"),
            "GRANT SELECT, INSERT ON schema1.table1, schema1.table2, schema1.table3 TO duyet;"
        );

        // Test role 2
        assert_eq!(config.roles[1].get_name(), "role_table_level_2");
        assert_eq!(config.roles[1].get_level(), RoleLevelType::Table);
        assert_eq!(config.roles[1].get_grants().len(), 1);
        assert_eq!(config.roles[1].get_grants()[0], "ALL");
        assert_eq!(config.roles[1].get_schemas().len(), 1);
        assert_eq!(config.roles[1].get_schemas()[0], "schema1");
        assert_eq!(config.roles[1].get_tables().len(), 3);
        assert_eq!(config.roles[1].get_tables()[0], "table1");
        assert_eq!(config.roles[1].get_tables()[1], "table2");
        assert_eq!(config.roles[1].get_tables()[2], "table3");
        assert_eq!(
            config.roles[1].to_sql("duyet"),
            "GRANT ALL PRIVILEGES ON schema1.table1, schema1.table2, schema1.table3 TO duyet;"
                .to_string()
        );
    }

    // Test config role type table level with table name is `ALL`
    #[test]
    fn test_read_config_role_type_table_level_all_tables() {
        let _text = indoc! {"
                 connection:
                   type: postgres
                   url: postgres://localhost:5432/postgres
                 roles:
                 - type: table
                   name: role_table_level_1
                   grants:
                     - SELECT
                   schemas:
                     - schema1
                   tables:
                     - ALL
                 - type: table
                   name: role_table_level_2
                   grants:
                     - SELECT
                   schemas:
                     - schema1
                   tables:
                     - ALL
                     - another_table_should_be_included_in_all_too
                 - type: table
                   name: role_table_level_3
                   grants:
                     - SELECT
                   schemas:
                     - schema1
                   tables:
                     - ALL
                     - -but_excluded_me
                 - type: table
                   name: role_table_level_4
                   grants:
                     - SELECT
                   schemas:
                     - schema1
                   tables:
                     - table_a
                     - -table_b
                 - type: table
                   name: role_table_level_5
                   grants:
                     - SELECT
                   schemas:
                     - schema1
                   tables:
                     - -table_a
                     - -table_b
                 - type: table
                   name: role_table_level_6
                   grants:
                     - SELECT
                   schemas:
                     - schema1
                   tables:
                     - -ALL
                 users: []
             "};

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        let config = Config::new(&path).expect("failed to parse config");
        assert_eq!(config.roles.len(), 6);

        assert_eq!(
            config.roles[0].to_sql("duyet"),
            "GRANT SELECT ON ALL TABLES IN SCHEMA schema1 TO duyet;"
        );
        assert_eq!(
            config.roles[1].to_sql("duyet"),
            "GRANT SELECT ON ALL TABLES IN SCHEMA schema1 TO duyet;"
        );
        assert_eq!(
            config.roles[2].to_sql("duyet"),
            "GRANT SELECT ON ALL TABLES IN SCHEMA schema1 TO duyet; REVOKE SELECT ON schema1.but_excluded_me FROM duyet;"
        );
        assert_eq!(
            config.roles[3].to_sql("duyet"),
            "GRANT SELECT ON schema1.table_a TO duyet; REVOKE SELECT ON schema1.table_b FROM duyet;"
        );
        assert_eq!(
            config.roles[4].to_sql("duyet"),
            "REVOKE SELECT ON schema1.table_a, schema1.table_b FROM duyet;"
        );
        assert_eq!(
            config.roles[5].to_sql("duyet"),
            "REVOKE SELECT ON ALL TABLES IN SCHEMA schema1 FROM duyet;"
        );
    }

    // Test config role type table level with invalid grants
    #[test]
    #[should_panic(expected = "role.grants invalid")]
    fn test_read_config_role_type_table_level_invalid_grants() {
        let _text = indoc! {"
                 connection:
                   type: postgres
                   url: postgres://localhost:5432/postgres
                 roles:
                 - type: table
                   name: role_table_level
                   grants:
                   - invalid
                   schemas:
                   - schema1
                   tables:
                   - table1
                   - table2
                   - table3
                 users: []
             "};

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        Config::new(&path).expect("failed to parse config");
    }

    // Test two role duplicated name error
    #[test]
    #[should_panic(expected = "duplicated role name: role_table_level")]
    fn test_read_config_two_role_duplicated_name() {
        let _text = indoc! {"
                 connection:
                   type: postgres
                   url: postgres://localhost:5432/postgres
                 roles:
                 - type: table
                   name: role_table_level
                   grants:
                   - SELECT
                   - INSERT
                   schemas:
                   - schema1
                   tables:
                   - table1
                   - table2
                   - table3
                 - type: table
                   name: role_table_level
                   grants:
                   - ALL
                   schemas:
                   - schema1
                   tables:
                   - table1
                   - table2
                   - table3
                 users: []
             "};

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        Config::new(&path).expect("failed to parse config");
    }

    // Test users config
    #[test]
    fn test_read_config_users() {
        let _text = indoc! {"
                 connection:
                   type: postgres
                   url: postgres://postgres:postgres@localhost:5432/postgres
                 roles:
                 - type: database
                   name: role_database_level
                   grants:
                   - CREATE
                   - TEMP
                   databases:
                   - db1
                   - db2
                   - db3
                 - type: schema
                   name: role_schema_level
                   grants:
                   - ALL
                   schemas:
                   - schema1
                   - schema2
                   - schema3
                 - type: table
                   name: role_table_level
                   grants:
                   - SELECT
                   - INSERT
                   schemas:
                   - schema1
                   tables:
                   - table1
                   - table2
                   - table3
                 users:
                 - name: duyet
                   password: 123456
                   roles:
                   - role_database_level
                   - role_schema_level
                   - role_table_level
                 - name: duyet_without_password
                   roles:
                   - role_database_level
                   - role_schema_level
                   - role_table_level
             "};

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        let config = Config::new(&path).expect("failed to parse config");
        assert_eq!(config.users.len(), 2);

        // Test user 1
        assert_eq!(config.users[0].get_name(), "duyet");
        assert_eq!(config.users[0].get_password(), "123456");
        assert_eq!(config.users[0].get_roles().len(), 3);
        assert_eq!(config.users[0].get_roles()[0], "role_database_level");
        assert_eq!(config.users[0].get_roles()[1], "role_schema_level");
        assert_eq!(config.users[0].get_roles()[2], "role_table_level");

        // Test sql create user
        assert_eq!(
            config.users[0].to_sql_create(),
            "CREATE USER duyet WITH PASSWORD '123456';"
        );

        // Test sql create user without password
        assert_eq!(
            config.users[1].to_sql_create(),
            "CREATE USER duyet_without_password;"
        );

        // Test sql drop user
        assert_eq!(config.users[0].to_sql_drop(), "DROP USER IF EXISTS duyet;");
    }

    // Test users config with revoke role by `-role_name`
    #[test]
    fn test_read_config_users_exclude_role_by_minus_role_name() {
        let _text = indoc! {"
             connection:
               type: postgres
               url: postgres://postgres:postgres@localhost:5432/postgres
             roles:
             - type: database
               name: role_database_level
               grants:
               - CREATE
               - TEMP
               databases:
               - db1
               - db2
               - db3
             - type: schema
               name: role_schema_level
               grants:
               - ALL
               schemas:
               - schema1
               - schema2
               - schema3
             - type: table
               name: role_table_level
               grants:
               - SELECT
               - INSERT
               schemas:
               - schema1
               tables:
               - table1
               - table2
               - table3
             users:
             - name: duyet
               password: 123456
               roles:
               - -role_database_level
               - -role_schema_level
               - -role_table_level
             - name: duyet_without_password
               roles:
               - role_database_level
               - role_schema_level
               - role_table_level
        "};

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        let config = Config::new(&path).expect("failed to parse config");
        assert_eq!(config.users.len(), 2);

        // Test user 1
        assert_eq!(config.users[0].get_name(), "duyet");
        assert_eq!(config.users[0].get_password(), "123456");
        assert_eq!(config.users[0].get_roles().len(), 3);
    }

    /// Test find role by name, name can contains `-` in case of exclude role
    #[test]
    fn test_find_role_by_name() {
        let _text = indoc! {"
             connection:
               type: postgres
               url: postgres://postgres:postgres@localhost:5432/postgres
             roles:
             - type: database
               name: role_database_level
               grants:
               - CREATE
               databases:
               - db1
             users: []
        "};

        let mut file = NamedTempFile::new().expect("failed to create temp file");
        file.write(_text.as_bytes())
            .expect("failed to write to temp file");
        let path = PathBuf::from(file.path().to_str().unwrap());

        let config = Config::new(&path).expect("failed to parse config");

        assert!(config
            .roles
            .iter()
            .find(|r| r.find("role_database_level"))
            .is_some());

        // Test find role by name with `-`
        assert!(config
            .roles
            .iter()
            .find(|r| r.find("-role_database_level"))
            .is_some());
    }
}