|
| 1 | +//! Table changes (CDC) functionality for DuckLake |
| 2 | +
|
| 3 | +use std::any::Any; |
| 4 | +use std::sync::Arc; |
| 5 | + |
| 6 | +use arrow::array::{ArrayRef, Int64Array, StringArray}; |
| 7 | +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; |
| 8 | +use arrow::record_batch::RecordBatch; |
| 9 | +use datafusion::catalog::Session; |
| 10 | +use datafusion::common::Result as DataFusionResult; |
| 11 | +use datafusion::datasource::memory::MemTable; |
| 12 | +use datafusion::datasource::{TableProvider, TableType}; |
| 13 | +use datafusion::physical_plan::ExecutionPlan; |
| 14 | + |
| 15 | +use crate::metadata_provider::MetadataProvider; |
| 16 | + |
| 17 | +#[derive(Debug)] |
| 18 | +pub struct TableChangesTable { |
| 19 | + provider: Arc<dyn MetadataProvider>, |
| 20 | + table_id: i64, |
| 21 | + start_snapshot: i64, |
| 22 | + end_snapshot: i64, |
| 23 | + schema: SchemaRef, |
| 24 | +} |
| 25 | + |
| 26 | +impl TableChangesTable { |
| 27 | + pub fn new( |
| 28 | + provider: Arc<dyn MetadataProvider>, |
| 29 | + table_id: i64, |
| 30 | + start_snapshot: i64, |
| 31 | + end_snapshot: i64, |
| 32 | + ) -> Self { |
| 33 | + let schema = Arc::new(Schema::new(vec![ |
| 34 | + Field::new("snapshot_id", DataType::Int64, false), |
| 35 | + Field::new("change_type", DataType::Utf8, false), |
| 36 | + ])); |
| 37 | + Self { |
| 38 | + provider, |
| 39 | + table_id, |
| 40 | + start_snapshot, |
| 41 | + end_snapshot, |
| 42 | + schema, |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + fn query_changes(&self) -> DataFusionResult<RecordBatch> { |
| 47 | + // Get data files added (INSERT changes) |
| 48 | + let data_files = self |
| 49 | + .provider |
| 50 | + .get_data_files_added_between_snapshots( |
| 51 | + self.table_id, |
| 52 | + self.start_snapshot, |
| 53 | + self.end_snapshot, |
| 54 | + ) |
| 55 | + .map_err(|e| datafusion::error::DataFusionError::External(Box::new(e)))?; |
| 56 | + |
| 57 | + // Get delete files added (DELETE changes) |
| 58 | + let delete_files = self |
| 59 | + .provider |
| 60 | + .get_delete_files_added_between_snapshots( |
| 61 | + self.table_id, |
| 62 | + self.start_snapshot, |
| 63 | + self.end_snapshot, |
| 64 | + ) |
| 65 | + .map_err(|e| datafusion::error::DataFusionError::External(Box::new(e)))?; |
| 66 | + |
| 67 | + // Collect all changes into a sortable structure |
| 68 | + struct ChangeRecord { |
| 69 | + snapshot_id: i64, |
| 70 | + change_type: &'static str, |
| 71 | + } |
| 72 | + |
| 73 | + let mut changes: Vec<ChangeRecord> = |
| 74 | + Vec::with_capacity(data_files.len() + delete_files.len()); |
| 75 | + |
| 76 | + // Add INSERT changes (data files added) |
| 77 | + for data_file in &data_files { |
| 78 | + changes.push(ChangeRecord { |
| 79 | + snapshot_id: data_file.begin_snapshot, |
| 80 | + change_type: "insert", |
| 81 | + }); |
| 82 | + } |
| 83 | + |
| 84 | + // Add DELETE changes (delete files added) |
| 85 | + for delete_file in &delete_files { |
| 86 | + changes.push(ChangeRecord { |
| 87 | + snapshot_id: delete_file.begin_snapshot, |
| 88 | + change_type: "delete", |
| 89 | + }); |
| 90 | + } |
| 91 | + |
| 92 | + // Sort by snapshot_id for deterministic output |
| 93 | + changes.sort_by_key(|c| c.snapshot_id); |
| 94 | + |
| 95 | + // Build arrays from sorted changes |
| 96 | + let snapshot_ids: ArrayRef = Arc::new(Int64Array::from( |
| 97 | + changes.iter().map(|c| c.snapshot_id).collect::<Vec<_>>(), |
| 98 | + )); |
| 99 | + let change_types: ArrayRef = Arc::new(StringArray::from( |
| 100 | + changes.iter().map(|c| c.change_type).collect::<Vec<_>>(), |
| 101 | + )); |
| 102 | + |
| 103 | + RecordBatch::try_new(self.schema.clone(), vec![snapshot_ids, change_types]) |
| 104 | + .map_err(|e| datafusion::error::DataFusionError::ArrowError(Box::new(e), None)) |
| 105 | + } |
| 106 | +} |
| 107 | + |
| 108 | +#[async_trait::async_trait] |
| 109 | +impl TableProvider for TableChangesTable { |
| 110 | + fn as_any(&self) -> &dyn Any { |
| 111 | + self |
| 112 | + } |
| 113 | + |
| 114 | + fn schema(&self) -> SchemaRef { |
| 115 | + self.schema.clone() |
| 116 | + } |
| 117 | + |
| 118 | + fn table_type(&self) -> TableType { |
| 119 | + TableType::View |
| 120 | + } |
| 121 | + |
| 122 | + async fn scan( |
| 123 | + &self, |
| 124 | + state: &dyn Session, |
| 125 | + projection: Option<&Vec<usize>>, |
| 126 | + filters: &[datafusion::prelude::Expr], |
| 127 | + limit: Option<usize>, |
| 128 | + ) -> DataFusionResult<Arc<dyn ExecutionPlan>> { |
| 129 | + let batch = self.query_changes()?; |
| 130 | + let mem_table = MemTable::try_new(self.schema.clone(), vec![vec![batch]])?; |
| 131 | + mem_table.scan(state, projection, filters, limit).await |
| 132 | + } |
| 133 | +} |
0 commit comments