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

/// `pg_upgrade` upgrades a `PostgreSQL` cluster to a different major version.
#[derive(Clone, Debug, Default)]
pub struct PgUpgradeBuilder {
    program_dir: Option<PathBuf>,
    envs: Vec<(OsString, OsString)>,
    old_bindir: Option<OsString>,
    new_bindir: Option<OsString>,
    check: bool,
    old_datadir: Option<OsString>,
    new_datadir: Option<OsString>,
    jobs: Option<OsString>,
    link: bool,
    no_sync: bool,
    old_options: Option<OsString>,
    new_options: Option<OsString>,
    old_port: Option<u16>,
    new_port: Option<u16>,
    retain: bool,
    socketdir: Option<OsString>,
    username: Option<OsString>,
    verbose: bool,
    version: bool,
    clone: bool,
    copy: bool,
    help: bool,
}

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

    /// Create a new [`PgUpgradeBuilder`] from [Settings]
    pub fn from(settings: &dyn Settings) -> Self {
        Self::new().program_dir(settings.get_binary_dir())
    }

    /// 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
    }

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

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

    /// check clusters only, don't change any data
    #[must_use]
    pub fn check(mut self) -> Self {
        self.check = true;
        self
    }

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

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

    /// number of simultaneous processes or threads to use
    #[must_use]
    pub fn jobs<S: AsRef<OsStr>>(mut self, jobs: S) -> Self {
        self.jobs = Some(jobs.as_ref().to_os_string());
        self
    }

    /// link instead of copying files to new cluster
    #[must_use]
    pub fn link(mut self) -> Self {
        self.link = true;
        self
    }

    /// do not wait for changes to be written safely to disk
    #[must_use]
    pub fn no_sync(mut self) -> Self {
        self.no_sync = true;
        self
    }

    /// old cluster options to pass to the server
    #[must_use]
    pub fn old_options<S: AsRef<OsStr>>(mut self, old_options: S) -> Self {
        self.old_options = Some(old_options.as_ref().to_os_string());
        self
    }

    /// new cluster options to pass to the server
    #[must_use]
    pub fn new_options<S: AsRef<OsStr>>(mut self, new_options: S) -> Self {
        self.new_options = Some(new_options.as_ref().to_os_string());
        self
    }

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

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

    /// retain SQL and log files after success
    #[must_use]
    pub fn retain(mut self) -> Self {
        self.retain = true;
        self
    }

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

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

    /// enable verbose internal logging
    #[must_use]
    pub fn verbose(mut self) -> Self {
        self.verbose = true;
        self
    }

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

    /// clone instead of copying files to new cluster
    #[must_use]
    pub fn clone(mut self) -> Self {
        self.clone = true;
        self
    }

    /// copy files to new cluster
    #[must_use]
    pub fn copy(mut self) -> Self {
        self.copy = true;
        self
    }

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

impl CommandBuilder for PgUpgradeBuilder {
    /// Get the program name
    fn get_program(&self) -> &'static OsStr {
        "pg_upgrade".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(old_bindir) = &self.old_bindir {
            args.push("--old-bindir".into());
            args.push(old_bindir.into());
        }

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

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

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

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

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

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

        if self.no_sync {
            args.push("--no-sync".into());
        }

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

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

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

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

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

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

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

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

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

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

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

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

        args
    }

    /// Get the environment variables for the command
    fn get_envs(&self) -> Vec<(OsString, OsString)> {
        self.envs.clone()
    }

    /// 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 = PgUpgradeBuilder::new().program_dir(".").build();
        assert_eq!(
            PathBuf::from(".").join("pg_upgrade"),
            PathBuf::from(command.to_command_string().replace('"', ""))
        );
    }

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

        assert_eq!(format!("{command_prefix}"), command.to_command_string());
    }

    #[test]
    fn test_builder() {
        let command = PgUpgradeBuilder::new()
            .env("PGDATABASE", "database")
            .old_bindir("old")
            .new_bindir("new")
            .check()
            .old_datadir("old_data")
            .new_datadir("new_data")
            .jobs("10")
            .link()
            .no_sync()
            .old_options("old")
            .new_options("new")
            .old_port(5432)
            .new_port(5433)
            .retain()
            .socketdir("socket")
            .username("user")
            .verbose()
            .version()
            .clone()
            .copy()
            .help()
            .build();
        #[cfg(not(target_os = "windows"))]
        let command_prefix = r#"PGDATABASE="database" "#;
        #[cfg(target_os = "windows")]
        let command_prefix = String::new();

        assert_eq!(
            format!(
                r#"{command_prefix}"pg_upgrade" "--old-bindir" "old" "--new-bindir" "new" "--check" "--old-datadir" "old_data" "--new-datadir" "new_data" "--jobs" "10" "--link" "--no-sync" "--old-options" "old" "--new-options" "new" "--old-port" "5432" "--new-port" "5433" "--retain" "--socketdir" "socket" "--username" "user" "--verbose" "--version" "--clone" "--copy" "--help""#
            ),
            command.to_command_string()
        );
    }
}