use crate::execution::storage::buffer::GroupedRanges;
use std::sync::{Arc, OnceLock};
use datafusion::arrow::array::make_comparator;
use datafusion::arrow::datatypes::SchemaRef;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion_common::{DataFusionError, Result, internal_err};
use datafusion_execution::memory_pool::MemoryReservation;
#[derive(Debug)]
pub(crate) struct PartitionKeySchema {
pub(crate) schema: SchemaRef,
_memory: MemoryReservation,
}
impl PartitionKeySchema {
pub(crate) fn new(schema: SchemaRef, memory: MemoryReservation) -> Arc<Self> {
Arc::new(Self {
schema,
_memory: memory,
})
}
}
#[derive(Debug)]
pub(crate) struct PartitionKeyBatch {
pub(crate) values: RecordBatch,
pub(crate) grouped: Option<Box<GroupedRanges>>,
_schema_owner: Option<Arc<PartitionKeySchema>>,
_memory: MemoryReservation,
_shared_backing: Option<Arc<MemoryReservation>>,
}
impl PartitionKeyBatch {
#[cfg(test)]
pub(crate) fn new(values: RecordBatch, memory: MemoryReservation) -> Arc<Self> {
Arc::new(Self {
values,
grouped: None,
_schema_owner: None,
_memory: memory,
_shared_backing: None,
})
}
pub(crate) fn closed_grouped(
grouped: Box<GroupedRanges>,
memory: MemoryReservation,
) -> Arc<Self> {
static EMPTY_SCHEMA: OnceLock<SchemaRef> = OnceLock::new();
let schema = Arc::clone(
EMPTY_SCHEMA
.get_or_init(|| Arc::new(datafusion::arrow::datatypes::Schema::empty())),
);
Arc::new(Self {
values: RecordBatch::new_empty(schema),
grouped: Some(grouped),
_schema_owner: None,
_memory: memory,
_shared_backing: None,
})
}
pub(crate) fn new_with_schema(
values: RecordBatch,
memory: MemoryReservation,
schema_owner: Arc<PartitionKeySchema>,
grouped: Option<Box<GroupedRanges>>,
shared_backing: Option<Arc<MemoryReservation>>,
) -> Arc<Self> {
debug_assert!(Arc::ptr_eq(&values.schema(), &schema_owner.schema));
Arc::new(Self {
values,
grouped,
_schema_owner: Some(schema_owner),
_memory: memory,
_shared_backing: shared_backing,
})
}
pub(crate) fn rows(&self) -> usize {
self.grouped
.as_ref()
.map_or_else(|| self.values.num_rows(), |groups| groups.rows())
}
}
#[derive(Debug, Clone)]
pub(crate) struct PartitionKeyRows {
pub(crate) batch: Arc<PartitionKeyBatch>,
pub(crate) offset: usize,
pub(crate) rows: usize,
}
impl PartitionKeyRows {
pub(crate) fn full(batch: Arc<PartitionKeyBatch>) -> Self {
Self {
rows: batch.rows(),
batch,
offset: 0,
}
}
pub(crate) fn slice(&self, offset: usize, rows: usize) -> Result<Self> {
if offset.checked_add(rows).is_none_or(|end| end > self.rows) {
return internal_err!(
"MATCH_RECOGNIZE cached partition keys do not cover their input view"
);
}
Ok(Self {
batch: Arc::clone(&self.batch),
offset: self.offset + offset,
rows,
})
}
pub(crate) fn column(&self, index: usize) -> datafusion::arrow::array::ArrayRef {
let column = self.batch.values.column(index);
if self.offset == 0 && self.rows == column.len() {
Arc::clone(column)
} else {
column.slice(self.offset, self.rows)
}
}
pub(crate) fn key(&self, row: usize) -> Result<PartitionKey> {
if row >= self.rows {
return internal_err!(
"MATCH_RECOGNIZE partition representative is outside its input view"
);
}
OwnedPartitionKey::try_new(Arc::clone(&self.batch), self.offset + row)
}
}
pub(crate) struct OwnedPartitionKey {
batch: Option<Arc<PartitionKeyBatch>>,
row: usize,
}
impl std::fmt::Debug for OwnedPartitionKey {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("PartitionKey")
.field("source", &self.batch.as_ref().map(Arc::as_ptr))
.field("row", &self.row)
.field("columns", &self.len())
.finish()
}
}
pub(crate) type PartitionKey = Arc<OwnedPartitionKey>;
pub(crate) fn shared_empty_partition_key() -> PartitionKey {
static EMPTY: OnceLock<PartitionKey> = OnceLock::new();
Arc::clone(EMPTY.get_or_init(|| {
Arc::new(OwnedPartitionKey {
batch: None,
row: 0,
})
}))
}
impl OwnedPartitionKey {
pub(crate) fn try_new(
batch: Arc<PartitionKeyBatch>,
row: usize,
) -> Result<PartitionKey> {
if batch.values.num_columns() == 0 && batch.grouped.is_none() {
return Ok(shared_empty_partition_key());
}
if row >= batch.rows()
|| batch
.grouped
.as_ref()
.is_some_and(|g| !g.has_representative(row))
{
return internal_err!(
"MATCH_RECOGNIZE canonical key row is outside its input batch"
);
}
Ok(Arc::new(Self {
batch: Some(batch),
row,
}))
}
pub(crate) fn group_start(&self) -> Option<usize> {
self.batch
.as_ref()?
.grouped
.as_ref()
.map(|groups| groups.start_at(self.row))
}
pub(crate) fn len(&self) -> usize {
self.batch
.as_ref()
.map_or(0, |batch| batch.values.num_columns())
}
#[cfg(test)]
pub(crate) fn is_empty(&self) -> bool {
self.batch.is_none()
}
pub(crate) fn column(&self, index: usize) -> datafusion::arrow::array::ArrayRef {
let batch = self.batch.as_ref().expect("a nonempty key has a batch");
batch
.values
.column(index)
.slice(if batch.grouped.is_some() { 0 } else { self.row }, 1)
}
pub(crate) fn same_values(&self, other: &Self) -> Result<bool> {
if std::ptr::eq(self, other) {
return Ok(true);
}
if self.len() != other.len() {
return Ok(false);
}
for index in 0..self.len() {
let left = self.column(index);
let right = other.column(index);
if !make_comparator(left.as_ref(), right.as_ref(), Default::default())?(0, 0)
.is_eq()
{
return Ok(false);
}
}
Ok(true)
}
#[cfg(test)]
pub(crate) fn scalar_values(&self) -> Result<Vec<datafusion_common::ScalarValue>> {
(0..self.len())
.map(|index| {
datafusion_common::ScalarValue::try_from_array(
self.column(index).as_ref(),
0,
)
})
.collect()
}
}
#[cfg(test)]
impl PartialEq for OwnedPartitionKey {
fn eq(&self, other: &Self) -> bool {
self.same_values(other)
.expect("test_case keys have comparable native values")
}
}
#[cfg(test)]
impl Eq for OwnedPartitionKey {}
#[cfg(test)]
pub(crate) fn owned_partition_key(
values: Vec<datafusion_common::ScalarValue>,
) -> PartitionKey {
use datafusion_execution::memory_pool::{
MemoryConsumer, MemoryPool, UnboundedMemoryPool,
};
if values.is_empty() {
return shared_empty_partition_key();
}
let batch = RecordBatch::try_from_iter(
values
.into_iter()
.enumerate()
.map(|(index, value)| {
value.to_array().map(|array| (format!("key{index}"), array))
})
.collect::<Result<Vec<_>>>()
.unwrap(),
)
.unwrap();
let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
let memory = MemoryConsumer::new("partition-key-test_case").register(&pool);
memory.try_grow(batch.get_array_memory_size()).unwrap();
OwnedPartitionKey::try_new(PartitionKeyBatch::new(batch, memory), 0).unwrap()
}
pub(crate) fn key_memory_overflow() -> DataFusionError {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE partition-key memory exceeds usize".into(),
)
}