use std::{collections::HashMap, sync::Arc};
use arrow_array::{Array, RecordBatch, StringArray};
use arrow_schema::{Field, Schema};
use crate::{
cdc::ChangeOp,
error::{BifrostError, Result},
mapping::SyncMode,
mutation::{EdgeSet, GraphMutation, VertexDelete, VertexSet},
};
#[derive(Debug, Clone)]
pub struct TableContext {
pub table: String,
}
pub trait Transform: Send + Sync {
fn apply(&self, ctx: &TableContext, batches: &[RecordBatch]) -> Result<GraphMutation>;
fn apply_deletes(&self, ctx: &TableContext, batches: &[RecordBatch]) -> Result<GraphMutation> {
self.apply(ctx, batches)
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct EndpointSpec {
pub label: String,
pub column: String,
#[serde(default)]
pub id_column: Option<String>,
}
impl EndpointSpec {
fn node_id_column(&self) -> &str {
self.id_column.as_deref().unwrap_or(&self.column)
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct VertexTransform {
pub label: String,
pub id_column: String,
#[serde(default)]
pub properties: Vec<String>,
#[serde(default)]
pub rename: HashMap<String, String>,
}
impl Transform for VertexTransform {
fn apply(&self, _ctx: &TableContext, batches: &[RecordBatch]) -> Result<GraphMutation> {
let mut out = GraphMutation::default();
for batch in batches {
let mut keep = vec![self.id_column.clone()];
keep.extend(self.properties.iter().cloned());
let projected = project(batch, &keep, &self.rename)?;
out.vertices.push(VertexSet {
label: self.label.clone(),
id_column: renamed(&self.id_column, &self.rename),
batch: projected,
});
}
Ok(out)
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct EdgeTransform {
#[serde(rename = "type")]
pub edge_type: String,
pub src: EndpointSpec,
pub dst: EndpointSpec,
#[serde(default)]
pub properties: Vec<String>,
#[serde(default)]
pub rename: HashMap<String, String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub key: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub replace: Option<bool>,
}
impl Transform for EdgeTransform {
fn apply(&self, _ctx: &TableContext, batches: &[RecordBatch]) -> Result<GraphMutation> {
let mut out = GraphMutation::default();
for batch in batches {
let projected = self.project_edge(batch)?;
out.edges.push(EdgeSet {
src_label: self.src.label.clone(),
edge_type: self.edge_type.clone(),
dst_label: self.dst.label.clone(),
src_id_column: self.src.node_id_column().to_string(),
dst_id_column: self.dst.node_id_column().to_string(),
edge_key_props: self.key.iter().map(|k| renamed(k, &self.rename)).collect(),
replace_outgoing: self.replace.unwrap_or(false) && self.key.is_empty(),
batch: projected,
});
}
Ok(out)
}
}
impl EdgeTransform {
fn project_edge(&self, batch: &RecordBatch) -> Result<RecordBatch> {
let schema = batch.schema();
let mut fields = Vec::new();
let mut arrays = Vec::new();
let mut seen_output = std::collections::HashSet::new();
let mut push = |out_name: &str, src_col: &str| -> Result<()> {
if !seen_output.insert(out_name.to_string()) {
return Err(BifrostError::DuplicateOutputColumn(out_name.to_string()));
}
let idx = schema
.index_of(src_col)
.map_err(|_| BifrostError::ColumnNotFound(src_col.to_string()))?;
let field = schema.field(idx);
fields.push(Field::new(
out_name,
field.data_type().clone(),
field.is_nullable(),
));
arrays.push(batch.column(idx).clone());
Ok(())
};
push("src", &self.src.column)?;
push("dst", &self.dst.column)?;
let mut seen_prop_source = std::collections::HashSet::new();
for prop in self.properties.iter().chain(&self.key) {
if !seen_prop_source.insert(prop.clone()) {
continue;
}
let out_name = renamed(prop, &self.rename);
push(&out_name, prop)?;
}
Ok(RecordBatch::try_new(Arc::new(Schema::new(fields)), arrays)?)
}
}
pub type FkEdgesTransform = EdgeTransform;
#[derive(Debug, Default)]
pub struct ChangeRows {
pub upserts: Vec<RecordBatch>,
pub deletes: Vec<RecordBatch>,
}
impl ChangeRows {
pub fn is_empty(&self) -> bool {
self.upserts.is_empty() && self.deletes.is_empty()
}
}
pub fn is_changelog_batch(batch: &RecordBatch) -> bool {
batch
.schema()
.index_of(SyncMode::CHANGE_TYPE_COLUMN)
.is_ok()
}
pub fn partition_change_rows(batches: &[RecordBatch]) -> Result<ChangeRows> {
let mut out = ChangeRows::default();
for batch in batches {
let Ok(ct_idx) = batch.schema().index_of(SyncMode::CHANGE_TYPE_COLUMN) else {
out.upserts.push(batch.clone());
continue;
};
let kinds = batch
.column(ct_idx)
.as_any()
.downcast_ref::<StringArray>()
.ok_or_else(|| {
BifrostError::Source(format!(
"{} must be a string column",
SyncMode::CHANGE_TYPE_COLUMN
))
})?;
let mut keep_upsert = Vec::with_capacity(batch.num_rows());
let mut keep_delete = Vec::with_capacity(batch.num_rows());
for row in 0..batch.num_rows() {
if kinds.is_null(row) {
return Err(BifrostError::Source(format!(
"null {} at row {row}",
SyncMode::CHANGE_TYPE_COLUMN
)));
}
match ChangeOp::parse(kinds.value(row)) {
Some(ChangeOp::Insert) | Some(ChangeOp::UpdateAfter) => {
keep_upsert.push(row as u32)
}
Some(ChangeOp::Delete) => keep_delete.push(row as u32),
Some(ChangeOp::Update) => keep_upsert.push(row as u32),
Some(ChangeOp::UpdateBefore) => {}
None => {
return Err(BifrostError::Source(format!(
"unknown {} '{}'",
SyncMode::CHANGE_TYPE_COLUMN,
kinds.value(row)
)));
}
}
}
let stripped = drop_column(batch, ct_idx)?;
if !keep_upsert.is_empty() {
out.upserts.push(take_rows(&stripped, &keep_upsert)?);
}
if !keep_delete.is_empty() {
out.deletes.push(take_rows(&stripped, &keep_delete)?);
}
}
Ok(out)
}
pub fn deletes_from_change_rows(
transforms: &[Arc<dyn Transform>],
ctx: &TableContext,
delete_batches: &[RecordBatch],
) -> Result<Vec<VertexDelete>> {
if delete_batches.is_empty() {
return Ok(Vec::new());
}
let mut deletes = Vec::new();
for transform in transforms {
let mutation = transform.apply_deletes(ctx, delete_batches)?;
for set in mutation.vertices {
deletes.push(VertexDelete {
label: set.label,
id_column: set.id_column,
batch: set.batch,
});
}
}
Ok(deletes)
}
pub fn edge_deletes_from_change_rows(
transforms: &[Arc<dyn Transform>],
ctx: &TableContext,
delete_batches: &[RecordBatch],
) -> Result<Vec<EdgeSet>> {
if delete_batches.is_empty() {
return Ok(Vec::new());
}
let mut out = Vec::new();
for transform in transforms {
out.extend(transform.apply_deletes(ctx, delete_batches)?.edges);
}
Ok(out)
}
fn renamed(name: &str, rename: &HashMap<String, String>) -> String {
rename
.get(name)
.cloned()
.unwrap_or_else(|| name.to_string())
}
fn drop_column(batch: &RecordBatch, idx: usize) -> Result<RecordBatch> {
let schema = batch.schema();
let fields: Vec<Field> = schema
.fields()
.iter()
.enumerate()
.filter(|(i, _)| *i != idx)
.map(|(_, f)| f.as_ref().clone())
.collect();
let columns = batch
.columns()
.iter()
.enumerate()
.filter(|(i, _)| *i != idx)
.map(|(_, c)| c.clone())
.collect();
Ok(RecordBatch::try_new(
Arc::new(Schema::new(fields)),
columns,
)?)
}
fn take_rows(batch: &RecordBatch, rows: &[u32]) -> Result<RecordBatch> {
let indices = arrow_array::UInt32Array::from(rows.to_vec());
let columns = batch
.columns()
.iter()
.map(|c| arrow::compute::take(c.as_ref(), &indices, None))
.collect::<std::result::Result<Vec<_>, _>>()?;
Ok(RecordBatch::try_new(batch.schema(), columns)?)
}
fn project(
batch: &RecordBatch,
columns: &[String],
rename: &HashMap<String, String>,
) -> Result<RecordBatch> {
let schema = batch.schema();
let mut fields = Vec::with_capacity(columns.len());
let mut arrays = Vec::with_capacity(columns.len());
let mut seen_source = std::collections::HashSet::new();
let mut seen_output = std::collections::HashSet::new();
for name in columns {
if !seen_source.insert(name.clone()) {
continue;
}
let out_name = renamed(name, rename);
if !seen_output.insert(out_name.clone()) {
return Err(BifrostError::DuplicateOutputColumn(out_name));
}
let idx = schema
.index_of(name)
.map_err(|_| BifrostError::ColumnNotFound(name.clone()))?;
let field = schema.field(idx);
fields.push(Field::new(
out_name,
field.data_type().clone(),
field.is_nullable(),
));
arrays.push(batch.column(idx).clone());
}
Ok(RecordBatch::try_new(Arc::new(Schema::new(fields)), arrays)?)
}