sql-splitter 1.19.0

High-performance CLI tool for splitting large SQL dump files into individual table files
Documentation
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
mod epoch;

#[allow(unused_imports)] // Public API re-export used by integration tests
pub use epoch::advance_epoch_boundary;
use epoch::EpochDriver;

use crate::parser::{determine_buffer_size, ContentFilter, Parser, SqlDialect, StatementType};
use crate::progress::ProgressReader;
use crate::writer::{
    env_writer_count, probe_output_dir, Clock, Controller, IoStrategy, ParallelWriters,
    ProfileKind, ProfileValues, RealClock, WriterProfile,
};
use ahash::AHashSet;
use anyhow::Context;
use serde::Serialize;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::Arc;

/// Statistics from a split operation.
#[derive(Serialize)]
pub struct Stats {
    /// Total statements processed.
    pub statements_processed: u64,
    /// Number of unique tables found.
    pub tables_found: usize,
    /// Total bytes processed from input.
    pub bytes_processed: u64,
    /// Names of all tables found.
    pub table_names: Vec<String>,
    /// Number of writer threads at the end of the run (observability for the
    /// adaptive controller's deferred writer spawn; not part of JSON output).
    #[serde(skip)]
    pub writers_used: usize,
    /// Adaptive I/O transition log lines emitted during the run, in order
    /// (observability for tests and debugging; not part of JSON output).
    #[serde(skip)]
    pub io_transitions: Vec<String>,
}

/// Configuration for the splitter.
#[derive(Default)]
pub struct SplitterConfig {
    /// SQL dialect for parsing.
    pub dialect: SqlDialect,
    /// If true, parse without writing output files.
    pub dry_run: bool,
    /// If set, only process tables in this set.
    pub table_filter: Option<AHashSet<String>>,
    /// Optional callback for progress reporting.
    pub progress_fn: Option<Box<dyn Fn(u64)>>,
    /// Filter for which statement types to include.
    pub content_filter: ContentFilter,
    /// Per-table output compression (default `None` → plain `.sql`).
    pub output_compression: Compression,
    /// I/O strategy for output writing (default `Auto`).
    pub io_strategy: IoStrategy,
    /// Clock driving epoch measurements (None → wall clock). Test seam: a
    /// stepping mock clock makes the adaptive controller fully deterministic.
    pub io_clock: Option<Arc<dyn Clock>>,
}

/// Compression format detected from file extension
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Compression {
    #[default]
    None,
    Gzip,
    Bzip2,
    Xz,
    Zstd,
    /// A zip *archive* (not a stream compressor) containing exactly one
    /// `.sql` member. Detected here so callers can branch on it, but it
    /// never goes through [`Compression::wrap_reader`] — see [`open_input`]
    /// and `crate::zip_input`.
    Zip,
}

impl Compression {
    /// Detect compression format from file extension
    pub fn from_path(path: &Path) -> Self {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_lowercase());

        match ext.as_deref() {
            Some("gz" | "gzip") => Compression::Gzip,
            Some("bz2" | "bzip2") => Compression::Bzip2,
            Some("xz" | "lzma") => Compression::Xz,
            Some("zst" | "zstd") => Compression::Zstd,
            Some("zip") => Compression::Zip,
            _ => Compression::None,
        }
    }

    /// Parse an output-compression format name (for the `--compress` flag).
    pub fn parse_output(s: &str) -> Result<Self, String> {
        match s.to_lowercase().as_str() {
            "none" | "" => Ok(Compression::None),
            "gzip" | "gz" => Ok(Compression::Gzip),
            "bzip2" | "bz2" => Ok(Compression::Bzip2),
            "xz" | "lzma" => Ok(Compression::Xz),
            "zstd" | "zst" => Ok(Compression::Zstd),
            other => Err(format!(
                "Unknown compression '{other}'. Valid: none, gzip, bzip2, xz, zstd"
            )),
        }
    }

    /// File-name extension for compressed output (empty for `None`).
    pub fn output_extension(&self) -> &'static str {
        match self {
            Compression::None => "",
            Compression::Gzip => ".gz",
            Compression::Bzip2 => ".bz2",
            Compression::Xz => ".xz",
            Compression::Zstd => ".zst",
            // Never selected as an output compression: `parse_output` has no
            // "zip" case, so per-table output stays rejected as documented.
            Compression::Zip => "",
        }
    }

    /// Wrap a reader with the appropriate decompressor
    pub fn wrap_reader<'a>(
        &self,
        reader: Box<dyn Read + 'a>,
    ) -> std::io::Result<Box<dyn Read + 'a>> {
        Ok(match self {
            Compression::None => reader,
            // Use the multi-member/multi-stream decoders: dumps are commonly
            // stored as concatenated members (e.g. `cat a.gz b.gz`, or tools
            // that flush a new stream per table). The single-member decoders
            // stop at the first member and silently truncate the rest.
            #[cfg(feature = "compression")]
            Compression::Gzip => Box::new(flate2::read::MultiGzDecoder::new(reader)),
            #[cfg(feature = "compression")]
            Compression::Bzip2 => Box::new(bzip2::read::MultiBzDecoder::new(reader)),
            #[cfg(feature = "compression")]
            Compression::Xz => Box::new(xz2::read::XzDecoder::new_multi_decoder(reader)),
            #[cfg(feature = "compression")]
            Compression::Zstd => Box::new(zstd::stream::read::Decoder::new(reader)?),
            // Zip is an archive, not a stream decoder: it needs a seekable
            // `File` to parse the central directory, so it can never be
            // wrapped here. Callers must go through `open_input` instead.
            Compression::Zip => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::Unsupported,
                    "zip input must be opened via open_input(), not wrap_reader() (needs a seekable File)",
                ))
            }
            #[cfg(not(feature = "compression"))]
            _ => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::Unsupported,
                    "compressed input requires the `compression` feature",
                ))
            }
        })
    }
}

