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
use crate::traits::CommandBuilder;
use crate::Settings;
use std::convert::AsRef;
use std::ffi::{OsStr, OsString};
use std::path::PathBuf;

/// `createdb` creates a `PostgreSQL` database.
#[derive(Clone, Debug, Default)]
pub struct CreateDbBuilder {
    program_dir: Option<PathBuf>,
    envs: Vec<(OsString, OsString)>,
    tablespace: Option<OsString>,
    echo: bool,
    encoding: Option<OsString>,
    locale: Option<OsString>,
    lc_collate: Option<OsString>,
    lc_ctype: Option<OsString>,
    icu_locale: Option<OsString>,
    icu_rules: Option<OsString>,
    locale_provider: Option<OsString>,
    owner: Option<OsString>,
    strategy: Option<OsString>,
    template: Option<OsString>,
    version: bool,
    help: bool,
    host: Option<OsString>,
    port: Option<u16>,
    username: Option<OsString>,
    no_password: bool,
    password: bool,
    pg_password: Option<OsString>,
    maintenance_db: Option<OsString>,
    dbname: Option<OsString>,
    description: Option<OsString>,
}

impl CreateDbBuilder {
    /// Create a new [`CreateDbBuilder`]
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a new [`CreateDbBuilder`] from [Settings]
    pub fn from(settings: &dyn Settings) -> Self {
        Self::new()
            .program_dir(settings.get_binary_dir())
            .host(settings.get_host())
            .port(settings.get_port())
            .username(settings.get_username())
            .pg_password(settings.get_password())
    }

    /// Location of the program binary
    #[must_use]
    pub fn program_dir<P: Into<PathBuf>>(mut self, path: P) -> Self {
        self.program_dir = Some(path.into());
        self
    }

    /// Default tablespace for the database
    #[must_use]
    pub fn tablespace<S: AsRef<OsStr>>(mut self, tablespace: S) -> Self {
        self.tablespace = Some(tablespace.as_ref().to_os_string());
        self
    }

    /// Show the commands being sent to the server
    #[must_use]
    pub fn echo(mut self) -> Self {
        self.echo = true;
        self
    }

    /// Encoding for the database
    #[must_use]
    pub fn encoding<S: AsRef<OsStr>>(mut self, encoding: S) -> Self {
        self.encoding = Some(encoding.as_ref().to_os_string());
        self
    }

    /// Locale settings for the database
    #[must_use]
    pub fn locale<S: AsRef<OsStr>>(mut self, locale: S) -> Self {
        self.locale = Some(locale.as_ref().to_os_string());
        self
    }

    /// `LC_COLLATE` setting for the database
    #[must_use]
    pub fn lc_collate<S: AsRef<OsStr>>(mut self, lc_collate: S) -> Self {
        self.lc_collate = Some(lc_collate.as_ref().to_os_string());
        self
    }

    /// `LC_CTYPE` setting for the database
    #[must_use]
    pub fn lc_ctype<S: AsRef<OsStr>>(mut self, lc_ctype: S) -> Self {
        self.lc_ctype = Some(lc_ctype.as_ref().to_os_string());
        self
    }

    /// ICU locale setting for the database
    #[must_use]
    pub fn icu_locale<S: AsRef<OsStr>>(mut self, icu_locale: S) -> Self {
        self.icu_locale = Some(icu_locale.as_ref().to_os_string());
        self
    }

    /// ICU rules setting for the database
    #[must_use]
    pub fn icu_rules<S: AsRef<OsStr>>(mut self, icu_rules: S) -> Self {
        self.icu_rules = Some(icu_rules.as_ref().to_os_string());
        self
    }

    /// Locale provider for the database's default collation
    #[must_use]
    pub fn locale_provider<S: AsRef<OsStr>>(mut self, locale_provider: S) -> Self {
        self.locale_provider = Some(locale_provider.as_ref().to_os_string());
        self
    }

    /// Database user to own the new database
    #[must_use]
    pub fn owner<S: AsRef<OsStr>>(mut self, owner: S) -> Self {
        self.owner = Some(owner.as_ref().to_os_string());
        self
    }

