Skip to main content

sql_splitter/convert/
copy_to_insert.rs

1//! Convert PostgreSQL COPY FROM stdin statements to INSERT statements.
2//!
3//! Handles:
4//! - Tab-separated value parsing
5//! - NULL handling (\N → NULL)
6//! - Escape sequence conversion (\t, \n, \\)
7//! - Batched INSERT generation for efficiency
8
9use once_cell::sync::Lazy;
10use regex::Regex;
11
12use crate::parser::SqlDialect;
13use crate::transform_common::quote_identifier;
14
15/// Maximum rows per INSERT statement (for readability and transaction size).
16///
17/// The DuckDB loader uses the same limit for its fast COPY path, then retries
18/// a failed chunk one row at a time so one malformed value does not discard
19/// unrelated rows from a dump.
20pub(crate) const MAX_ROWS_PER_INSERT: usize = 1000;
21
22/// Result of parsing a COPY header
23#[derive(Debug, Clone)]
24pub struct CopyHeader {
25    /// Schema name (e.g., "public")
26    pub schema: Option<String>,
27    /// Table name
28    pub table: String,
29    /// Column list (may be empty if not specified)
30    pub columns: Vec<String>,
31}
32
33/// Parse a COPY header to extract table and columns
34/// Input: "COPY schema.table (col1, col2) FROM stdin;"
35pub fn parse_copy_header(stmt: &str) -> Option<CopyHeader> {
36    // Strip comments from the beginning
37    let stmt = strip_leading_comments(stmt);
38
39    static RE_COPY: Lazy<Regex> = Lazy::new(|| {
40        // Pattern: COPY [ONLY] [schema.]table [(columns)] FROM stdin
41        // Schema and table can be quoted with double quotes
42        Regex::new(
43            r#"(?i)^\s*COPY\s+(?:ONLY\s+)?(?:"?(\w+)"?\.)?["]?(\w+)["]?\s*(?:\(([^)]+)\))?\s+FROM\s+stdin"#
44        ).unwrap()
45    });
46
47    let caps = RE_COPY.captures(&stmt)?;
48
49    let schema = caps.get(1).map(|m| m.as_str().to_string());
50    let table = caps.get(2)?.as_str().to_string();
51    let columns = caps
52        .get(3)
53        .map(|m| {
54            m.as_str()
55                .split(',')
56                .map(|c| c.trim().trim_matches('"').trim_matches('`').to_string())
57                .collect()
58        })
59        .unwrap_or_default();
60
61    Some(CopyHeader {
62        schema,
63        table,
64        columns,
65    })
66}
67
68/// Strip leading SQL comments from a string
69fn strip_leading_comments(stmt: &str) -> String {
70    let mut result = stmt.trim();
71    loop {
72        if result.starts_with("--") {
73            if let Some(pos) = result.find('\n') {
74                result = result[pos + 1..].trim();
75                continue;
76            } else {
77                return String::new();
78            }
79        }
80        if result.starts_with("/*") {
81            if let Some(pos) = result.find("*/") {
82                result = result[pos + 2..].trim();
83                continue;
84            } else {
85                return String::new();
86            }
87        }
88        break;
89    }
90    result.to_string()
91}
92
93/// Convert a COPY data block to INSERT statements
94///
95/// # Arguments
96/// * `header` - Parsed COPY header with table/column info
97/// * `data` - The data block (tab-separated rows ending with \.)
98/// * `target_dialect` - Target SQL dialect for quoting
99///
100/// # Returns
101/// Vector of INSERT statements as bytes
102pub fn copy_to_inserts(
103    header: &CopyHeader,
104    data: &[u8],
105    target_dialect: SqlDialect,
106) -> Vec<Vec<u8>> {
107    let rows = parse_copy_data(data);
108
109    if rows.is_empty() {
110        return Vec::new();
111    }
112
113    rows.chunks(MAX_ROWS_PER_INSERT)
114        .map(|chunk| copy_rows_to_insert(header, chunk, target_dialect))
115        .collect()
116}
117
118/// Convert one non-empty sequence of parsed COPY rows to a single INSERT.
119///
120/// This is crate-visible so the DuckDB loader can retry a rejected multi-row
121/// insert one row at a time without reparsing or changing SQL escaping.
122pub(crate) fn copy_rows_to_insert(
123    header: &CopyHeader,
124    rows: &[Vec<CopyValue>],
125    target_dialect: SqlDialect,
126) -> Vec<u8> {
127    debug_assert!(!rows.is_empty());
128
129    let table_ref = if let Some(ref schema) = header.schema {
130        if target_dialect == SqlDialect::MySql {
131            // MySQL: just use table name without schema
132            quote_identifier(target_dialect, &header.table)
133        } else if schema == "public" || schema == "pg_catalog" {
134            // Common PostgreSQL schemas - strip for DuckDB compatibility
135            quote_identifier(target_dialect, &header.table)
136        } else {
137            format!(
138                "{}.{}",
139                quote_identifier(target_dialect, schema),
140                quote_identifier(target_dialect, &header.table)
141            )
142        }
143    } else {
144        quote_identifier(target_dialect, &header.table)
145    };
146
147    let columns_str = if header.columns.is_empty() {
148        String::new()
149    } else {
150        let cols: Vec<String> = header
151            .columns
152            .iter()
153            .map(|column| quote_identifier(target_dialect, column))
154            .collect();
155        format!(" ({})", cols.join(", "))
156    };
157
158    let mut insert = format!("INSERT INTO {}{} VALUES\n", table_ref, columns_str);
159
160    for (i, row) in rows.iter().enumerate() {
161        if i > 0 {
162            insert.push_str(",\n");
163        }
164        insert.push('(');
165
166        for (j, value) in row.iter().enumerate() {
167            if j > 0 {
168                insert.push_str(", ");
169            }
170            insert.push_str(&format_value(value, target_dialect));
171        }
172
173        insert.push(')');
174    }
175
176    insert.push(';');
177    insert.into_bytes()
178}
179
180/// A parsed value from COPY data
181#[derive(Debug, Clone)]
182pub enum CopyValue {
183    Null,
184    Text(String),
185}
186
187/// Parse COPY data block into rows of values
188pub fn parse_copy_data(data: &[u8]) -> Vec<Vec<CopyValue>> {
189    let mut rows = Vec::new();
190    let mut pos = 0;
191
192    while pos < data.len() {
193        // Find end of line
194        let line_end = data[pos..]
195            .iter()
196            .position(|&b| b == b'\n')
197            .map(|p| pos + p)
198            .unwrap_or(data.len());
199
200        let mut line = &data[pos..line_end];
201        // Strip a trailing CR so CRLF-terminated dumps don't produce a phantom
202        // `\.\r` terminator, phantom `\r` empty rows, or a `\r` retained in the
203        // last column (mirrors CopyParser in parser/postgres_copy.rs).
204        if line.last() == Some(&b'\r') {
205            line = &line[..line.len() - 1];
206        }
207
208        // Check for terminator
209        if line == b"\\." || line.is_empty() {
210            pos = line_end + 1;
211            continue;
212        }
213
214        // Parse the row
215        let row = parse_row(line);
216        if !row.is_empty() {
217            rows.push(row);
218        }
219
220        pos = line_end + 1;
221    }
222
223    rows
224}
225
226/// Parse a single tab-separated row
227fn parse_row(line: &[u8]) -> Vec<CopyValue> {
228    let mut values = Vec::new();
229    let mut start = 0;
230
231    for (i, &b) in line.iter().enumerate() {
232        if b == b'\t' {
233            values.push(parse_value(&line[start..i]));
234            start = i + 1;
235        }
236    }
237    // Last value
238    if start <= line.len() {
239        values.push(parse_value(&line[start..]));
240    }
241
242    values
243}
244
245/// Parse a single COPY value
246fn parse_value(value: &[u8]) -> CopyValue {
247    // Check for NULL marker
248    if value == b"\\N" {
249        return CopyValue::Null;
250    }
251
252    // Decode escape sequences
253    let decoded = decode_escapes(value);
254    CopyValue::Text(decoded)
255}
256
257/// Decode PostgreSQL COPY escape sequences
258fn decode_escapes(value: &[u8]) -> String {
259    let mut result = String::with_capacity(value.len());
260    let mut i = 0;
261
262    while i < value.len() {
263        if value[i] == b'\\' && i + 1 < value.len() {
264            let next = value[i + 1];
265            let decoded = match next {
266                b'n' => '\n',
267                b'r' => '\r',
268                b't' => '\t',
269                b'\\' => '\\',
270                b'b' => '\x08', // backspace
271                b'f' => '\x0C', // form feed
272                b'v' => '\x0B', // vertical tab
273                _ => {
274                    // Unknown escape or octal, try octal
275                    if next.is_ascii_digit() {
276                        // Try to parse octal (up to 3 digits)
277                        let mut octal_val = 0u8;
278                        let mut consumed = 0;
279                        for j in 0..3 {
280                            if i + 1 + j < value.len() {
281                                let d = value[i + 1 + j];
282                                if (b'0'..=b'7').contains(&d) {
283                                    octal_val = octal_val * 8 + (d - b'0');
284                                    consumed += 1;
285                                } else {
286                                    break;
287                                }
288                            }
289                        }
290                        if consumed > 0 {
291                            result.push(octal_val as char);
292                            i += 1 + consumed;
293                            continue;
294                        }
295                    }
296                    // Unknown escape, keep as-is
297                    result.push('\\');
298                    result.push(next as char);
299                    i += 2;
300                    continue;
301                }
302            };
303            result.push(decoded);
304            i += 2;
305        } else {
306            // Regular character - handle UTF-8 properly
307            if value[i] < 128 {
308                result.push(value[i] as char);
309                i += 1;
310            } else {
311                // Multi-byte UTF-8 sequence
312                let remaining = &value[i..];
313                if let Ok(s) = std::str::from_utf8(remaining) {
314                    if let Some(c) = s.chars().next() {
315                        result.push(c);
316                        i += c.len_utf8();
317                    } else {
318                        i += 1;
319                    }
320                } else {
321                    // Invalid UTF-8, just push the byte as replacement char
322                    result.push('\u{FFFD}');
323                    i += 1;
324                }
325            }
326        }
327    }
328
329    result
330}
331
332/// Format a value for SQL INSERT
333fn format_value(value: &CopyValue, dialect: crate::parser::SqlDialect) -> String {
334    match value {
335        CopyValue::Null => "NULL".to_string(),
336        CopyValue::Text(s) => {
337            // Escape quotes based on dialect
338            let escaped = match dialect {
339                crate::parser::SqlDialect::MySql => {
340                    // MySQL: escape with backslash
341                    s.replace('\\', "\\\\")
342                        .replace('\'', "\\'")
343                        .replace('\n', "\\n")
344                        .replace('\r', "\\r")
345                        .replace('\t', "\\t")
346                        .replace('\0', "\\0")
347                }
348                _ => {
349                    // PostgreSQL/SQLite: escape by doubling
350                    s.replace('\'', "''")
351                }
352            };
353            format!("'{}'", escaped)
354        }
355    }
356}