postgresql_embedded 0.1.0

Embed PostgreSQL in Rust applications
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
use crate::command::traits::CommandBuilder;
use std::ffi::{OsStr, OsString};
use std::path::PathBuf;

/// postgres is the PostgreSQL server.
#[derive(Clone, Debug, Default)]
pub struct PostgresBuilder {
    program_dir: Option<PathBuf>,
    n_buffers: Option<u32>,
    runtime_param: Option<(OsString, OsString)>,
    print_runtime_param: Option<OsString>,
    debugging_level: Option<u8>,
    data_dir: Option<PathBuf>,
    european_date_format: bool,
    fsync_off: bool,
    hostname: Option<OsString>,
    tcp_ip_connections: bool,
    socket_location: Option<PathBuf>,
    max_connections: Option<u32>,
    port: Option<u16>,
    show_stats: bool,
    work_mem: Option<u32>,
    version: bool,
    describe_config: bool,
    help: bool,
    forbidden_plan_types: Option<OsString>,
    allow_system_table_changes: bool,
    disable_system_indexes: bool,
    show_timings: Option<OsString>,
    send_sigabrt: bool,
    wait_seconds: Option<u32>,
    single_user_mode: bool,
    dbname: Option<OsString>,
    override_debugging_level: Option<u8>,
    echo_statement: bool,
    no_newline_delimiter: bool,
    output_file: Option<PathBuf>,
    bootstrapping_mode: bool,
    check_mode: bool,
}

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

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

    /// number of shared buffers
    pub fn n_buffers(mut self, n_buffers: u32) -> Self {
        self.n_buffers = Some(n_buffers);
        self
    }

    /// set run-time parameter
    pub fn runtime_param<S: AsRef<OsStr>>(mut self, name: S, value: S) -> Self {
        self.runtime_param = Some((name.as_ref().into(), value.as_ref().into()));
        self
    }

    /// print value of run-time parameter, then exit
    pub fn print_runtime_param<S: AsRef<OsStr>>(mut self, name: S) -> Self {
        self.print_runtime_param = Some(name.as_ref().to_os_string());
        self
    }

    /// debugging level
    pub fn debugging_level(mut self, level: u8) -> Self {
        self.debugging_level = Some(level);
        self
    }

    /// database directory
    pub fn data_dir<P: Into<PathBuf>>(mut self, dir: P) -> Self {
        self.data_dir = Some(dir.into());
        self
    }

    /// use European date input format (DMY)
    pub fn european_date_format(mut self) -> Self {
        self.european_date_format = true;
        self
    }

    /// turn fsync off
    pub fn fsync_off(mut self) -> Self {
        self.fsync_off = true;
        self
    }

    /// host name or IP address to listen on
    pub fn hostname<S: AsRef<OsStr>>(mut self, hostname: S) -> Self {
        self.hostname = Some(hostname.as_ref().to_os_string());
        self
    }

    /// enable TCP/IP connections (deprecated)
    pub fn tcp_ip_connections(mut self) -> Self {
        self.tcp_ip_connections = true;
        self
    }

    /// Unix-domain socket location
    pub fn socket_location<P: Into<PathBuf>>(mut self, dir: P) -> Self {
        self.socket_location = Some(dir.into());
        self
    }

    /// maximum number of allowed connections
    pub fn max_connections(mut self, max: u32) -> Self {
        self.max_connections = Some(max);
        self
    }

    /// port number to listen on
    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    /// show statistics after each query
    pub fn show_stats(mut self) -> Self {
        self.show_stats = true;
        self
    }

    /// set amount of memory for sorts (in kB)
    pub fn work_mem(mut self, mem: u32) -> Self {
        self.work_mem = Some(mem);
        self
    }

    /// output version information, then exit
    pub fn version(mut self) -> Self {
        self.version = true;
        self
    }

    /// describe configuration parameters, then exit
    pub fn describe_config(mut self) -> Self {
        self.describe_config = true;
        self
    }

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

    /// forbid use of some plan types
    pub fn forbidden_plan_types<S: AsRef<OsStr>>(mut self, types: S) -> Self {
        self.forbidden_plan_types = Some(types.as_ref().to_os_string());
        self
    }

    /// allow system table structure changes
    pub fn allow_system_table_changes(mut self) -> Self {
        self.allow_system_table_changes = true;
        self
    }

    /// disable system indexes
    pub fn disable_system_indexes(mut self) -> Self {
        self.disable_system_indexes = true;
        self
    }

    /// show timings after each query
    pub fn show_timings<S: AsRef<OsStr>>(mut self, timings: S) -> Self {
        self.show_timings = Some(timings.as_ref().to_os_string());
        self
    }

    /// send SIGABRT to all backend processes if one dies
    pub fn send_sigabrt(mut self) -> Self {
        self.send_sigabrt = true;
        self
    }

    /// wait NUM seconds to allow attach from a debugger
    pub fn wait_seconds(mut self, seconds: u32) -> Self {
        self.wait_seconds = Some(seconds);
        self
    }

    /// selects single-user mode (must be first argument)
    pub fn single_user_mode(mut self) -> Self {
        self.single_user_mode = true;
        self
    }

    /// database name (defaults to user name)
    pub fn dbname<S: AsRef<OsStr>>(mut self, dbname: S) -> Self {
        self.dbname = Some(dbname.as_ref().to_os_string());
        self
    }

    /// override debugging level
    pub fn override_debugging_level(mut self, level: u8) -> Self {
        self.override_debugging_level = Some(level);
        self
    }

    /// echo statement before execution
    pub fn echo_statement(mut self) -> Self {
        self.echo_statement = true;
        self
    }

    /// do not use newline as interactive query delimiter
    pub fn no_newline_delimiter(mut self) -> Self {
        self.no_newline_delimiter = true;
        self
    }

    /// send stdout and stderr to given file
    pub fn output_file<P: Into<PathBuf>>(mut self, file: P) -> Self {
        self.output_file = Some(file.into());
        self
    }

    /// selects bootstrapping mode (must be first argument)
    pub fn bootstrapping_mode(mut self) -> Self {
        self.bootstrapping_mode = true;
        self
    }

    /// selects check mode (must be first argument)
    pub fn check_mode(mut self) -> Self {
        self.check_mode = true;
        self
    }
}