impl std::fmt::Display for Compression {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Compression::None => write!(f, "none"),
            Compression::Gzip => write!(f, "gzip"),
            Compression::Bzip2 => write!(f, "bzip2"),
            Compression::Xz => write!(f, "xz"),
            Compression::Zstd => write!(f, "zstd"),
            Compression::Zip => write!(f, "zip"),
        }
    }
}

/// Open `path` as a streaming byte source, transparently handling any
/// supported compression format — including zip archives, which need a
/// different opening strategy than the stream decoders (see
/// `crate::zip_input`). This is the entry point call sites should use
/// instead of manually pairing `File::open` with [`Compression::wrap_reader`].
///
/// When `progress_fn` is `Some`, it receives cumulative bytes read from disk
/// (raw/compressed bytes, for compressed/zip inputs) as they're read; size a
/// progress bar over this with [`input_progress_len`]. The zero- and
/// always-progress conveniences [`open_input`] / [`open_input_with_progress`]
/// are thin wrappers over this.
pub fn open_input_opt_progress(
    path: &Path,
    progress_fn: Option<Box<dyn Fn(u64)>>,
) -> anyhow::Result<Box<dyn Read>> {
    let compression = Compression::from_path(path);

    if compression == Compression::Zip {
        #[cfg(feature = "archive")]
        {
            return crate::zip_input::open_zip_member(path, progress_fn);
        }
        #[cfg(not(feature = "archive"))]
        {
            anyhow::bail!("zip input requires the `archive` feature");
        }
    }

    let file = File::open(path).with_context(|| format!("Failed to open input file: {path:?}"))?;
    let reader: Box<dyn Read> = match progress_fn {
        Some(cb) => Box::new(ProgressReader::new(file, cb)),
        None => Box::new(file),
    };
    compression
        .wrap_reader(reader)
        .with_context(|| format!("Failed to initialize {compression} decompression for {path:?}"))
}

/// Convenience wrapper: [`open_input_opt_progress`] without progress reporting.
pub fn open_input(path: &Path) -> anyhow::Result<Box<dyn Read>> {
    open_input_opt_progress(path, None)
}

/// Convenience wrapper: [`open_input_opt_progress`] with progress reporting.
pub fn open_input_with_progress(
    path: &Path,
    progress_fn: Box<dyn Fn(u64)>,
) -> anyhow::Result<Box<dyn Read>> {
    open_input_opt_progress(path, Some(progress_fn))
}

/// Total number of bytes the progress callback installed by
/// [`open_input_with_progress`] can report for `path` — i.e. the correct
/// length for a progress bar over this input.
///
/// For most inputs this is simply the on-disk file size (progress counts
/// raw/compressed bytes read from disk). Zip archives are the exception:
/// only the sole `.sql` member's compressed bytes are ever streamed, so the
/// total is that member's compressed size — sizing a bar with the archive's
/// file size would leave it stuck below 100% by the archive overhead and any
/// sibling members. Falls back to the file size when the member can't be
/// located (the subsequent open reports the real error).
pub fn input_progress_len(path: &Path) -> u64 {
    #[cfg(feature = "archive")]
    if Compression::from_path(path) == Compression::Zip {
        if let Ok(size) = crate::zip_input::sql_member_compressed_size(path) {
            return size;
        }
    }
    std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
}

