use std::collections::HashMap;
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use datafusion::arrow::array::{Array, Int64Array};
use datafusion::arrow::datatypes::{DataType, SchemaRef};
use datafusion::catalog::{ScanArgs, ScanResult, Session, TableProvider};
use datafusion::common::tree_node::TreeNodeRecursion;
use datafusion::common::{Column, Constraints, ScalarValue, Statistics, TableReference};
use datafusion::datasource::{provider_as_source, TableType};
use datafusion::error::{DataFusionError, Result};
use datafusion::execution::TaskContext;
use datafusion::functions_aggregate::count::{count, count_distinct};
use datafusion::logical_expr::{
lit, Expr, LogicalPlanBuilder, SortExpr, TableProviderFilterPushDown,
};
use datafusion::physical_expr::PhysicalExpr;
use datafusion::physical_plan::execution_plan::CardinalityEffect;
use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
use datafusion::physical_plan::{
collect, DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties, SendableRecordBatchStream,
};
use datafusion::prelude::{SessionConfig, SessionContext};
use futures::TryStreamExt;
use ursa_core::KeyRows;
use super::index::{file_identities, fingerprint, portable, FileIdentity};
use crate::database::{database_of_config, IndexKey, IndexStore};
pub(crate) const VERTEX_KEY: &str = "__ursa_key";
pub(crate) const UNIQUE_KEYS: &str = "\n-- unique vertex keys --\n";
pub(crate) fn key_error(
graph: &str,
table: &str,
key: &str,
rows: &KeyRows,
quoted: bool,
) -> DataFusionError {
let n = |n: u64, what: &str| match n {
1 => format!("1 row with {what}"),
n => format!("{n} rows with {what}"),
};
let mut found = Vec::new();
if rows.duplicates > 0 {
let example = match (&rows.duplicate, quoted) {
(Some(value), true) => format!(" ({key} = '{}')", value.replace('\'', "''")),
(Some(value), false) => format!(" ({key} = {value})"),
(None, _) => String::new(),
};
found.push(format!(
"{}{example}",
n(rows.duplicates, "a duplicate key")
));
}
if rows.nulls > 0 {
found.push(n(rows.nulls, "a NULL key"));
}
DataFusionError::Execution(format!(
"graph '{graph}': vertex table '{table}' has {}; a vertex table's KEY must identify one \
row. Deduplicate it in a view and define the graph over the view, for example: \
CREATE VIEW {table}_nodes AS SELECT DISTINCT ON ({key}) * FROM {table} \
WHERE {key} IS NOT NULL ORDER BY {key}",
found.join(" and ")
))
}
pub(crate) fn unique_keys(
graph: &str,
name: &str,
table: &TableReference,
key: &str,
inner: Arc<dyn TableProvider>,
) -> Arc<dyn TableProvider> {
Arc::new(UniqueKeys {
graph: graph.to_string(),
name: name.to_string(),
table: table.clone(),
key: key.to_string(),
inner,
})
}
#[derive(Debug)]
struct UniqueKeys {
graph: String,
name: String,
table: TableReference,
key: String,
inner: Arc<dyn TableProvider>,
}
impl UniqueKeys {
async fn checked(
&self,
state: &dyn Session,
scan: Arc<dyn ExecutionPlan>,
) -> Result<Arc<dyn ExecutionPlan>> {
let schema = self.inner.schema();
let Ok(index) = schema.index_of(&self.key) else {
return Ok(scan);
};
let key_type = match schema.field(index).data_type().clone() {
DataType::Dictionary(_, values) => *values,
other => other,
};
let key = Expr::Column(Column::new(Some(self.table.clone()), &self.key));
let rows = LogicalPlanBuilder::scan(
self.table.clone(),
provider_as_source(Arc::clone(&self.inner)),
None,
)?;
let keys = rows
.clone()
.project(vec![key.clone().alias(VERTEX_KEY)])?
.build()?;
let counts = rows
.clone()
.aggregate(
Vec::<Expr>::new(),
vec![
count(lit(1i64)).alias("rows"),
count(key.clone()).alias("keys"),
count_distinct(key.clone()).alias("distinct"),
],
)?
.build()?;
let counts = state.create_physical_plan(&counts).await?;
let config = state.config();
let checks = config.get_extension::<KeyChecks>();
let store = database_of_config(config).map(|db| (db.index_store(), db.dir().to_path_buf()));
let identity = match state.optimize(&keys).ok().and_then(|p| fingerprint(&p)) {
Some(fingerprint) => Some((
fingerprint,
file_identities(&counts, &state.task_ctx()).await?,
)),
None => None,
};
let stored = match (&store, &identity) {
(Some((store, dir)), Some((fingerprint, files))) => Some((
Arc::clone(store),
IndexKey::new(portable(fingerprint, dir), files.clone()),
)),
_ => None,
};
if let Some((fingerprint, files)) = &identity {
if checks.as_ref().is_some_and(|c| c.holds(fingerprint, files)) {
return Ok(scan);
}
if let Some((store, key)) = &stored {
if store.keys_counted(key) || index_proves(&store.entries(), key) {
if let Some(checks) = &checks {
checks.record(fingerprint.clone(), files.clone());
}
return Ok(scan);
}
}
}
let count_of = Expr::Column(Column::new_unqualified("rows"));
let duplicate = rows
.filter(key.clone().is_not_null())?
.aggregate(vec![key.alias("key")], vec![count(lit(1i64)).alias("rows")])?
.filter(count_of.gt(lit(1i64)))?
.sort(vec![SortExpr::new(
Expr::Column(Column::new_unqualified("key")),
true,
false,
)])?
.limit(0, Some(1))?
.build()?;
let duplicate = state.create_physical_plan(&duplicate).await?;
Ok(Arc::new(KeyCheckExec {
input: scan,
check: Arc::new(Check {
graph: self.graph.clone(),
table: self.name.clone(),
key: self.key.clone(),
quoted: matches!(
key_type,
DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View
),
counts,
duplicate,
checks,
identity,
stored,
done: tokio::sync::OnceCell::new(),
}),
}))
}
}
fn index_proves(entries: &[crate::database::index_store::Entry], key: &IndexKey) -> bool {
entries.iter().any(|e| {
e.key
.fingerprint
.split_once(UNIQUE_KEYS)
.is_some_and(|(_, keys)| keys == key.fingerprint)
&& key.files.iter().all(|f| e.key.files.contains(f))
})
}
#[async_trait]
impl TableProvider for UniqueKeys {
fn schema(&self) -> SchemaRef {
self.inner.schema()
}
fn constraints(&self) -> Option<&Constraints> {
self.inner.constraints()
}
fn table_type(&self) -> TableType {
self.inner.table_type()
}
fn get_table_definition(&self) -> Option<&str> {
self.inner.get_table_definition()
}
fn get_column_default(&self, column: &str) -> Option<&Expr> {
self.inner.get_column_default(column)
}
async fn scan(
&self,
state: &dyn Session,
projection: Option<&Vec<usize>>,
filters: &[Expr],
limit: Option<usize>,
) -> Result<Arc<dyn ExecutionPlan>> {
let scan = self.inner.scan(state, projection, filters, limit).await?;
self.checked(state, scan).await
}
async fn scan_with_args<'a>(
&self,
state: &dyn Session,
args: ScanArgs<'a>,
) -> Result<ScanResult> {
let scan = self.inner.scan_with_args(state, args).await?.into_inner();
Ok(ScanResult::new(self.checked(state, scan).await?))
}
fn supports_filters_pushdown(
&self,
filters: &[&Expr],
) -> Result<Vec<TableProviderFilterPushDown>> {
self.inner.supports_filters_pushdown(filters)
}
fn statistics(&self) -> Option<Statistics> {
self.inner.statistics()
}
}
#[derive(Debug)]
struct Check {
graph: String,
table: String,
key: String,
quoted: bool,
counts: Arc<dyn ExecutionPlan>,
duplicate: Arc<dyn ExecutionPlan>,
checks: Option<Arc<KeyChecks>>,
identity: Option<(String, Vec<FileIdentity>)>,
stored: Option<(Arc<IndexStore>, IndexKey)>,
done: tokio::sync::OnceCell<()>,
}
impl Check {
async fn run(&self, context: &Arc<TaskContext>) -> Result<()> {
self.done
.get_or_try_init(|| self.count(context))
.await
.map(|_| ())
}
async fn count(&self, context: &Arc<TaskContext>) -> Result<()> {
if let Some(checks) = &self.checks {
checks.counts.fetch_add(1, Ordering::Relaxed);
}
let batches = collect(Arc::clone(&self.counts), Arc::clone(context)).await?;
let value = |column: usize| -> u64 {
batches
.iter()
.find(|b| b.num_rows() > 0)
.and_then(|b| b.column(column).as_any().downcast_ref::<Int64Array>())
.filter(|a| a.is_valid(0))
.map_or(0, |a| a.value(0).max(0) as u64)
};
let (rows, non_null, distinct) = (value(0), value(1), value(2));
let mut found = KeyRows {
duplicates: non_null.saturating_sub(distinct),
nulls: rows.saturating_sub(non_null),
duplicate: None,
};
if found.is_unique() {
if let (Some(checks), Some((fingerprint, files))) = (&self.checks, &self.identity) {
checks.record(fingerprint.clone(), files.clone());
}
if let Some((store, key)) = &self.stored {
store.record_keys_counted(key.clone());
}
return Ok(());
}
if found.duplicates > 0 {
let batches = collect(Arc::clone(&self.duplicate), Arc::clone(context)).await?;
if let Some(batch) = batches.iter().find(|b| b.num_rows() > 0) {
found.duplicate = Some(match ScalarValue::try_from_array(batch.column(0), 0)? {
ScalarValue::Dictionary(_, value) => value.to_string(),
value => value.to_string(),
});
}
}
Err(key_error(
&self.graph,
&self.table,
&self.key,
&found,
self.quoted,
))
}
}
#[derive(Debug)]
struct KeyCheckExec {
input: Arc<dyn ExecutionPlan>,
check: Arc<Check>,
}
impl DisplayAs for KeyCheckExec {
fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"VertexKeyCheckExec: graph={}, table={}, key={}",
self.check.graph, self.check.table, self.check.key
)
}
}
impl ExecutionPlan for KeyCheckExec {
fn name(&self) -> &str {
"VertexKeyCheckExec"
}
fn properties(&self) -> &Arc<PlanProperties> {
self.input.properties()
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.input]
}
fn maintains_input_order(&self) -> Vec<bool> {
vec![true]
}
fn benefits_from_input_partitioning(&self) -> Vec<bool> {
vec![false]
}
fn cardinality_effect(&self) -> CardinalityEffect {
CardinalityEffect::Equal
}
fn apply_expressions(
&self,
_f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
Ok(TreeNodeRecursion::Continue)
}
fn with_new_children(
self: Arc<Self>,
mut children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
match (children.pop(), children.is_empty()) {
(Some(input), true) => Ok(Arc::new(Self {
input,
check: Arc::clone(&self.check),
})),
_ => Err(DataFusionError::Internal(
"VertexKeyCheckExec has one child".to_string(),
)),
}
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
let (input, check) = (Arc::clone(&self.input), Arc::clone(&self.check));
let rows = futures::stream::once(async move {
check.run(&context).await?;
input.execute(partition, context)
})
.try_flatten();
Ok(Box::pin(RecordBatchStreamAdapter::new(self.schema(), rows)))
}
}
const CAPACITY: usize = 64;
#[derive(Debug, Default)]
pub(crate) struct KeyChecks {
unique: Mutex<HashMap<String, Vec<FileIdentity>>>,
counts: AtomicU64,
}
impl KeyChecks {
fn holds(&self, fingerprint: &str, files: &[FileIdentity]) -> bool {
let unique = self.unique.lock().unwrap_or_else(|e| e.into_inner());
unique.get(fingerprint).is_some_and(|f| f == files)
}
fn record(&self, fingerprint: String, files: Vec<FileIdentity>) {
let mut unique = self.unique.lock().unwrap_or_else(|e| e.into_inner());
if unique.len() >= CAPACITY && !unique.contains_key(&fingerprint) {
unique.clear();
}
unique.insert(fingerprint, files);
}
}
pub(crate) fn with_key_checks(config: SessionConfig) -> SessionConfig {
config.with_extension(Arc::new(KeyChecks::default()))
}
pub fn vertex_key_counts(ctx: &SessionContext) -> u64 {
ctx.state()
.config()
.get_extension::<KeyChecks>()
.map(|c| c.counts.load(Ordering::Relaxed))
.unwrap_or(0)
}