    /// Database creation strategy `wal_log` or `file_copy`
    #[must_use]
    pub fn strategy<S: AsRef<OsStr>>(mut self, strategy: S) -> Self {
        self.strategy = Some(strategy.as_ref().to_os_string());
        self
    }

    /// Template database to copy
    #[must_use]
    pub fn template<S: AsRef<OsStr>>(mut self, template: S) -> Self {
        self.template = Some(template.as_ref().to_os_string());
        self
    }

    /// Output version information, then exit
    #[must_use]
    pub fn version(mut self) -> Self {
        self.version = true;
        self
    }

    /// Show help, then exit
    #[must_use]
    pub fn help(mut self) -> Self {
        self.help = true;
        self
    }

    /// Database server host or socket directory
    #[must_use]
    pub fn host<S: AsRef<OsStr>>(mut self, host: S) -> Self {
        self.host = Some(host.as_ref().to_os_string());
        self
    }

    /// Database server port
    #[must_use]
    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    /// User name to connect as
    #[must_use]
    pub fn username<S: AsRef<OsStr>>(mut self, username: S) -> Self {
        self.username = Some(username.as_ref().to_os_string());
        self
    }

    /// Never prompt for password
    #[must_use]
    pub fn no_password(mut self) -> Self {
        self.no_password = true;
        self
    }

    /// Force password prompt
    #[must_use]
    pub fn password(mut self) -> Self {
        self.password = true;
        self
    }

    /// user password
    #[must_use]
    pub fn pg_password<S: AsRef<OsStr>>(mut self, pg_password: S) -> Self {
        self.pg_password = Some(pg_password.as_ref().to_os_string());
        self
    }

    /// Alternate maintenance database
    #[must_use]
    pub fn maintenance_db<S: AsRef<OsStr>>(mut self, db: S) -> Self {
        self.maintenance_db = Some(db.as_ref().to_os_string());
        self
    }

    /// Database name
    #[must_use]
    pub fn dbname<S: AsRef<OsStr>>(mut self, dbname: S) -> Self {
        self.dbname = Some(dbname.as_ref().to_os_string());
        self
    }

    /// Database description
    #[must_use]
    pub fn description<S: AsRef<OsStr>>(mut self, description: S) -> Self {
        self.description = Some(description.as_ref().to_os_string());
        self
    }
}