/// Estimated decompressed size of an input file, for adaptive-I/O gating and
/// epoch sizing. Exact for uncompressed input; for compressed/zip input a
/// deliberately conservative 4× multiplier is applied (SQL text typically
/// compresses 4–10×) so a small-but-dense archive doesn't silently pin the
/// SSD profile for hundreds of MB of output.
#[doc(hidden)]
pub fn estimate_uncompressed_size(file_size: u64, compression: Compression) -> u64 {
    match compression {
        Compression::None => file_size,
        _ => file_size.saturating_mul(4),
    }
}

pub struct Splitter {
    input_file: PathBuf,
    output_dir: PathBuf,
    config: SplitterConfig,
}

impl Splitter {
    pub fn new(input_file: PathBuf, output_dir: PathBuf) -> Self {
        Self {
            input_file,
            output_dir,
            config: SplitterConfig::default(),
        }
    }

    pub fn with_dialect(mut self, dialect: SqlDialect) -> Self {
        self.config.dialect = dialect;
        self
    }

    pub fn with_dry_run(mut self, dry_run: bool) -> Self {
        self.config.dry_run = dry_run;
        self
    }

    pub fn with_table_filter(mut self, tables: Vec<String>) -> Self {
        if !tables.is_empty() {
            self.config.table_filter = Some(tables.into_iter().collect());
        }
        self
    }

