sql_splitter/convert/
copy_to_insert.rs1use once_cell::sync::Lazy;
10use regex::Regex;
11
12use crate::parser::SqlDialect;
13use crate::transform_common::quote_identifier;
14
15pub(crate) const MAX_ROWS_PER_INSERT: usize = 1000;
21
22#[derive(Debug, Clone)]
24pub struct CopyHeader {
25 pub schema: Option<String>,
27 pub table: String,
29 pub columns: Vec<String>,
31}
32
33pub fn parse_copy_header(stmt: &str) -> Option<CopyHeader> {
36 let stmt = strip_leading_comments(stmt);
38
39 static RE_COPY: Lazy<Regex> = Lazy::new(|| {
40 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
68fn 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
93pub 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
118pub(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 quote_identifier(target_dialect, &header.table)
133 } else if schema == "public" || schema == "pg_catalog" {
134 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#[derive(Debug, Clone)]
182pub enum CopyValue {
183 Null,
184 Text(String),
185}
186
187pub 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 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 if line.last() == Some(&b'\r') {
205 line = &line[..line.len() - 1];
206 }
207
208 if line == b"\\." || line.is_empty() {
210 pos = line_end + 1;
211 continue;
212 }
213
214 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
226fn 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 if start <= line.len() {
239 values.push(parse_value(&line[start..]));
240 }
241
242 values
243}
244
245fn parse_value(value: &[u8]) -> CopyValue {
247 if value == b"\\N" {
249 return CopyValue::Null;
250 }
251
252 let decoded = decode_escapes(value);
254 CopyValue::Text(decoded)
255}
256
257fn 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', b'f' => '\x0C', b'v' => '\x0B', _ => {
274 if next.is_ascii_digit() {
276 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 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 if value[i] < 128 {
308 result.push(value[i] as char);
309 i += 1;
310 } else {
311 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 result.push('\u{FFFD}');
323 i += 1;
324 }
325 }
326 }
327 }
328
329 result
330}
331
332fn format_value(value: &CopyValue, dialect: crate::parser::SqlDialect) -> String {
334 match value {
335 CopyValue::Null => "NULL".to_string(),
336 CopyValue::Text(s) => {
337 let escaped = match dialect {
339 crate::parser::SqlDialect::MySql => {
340 s.replace('\\', "\\\\")
342 .replace('\'', "\\'")
343 .replace('\n', "\\n")
344 .replace('\r', "\\r")
345 .replace('\t', "\\t")
346 .replace('\0', "\\0")
347 }
348 _ => {
349 s.replace('\'', "''")
351 }
352 };
353 format!("'{}'", escaped)
354 }
355 }
356}