1use crate::schema::{ColumnId, ColumnType, TableSchema};
7use smallvec::SmallVec;
8use std::borrow::Cow;
9use std::sync::Arc;
10
11use super::mysql_insert::{FkRef, PkValue, RowExtraction};
13
14pub type PkTuple = SmallVec<[PkValue; 2]>;
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 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 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 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 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 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 if line.last() == Some(&b'\r') {
139 line = &line[..line.len() - 1];
140 }
141
142 if line == b"\\." || (line.is_empty() && !empty_line_is_row) {
144 pos = line_end + 1;
145 continue;
146 }
147
148 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 fn parse_row(&self, line: &[u8]) -> anyhow::Result<Option<ParsedCopyRow>> {
161 let raw = line.to_vec();
162
163 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 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 if start <= line.len() {
195 values.push(self.parse_copy_value(&line[start..]));
196 }
197
198 values
199 }
200
201 fn parse_copy_value<'b>(&self, value: &'b [u8]) -> CopyValue<'b> {
203 if value == b"\\N" {
205 return CopyValue::Null;
206 }
207
208 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 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 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 result.push(b'\\');
250 result.push(b'N');
251 i += 2;
252 continue;
253 }
254 _ => {
255 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 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 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 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#[derive(Debug, Clone)]
324enum CopyValue<'a> {
325 Null,
326 Integer(i64),
327 BigInteger(i128),
328 Text(Cow<'a, [u8]>),
329}
330
331fn 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
349pub fn parse_copy_columns(header: &str) -> Vec<String> {
351 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
364pub 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
373pub 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}