    pub fn with_progress<F: Fn(u64) + 'static>(mut self, f: F) -> Self {
        self.config.progress_fn = Some(Box::new(f));
        self
    }

    pub fn with_content_filter(mut self, filter: ContentFilter) -> Self {
        self.config.content_filter = filter;
        self
    }

    pub fn with_output_compression(mut self, format: Compression) -> Self {
        self.config.output_compression = format;
        self
    }

    /// Choose the I/O strategy for output writing (`--io-strategy`). Explicit
    /// profiles pin the writer configuration; `Auto` (the default) probes the
    /// output device and adapts at runtime.
    pub fn with_io_profile(mut self, profile: IoStrategy) -> Self {
        self.config.io_strategy = profile;
        self
    }

    /// Override the clock used for adaptive-I/O epoch measurements.
    /// Deterministic-test seam; production code always uses the default
    /// wall clock.
    #[doc(hidden)]
    pub fn with_io_clock(mut self, clock: Arc<dyn Clock>) -> Self {
        self.config.io_clock = Some(clock);
        self
    }

    pub fn split(mut self) -> anyhow::Result<Stats> {
        let file_size = std::fs::metadata(&self.input_file)
            .with_context(|| format!("Failed to open input file: {:?}", self.input_file))?
            .len();
        let buffer_size = determine_buffer_size(file_size);
        let dialect = self.config.dialect;
        let content_filter = self.config.content_filter;

        // Open the input, transparently handling any supported compression
        // format (including zip archives, which need a two-phase open).
        let reader: Box<dyn Read> =
            open_input_opt_progress(&self.input_file, self.config.progress_fn.take())?;

        let mut parser = Parser::with_dialect(reader, buffer_size, dialect);

        // Parallel, pipelined writers (skipped for dry runs), configured by
        // the selected I/O strategy (see docs/features/ADAPTIVE_IO_PROFILES.md).
        // Precedence: SQL_SPLITTER_WRITERS / SQL_SPLITTER_WRITE_BUF env vars >
        // explicit --io-strategy > auto.
        let out_compression = self.config.output_compression;
        let compressing = out_compression != Compression::None;
        let cores = std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(4);

        // Epoch length for the adaptive controller: byte-based so controller
        // decisions are a pure function of (bytes, measured durations). The
        // hidden env override is the deterministic-test seam.
        let epoch_bytes = std::env::var("SQL_SPLITTER_EPOCH_BYTES")
            .ok()
            .and_then(|v| v.parse::<u64>().ok())
            .filter(|&n| n > 0);
        // Adaptation only pays off at scale: below ~4 default epochs' worth of
        // input the run is over before the controller could act, so `auto`
        // just pins FAST (today's defaults) and skips the 8MB probe. An
        // explicit epoch override (tests) engages the full machinery.
        // Compressed inputs are gated (and epoch-sized) on an estimate of the
        // *decompressed* volume: run length is governed by how much SQL comes
        // out of the archive, not by its on-disk size, and `bytes_processed`
        // (which epoch boundaries compare against) counts decompressed bytes.
        const DEFAULT_EPOCH_BYTES: u64 = 256 * 1024 * 1024;
        const AUTO_MIN_FILE_SIZE: u64 = 64 * 1024 * 1024;
        let input_size_estimate =
            estimate_uncompressed_size(file_size, Compression::from_path(&self.input_file));
        let adaptive = self.config.io_strategy == IoStrategy::Auto
            && !self.config.dry_run
            && (epoch_bytes.is_some() || input_size_estimate >= AUTO_MIN_FILE_SIZE);
        // Aim for at least 4 epochs per file so short runs still measure.
        let epoch_bytes = epoch_bytes
            .unwrap_or_else(|| DEFAULT_EPOCH_BYTES.min((input_size_estimate / 4).max(1)));

        let opening_kind = match self.config.io_strategy.pinned() {
            Some(kind) => kind,
            // The fsync probe picks auto's *opening* state only; the feedback
            // controller owns the truth once the pipeline runs.
            None if adaptive => probe_output_dir(&self.output_dir),
            None => ProfileKind::Ssd,
        };
        let profile =
            WriterProfile::for_kind(opening_kind, cores, compressing).with_env_overrides();

        // In auto mode, open at W=1 and let the controller spawn up to FAST's
        // writer count once the device proves fast: on NVMe the W=1 opening
        // costs ~15% for one epoch; on slow media it avoids ever thrashing.
        // SQL_SPLITTER_WRITERS pins the count and disables growth entirely.
        //
        // Compressed output can never deliver that proof: throughput is
        // measured in *compressed* bytes beneath the encoders (a lone gzip
        // writer never shows 150 MB/s compressed) and a CPU-bound encoder
        // stalls the producer exactly like a slow device. Such runs open
        // with the probe-chosen profile's full writer count and freeze the
        // controller (see `Controller::for_compressed_output`).
        let initial_writers = if adaptive && !compressing {
            env_writer_count().unwrap_or(1)
        } else {
            profile.writers
        };
        let fast_writers = if env_writer_count().is_some() {
            initial_writers
        } else {
            WriterProfile::for_kind(ProfileKind::Ssd, cores, compressing).writers
        };

        let values = Arc::new(ProfileValues::new(&profile));
        let mut writers = if self.config.dry_run {
            None
        } else {
            // Channel depth scales with chunk size so in-flight bytes stay in
            // the same ballpark as the profile's stage cap: FAST keeps the
            // historical 64 × 256KB; the slow profiles get fewer, bigger slots.
            let capacity = (profile.stage_cap / profile.flush_chunk.max(1)).clamp(4, 64);
            Some(
                ParallelWriters::new(
                    self.output_dir.clone(),
                    initial_writers,
                    capacity,
                    out_compression,
                    Arc::clone(&values),
                )
                .with_context(|| {
                    format!("Failed to create output directory: {:?}", self.output_dir)
                })?,
            )
        };

        // The adaptive feedback loop, evaluated at every epoch boundary
        // (measurement + controller decision + writer retuning) — see
        // `epoch::EpochDriver`.
        let mut epoch_driver = adaptive.then(|| {
            let ctrl = Controller::new(opening_kind, fast_writers);
            let ctrl = if compressing {
                ctrl.for_compressed_output()
            } else {
                ctrl
            };
            let clock: Arc<dyn Clock> = self
                .config
                .io_clock
                .take()
                .unwrap_or_else(|| Arc::new(RealClock::new()));
            EpochDriver::new(
                ctrl,
                clock,
                Arc::clone(&values),
                epoch_bytes,
                cores,
                compressing,
            )
        });

        let mut tables_seen: AHashSet<String> = AHashSet::new();
        let mut stats = Stats {
            statements_processed: 0,
            tables_found: 0,
            bytes_processed: 0,
            table_names: Vec::new(),
            writers_used: initial_writers,
            io_transitions: Vec::new(),
        };

        // Track the last COPY table for PostgreSQL COPY data blocks
        let mut last_copy_table: Option<String> = None;

        while let Some(stmt) = parser.read_statement()? {
            let (stmt_type, mut table_name) =
                Parser::<&[u8]>::parse_statement_with_dialect(&stmt, dialect);

            // Track COPY statements for data association
            if stmt_type == StatementType::Copy {
                last_copy_table = Some(table_name.clone());
            }

            // Handle PostgreSQL COPY data blocks - associate with last COPY table
            let is_copy_data = if stmt_type == StatementType::Unknown && last_copy_table.is_some() {
                // Check if this looks like COPY data (ends with \.\n)
                if stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n") {
                    // Safe: we just checked is_some() above
                    if let Some(copy_table) = last_copy_table.take() {
                        table_name = copy_table;
                        true
                    } else {
                        false
                    }
                } else {
                    false
                }
            } else {
                false
            };

            if !is_copy_data && (stmt_type == StatementType::Unknown || table_name.is_empty()) {
                continue;
            }

            // Apply content filter (schema-only or data-only)
            match content_filter {
                ContentFilter::SchemaOnly => {
                    if !stmt_type.is_schema() {
                        continue;
                    }
                }
                ContentFilter::DataOnly => {
                    // For data-only, include INSERT, COPY, and COPY data blocks
                    if !stmt_type.is_data() && !is_copy_data {
                        continue;
                    }
                }
                ContentFilter::All => {}
            }

            if let Some(ref filter) = self.config.table_filter {
                if !filter.contains(&table_name) {
                    continue;
                }
            }

            if !tables_seen.contains(&table_name) {
                tables_seen.insert(table_name.clone());
                stats.tables_found += 1;
                stats.table_names.push(table_name.clone());
            }

            if let Some(w) = writers.as_mut() {
                // For MSSQL, add a semicolon when the statement doesn't already
                // end with one (GO is the batch separator, but we need `;` for
                // re-parsing). Other dialects add no suffix.
                let suffix: &[u8] = if self.config.dialect == SqlDialect::Mssql {
                    let last = stmt
                        .iter()
                        .rev()
                        .find(|&&b| b != b'\n' && b != b'\r' && b != b' ' && b != b'\t');
                    if last != Some(&b';') {
                        b";"
                    } else {
                        b""
                    }
                } else {
                    b""
                };
                w.write(&table_name, &stmt, suffix);

                // A writer thread hit an I/O error; stop parsing and surface it.
                if w.errored() {
                    break;
                }
            }

            stats.statements_processed += 1;
            stats.bytes_processed += stmt.len() as u64;

            // Adaptive-I/O epoch boundary: byte-based (see epoch module
            // docs), so the controller's decisions are a pure function of
            // measured data, not wall-clock scheduling. `writers` is always
            // `Some` when the driver is `Some` (adaptive requires
            // `!dry_run`, see above).
            if let (Some(driver), Some(w)) = (epoch_driver.as_mut(), writers.as_mut()) {
                driver.on_bytes(w, &mut stats);
            }
        }

        if let Some(w) = writers {
            w.finish()
                .with_context(|| format!("Failed writing output to {:?}", self.output_dir))?;
        }

        Ok(stats)
    }
}

