Skip to main content

sql_splitter/parser/
postgres_copy.rs

1//! PostgreSQL COPY statement parser.
2//!
3//! Parses COPY ... FROM stdin data blocks to extract individual rows
4//! and optionally extract PK/FK column values for dependency tracking.
5
6use crate::schema::{ColumnId, TableSchema};
7use std::borrow::Cow;
8use std::sync::Arc;
9
10// Re-use types from mysql_insert for consistency
11use super::mysql_insert::{coerce_text_pk, FkRef, PkValue, RowExtraction};
12use super::RowFlow;
13
14// Re-export (rather than re-declare) the shared PK tuple type.
15pub use super::mysql_insert::PkTuple;
16
17/// A parsed row from a COPY data block
18#[derive(Debug, Clone)]
19pub struct ParsedCopyRow {
20    /// Raw bytes of the row (tab-separated values, no newline)
21    pub raw: Vec<u8>,
22    /// Extracted primary key values (if table has PK and values are non-NULL)
23    pub pk: Option<PkTuple>,
24    /// Extracted foreign key values with their references
25    pub fk_values: Vec<(FkRef, PkTuple)>,
26    /// All column values (for data diff comparison).
27    /// Empty unless parsed with [`RowExtraction::Full`].
28    pub all_values: Vec<PkValue>,
29    /// Mapping from schema column index to value index (for finding specific
30    /// columns). Shared across all rows of a block (computed once).
31    pub column_map: Arc<[Option<usize>]>,
32}
33
34impl ParsedCopyRow {
35    /// Get the value for a specific schema column index
36    pub fn get_column_value(&self, schema_col_index: usize) -> Option<&PkValue> {
37        self.column_map
38            .get(schema_col_index)
39            .and_then(|v| *v)
40            .and_then(|val_idx| self.all_values.get(val_idx))
41    }
42}
43
44/// Parser for PostgreSQL COPY data blocks
45pub struct CopyParser<'a> {
46    data: &'a [u8],
47    table_schema: Option<&'a TableSchema>,
48    /// Column names from the COPY header, resolved against the schema lazily
49    /// in `parse_rows` (so builder order doesn't matter).
50    column_names: Vec<String>,
51    /// Resolved column order (value index -> column ID)
52    column_order: Vec<Option<ColumnId>>,
53    /// Reverse of `column_order` (schema column ordinal -> value index),
54    /// computed once per block and shared with every row via `Arc`.
55    col_to_value: Arc<[Option<usize>]>,
56    /// How much derived data to compute per row.
57    extraction: RowExtraction,
58}
59
60impl<'a> CopyParser<'a> {
61    /// Create a new parser for COPY data
62    pub fn new(data: &'a [u8]) -> Self {
63        Self {
64            data,
65            table_schema: None,
66            column_names: Vec::new(),
67            column_order: Vec::new(),
68            col_to_value: Arc::from(Vec::new()),
69            extraction: RowExtraction::Full,
70        }
71    }
72
73    /// Set the table schema for PK/FK extraction
74    pub fn with_schema(mut self, schema: &'a TableSchema) -> Self {
75        self.table_schema = Some(schema);
76        self
77    }
78
79    /// Choose how much per-row derived data to compute (default: [`RowExtraction::Full`]).
80    pub fn with_extraction(mut self, extraction: RowExtraction) -> Self {
81        self.extraction = extraction;
82        self
83    }
84
85    /// Set column order from the COPY header. Resolution against the schema is
86    /// deferred to `parse_rows`, so this may be called before `with_schema`.
87    pub fn with_column_order(mut self, columns: Vec<String>) -> Self {
88        self.column_names = columns;
89        self
90    }
91
92    /// Resolve the column order / reverse map from the schema and header, and
93    /// return whether an empty line is a legitimate one-column row. Shared by
94    /// the collecting and streaming paths (and the single-line helper).
95    fn prepare(&mut self) -> bool {
96        if let Some(schema) = self.table_schema {
97            self.column_order = if self.column_names.is_empty() {
98                // No explicit column list - use natural schema order
99                schema.columns.iter().map(|c| Some(c.ordinal)).collect()
100            } else {
101                self.column_names
102                    .iter()
103                    .map(|name| schema.get_column_id(name))
104                    .collect()
105            };
106
107            // Precompute the reverse column map once for the whole block.
108            self.col_to_value =
109                super::mysql_insert::build_col_to_value(&self.column_order, schema.columns.len());
110        }
111
112        // An empty line is a legitimate single empty-string value only for a
113        // one-column table; for anything else it's padding and is skipped.
114        self.table_schema
115            .map(|s| s.columns.len() == 1)
116            .unwrap_or(false)
117    }
118
119    /// Parse all rows from the COPY data block, collecting them into a `Vec`.
120    ///
121    /// A thin collecting adapter over [`CopyParser::parse_rows_visit`].
122    pub fn parse_rows(&mut self) -> anyhow::Result<Vec<ParsedCopyRow>> {
123        let mut rows = Vec::new();
124        self.parse_rows_visit(|row| {
125            rows.push(row);
126            Ok(RowFlow::Continue)
127        })?;
128        Ok(rows)
129    }
130
131    /// Stream each parsed COPY row to `f` without collecting a block-sized
132    /// `Vec`. `f` returns a [`RowFlow`] to stop early.
133    pub fn parse_rows_visit<F>(&mut self, mut f: F) -> anyhow::Result<()>
134    where
135        F: FnMut(ParsedCopyRow) -> anyhow::Result<RowFlow>,
136    {
137        let empty_line_is_row = self.prepare();
138
139        let mut pos = 0;
140        while pos < self.data.len() {
141            // Find end of line
142            let line_end = memchr::memchr(b'\n', &self.data[pos..])
143                .map(|p| pos + p)
144                .unwrap_or(self.data.len());
145
146            let mut line = &self.data[pos..line_end];
147            // Strip a trailing CR so CRLF-terminated dumps don't leave \r in the
148            // last value of every row (and so the \. terminator still matches).
149            if line.last() == Some(&b'\r') {
150                line = &line[..line.len() - 1];
151            }
152
153            // Check for terminator / skippable blank line
154            if line == b"\\." || (line.is_empty() && !empty_line_is_row) {
155                pos = line_end + 1;
156                continue;
157            }
158
159            match f(self.parse_row(line))? {
160                RowFlow::Continue => {}
161                RowFlow::SkipStatement | RowFlow::Stop => break,
162            }
163
164            pos = line_end + 1;
165        }
166
167        Ok(())
168    }
169
170    /// Finish column-context setup and report whether an empty line counts as a
171    /// row, for the [`Parser::visit_events`] single-line streaming path.
172    ///
173    /// [`Parser::visit_events`]: crate::parser::Parser::visit_events
174    pub fn prepared(mut self) -> (Self, bool) {
175        let empty_line_is_row = self.prepare();
176        (self, empty_line_is_row)
177    }
178
179    /// Parse a single raw COPY data line (as delivered by
180    /// [`crate::parser::ParserEvent::CopyRow`]). Strips a trailing `\r`, and
181    /// returns `None` for a skippable blank line or the `\.` terminator, exactly
182    /// matching [`CopyParser::parse_rows_visit`]. Requires [`CopyParser::prepared`]
183    /// to have been called first.
184    pub fn parse_line(&self, line: &[u8], empty_line_is_row: bool) -> Option<ParsedCopyRow> {
185        let line = if line.last() == Some(&b'\r') {
186            &line[..line.len() - 1]
187        } else {
188            line
189        };
190        if line == b"\\." || (line.is_empty() && !empty_line_is_row) {
191            return None;
192        }
193        Some(self.parse_row(line))
194    }
195
196    /// Parse a single tab-separated row (infallible: any line is a valid row)
197    fn parse_row(&self, line: &[u8]) -> ParsedCopyRow {
198        let raw = line.to_vec();
199
200        // Split, parse and extract PK/FK only when the caller wants them;
201        // ValuesOnly consumers (e.g. redact) just need `raw`.
202        let (pk, fk_values, all_values) = match (self.table_schema, self.extraction) {
203            (Some(schema), RowExtraction::PkFk | RowExtraction::Full) => {
204                let values: Vec<CopyValue> = self.split_and_parse_values(line);
205                self.extract_pk_fk(&values, schema)
206            }
207            _ => (None, Vec::new(), Vec::new()),
208        };
209
210        ParsedCopyRow {
211            raw,
212            pk,
213            fk_values,
214            all_values,
215            column_map: Arc::clone(&self.col_to_value),
216        }
217    }
218
219    /// Split line by tabs and parse each value
220    fn split_and_parse_values<'b>(&self, line: &'b [u8]) -> Vec<CopyValue<'b>> {
221        let mut values = Vec::new();
222        let mut start = 0;
223
224        for (i, &b) in line.iter().enumerate() {
225            if b == b'\t' {
226                values.push(self.parse_copy_value(&line[start..i]));
227                start = i + 1;
228            }
229        }
230        // Last value
231        if start <= line.len() {
232            values.push(self.parse_copy_value(&line[start..]));
233        }
234
235        values
236    }
237
238    /// Parse a single COPY value
239    fn parse_copy_value<'b>(&self, value: &'b [u8]) -> CopyValue<'b> {
240        // Check for NULL marker
241        if value == b"\\N" {
242            return CopyValue::Null;
243        }
244
245        // Decode escape sequences; values without a backslash (the common
246        // case) are borrowed as-is instead of copied.
247        let decoded: Cow<'b, [u8]> = if memchr::memchr(b'\\', value).is_none() {
248            Cow::Borrowed(value)
249        } else {
250            Cow::Owned(decode_copy_escapes(value))
251        };
252
253        // Try to parse as integer, but only when the text is the *canonical*
254        // representation of that integer. Otherwise "0123" or "+5" would be
255        // treated as numbers and compare equal to their numeric forms in diff,
256        // silently conflating distinct text primary keys (bug #12).
257        if let Ok(s) = std::str::from_utf8(&decoded) {
258            if is_canonical_int(s) {
259                if let Ok(n) = s.parse::<i64>() {
260                    return CopyValue::Integer(n);
261                }
262                if let Ok(n) = s.parse::<i128>() {
263                    return CopyValue::BigInteger(n);
264                }
265            }
266        }
267
268        CopyValue::Text(decoded)
269    }
270
271    /// Decode PostgreSQL COPY escape sequences.
272    ///
273    /// Thin wrapper kept for API compatibility; the implementation lives in
274    /// the free function [`decode_copy_escapes`].
275    pub fn decode_copy_escapes(&self, value: &[u8]) -> Vec<u8> {
276        decode_copy_escapes(value)
277    }
278
279    /// Extract PK, FK, and all values from parsed values
280    fn extract_pk_fk(
281        &self,
282        values: &[CopyValue<'_>],
283        schema: &TableSchema,
284    ) -> (Option<PkTuple>, Vec<(FkRef, PkTuple)>, Vec<PkValue>) {
285        super::mysql_insert::extract_pk_fk_generic(
286            values,
287            schema,
288            &self.column_order,
289            &self.col_to_value,
290            self.extraction == RowExtraction::Full,
291            |v, col| self.value_to_pk(v, col),
292        )
293    }
294
295    /// Convert a parsed value to a PkValue
296    fn value_to_pk(&self, value: &CopyValue<'_>, col: Option<&crate::schema::Column>) -> PkValue {
297        match value {
298            CopyValue::Null => PkValue::Null,
299            CopyValue::Integer(n) => PkValue::Int(*n),
300            CopyValue::BigInteger(n) => PkValue::BigInt(*n),
301            CopyValue::Text(bytes) => {
302                let s = String::from_utf8_lossy(bytes);
303
304                // Check if this might be an integer stored as text
305                coerce_text_pk(&s, col)
306                    .unwrap_or_else(|| PkValue::Text(s.into_owned().into_boxed_str()))
307            }
308        }
309    }
310}
311
312/// Internal representation of a parsed COPY value. Text borrows from the line
313/// unless escape decoding forced a copy.
314#[derive(Debug, Clone)]
315enum CopyValue<'a> {
316    Null,
317    Integer(i64),
318    BigInteger(i128),
319    Text(Cow<'a, [u8]>),
320}
321
322/// Decode PostgreSQL COPY escape sequences (`\t`, `\n`, `\r`, `\\`; a `\N`
323/// or unknown escape passes through verbatim).
324///
325/// This is the canonical decoder for the COPY text wire format — consumers
326/// elsewhere in the crate (e.g. the redactor's `ValueRewriter` in
327/// `src/redactor/rewriter.rs`) should call this instead of keeping their own
328/// copy, so escape-handling fixes land in exactly one place.
329pub fn decode_copy_escapes(value: &[u8]) -> Vec<u8> {
330    let mut result = Vec::with_capacity(value.len());
331    let mut i = 0;
332
333    while i < value.len() {
334        if value[i] == b'\\' && i + 1 < value.len() {
335            let next = value[i + 1];
336            let decoded = match next {
337                b'n' => b'\n',
338                b'r' => b'\r',
339                b't' => b'\t',
340                b'\\' => b'\\',
341                b'N' => {
342                    // \N is the NULL marker, not an escape; callers filter it
343                    // out before decoding, so keep it verbatim here.
344                    result.push(b'\\');
345                    result.push(b'N');
346                    i += 2;
347                    continue;
348                }
349                _ => {
350                    // Unknown escape, keep as-is
351                    result.push(b'\\');
352                    result.push(next);
353                    i += 2;
354                    continue;
355                }
356            };
357            result.push(decoded);
358            i += 2;
359        } else {
360            result.push(value[i]);
361            i += 1;
362        }
363    }
364
365    result
366}
367
368/// True when `s` is the canonical decimal rendering of an integer — digits
369/// only, no `+`, no leading zeros, no `-0`. Combined with a successful parse
370/// this is equivalent to `n.to_string() == s` without the allocation (bug #12).
371fn is_canonical_int(s: &str) -> bool {
372    let b = s.as_bytes();
373    let (neg, digits) = match b.split_first() {
374        Some((b'+', _)) => return false,
375        Some((b'-', rest)) => (true, rest),
376        _ => (false, b),
377    };
378    match digits {
379        [] => false,
380        [b'0'] => !neg,
381        [b'0', ..] => false,
382        _ => digits.iter().all(u8::is_ascii_digit),
383    }
384}
385
386/// Parse column list from COPY header
387pub fn parse_copy_columns(header: &str) -> Vec<String> {
388    // COPY table_name (col1, col2, ...) FROM stdin;
389    if let Some(start) = header.find('(') {
390        if let Some(end) = header.find(')') {
391            let cols = &header[start + 1..end];
392            return cols
393                .split(',')
394                .map(|c| c.trim().trim_matches('"').to_string())
395                .collect();
396        }
397    }
398    Vec::new()
399}
400
401/// Parse all rows from a PostgreSQL COPY data block
402pub fn parse_postgres_copy_rows(
403    data: &[u8],
404    schema: &TableSchema,
405    column_order: Vec<String>,
406) -> anyhow::Result<Vec<ParsedCopyRow>> {
407    parse_postgres_copy_rows_with(data, schema, column_order, RowExtraction::Full)
408}
409
410/// Like [`parse_postgres_copy_rows`], but with an explicit [`RowExtraction`]
411/// level so consumers that don't need `all_values` skip that work.
412pub fn parse_postgres_copy_rows_with(
413    data: &[u8],
414    schema: &TableSchema,
415    column_order: Vec<String>,
416    extraction: RowExtraction,
417) -> anyhow::Result<Vec<ParsedCopyRow>> {
418    let mut rows = Vec::new();
419    visit_postgres_copy_rows_with(data, schema, column_order, extraction, |row| {
420        rows.push(row);
421        Ok(RowFlow::Continue)
422    })?;
423    Ok(rows)
424}
425
426/// Stream the rows of a COPY data block to a visitor, one at a time, without
427/// building a block-sized `Vec`. `f` returns a [`RowFlow`] to stop early.
428pub fn visit_postgres_copy_rows_with<F>(
429    data: &[u8],
430    schema: &TableSchema,
431    column_order: Vec<String>,
432    extraction: RowExtraction,
433    f: F,
434) -> anyhow::Result<()>
435where
436    F: FnMut(ParsedCopyRow) -> anyhow::Result<RowFlow>,
437{
438    let mut parser = CopyParser::new(data)
439        .with_schema(schema)
440        .with_column_order(column_order)
441        .with_extraction(extraction);
442    parser.parse_rows_visit(f)
443}