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, ColumnType, TableSchema};
7use smallvec::SmallVec;
8use std::borrow::Cow;
9use std::sync::Arc;
10
11// Re-use types from mysql_insert for consistency
12use super::mysql_insert::{FkRef, PkValue, RowExtraction};
13
14/// Tuple of PK values for composite primary keys
15pub type PkTuple = SmallVec<[PkValue; 2]>;
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    /// Parse all rows from the COPY data block
93    pub fn parse_rows(&mut self) -> anyhow::Result<Vec<ParsedCopyRow>> {
94        if let Some(schema) = self.table_schema {
95            self.column_order = if self.column_names.is_empty() {
96                // No explicit column list - use natural schema order
97                schema.columns.iter().map(|c| Some(c.ordinal)).collect()
98            } else {
99                self.column_names
100                    .iter()
101                    .map(|name| schema.get_column_id(name))
102                    .collect()
103            };
104
105            // Precompute the reverse column map once for the whole block;
106            // rows share it via Arc instead of cloning it per row.
107            let mut map = vec![None; schema.columns.len()];
108            for (val_idx, col_id_opt) in self.column_order.iter().enumerate() {
109                if let Some(col_id) = col_id_opt {
110                    let ord = col_id.0 as usize;
111                    if ord < map.len() {
112                        map[ord] = Some(val_idx);
113                    }
114                }
115            }
116            self.col_to_value = map.into();
117        }
118
119        // An empty line is a legitimate single empty-string value only for a
120        // one-column table; for anything else it's padding and is skipped.
121        let empty_line_is_row = self
122            .table_schema
123            .map(|s| s.columns.len() == 1)
124            .unwrap_or(false);
125
126        let mut rows = Vec::new();
127        let mut pos = 0;
128
129        while pos < self.data.len() {
130            // Find end of line
131            let line_end = memchr::memchr(b'\n', &self.data[pos..])
132                .map(|p| pos + p)
133                .unwrap_or(self.data.len());
134
135            let mut line = &self.data[pos..line_end];
136            // Strip a trailing CR so CRLF-terminated dumps don't leave \r in the
137            // last value of every row (and so the \. terminator still matches).
138            if line.last() == Some(&b'\r') {
139                line = &line[..line.len() - 1];
140            }
141
142            // Check for terminator / skippable blank line
143            if line == b"\\." || (line.is_empty() && !empty_line_is_row) {
144                pos = line_end + 1;
145                continue;
146            }
147
148            // Parse the row
149            if let Some(row) = self.parse_row(line)? {
150                rows.push(row);
151            }
152
153            pos = line_end + 1;
154        }
155
156        Ok(rows)
157    }
158
159    /// Parse a single tab-separated row
160    fn parse_row(&self, line: &[u8]) -> anyhow::Result<Option<ParsedCopyRow>> {
161        let raw = line.to_vec();
162
163        // Split, parse and extract PK/FK only when the caller wants them;
164        // ValuesOnly consumers (e.g. redact) just need `raw`.
165        let (pk, fk_values, all_values) = match (self.table_schema, self.extraction) {
166            (Some(schema), RowExtraction::PkFk | RowExtraction::Full) => {
167                let values: Vec<CopyValue> = self.split_and_parse_values(line);
168                self.extract_pk_fk(&values, schema)
169            }
170            _ => (None, Vec::new(), Vec::new()),
171        };
172
173        Ok(Some(ParsedCopyRow {
174            raw,
175            pk,
176            fk_values,
177            all_values,
178            column_map: Arc::clone(&self.col_to_value),
179        }))
180    }
181
182    /// Split line by tabs and parse each value
183    fn split_and_parse_values<'b>(&self, line: &'b [u8]) -> Vec<CopyValue<'b>> {
184        let mut values = Vec::new();
185        let mut start = 0;
186
187        for (i, &b) in line.iter().enumerate() {
188            if b == b'\t' {
189                values.push(self.parse_copy_value(&line[start..i]));
190                start = i + 1;
191            }
192        }
193        // Last value
194        if start <= line.len() {
195            values.push(self.parse_copy_value(&line[start..]));
196        }
197
198        values
199    }
200
201    /// Parse a single COPY value
202    fn parse_copy_value<'b>(&self, value: &'b [u8]) -> CopyValue<'b> {
203        // Check for NULL marker
204        if value == b"\\N" {
205            return CopyValue::Null;
206        }
207
208        // Decode escape sequences; values without a backslash (the common
209        // case) are borrowed as-is instead of copied.
210        let decoded: Cow<'b, [u8]> = if memchr::memchr(b'\\', value).is_none() {
211            Cow::Borrowed(value)
212        } else {
213            Cow::Owned(self.decode_copy_escapes(value))
214        };
215
216        // Try to parse as integer, but only when the text is the *canonical*
217        // representation of that integer. Otherwise "0123" or "+5" would be
218        // treated as numbers and compare equal to their numeric forms in diff,
219        // silently conflating distinct text primary keys (bug #12).
220        if let Ok(s) = std::str::from_utf8(&decoded) {
221            if is_canonical_int(s) {
222                if let Ok(n) = s.parse::<i64>() {
223                    return CopyValue::Integer(n);
224                }
225                if let Ok(n) = s.parse::<i128>() {
226                    return CopyValue::BigInteger(n);
227                }
228            }
229        }
230
231        CopyValue::Text(decoded)
232    }
233
234    /// Decode PostgreSQL COPY escape sequences
235    pub fn decode_copy_escapes(&self, value: &[u8]) -> Vec<u8> {
236        let mut result = Vec::with_capacity(value.len());
237        let mut i = 0;
238
239        while i < value.len() {
240            if value[i] == b'\\' && i + 1 < value.len() {
241                let next = value[i + 1];
242                let decoded = match next {
243                    b'n' => b'\n',
244                    b'r' => b'\r',
245                    b't' => b'\t',
246                    b'\\' => b'\\',
247                    b'N' => {
248                        // This shouldn't happen here since we check for \N above
249                        result.push(b'\\');
250                        result.push(b'N');
251                        i += 2;
252                        continue;
253                    }
254                    _ => {
255                        // Unknown escape, keep as-is
256                        result.push(b'\\');
257                        result.push(next);
258                        i += 2;
259                        continue;
260                    }
261                };
262                result.push(decoded);
263                i += 2;
264            } else {
265                result.push(value[i]);
266                i += 1;
267            }
268        }
269
270        result
271    }
272
273    /// Extract PK, FK, and all values from parsed values
274    fn extract_pk_fk(
275        &self,
276        values: &[CopyValue<'_>],
277        schema: &TableSchema,
278    ) -> (Option<PkTuple>, Vec<(FkRef, PkTuple)>, Vec<PkValue>) {
279        super::mysql_insert::extract_pk_fk_generic(
280            values,
281            schema,
282            &self.column_order,
283            &self.col_to_value,
284            self.extraction == RowExtraction::Full,
285            |v, col| self.value_to_pk(v, col),
286        )
287    }
288
289    /// Convert a parsed value to a PkValue
290    fn value_to_pk(&self, value: &CopyValue<'_>, col: Option<&crate::schema::Column>) -> PkValue {
291        match value {
292            CopyValue::Null => PkValue::Null,
293            CopyValue::Integer(n) => PkValue::Int(*n),
294            CopyValue::BigInteger(n) => PkValue::BigInt(*n),
295            CopyValue::Text(bytes) => {
296                let s = String::from_utf8_lossy(bytes);
297
298                // Check if this might be an integer stored as text
299                if let Some(col) = col {
300                    match col.col_type {
301                        ColumnType::Int => {
302                            if let Ok(n) = s.parse::<i64>() {
303                                return PkValue::Int(n);
304                            }
305                        }
306                        ColumnType::BigInt => {
307                            if let Ok(n) = s.parse::<i128>() {
308                                return PkValue::BigInt(n);
309                            }
310                        }
311                        _ => {}
312                    }
313                }
314
315                PkValue::Text(s.into_owned().into_boxed_str())
316            }
317        }
318    }
319}
320
321/// Internal representation of a parsed COPY value. Text borrows from the line
322/// unless escape decoding forced a copy.
323#[derive(Debug, Clone)]
324enum CopyValue<'a> {
325    Null,
326    Integer(i64),
327    BigInteger(i128),
328    Text(Cow<'a, [u8]>),
329}
330
331/// True when `s` is the canonical decimal rendering of an integer — digits
332/// only, no `+`, no leading zeros, no `-0`. Combined with a successful parse
333/// this is equivalent to `n.to_string() == s` without the allocation (bug #12).
334fn is_canonical_int(s: &str) -> bool {
335    let b = s.as_bytes();
336    let (neg, digits) = match b.split_first() {
337        Some((b'+', _)) => return false,
338        Some((b'-', rest)) => (true, rest),
339        _ => (false, b),
340    };
341    match digits {
342        [] => false,
343        [b'0'] => !neg,
344        [b'0', ..] => false,
345        _ => digits.iter().all(u8::is_ascii_digit),
346    }
347}
348
349/// Parse column list from COPY header
350pub fn parse_copy_columns(header: &str) -> Vec<String> {
351    // COPY table_name (col1, col2, ...) FROM stdin;
352    if let Some(start) = header.find('(') {
353        if let Some(end) = header.find(')') {
354            let cols = &header[start + 1..end];
355            return cols
356                .split(',')
357                .map(|c| c.trim().trim_matches('"').to_string())
358                .collect();
359        }
360    }
361    Vec::new()
362}
363
364/// Parse all rows from a PostgreSQL COPY data block
365pub fn parse_postgres_copy_rows(
366    data: &[u8],
367    schema: &TableSchema,
368    column_order: Vec<String>,
369) -> anyhow::Result<Vec<ParsedCopyRow>> {
370    parse_postgres_copy_rows_with(data, schema, column_order, RowExtraction::Full)
371}
372
373/// Like [`parse_postgres_copy_rows`], but with an explicit [`RowExtraction`]
374/// level so consumers that don't need `all_values` skip that work.
375pub fn parse_postgres_copy_rows_with(
376    data: &[u8],
377    schema: &TableSchema,
378    column_order: Vec<String>,
379    extraction: RowExtraction,
380) -> anyhow::Result<Vec<ParsedCopyRow>> {
381    let mut parser = CopyParser::new(data)
382        .with_schema(schema)
383        .with_column_order(column_order)
384        .with_extraction(extraction);
385    parser.parse_rows()
386}