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

/// `pg_recvlogical` controls `PostgreSQL` logical decoding streams.
#[derive(Clone, Debug, Default)]
pub struct PgRecvLogicalBuilder {
    program_dir: Option<PathBuf>,
    envs: Vec<(OsString, OsString)>,
    create_slot: bool,
    drop_slot: bool,
    start: bool,
    endpos: Option<OsString>,
    file: Option<OsString>,
    fsync_interval: Option<OsString>,
    if_not_exists: bool,
    startpos: Option<OsString>,
    no_loop: bool,
    option: Option<OsString>,
    plugin: Option<OsString>,
    status_interval: Option<OsString>,
    slot: Option<OsString>,
    two_phase: bool,
    verbose: bool,
    version: bool,
    help: bool,
    dbname: Option<OsString>,
    host: Option<OsString>,
    port: Option<u16>,
    username: Option<OsString>,
    no_password: bool,
    password: bool,
    pg_password: Option<OsString>,
}

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

    /// Create a new [`PgRecvLogicalBuilder`] 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
    }

    /// create a new replication slot
    #[must_use]
    pub fn create_slot(mut self) -> Self {
        self.create_slot = true;
        self
    }

    /// drop the replication slot
    #[must_use]
    pub fn drop_slot(mut self) -> Self {
        self.drop_slot = true;
        self
    }

    /// start streaming in a replication slot
    #[must_use]
    pub fn start(mut self) -> Self {
        self.start = true;
        self
    }

    /// exit after receiving the specified LSN
    #[must_use]
    pub fn endpos<S: AsRef<OsStr>>(mut self, endpos: S) -> Self {
        self.endpos = Some(endpos.as_ref().to_os_string());
        self
    }

    /// receive log into this file, - for stdout
    #[must_use]
    pub fn file<S: AsRef<OsStr>>(mut self, file: S) -> Self {
        self.file = Some(file.as_ref().to_os_string());
        self
    }

    /// time between fsyncs to the output file (default: 10)
    #[must_use]
    pub fn fsync_interval<S: AsRef<OsStr>>(mut self, fsync_interval: S) -> Self {
        self.fsync_interval = Some(fsync_interval.as_ref().to_os_string());
        self
    }

    /// do not error if slot already exists when creating a slot
    #[must_use]
    pub fn if_not_exists(mut self) -> Self {
        self.if_not_exists = true;
        self
    }

    /// where in an existing slot should the streaming start
    #[must_use]
    pub fn startpos<S: AsRef<OsStr>>(mut self, startpos: S) -> Self {
        self.startpos = Some(startpos.as_ref().to_os_string());
        self
    }

    /// do not loop on connection lost
    #[must_use]
    pub fn no_loop(mut self) -> Self {
        self.no_loop = true;
        self
    }

    /// pass option NAME with optional value VALUE to the output plugin
    #[must_use]
    pub fn option<S: AsRef<OsStr>>(mut self, option: S) -> Self {
        self.option = Some(option.as_ref().to_os_string());
        self
    }

    /// use output plugin PLUGIN (default: `test_decoding`)
    #[must_use]
    pub fn plugin<S: AsRef<OsStr>>(mut self, plugin: S) -> Self {
        self.plugin = Some(plugin.as_ref().to_os_string());
        self
    }

    /// time between status packets sent to server (default: 10)
    #[must_use]
    pub fn status_interval<S: AsRef<OsStr>>(mut self, status_interval: S) -> Self {
        self.status_interval = Some(status_interval.as_ref().to_os_string());
        self
    }

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

    /// enable decoding of prepared transactions when creating a slot
    #[must_use]
    pub fn two_phase(mut self) -> Self {
        self.two_phase = true;
        self
    }

    /// output verbose messages
    #[must_use]
    pub fn verbose(mut self) -> Self {
        self.verbose = true;
        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 to connect to
    #[must_use]
    pub fn dbname<S: AsRef<OsStr>>(mut self, dbname: S) -> Self {
        self.dbname = Some(dbname.as_ref().to_os_string());
        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 number
    #[must_use]
    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    /// connect as specified database user
    #[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 (should happen automatically)
    #[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
    }
}

impl CommandBuilder for PgRecvLogicalBuilder {
    /// Get the program name
    fn get_program(&self) -> &'static OsStr {
        "pg_recvlogical".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 self.create_slot {
            args.push("--create-slot".into());
        }

        if self.drop_slot {
            args.push("--drop-slot".into());
        }

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

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

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

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

        if self.if_not_exists {
            args.push("--if-not-exists".into());
        }

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

        if self.no_loop {
            args.push("--no-loop".into());
        }

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

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

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

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

        if self.two_phase {
            args.push("--two-phase".into());
        }

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

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

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

        if let Some(dbname) = &self.dbname {
            args.push("--dbname".into());
            args.push(dbname.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());
        }

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

    #[test]
    fn test_builder_from() {
        let command = PgRecvLogicalBuilder::from(&TestSettings).build();
        assert_eq!(
            r#"PGPASSWORD="password" "./pg_recvlogical" "--host" "localhost" "--port" "5432" "--username" "postgres""#,
            command.to_command_string()
        );
    }

    #[test]
    fn test_builder() {
        let command = PgRecvLogicalBuilder::new()
            .env("PGDATABASE", "database")
            .create_slot()
            .drop_slot()
            .start()
            .endpos("endpos")
            .file("file")
            .fsync_interval("fsync_interval")
            .if_not_exists()
            .startpos("startpos")
            .no_loop()
            .option("option")
            .plugin("plugin")
            .status_interval("status_interval")
            .slot("slot")
            .two_phase()
            .verbose()
            .version()
            .help()
            .dbname("dbname")
            .host("localhost")
            .port(5432)
            .username("username")
            .no_password()
            .password()
            .pg_password("password")
            .build();

        assert_eq!(
            r#"PGDATABASE="database" PGPASSWORD="password" "pg_recvlogical" "--create-slot" "--drop-slot" "--start" "--endpos" "endpos" "--file" "file" "--fsync-interval" "fsync_interval" "--if-not-exists" "--startpos" "startpos" "--no-loop" "--option" "option" "--plugin" "plugin" "--status-interval" "status_interval" "--slot" "slot" "--two-phase" "--verbose" "--version" "--help" "--dbname" "dbname" "--host" "localhost" "--port" "5432" "--username" "username" "--no-password" "--password""#,
            command.to_command_string()
        );
    }
}