1use crate::schema::{ColumnId, TableSchema};
7use std::borrow::Cow;
8use std::sync::Arc;
9
10use super::mysql_insert::{coerce_text_pk, FkRef, PkValue, RowExtraction};
12use super::RowFlow;
13
14pub use super::mysql_insert::PkTuple;
16
17#[derive(Debug, Clone)]
19pub struct ParsedCopyRow {
20 pub raw: Vec<u8>,
22 pub pk: Option<PkTuple>,
24 pub fk_values: Vec<(FkRef, PkTuple)>,
26 pub all_values: Vec<PkValue>,
29 pub column_map: Arc<[Option<usize>]>,
32}
33
34impl ParsedCopyRow {
35 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
44pub struct CopyParser<'a> {
46 data: &'a [u8],
47 table_schema: Option<&'a TableSchema>,
48 column_names: Vec<String>,
51 column_order: Vec<Option<ColumnId>>,
53 col_to_value: Arc<[Option<usize>]>,
56 extraction: RowExtraction,
58}
59
60impl<'a> CopyParser<'a> {
61 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 pub fn with_schema(mut self, schema: &'a TableSchema) -> Self {
75 self.table_schema = Some(schema);
76 self
77 }
78
79 pub fn with_extraction(mut self, extraction: RowExtraction) -> Self {
81 self.extraction = extraction;
82 self
83 }
84
85 pub fn with_column_order(mut self, columns: Vec<String>) -> Self {
88 self.column_names = columns;
89 self
90 }
91
92 fn prepare(&mut self) -> bool {
96 if let Some(schema) = self.table_schema {
97 self.column_order = if self.column_names.is_empty() {
98 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 self.col_to_value =
109 super::mysql_insert::build_col_to_value(&self.column_order, schema.columns.len());
110 }
111
112 self.table_schema
115 .map(|s| s.columns.len() == 1)
116 .unwrap_or(false)
117 }
118
119 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 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 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 if line.last() == Some(&b'\r') {
150 line = &line[..line.len() - 1];
151 }
152
153 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 pub fn prepared(mut self) -> (Self, bool) {
175 let empty_line_is_row = self.prepare();
176 (self, empty_line_is_row)
177 }
178
179 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 fn parse_row(&self, line: &[u8]) -> ParsedCopyRow {
198 let raw = line.to_vec();
199
200 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 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 if start <= line.len() {
232 values.push(self.parse_copy_value(&line[start..]));
233 }
234
235 values
236 }
237
238 fn parse_copy_value<'b>(&self, value: &'b [u8]) -> CopyValue<'b> {
240 if value == b"\\N" {
242 return CopyValue::Null;
243 }
244
245 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 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 pub fn decode_copy_escapes(&self, value: &[u8]) -> Vec<u8> {
276 decode_copy_escapes(value)
277 }
278
279 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 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 coerce_text_pk(&s, col)
306 .unwrap_or_else(|| PkValue::Text(s.into_owned().into_boxed_str()))
307 }
308 }
309 }
310}
311
312#[derive(Debug, Clone)]
315enum CopyValue<'a> {
316 Null,
317 Integer(i64),
318 BigInteger(i128),
319 Text(Cow<'a, [u8]>),
320}
321
322pub 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 result.push(b'\\');
345 result.push(b'N');
346 i += 2;
347 continue;
348 }
349 _ => {
350 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
368fn 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
386pub fn parse_copy_columns(header: &str) -> Vec<String> {
388 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
401pub 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
410pub 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
426pub 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}