#[cfg(all(test, feature = "compression"))]
mod multi_member_tests {
    use super::Compression;
    use std::io::{Read, Write};

    fn gzip(data: &[u8]) -> Vec<u8> {
        let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        e.write_all(data).unwrap();
        e.finish().unwrap()
    }

    fn bzip2(data: &[u8]) -> Vec<u8> {
        let mut e = bzip2::write::BzEncoder::new(Vec::new(), bzip2::Compression::default());
        e.write_all(data).unwrap();
        e.finish().unwrap()
    }

    fn xz(data: &[u8]) -> Vec<u8> {
        let mut e = xz2::write::XzEncoder::new(Vec::new(), 6);
        e.write_all(data).unwrap();
        e.finish().unwrap()
    }

    fn decoded(compression: Compression, bytes: Vec<u8>) -> Vec<u8> {
        let reader: Box<dyn Read> = Box::new(std::io::Cursor::new(bytes));
        let mut out = Vec::new();
        compression
            .wrap_reader(reader)
            .unwrap()
            .read_to_end(&mut out)
            .unwrap();
        out
    }

    #[test]
    fn gzip_reads_all_concatenated_members() {
        let mut concat = gzip(b"CREATE TABLE a (id INT);\n");
        concat.extend(gzip(b"CREATE TABLE b (id INT);\n"));
        assert_eq!(
            decoded(Compression::Gzip, concat),
            b"CREATE TABLE a (id INT);\nCREATE TABLE b (id INT);\n",
            "second gzip member was truncated"
        );
    }

    #[test]
    fn bzip2_reads_all_concatenated_streams() {
        let mut concat = bzip2(b"CREATE TABLE a (id INT);\n");
        concat.extend(bzip2(b"CREATE TABLE b (id INT);\n"));
        assert_eq!(
            decoded(Compression::Bzip2, concat),
            b"CREATE TABLE a (id INT);\nCREATE TABLE b (id INT);\n",
            "second bzip2 stream was truncated"
        );
    }

    #[test]
    fn xz_reads_all_concatenated_streams() {
        let mut concat = xz(b"CREATE TABLE a (id INT);\n");
        concat.extend(xz(b"CREATE TABLE b (id INT);\n"));
        assert_eq!(
            decoded(Compression::Xz, concat),
            b"CREATE TABLE a (id INT);\nCREATE TABLE b (id INT);\n",
            "second xz stream was truncated"
        );
    }
}