impl CommandBuilder for CreateDbBuilder {
    /// Get the program name
    fn get_program(&self) -> &'static OsStr {
        "createdb".as_ref()
    }

    /// Location of the program binary
    fn get_program_dir(&self) -> &Option<PathBuf> {
        &self.program_dir
    }

    /// Get the arguments for the command
    fn get_args(&self) -> Vec<OsString> {
        let mut args: Vec<OsString> = Vec::new();

        if let Some(tablespace) = &self.tablespace {
            args.push("--tablespace".into());
            args.push(tablespace.into());
        }

        if self.echo {
            args.push("--echo".into());
        }

        if let Some(encoding) = &self.encoding {
            args.push("--encoding".into());
            args.push(encoding.into());
        }

        if let Some(locale) = &self.locale {
            args.push("--locale".into());
            args.push(locale.into());
        }

        if let Some(lc_collate) = &self.lc_collate {
            args.push("--lc-collate".into());
            args.push(lc_collate.into());
        }

        if let Some(lc_ctype) = &self.lc_ctype {
            args.push("--lc-ctype".into());
            args.push(lc_ctype.into());
        }

        if let Some(icu_locale) = &self.icu_locale {
            args.push("--icu-locale".into());
            args.push(icu_locale.into());
        }

        if let Some(icu_rules) = &self.icu_rules {
            args.push("--icu-rules".into());
            args.push(icu_rules.into());
        }

        if let Some(locale_provider) = &self.locale_provider {
            args.push("--locale-provider".into());
            args.push(locale_provider.into());
        }

        if let Some(owner) = &self.owner {
            args.push("--owner".into());
            args.push(owner.into());
        }

        if let Some(strategy) = &self.strategy {
            args.push("--strategy".into());
            args.push(strategy.into());
        }

        if let Some(template) = &self.template {
            args.push("--template".into());
            args.push(template.into());
        }

        if self.version {
            args.push("--version".into());
        }

        if self.help {
            args.push("--help".into());
        }

        if let Some(host) = &self.host {
            args.push("--host".into());
            args.push(host.into());
        }

        if let Some(port) = &self.port {
            args.push("--port".into());
            args.push(port.to_string().into());
        }

        if let Some(username) = &self.username {
            args.push("--username".into());
            args.push(username.into());
        }

        if self.no_password {
            args.push("--no-password".into());
        }

        if self.password {
            args.push("--password".into());
        }

        if let Some(maintenance_db) = &self.maintenance_db {
            args.push("--maintenance-db".into());
            args.push(maintenance_db.into());
        }

        if let Some(dbname) = &self.dbname {
            args.push(dbname.into());
        }

        if let Some(description) = &self.description {
            args.push(description.into());
        }

        args
    }

    /// Get the environment variables for the command
    fn get_envs(&self) -> Vec<(OsString, OsString)> {
        let mut envs: Vec<(OsString, OsString)> = self.envs.clone();

        if let Some(password) = &self.pg_password {
            envs.push(("PGPASSWORD".into(), password.into()));
        }

        envs
    }

    /// Set an environment variable for the command
    fn env<S: AsRef<OsStr>>(mut self, key: S, value: S) -> Self {
        self.envs
            .push((key.as_ref().to_os_string(), value.as_ref().to_os_string()));
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::traits::CommandToString;
    use crate::TestSettings;
    use test_log::test;

    #[test]
    fn test_builder_new() {
        let command = CreateDbBuilder::new().program_dir(".").build();
        assert_eq!(
            PathBuf::from(".").join("createdb"),
            PathBuf::from(command.to_command_string().replace('"', ""))
        );
    }

    #[test]
    fn test_builder_from() {
        let command = CreateDbBuilder::from(&TestSettings).build();
        #[cfg(not(target_os = "windows"))]
        let command_prefix = r#"PGPASSWORD="password" "./createdb" "#;
        #[cfg(target_os = "windows")]
        let command_prefix = r#"".\\createdb" "#;

        assert_eq!(
            format!(
                r#"{command_prefix}"--host" "localhost" "--port" "5432" "--username" "postgres""#
            ),
            command.to_command_string()
        );
    }

    #[test]
    fn test_builder() {
        let command = CreateDbBuilder::new()
            .env("PGDATABASE", "database")
            .tablespace("pg_default")
            .echo()
            .encoding("UTF8")
            .locale("en_US.UTF-8")
            .lc_collate("en_US.UTF-8")
            .lc_ctype("en_US.UTF-8")
            .icu_locale("en_US")
            .icu_rules("standard")
            .locale_provider("icu")
            .owner("postgres")
            .strategy("wal_log")
            .template("template0")
            .version()
            .help()
            .host("localhost")
            .port(5432)
            .username("postgres")
            .no_password()
            .password()
            .pg_password("password")
            .maintenance_db("postgres")
            .dbname("testdb")
            .description("Test Database")
            .build();
        #[cfg(not(target_os = "windows"))]
        let command_prefix = r#"PGDATABASE="database" PGPASSWORD="password" "#;
        #[cfg(target_os = "windows")]
        let command_prefix = String::new();

        assert_eq!(
            format!(
                r#"{command_prefix}"createdb" "--tablespace" "pg_default" "--echo" "--encoding" "UTF8" "--locale" "en_US.UTF-8" "--lc-collate" "en_US.UTF-8" "--lc-ctype" "en_US.UTF-8" "--icu-locale" "en_US" "--icu-rules" "standard" "--locale-provider" "icu" "--owner" "postgres" "--strategy" "wal_log" "--template" "template0" "--version" "--help" "--host" "localhost" "--port" "5432" "--username" "postgres" "--no-password" "--password" "--maintenance-db" "postgres" "testdb" "Test Database""#
            ),
            command.to_command_string()
        );
    }
}