rjoin 0.2.0

A tool for joining CSV data on command line.
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
use super::printer::Print;
use super::csv::basic::{FirstRec, Group, cmp_records,};
use std::io;
use std::cmp::Ordering;
use std::error::Error;
use std::ops::Range;

/// Options defining the output of the join.
///
/// For those familiar with SQL, you can tweak these to obtain:
///   * INNER JOIN - `show_left: false`, `show_right: false`, `show_both: true`
///   * LEFT OUTER JOIN - `show_left: true`, `show_right: false`, `show_both: true`
///   * RIGHT OUTER JOIN - `show_left: false`, `show_right: true`, `show_both: true`
///   * FULL OUTER JOIN - `show_left: true`, `show_right: true`, `show_both: true`
///
/// and even exclusive joins (outer joins without the inner part).
#[derive(Debug, Clone, Copy)]
pub struct JoinOptions {
    show_left: bool,
    show_right: bool,
    show_both: bool,
}

impl Default for JoinOptions {
    fn default() -> Self {
        JoinOptions {
            show_left: false,
            show_right: false,
            show_both: true,
        }
    }
}
        
impl JoinOptions {
    /// Create a new instance of `JoinOptions`. By default, only `show_both` is enabled. 
    pub fn new() -> Self {
        JoinOptions::default()
    }

    /// Create a new instance of `JoinOptions` with the specified options.
    pub fn from_options(show_left: bool, show_right: bool, show_both: bool) -> Self {
        JoinOptions {
            show_left: show_left,
            show_right: show_right,
            show_both: show_both,
        }
    }
}

/// Join the groups of records `group0` and `group1`. The output is
/// written into `w` using the provided printer `p`. 
pub fn join<R0,R1,W,P>(
    group0: &mut Group<R0>,
    group1: &mut Group<R1>,
    w: &mut W,
    mut p: P,
    opts: JoinOptions,
) -> Result<(), Box<Error>>
    where R0: io::Read,
          R1: io::Read,
          W: io::Write,
          P: Print<W>,
{
    let mut ord = Ordering::Equal;
    let mut g0: Option<Range<usize>> = None;
    let mut g1: Option<Range<usize>> = None;
    let mut r0: Range<usize>;
    let mut r1: Range<usize>;
    loop {
        match ord {
            Ordering::Less => {
                g0 = match group0.next_group() {
                    Ok(o) => o,
                    Err(e) => return Err(format!("left input: {}", e).into()),
                };
            }
            Ordering::Greater => {
                g1 = match group1.next_group() {
                    Ok(o) => o,
                    Err(e) => return Err(format!("right input: {}", e).into()),
                };
            }
            Ordering::Equal => {
                g0 = match group0.next_group() {
                    Ok(o) => o,
                    Err(e) => return Err(format!("left input: {}", e).into()),
                };
                g1 = match group1.next_group() {
                    Ok(o) => o,
                    Err(e) => return Err(format!("right input: {}", e).into()),
                };
            }
        }
        ord = match (&g0, &g1) {
            (&Some(ref rng0), &Some(ref rng1)) => {
                let (buf0, idx0) = group0.buf_index();
                let (buf1, idx1) = group1.buf_index();
                r0 = idx0.get_record(rng0.start).unwrap_or(0..0);
                r1 = idx1.get_record(rng1.start).unwrap_or(0..0);
                match cmp_records(
                    buf0,
                    buf1,
                    &idx0.fields()[r0.clone()],
                    &idx1.fields()[r1.clone()],
                    group0.key_idx(),
                    group1.key_idx(),
                    ) {

                    Ok(ord) => {
                        match ord {
                            Ordering::Less => {
                                if opts.show_left {
                                    p.print_left(w, buf0, idx0.fields(), idx0.records(), rng0.clone())?;
                                }
                            }
                            Ordering::Greater => {
                                if opts.show_right {
                                    p.print_right(w, buf1, idx1.fields(), idx1.records(), rng1.clone())?;
                                }
                            }
                            Ordering::Equal => {
                                if opts.show_both {
                                    p.print_both(
                                        w,
                                        buf0,
                                        buf1,
                                        idx0.fields(),
                                        idx1.fields(),
                                        idx0.records(),
                                        idx1.records(),
                                        rng0.clone(),
                                        rng1.clone(),
                                    )?;
                                }
                            }
                        }
                        ord
                    }
                    Err(_) => {
                        return Err("internal: the record was not grouped properly".into());
                    }
                }
            }
            (&Some(ref rng0), &None) => {
                let (buf0, idx0) = group0.buf_index();
                if opts.show_left {
                    p.print_left(w, buf0, idx0.fields(), idx0.records(), rng0.clone())?;
                } else {
                    return Ok(());
                }
                Ordering::Less
            }
            (&None, &Some(ref rng1)) => {
                let (buf1, idx1) = group1.buf_index();
                if opts.show_right {
                    p.print_right(w, buf1, idx1.fields(), idx1.records(), rng1.clone())?;
                } else {
                    return Ok(());
                }
                Ordering::Greater
            }
            (&None, &None) => return Ok(()),
        }
    }
}

