use crate::schema::{ColumnId, TableSchema};
use std::borrow::Cow;
use std::sync::Arc;
use super::mysql_insert::{coerce_text_pk, FkRef, PkValue, RowExtraction};
use super::RowFlow;
pub use super::mysql_insert::PkTuple;
#[derive(Debug, Clone)]
pub struct ParsedCopyRow {
pub raw: Vec<u8>,
pub pk: Option<PkTuple>,
pub fk_values: Vec<(FkRef, PkTuple)>,
pub all_values: Vec<PkValue>,
pub column_map: Arc<[Option<usize>]>,
}
impl ParsedCopyRow {
pub fn get_column_value(&self, schema_col_index: usize) -> Option<&PkValue> {
self.column_map
.get(schema_col_index)
.and_then(|v| *v)
.and_then(|val_idx| self.all_values.get(val_idx))
}
}
pub struct CopyParser<'a> {
data: &'a [u8],
table_schema: Option<&'a TableSchema>,
column_names: Vec<String>,
column_order: Vec<Option<ColumnId>>,
col_to_value: Arc<[Option<usize>]>,
extraction: RowExtraction,
}
impl<'a> CopyParser<'a> {
pub fn new(data: &'a [u8]) -> Self {
Self {
data,
table_schema: None,
column_names: Vec::new(),
column_order: Vec::new(),
col_to_value: Arc::from(Vec::new()),
extraction: RowExtraction::Full,
}
}
pub fn with_schema(mut self, schema: &'a TableSchema) -> Self {
self.table_schema = Some(schema);
self
}
pub fn with_extraction(mut self, extraction: RowExtraction) -> Self {
self.extraction = extraction;
self
}
pub fn with_column_order(mut self, columns: Vec<String>) -> Self {
self.column_names = columns;
self
}
fn prepare(&mut self) -> bool {
if let Some(schema) = self.table_schema {
self.column_order = if self.column_names.is_empty() {
schema.columns.iter().map(|c| Some(c.ordinal)).collect()
} else {
self.column_names
.iter()
.map(|name| schema.get_column_id(name))
.collect()
};
self.col_to_value =
super::mysql_insert::build_col_to_value(&self.column_order, schema.columns.len());
}
self.table_schema
.map(|s| s.columns.len() == 1)
.unwrap_or(false)
}
pub fn parse_rows(&mut self) -> anyhow::Result<Vec<ParsedCopyRow>> {
let mut rows = Vec::new();
self.parse_rows_visit(|row| {
rows.push(row);
Ok(RowFlow::Continue)
})?;
Ok(rows)
}
pub fn parse_rows_visit<F>(&mut self, mut f: F) -> anyhow::Result<()>
where
F: FnMut(ParsedCopyRow) -> anyhow::Result<RowFlow>,
{
let empty_line_is_row = self.prepare();
let mut pos = 0;
while pos < self.data.len() {
let line_end = memchr::memchr(b'\n', &self.data[pos..])
.map(|p| pos + p)
.unwrap_or(self.data.len());
let mut line = &self.data[pos..line_end];
if line.last() == Some(&b'\r') {
line = &line[..line.len() - 1];
}
if line == b"\\." || (line.is_empty() && !empty_line_is_row) {
pos = line_end + 1;
continue;
}
match f(self.parse_row(line))? {
RowFlow::Continue => {}
RowFlow::SkipStatement | RowFlow::Stop => break,
}
pos = line_end + 1;
}
Ok(())
}
pub fn prepared(mut self) -> (Self, bool) {
let empty_line_is_row = self.prepare();
(self, empty_line_is_row)
}
pub fn parse_line(&self, line: &[u8], empty_line_is_row: bool) -> Option<ParsedCopyRow> {
let line = if line.last() == Some(&b'\r') {
&line[..line.len() - 1]
} else {
line
};
if line == b"\\." || (line.is_empty() && !empty_line_is_row) {
return None;
}
Some(self.parse_row(line))
}
fn parse_row(&self, line: &[u8]) -> ParsedCopyRow {
let raw = line.to_vec();
let (pk, fk_values, all_values) = match (self.table_schema, self.extraction) {
(Some(schema), RowExtraction::PkFk | RowExtraction::Full) => {
let values: Vec<CopyValue> = self.split_and_parse_values(line);
self.extract_pk_fk(&values, schema)
}
_ => (None, Vec::new(), Vec::new()),
};
ParsedCopyRow {
raw,
pk,
fk_values,
all_values,
column_map: Arc::clone(&self.col_to_value),
}
}
fn split_and_parse_values<'b>(&self, line: &'b [u8]) -> Vec<CopyValue<'b>> {
let mut values = Vec::new();
let mut start = 0;
for (i, &b) in line.iter().enumerate() {
if b == b'\t' {
values.push(self.parse_copy_value(&line[start..i]));
start = i + 1;
}
}
if start <= line.len() {
values.push(self.parse_copy_value(&line[start..]));
}
values
}
fn parse_copy_value<'b>(&self, value: &'b [u8]) -> CopyValue<'b> {
if value == b"\\N" {
return CopyValue::Null;
}
let decoded: Cow<'b, [u8]> = if memchr::memchr(b'\\', value).is_none() {
Cow::Borrowed(value)
} else {
Cow::Owned(decode_copy_escapes(value))
};
if let Ok(s) = std::str::from_utf8(&decoded) {
if is_canonical_int(s) {
if let Ok(n) = s.parse::<i64>() {
return CopyValue::Integer(n);
}
if let Ok(n) = s.parse::<i128>() {
return CopyValue::BigInteger(n);
}
}
}
CopyValue::Text(decoded)
}
pub fn decode_copy_escapes(&self, value: &[u8]) -> Vec<u8> {
decode_copy_escapes(value)
}
fn extract_pk_fk(
&self,
values: &[CopyValue<'_>],
schema: &TableSchema,
) -> (Option<PkTuple>, Vec<(FkRef, PkTuple)>, Vec<PkValue>) {
super::mysql_insert::extract_pk_fk_generic(
values,
schema,
&self.column_order,
&self.col_to_value,
self.extraction == RowExtraction::Full,
|v, col| self.value_to_pk(v, col),
)
}
fn value_to_pk(&self, value: &CopyValue<'_>, col: Option<&crate::schema::Column>) -> PkValue {
match value {
CopyValue::Null => PkValue::Null,
CopyValue::Integer(n) => PkValue::Int(*n),
CopyValue::BigInteger(n) => PkValue::BigInt(*n),
CopyValue::Text(bytes) => {
let s = String::from_utf8_lossy(bytes);
coerce_text_pk(&s, col)
.unwrap_or_else(|| PkValue::Text(s.into_owned().into_boxed_str()))
}
}
}
}
#[derive(Debug, Clone)]
enum CopyValue<'a> {
Null,
Integer(i64),
BigInteger(i128),
Text(Cow<'a, [u8]>),
}
pub fn decode_copy_escapes(value: &[u8]) -> Vec<u8> {
let mut result = Vec::with_capacity(value.len());
let mut i = 0;
while i < value.len() {
if value[i] == b'\\' && i + 1 < value.len() {
let next = value[i + 1];
let decoded = match next {
b'n' => b'\n',
b'r' => b'\r',
b't' => b'\t',
b'\\' => b'\\',
b'N' => {
result.push(b'\\');
result.push(b'N');
i += 2;
continue;
}
_ => {
result.push(b'\\');
result.push(next);
i += 2;
continue;
}
};
result.push(decoded);
i += 2;
} else {
result.push(value[i]);
i += 1;
}
}
result
}
fn is_canonical_int(s: &str) -> bool {
let b = s.as_bytes();
let (neg, digits) = match b.split_first() {
Some((b'+', _)) => return false,
Some((b'-', rest)) => (true, rest),
_ => (false, b),
};
match digits {
[] => false,
[b'0'] => !neg,
[b'0', ..] => false,
_ => digits.iter().all(u8::is_ascii_digit),
}
}
pub fn parse_copy_columns(header: &str) -> Vec<String> {
if let Some(start) = header.find('(') {
if let Some(end) = header.find(')') {
let cols = &header[start + 1..end];
return cols
.split(',')
.map(|c| c.trim().trim_matches('"').to_string())
.collect();
}
}
Vec::new()
}
pub fn parse_postgres_copy_rows(
data: &[u8],
schema: &TableSchema,
column_order: Vec<String>,
) -> anyhow::Result<Vec<ParsedCopyRow>> {
parse_postgres_copy_rows_with(data, schema, column_order, RowExtraction::Full)
}
pub fn parse_postgres_copy_rows_with(
data: &[u8],
schema: &TableSchema,
column_order: Vec<String>,
extraction: RowExtraction,
) -> anyhow::Result<Vec<ParsedCopyRow>> {
let mut rows = Vec::new();
visit_postgres_copy_rows_with(data, schema, column_order, extraction, |row| {
rows.push(row);
Ok(RowFlow::Continue)
})?;
Ok(rows)
}
pub fn visit_postgres_copy_rows_with<F>(
data: &[u8],
schema: &TableSchema,
column_order: Vec<String>,
extraction: RowExtraction,
f: F,
) -> anyhow::Result<()>
where
F: FnMut(ParsedCopyRow) -> anyhow::Result<RowFlow>,
{
let mut parser = CopyParser::new(data)
.with_schema(schema)
.with_column_order(column_order)
.with_extraction(extraction);
parser.parse_rows_visit(f)
}