impl CommandBuilder for PostgresBuilder {
    /// Get the program name
    fn get_program(&self) -> &'static OsStr {
        "postgres".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(n_buffers) = &self.n_buffers {
            args.push("-B".into());
            args.push(n_buffers.to_string().into());
        }

        if let Some((name, value)) = &self.runtime_param {
            args.push("-c".into());
            args.push(format!("{}={}", name.to_string_lossy(), value.to_string_lossy()).into());
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

        if self.describe_config {
            args.push("--describe-config".into());
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        args
    }
}

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

    #[test]
    fn test_builder_new() {
        let command = PostgresBuilder::new().program_dir(".").build();

        assert_eq!(
            PathBuf::from(".").join("postgres"),
            PathBuf::from(command.to_command_string().replace("\"", ""))
        );
    }

    #[test]
    fn test_builder() {
        let command = PostgresBuilder::new()
            .n_buffers(100)
            .runtime_param("name", "value")
            .print_runtime_param("name")
            .debugging_level(3)
            .data_dir("data_dir")
            .european_date_format()
            .fsync_off()
            .hostname("localhost")
            .tcp_ip_connections()
            .socket_location("socket_location")
            .max_connections(100)
            .port(5432)
            .show_stats()
            .work_mem(100)
            .version()
            .describe_config()
            .help()
            .forbidden_plan_types("type")
            .allow_system_table_changes()
            .disable_system_indexes()
            .show_timings("timings")
            .send_sigabrt()
            .wait_seconds(10)
            .single_user_mode()
            .dbname("dbname")
            .override_debugging_level(3)
            .echo_statement()
            .no_newline_delimiter()
            .output_file("output_file")
            .bootstrapping_mode()
            .check_mode()
            .build();

        assert_eq!(
            r#""postgres" "-B" "100" "-c" "name=value" "-C" "name" "-d" "3" "-D" "data_dir" "-e" "-F" "-h" "localhost" "-i" "-k" "socket_location" "-N" "100" "-p" "5432" "-s" "-S" "100" "--version" "--describe-config" "--help" "-f" "type" "-O" "-P" "-t" "timings" "-T" "-W" "10" "--single" "dbname" "-d" "3" "-E" "-j" "-r" "output_file" "--boot" "--check""#,
            command.to_command_string()
        );
    }
}