pub fn head<R0,R1,W,P>(
    first_rec0: &mut FirstRec<R0>,
    first_rec1: &mut FirstRec<R1>,
    w: &mut W,
    mut p: P,
    opts: JoinOptions,
) -> Result<(), Box<Error>>
    where R0: io::Read,
          R1: io::Read,
          W: io::Write,
          P: Print<W>,
{
    let fr0 = first_rec0.is_present()?;
    let fr1 = first_rec1.is_present()?;

    if opts.show_both || (opts.show_left && opts.show_right) {
        if fr0 && fr1 {
            let (buf0, idx0) = first_rec0.buf_index();
            let (buf1, idx1) = first_rec1.buf_index();
            p.print_both(
                w,
                buf0,
                buf1,
                idx0.fields(),
                idx1.fields(),
                idx0.records(),
                idx1.records(),
                0..1,
                0..1,
            )?;
        }
    } else if opts.show_left {
        if fr0 {
            let (buf0, idx0) = first_rec0.buf_index();
            p.print_left(w, buf0, idx0.fields(), idx0.records(), 0..1)?;
        }
    }
    else {
        if fr1 {
            let (buf1, idx1) = first_rec1.buf_index();
            p.print_right(w, buf1, idx1.fields(), idx1.records(), 0..1)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{JoinOptions, join, head,};
    use printer::KeyFirst;
    use csv::basic::{FirstRec, Group};
    use rollbuf::RollBuf;
    use csvroll::index_builder::IndexBuilder;
    use csvroll::parser::Parser;

    #[test]
    fn test_join() {
        struct TestCase {
            note: String,
            data0: String,
            data1: String,
            opts: JoinOptions,
            want: String,
        }

        let test_cases = vec![
            TestCase {
                note: "inner join with cartesian product".into(),
                data0: "color,red\ncolor,green\ncolor,blue\nshape,circle\nshape,square".into(),
                data1: "color,orange\ncolor,purple\nsize,small\nsize,large".into(),
                opts: JoinOptions { show_left: false, show_right: false, show_both: true },
                want: 
                    "\
                     color,red,orange\n\
                     color,red,purple\n\
                     color,green,orange\n\
                     color,green,purple\n\
                     color,blue,orange\n\
                     color,blue,purple\n\
                    ".into(),
            },
            TestCase {
                note: "inner join simple".into(),
                data0: "altitude,low\naltitude,high\ncolor,red".into(),
                data1: "color,orange\nsize,small\nsize,large".into(),
                opts: JoinOptions { show_left: false, show_right: false, show_both: true },
                want: "color,red,orange\n".into(),
            },
            TestCase {
                note: "left outer join simple".into(),
                data0: "altitude,low\naltitude,high\ncolor,red".into(),
                data1: "color,orange\nsize,small\nsize,large".into(),
                opts: JoinOptions { show_left: true, show_right: false, show_both: true },
                want: 
                    "\
                     altitude,low\n\
                     altitude,high\n\
                     color,red,orange\n\
                    ".into(),
            },
            TestCase {
                note: "left exclusion join simple".into(),
                data0: "altitude,low\naltitude,high\ncolor,red".into(),
                data1: "color,orange\nsize,small\nsize,large".into(),
                opts: JoinOptions { show_left: true, show_right: false, show_both: false },
                want: 
                    "\
                     altitude,low\n\
                     altitude,high\n\
                    ".into(),
            },
            TestCase {
                note: "right outer join simple".into(),
                data0: "altitude,low\naltitude,high\ncolor,red".into(),
                data1: "color,orange\nsize,small\nsize,large".into(),
                opts: JoinOptions { show_left: false, show_right: true, show_both: true },
                want: 
                    "\
                     color,red,orange\n\
                     size,small\n\
                     size,large\n\
                    ".into(),
            },
            TestCase {
                note: "right exclusion join simple".into(),
                data0: "altitude,low\naltitude,high\ncolor,red".into(),
                data1: "color,orange\nsize,small\nsize,large".into(),
                opts: JoinOptions { show_left: false, show_right: true, show_both: false },
                want: 
                    "\
                     size,small\n\
                     size,large\n\
                    ".into(),
            },
            TestCase {
                note: "full outer join simple".into(),
                data0: "altitude,low\naltitude,high\ncolor,red".into(),
                data1: "color,orange\nsize,small\nsize,large".into(),
                opts: JoinOptions { show_left: true, show_right: true, show_both: true },
                want: 
                    "\
                     altitude,low\n\
                     altitude,high\n\
                     color,red,orange\n\
                     size,small\n\
                     size,large\n\
                    ".into(),
            },
        ];

        for t in test_cases {
            let TestCase {note, data0, data1, opts, want } = t;
            let buf0 = RollBuf::with_capacity(16, data0.as_bytes());
            let buf1 = RollBuf::with_capacity(16, data1.as_bytes());
            let idx_builder0 = IndexBuilder::new(b',', b'\n');
            let idx_builder1 = IndexBuilder::new(b',', b'\n');
            let parser0 = Parser::from_parts(buf0, idx_builder0);
            let parser1 = Parser::from_parts(buf1, idx_builder1);
            let mut group0 = Group::init(parser0, vec![0]).unwrap();
            let mut group1 = Group::init(parser1, vec![0]).unwrap();
            let mut out: Vec<u8> = Vec::new();
            let printer = KeyFirst::from_parts(b',', b'\n', vec![0], vec![0]);

            println!("{}", note);
            join(&mut group0, &mut group1, &mut out, printer, opts).unwrap();
            assert_eq!(out, want.as_bytes());
        }
    }

    #[test]
    fn test_header() {
        struct TestCase {
            note: String,
            data0: String,
            data1: String,
            opts: JoinOptions,
            want: String,
        }

        let test_cases = vec![
            TestCase {
                note: "inner join".into(),
                data0: "col0,col1\naltitude,low\naltitude,high\ncolor,red".into(),
                data1: "col2,col3\ncolor,orange\nsize,small\nsize,large".into(),
                opts: JoinOptions { show_left: false, show_right: false, show_both: true },
                want: "col0,col1,col3\n".into(),
            },
            TestCase {
                note: "left outer join".into(),
                data0: "col0,col1\naltitude,low\naltitude,high\ncolor,red".into(),
                data1: "col2,col3\ncolor,orange\nsize,small\nsize,large".into(),
                opts: JoinOptions { show_left: true, show_right: false, show_both: true },
                want: "col0,col1,col3\n".into(),
            },
            TestCase {
                note: "left exclusion join".into(),
                data0: "col0,col1\naltitude,low\naltitude,high\ncolor,red".into(),
                data1: "col2,col3\ncolor,orange\nsize,small\nsize,large".into(),
                opts: JoinOptions { show_left: true, show_right: false, show_both: false },
                want: "col0,col1\n".into(),
            },
            TestCase {
                note: "right outer join".into(),
                data0: "col0,col1\naltitude,low\naltitude,high\ncolor,red".into(),
                data1: "col2,col3\ncolor,orange\nsize,small\nsize,large".into(),
                opts: JoinOptions { show_left: false, show_right: true, show_both: true },
                want: "col0,col1,col3\n".into(),
            },
            TestCase {
                note: "right exclusion join".into(),
                data0: "col0,col1\naltitude,low\naltitude,high\ncolor,red".into(),
                data1: "col2,col3\ncolor,orange\nsize,small\nsize,large".into(),
                opts: JoinOptions { show_left: false, show_right: true, show_both: false },
                want: "col2,col3\n".into(),
            },
            TestCase {
                note: "full outer join".into(),
                data0: "col0,col1\naltitude,low\naltitude,high\ncolor,red".into(),
                data1: "col2,col3\ncolor,orange\nsize,small\nsize,large".into(),
                opts: JoinOptions { show_left: true, show_right: true, show_both: true },
                want: "col0,col1,col3\n".into(),
            },
        ];

        for t in test_cases {
            let TestCase {note, data0, data1, opts, want } = t;
            let buf0 = RollBuf::with_capacity(16, data0.as_bytes());
            let buf1 = RollBuf::with_capacity(16, data1.as_bytes());
            let idx_builder0 = IndexBuilder::new(b',', b'\n');
            let idx_builder1 = IndexBuilder::new(b',', b'\n');
            let parser0 = Parser::from_parts(buf0, idx_builder0);
            let parser1 = Parser::from_parts(buf1, idx_builder1);
            let mut first_rec0 = FirstRec::init(parser0).unwrap();
            let mut first_rec1 = FirstRec::init(parser1).unwrap();
            let mut out: Vec<u8> = Vec::new();
            let printer = KeyFirst::from_parts(b',', b'\n', vec![0], vec![0]);

            println!("{}", note);
            head(&mut first_rec0, &mut first_rec1, &mut out, printer, opts).unwrap();
            assert_eq!(out, want.as_bytes());
        }
    }
}