diff --git a/.github/workflows/fh.yml b/.github/workflows/fh.yml index da561b4..40ac72c 100644 --- a/.github/workflows/fh.yml +++ b/.github/workflows/fh.yml @@ -1,7 +1,6 @@ name: Build 🏗️ and Cache ❄️ on: workflow_dispatch: - pull_request: push: branches: - main @@ -12,7 +11,7 @@ on: - "LICENSE" concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true env: diff --git a/src/cache.rs b/src/cache.rs index f5a13f2..782aa40 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -1,14 +1,22 @@ use std::collections::HashMap; use std::sync::{Mutex, MutexGuard}; +use std::time::SystemTime; -use datafusion::prelude::DataFrame; -use nu_protocol::{LabeledError, ShellError, Span, shell_error::generic::GenericError}; +use chrono::{DateTime, Utc}; +use log::trace; +use nu_plugin::EngineInterface; +use nu_protocol::{LabeledError, Span}; use uuid::Uuid; -use crate::plugin::EngineWrapper; +use crate::plugin::{DfPlugin, EngineWrapper}; +use crate::values::NuDataFusionObject; +#[derive(Debug, Clone)] pub struct CacheEntry { - pub df: DataFrame, + pub id: Uuid, + pub value: NuDataFusionObject, + pub created: DateTime, + pub span: Span, pub reference_count: i16, } @@ -18,56 +26,210 @@ pub struct Cache { } impl Cache { - fn lock(&self) -> Result>, ShellError> { - self.inner.lock().map_err(|e| { - ShellError::Generic(GenericError::new_internal( - format!("error acquiring cache lock: {e}"), - "", - )) - }) + fn lock(&self) -> Result>, LabeledError> { + self.inner + .lock() + .map_err(|e| LabeledError::new(format!("error acquiring cache lock: {e}"))) } + /// Inserts an item into the plugin cache, disabling plugin GC while + /// any live values exist. pub fn insert( &self, engine: impl EngineWrapper, id: Uuid, - df: DataFrame, - _span: Span, - ) -> Result<(), ShellError> { + value: NuDataFusionObject, + span: Span, + ) -> Result, LabeledError> { let mut lock = self.lock()?; + trace!("DataFusion plugin: inserting {id} into cache: {value:?}"); engine.set_gc_disabled(true).map_err(LabeledError::from)?; - lock.insert( + let entry = CacheEntry { id, - CacheEntry { - df, - reference_count: 1, - }, - ); - Ok(()) + value, + created: SystemTime::now().into(), + span, + reference_count: 1, + }; + Ok(lock.insert(id, entry)) } - pub fn get(&self, id: &Uuid) -> Result, ShellError> { - let lock = self.lock()?; - Ok(lock.get(id).map(|entry| entry.df.clone())) + /// Looks up a cache entry. + /// + /// * `increment` - Only pass `true` when handing an existing value back to + /// Nushell without minting a new id. Nushell will send a drop + /// notification for that copy too, so it needs its own reference. + pub fn get(&self, id: &Uuid, increment: bool) -> Result, LabeledError> { + let mut lock = self.lock()?; + Ok(lock.get_mut(id).map(|entry| { + if increment { + entry.reference_count += 1; + trace!( + "DataFusion plugin: incremented reference count for {id} to {}", + entry.reference_count + ); + } + entry.clone() + })) } + /// Removes an item from the plugin cache, re-enabling plugin GC once the + /// cache is empty. + /// + /// * `force` - Delete even if there are outstanding references pub fn remove( &self, engine: impl EngineWrapper, id: &Uuid, force: bool, - ) -> Result<(), ShellError> { + ) -> Result, LabeledError> { let mut lock = self.lock()?; let remaining = lock.get_mut(id).map(|entry| { entry.reference_count -= 1; entry.reference_count }); - if force || remaining.unwrap_or_default() < 1 { - lock.remove(id); - } + + let removed = if force || remaining.unwrap_or_default() < 1 { + let removed = lock.remove(id); + trace!("DataFusion plugin: removed {id} from cache: {removed:?}"); + removed + } else { + trace!("DataFusion plugin: decremented reference count for {id}"); + None + }; + if lock.is_empty() { + trace!("DataFusion plugin: cache is empty, enabling GC"); engine.set_gc_disabled(false).map_err(LabeledError::from)?; } - Ok(()) + Ok(removed) + } +} + +/// A value that can be stored in the plugin cache. +pub trait Cacheable: Sized + Clone { + fn cache_id(&self) -> &Uuid; + + fn to_cache_value(&self) -> NuDataFusionObject; + + fn from_cache_value(value: NuDataFusionObject) -> Result; + + fn cache( + self, + plugin: &DfPlugin, + engine: &EngineInterface, + span: Span, + ) -> Result { + plugin + .cache + .insert(engine, *self.cache_id(), self.to_cache_value(), span)?; + Ok(self) + } + + fn get_cached(plugin: &DfPlugin, id: &Uuid) -> Result, LabeledError> { + plugin + .cache + .get(id, false)? + .map(|entry| Self::from_cache_value(entry.value)) + .transpose() + } +} + +#[cfg(test)] +mod tests { + use std::cell::Cell; + + use datafusion::prelude::SessionContext; + use nu_protocol::ShellError; + + use super::*; + use crate::values::NuDataFrame; + + struct MockEngine { + gc_enabled: Cell, + } + + impl MockEngine { + fn new() -> Self { + Self { + gc_enabled: Cell::new(true), + } + } + } + + impl EngineWrapper for &MockEngine { + fn set_gc_disabled(&self, disabled: bool) -> Result<(), ShellError> { + self.gc_enabled.set(!disabled); + Ok(()) + } + } + + fn test_object() -> NuDataFusionObject { + let df = SessionContext::new() + .read_empty() + .expect("should create empty dataframe"); + NuDataFusionObject::DataFrame(NuDataFrame::new(df)) + } + + fn insert(cache: &Cache, engine: &MockEngine) -> Uuid { + let id = Uuid::new_v4(); + cache + .insert(engine, id, test_object(), Span::test_data()) + .expect("should insert"); + id + } + + #[test] + fn gc_disabled_until_cache_empty() { + let engine = MockEngine::new(); + let cache = Cache::default(); + let a = insert(&cache, &engine); + let b = insert(&cache, &engine); + assert!(!engine.gc_enabled.get()); + + cache.remove(&engine, &a, false).expect("should remove a"); + assert!(!engine.gc_enabled.get()); + + cache.remove(&engine, &b, false).expect("should remove b"); + assert!(engine.gc_enabled.get()); + } + + #[test] + fn get_without_increment_does_not_leak() { + let engine = MockEngine::new(); + let cache = Cache::default(); + let id = insert(&cache, &engine); + + for _ in 0..3 { + cache.get(&id, false).expect("should get"); + } + + let removed = cache.remove(&engine, &id, false).expect("should remove"); + assert!(removed.is_some()); + assert!(cache.get(&id, false).expect("should get").is_none()); + } + + #[test] + fn get_with_increment_needs_extra_remove() { + let engine = MockEngine::new(); + let cache = Cache::default(); + let id = insert(&cache, &engine); + + let entry = cache.get(&id, true).expect("should get").expect("exists"); + assert_eq!(entry.reference_count, 2); + + assert!(cache.remove(&engine, &id, false).expect("ok").is_none()); + assert!(cache.remove(&engine, &id, false).expect("ok").is_some()); + } + + #[test] + fn force_remove_ignores_references() { + let engine = MockEngine::new(); + let cache = Cache::default(); + let id = insert(&cache, &engine); + cache.get(&id, true).expect("should get"); + + assert!(cache.remove(&engine, &id, true).expect("ok").is_some()); + assert!(engine.gc_enabled.get()); } } diff --git a/src/commands/aggregate.rs b/src/commands/aggregate.rs index 6b88ab7..f5fde72 100644 --- a/src/commands/aggregate.rs +++ b/src/commands/aggregate.rs @@ -7,7 +7,7 @@ use crate::error::from_datafusion; use crate::expr::parse_sql_expr; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{cache_and_value, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Aggregate; @@ -36,8 +36,11 @@ impl PluginCommand for Aggregate { "SQL aggregates, e.g. [\"sum(amount) as total\" \"count(*) as n\"]", Some('a'), ) - .input_output_type(dataframe_type(), dataframe_type()) - .input_output_type(Type::table(), dataframe_type()) + .input_output_type( + NuDataFusionType::DataFrame.nu_type(), + NuDataFusionType::DataFrame.nu_type(), + ) + .input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -69,7 +72,7 @@ impl PluginCommand for Aggregate { .aggregate(group_expr, agg_expr) .map_err(|e| from_datafusion(e, span))?; Ok(PipelineData::value( - cache_and_value(plugin, engine, out, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/cast.rs b/src/commands/cast.rs index d185c45..30fd1fd 100644 --- a/src/commands/cast.rs +++ b/src/commands/cast.rs @@ -7,7 +7,7 @@ use crate::convert::parse_arrow_type; use crate::error::{from_datafusion, shell}; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{cache_and_value, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Cast; @@ -26,8 +26,11 @@ impl PluginCommand for Cast { Signature::build(self.name()) .required("column", SyntaxShape::String, "Column to cast") .required("type", SyntaxShape::String, "Arrow type name") - .input_output_type(dataframe_type(), dataframe_type()) - .input_output_type(Type::table(), dataframe_type()) + .input_output_type( + NuDataFusionType::DataFrame.nu_type(), + NuDataFusionType::DataFrame.nu_type(), + ) + .input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -62,7 +65,7 @@ impl PluginCommand for Cast { .with_column(&column, expr) .map_err(|e| from_datafusion(e, span))?; Ok(PipelineData::value( - cache_and_value(plugin, engine, out, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/collect.rs b/src/commands/collect.rs index 82528c7..ab1cc58 100644 --- a/src/commands/collect.rs +++ b/src/commands/collect.rs @@ -8,7 +8,7 @@ use crate::commands::category; use crate::convert::collect_to_nu; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{COLLECT_DEFAULT, dataframe_type}; +use crate::values::{COLLECT_DEFAULT, NuDataFusionType}; pub struct Collect; @@ -40,7 +40,7 @@ impl PluginCommand for Collect { "Collect every row (can lock up the shell)", Some('a'), ) - .input_output_type(dataframe_type(), Type::table()) + .input_output_type(NuDataFusionType::DataFrame.nu_type(), Type::table()) .input_output_type(Type::table(), Type::table()) .category(category()) } diff --git a/src/commands/count.rs b/src/commands/count.rs index 00a7e1d..116a214 100644 --- a/src/commands/count.rs +++ b/src/commands/count.rs @@ -4,7 +4,7 @@ use nu_protocol::{Example, LabeledError, PipelineData, Signature, Type, Value}; use crate::commands::category; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::dataframe_type; +use crate::values::NuDataFusionType; pub struct Count; @@ -21,7 +21,7 @@ impl PluginCommand for Count { fn signature(&self) -> Signature { Signature::build(self.name()) - .input_output_type(dataframe_type(), Type::Int) + .input_output_type(NuDataFusionType::DataFrame.nu_type(), Type::Int) .input_output_type(Type::table(), Type::Int) .category(category()) } diff --git a/src/commands/describe.rs b/src/commands/describe.rs index fa566af..0011e03 100644 --- a/src/commands/describe.rs +++ b/src/commands/describe.rs @@ -5,7 +5,7 @@ use crate::commands::category; use crate::convert::collect_to_nu; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::dataframe_type; +use crate::values::NuDataFusionType; pub struct Describe; @@ -22,7 +22,7 @@ impl PluginCommand for Describe { fn signature(&self) -> Signature { Signature::build(self.name()) - .input_output_type(dataframe_type(), Type::table()) + .input_output_type(NuDataFusionType::DataFrame.nu_type(), Type::table()) .input_output_type(Type::table(), Type::table()) .category(category()) } diff --git a/src/commands/distinct.rs b/src/commands/distinct.rs index 482d91a..c6f9b36 100644 --- a/src/commands/distinct.rs +++ b/src/commands/distinct.rs @@ -6,7 +6,7 @@ use crate::commands::category; use crate::error::from_datafusion; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{cache_and_value, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Distinct; @@ -28,8 +28,11 @@ impl PluginCommand for Distinct { SyntaxShape::String, "Columns that define uniqueness (default: all)", ) - .input_output_type(dataframe_type(), dataframe_type()) - .input_output_type(Type::table(), dataframe_type()) + .input_output_type( + NuDataFusionType::DataFrame.nu_type(), + NuDataFusionType::DataFrame.nu_type(), + ) + .input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -59,7 +62,7 @@ impl PluginCommand for Distinct { .map_err(|e| from_datafusion(e, span))? }; Ok(PipelineData::value( - cache_and_value(plugin, engine, out, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/drop.rs b/src/commands/drop.rs index 9fd2925..e9cf1bd 100644 --- a/src/commands/drop.rs +++ b/src/commands/drop.rs @@ -5,7 +5,7 @@ use crate::commands::category; use crate::error::from_datafusion; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{cache_and_value, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct DropCols; @@ -23,8 +23,11 @@ impl PluginCommand for DropCols { fn signature(&self) -> Signature { Signature::build(self.name()) .rest("columns", SyntaxShape::String, "Column names to drop") - .input_output_type(dataframe_type(), dataframe_type()) - .input_output_type(Type::table(), dataframe_type()) + .input_output_type( + NuDataFusionType::DataFrame.nu_type(), + NuDataFusionType::DataFrame.nu_type(), + ) + .input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -50,7 +53,7 @@ impl PluginCommand for DropCols { .drop_columns(&cols) .map_err(|e| from_datafusion(e, span))?; Ok(PipelineData::value( - cache_and_value(plugin, engine, out, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/explain.rs b/src/commands/explain.rs index 57594f8..1203d01 100644 --- a/src/commands/explain.rs +++ b/src/commands/explain.rs @@ -6,7 +6,7 @@ use crate::convert::collect_to_nu; use crate::error::from_datafusion; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::dataframe_type; +use crate::values::NuDataFusionType; pub struct Explain; @@ -25,7 +25,7 @@ impl PluginCommand for Explain { Signature::build(self.name()) .switch("verbose", "Verbose plan", Some('v')) .switch("analyze", "Execute the plan and include metrics", Some('a')) - .input_output_type(dataframe_type(), Type::table()) + .input_output_type(NuDataFusionType::DataFrame.nu_type(), Type::table()) .input_output_type(Type::table(), Type::table()) .category(category()) } diff --git a/src/commands/filter.rs b/src/commands/filter.rs index 543b843..bc0a40e 100644 --- a/src/commands/filter.rs +++ b/src/commands/filter.rs @@ -6,7 +6,7 @@ use crate::error::from_datafusion; use crate::expr::parse_sql_expr; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{cache_and_value, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Filter; @@ -28,8 +28,11 @@ impl PluginCommand for Filter { SyntaxShape::String, "SQL boolean expression, e.g. \"amount > 1000\"", ) - .input_output_type(dataframe_type(), dataframe_type()) - .input_output_type(Type::table(), dataframe_type()) + .input_output_type( + NuDataFusionType::DataFrame.nu_type(), + NuDataFusionType::DataFrame.nu_type(), + ) + .input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -54,7 +57,7 @@ impl PluginCommand for Filter { let expr = parse_sql_expr(&df, &predicate, span)?; let out = df.filter(expr).map_err(|e| from_datafusion(e, span))?; Ok(PipelineData::value( - cache_and_value(plugin, engine, out, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/from_nu.rs b/src/commands/from_nu.rs index bebccca..ca84f71 100644 --- a/src/commands/from_nu.rs +++ b/src/commands/from_nu.rs @@ -4,7 +4,7 @@ use nu_protocol::{Example, LabeledError, PipelineData, Signature, Type}; use crate::commands::category; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{cache_and_value, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct FromNu; @@ -25,7 +25,7 @@ impl PluginCommand for FromNu { fn signature(&self) -> Signature { Signature::build(self.name()) - .input_output_type(Type::Any, dataframe_type()) + .input_output_type(Type::Any, NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -47,7 +47,7 @@ impl PluginCommand for FromNu { let span = call.head; let df = resolve_df(plugin, input, span)?; Ok(PipelineData::value( - cache_and_value(plugin, engine, df, span)?, + NuDataFrame::new(df).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/join.rs b/src/commands/join.rs index 82802a4..e44d900 100644 --- a/src/commands/join.rs +++ b/src/commands/join.rs @@ -1,4 +1,5 @@ -use datafusion::prelude::JoinType; +use datafusion::common::Column; +use datafusion::prelude::{DataFrame, Expr, JoinType, coalesce, col}; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Example, LabeledError, PipelineData, Signature, SyntaxShape, Type, Value}; @@ -6,7 +7,7 @@ use crate::commands::category; use crate::error::{from_datafusion, shell}; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{cache_and_value, dataframe_from_custom, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Join; @@ -46,14 +47,23 @@ impl PluginCommand for Join { "Right join key(s)", None, ) + .named( + "suffix", + SyntaxShape::String, + "Suffix for right-side columns whose names clash with the left (default _x)", + Some('s'), + ) .named( "type", SyntaxShape::String, "inner, left, right, full, semi, anti (default inner)", Some('t'), ) - .input_output_type(dataframe_type(), dataframe_type()) - .input_output_type(Type::table(), dataframe_type()) + .input_output_type( + NuDataFusionType::DataFrame.nu_type(), + NuDataFusionType::DataFrame.nu_type(), + ) + .input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -76,7 +86,7 @@ impl PluginCommand for Join { let left = resolve_df(plugin, input, span)?; let right_val: Value = call.req(0)?; let right = match &right_val { - Value::Custom { .. } => dataframe_from_custom(&plugin.cache, &right_val, span)?, + Value::Custom { .. } => NuDataFrame::try_from_value(plugin, &right_val)?.into_df(), Value::String { val, .. } => plugin.block_on(plugin.ctx.table(val.as_str()), span)?, _ => { return Err(shell( @@ -89,18 +99,108 @@ impl PluginCommand for Join { }; let join_type = parse_join_type(call.get_flag::("type")?.as_deref(), span)?; let (left_on, right_on) = join_keys(call, span)?; - let left_refs: Vec<&str> = left_on.iter().map(String::as_str).collect(); - let right_refs: Vec<&str> = right_on.iter().map(String::as_str).collect(); - let out = left - .join(right, join_type, &left_refs, &right_refs, None) + let suffix = call + .get_flag::("suffix")? + .unwrap_or_else(|| "_x".into()); + let out = join_dataframes(left, right, join_type, &left_on, &right_on, &suffix) .map_err(|e| from_datafusion(e, span))?; Ok(PipelineData::value( - cache_and_value(plugin, engine, out, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } } +const LEFT: &str = "left"; +const RIGHT: &str = "right"; + +/// Joins two dataframes and returns a result with unique column names. +/// +/// Dataframes built in memory are all scanned under DataFusion's placeholder +/// table name, so each side gets its own alias. Otherwise a shared column such +/// as `id` becomes a duplicate qualified field and the join fails. +/// +/// The output then follows the polars plugin's conventions: +/// * A right key with the same name as its left key is dropped. For right and +/// full joins, the remaining key is `coalesce(left, right)`, so rows that +/// exist only on the right keep their key. +/// * Other right columns that clash with a left column get `suffix`. +fn join_dataframes( + left: DataFrame, + right: DataFrame, + join_type: JoinType, + left_on: &[String], + right_on: &[String], + suffix: &str, +) -> datafusion::error::Result { + let left = left.alias(LEFT)?; + let right = right.alias(RIGHT)?; + + let left_names: Vec = left + .schema() + .fields() + .iter() + .map(|f| f.name().clone()) + .collect(); + let right_names: Vec = right + .schema() + .fields() + .iter() + .map(|f| f.name().clone()) + .collect(); + + let left_col = |name: &str| col(Column::new(Some(LEFT), name)); + let right_col = |name: &str| col(Column::new(Some(RIGHT), name)); + + let on: Vec = left_on + .iter() + .zip(right_on) + .map(|(l, r)| left_col(l).eq(right_col(r))) + .collect(); + let joined = left.join_on(right, join_type, on)?; + + // Semi and anti joins only produce left-side columns. + if !matches!( + join_type, + JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full + ) { + return Ok(joined); + } + + let is_shared_key = |name: &str| { + left_on + .iter() + .zip(right_on) + .any(|(l, r)| l == name && r == name) + }; + let coalesce_keys = matches!(join_type, JoinType::Right | JoinType::Full); + + let mut projection: Vec = left_names + .iter() + .map(|name| { + if coalesce_keys && is_shared_key(name) { + coalesce(vec![left_col(name), right_col(name)]).alias(name) + } else { + left_col(name).alias(name) + } + }) + .collect(); + + for name in &right_names { + if is_shared_key(name) { + continue; + } + let expr = right_col(name); + projection.push(if left_names.contains(name) { + expr.alias(format!("{name}{suffix}")) + } else { + expr.alias(name) + }); + } + + joined.select(projection) +} + fn parse_join_type( name: Option<&str>, span: nu_protocol::Span, @@ -146,3 +246,95 @@ fn join_keys( )), } } + +#[cfg(test)] +mod tests { + use datafusion::arrow::array::{Int64Array, RecordBatch, StringArray}; + use datafusion::arrow::datatypes::{DataType, Field, Schema}; + use datafusion::prelude::SessionContext; + use std::sync::Arc; + + use super::*; + + fn df(ctx: &SessionContext, xs: Vec, ys: Vec<&str>) -> DataFrame { + let schema = Arc::new(Schema::new(vec![ + Field::new("x", DataType::Int64, false), + Field::new("y", DataType::Utf8, false), + ])); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(Int64Array::from(xs)), + Arc::new(StringArray::from(ys)), + ], + ) + .expect("valid batch"); + ctx.read_batch(batch).expect("readable batch") + } + + fn names(df: &DataFrame) -> Vec { + df.schema() + .fields() + .iter() + .map(|f| f.name().clone()) + .collect() + } + + async fn row_count(df: DataFrame) -> usize { + df.collect() + .await + .expect("collects") + .iter() + .map(RecordBatch::num_rows) + .sum() + } + + fn keys(k: &str) -> Vec { + vec![k.to_string()] + } + + #[tokio::test] + async fn shared_column_names_do_not_conflict() { + let ctx = SessionContext::new(); + let left = df(&ctx, vec![1, 2], vec!["a", "b"]); + let right = df(&ctx, vec![1, 3], vec!["c", "d"]); + let out = join_dataframes(left, right, JoinType::Inner, &keys("x"), &keys("x"), "_x") + .expect("join plans"); + assert_eq!(names(&out), ["x", "y", "y_x"]); + assert_eq!(row_count(out).await, 1); + } + + #[tokio::test] + async fn self_join() { + let ctx = SessionContext::new(); + let a = df(&ctx, vec![1, 2], vec!["a", "b"]); + let out = join_dataframes(a.clone(), a, JoinType::Inner, &keys("x"), &keys("x"), "_r") + .expect("join plans"); + assert_eq!(names(&out), ["x", "y", "y_r"]); + assert_eq!(row_count(out).await, 2); + } + + #[tokio::test] + async fn full_join_coalesces_shared_key() { + let ctx = SessionContext::new(); + let left = df(&ctx, vec![1], vec!["a"]); + let right = df(&ctx, vec![2], vec!["b"]); + let out = join_dataframes(left, right, JoinType::Full, &keys("x"), &keys("x"), "_x") + .expect("join plans"); + let batches = out.collect().await.expect("collects"); + let mut xs: Vec = batches + .iter() + .flat_map(|b| { + b.column(0) + .as_any() + .downcast_ref::() + .expect("int column") + .iter() + .map(|v| v.expect("key is never null")) + .collect::>() + }) + .collect(); + xs.sort(); + assert_eq!(xs, [1, 2]); + } +} diff --git a/src/commands/limit.rs b/src/commands/limit.rs index c6cdf43..9d5fa42 100644 --- a/src/commands/limit.rs +++ b/src/commands/limit.rs @@ -5,7 +5,7 @@ use crate::commands::category; use crate::error::from_datafusion; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{cache_and_value, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Limit; @@ -24,8 +24,11 @@ impl PluginCommand for Limit { Signature::build(self.name()) .required("n", SyntaxShape::Int, "Number of rows to keep") .named("skip", SyntaxShape::Int, "Rows to skip first", Some('s')) - .input_output_type(dataframe_type(), dataframe_type()) - .input_output_type(Type::table(), dataframe_type()) + .input_output_type( + NuDataFusionType::DataFrame.nu_type(), + NuDataFusionType::DataFrame.nu_type(), + ) + .input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -52,7 +55,7 @@ impl PluginCommand for Limit { .limit(skip as usize, Some(n as usize)) .map_err(|e| from_datafusion(e, span))?; Ok(PipelineData::value( - cache_and_value(plugin, engine, out, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/open.rs b/src/commands/open.rs index b7386ac..5206d0a 100644 --- a/src/commands/open.rs +++ b/src/commands/open.rs @@ -8,7 +8,7 @@ use crate::commands::category; use crate::error::shell; use crate::plugin::DfPlugin; use crate::session::register_table; -use crate::values::{cache_and_value, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Open; @@ -50,7 +50,7 @@ impl PluginCommand for Open { "CSV/JSON rows to infer schema (default 1000)", None, ) - .input_output_type(Type::Nothing, dataframe_type()) + .input_output_type(Type::Nothing, NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -85,7 +85,7 @@ impl PluginCommand for Open { )?; } Ok(PipelineData::value( - cache_and_value(plugin, engine, df, span)?, + NuDataFrame::new(df).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/register.rs b/src/commands/register.rs index a42f5e8..9fc55bb 100644 --- a/src/commands/register.rs +++ b/src/commands/register.rs @@ -5,7 +5,7 @@ use crate::commands::category; use crate::input::resolve_df; use crate::plugin::DfPlugin; use crate::session::register_table; -use crate::values::{cache_and_value, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Register; @@ -28,8 +28,11 @@ impl PluginCommand for Register { "Replace an existing table with this name", Some('f'), ) - .input_output_type(dataframe_type(), dataframe_type()) - .input_output_type(Type::table(), dataframe_type()) + .input_output_type( + NuDataFusionType::DataFrame.nu_type(), + NuDataFusionType::DataFrame.nu_type(), + ) + .input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -62,7 +65,7 @@ impl PluginCommand for Register { span, )?; Ok(PipelineData::value( - cache_and_value(plugin, engine, df, span)?, + NuDataFrame::new(df).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/rename.rs b/src/commands/rename.rs index 91fe57f..03719e7 100644 --- a/src/commands/rename.rs +++ b/src/commands/rename.rs @@ -5,7 +5,7 @@ use crate::commands::category; use crate::error::{from_datafusion, shell}; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{cache_and_value, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Rename; @@ -27,8 +27,11 @@ impl PluginCommand for Rename { SyntaxShape::Record(vec![].into()), "Record of old names to new names", ) - .input_output_type(dataframe_type(), dataframe_type()) - .input_output_type(Type::table(), dataframe_type()) + .input_output_type( + NuDataFusionType::DataFrame.nu_type(), + NuDataFusionType::DataFrame.nu_type(), + ) + .input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -61,7 +64,7 @@ impl PluginCommand for Rename { return Err(shell(span, "empty mapping", "pass at least one old: new pair").into()); } Ok(PipelineData::value( - cache_and_value(plugin, engine, df, span)?, + NuDataFrame::new(df).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/sample.rs b/src/commands/sample.rs index bc170bb..300c15d 100644 --- a/src/commands/sample.rs +++ b/src/commands/sample.rs @@ -10,7 +10,7 @@ use crate::convert::dataframe_from_batches; use crate::error::shell; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{cache_and_value, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Sample; @@ -33,8 +33,11 @@ impl PluginCommand for Sample { "Number of rows to sample (default 10)", Some('n'), ) - .input_output_type(dataframe_type(), dataframe_type()) - .input_output_type(Type::table(), dataframe_type()) + .input_output_type( + NuDataFusionType::DataFrame.nu_type(), + NuDataFusionType::DataFrame.nu_type(), + ) + .input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -62,7 +65,7 @@ impl PluginCommand for Sample { let sampled = plugin.block_on(sample_stream(df, n), span)?; let out = dataframe_from_batches(&plugin.ctx, sampled, span)?; Ok(PipelineData::value( - cache_and_value(plugin, engine, out, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/save.rs b/src/commands/save.rs index 4ab6428..9b0a153 100644 --- a/src/commands/save.rs +++ b/src/commands/save.rs @@ -12,7 +12,7 @@ use crate::commands::category; use crate::error::shell; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::dataframe_type; +use crate::values::NuDataFusionType; pub struct Save; @@ -37,7 +37,7 @@ impl PluginCommand for Save { Some('t'), ) .switch("force", "Overwrite an existing file", Some('f')) - .input_output_type(dataframe_type(), Type::Nothing) + .input_output_type(NuDataFusionType::DataFrame.nu_type(), Type::Nothing) .input_output_type(Type::table(), Type::Nothing) .category(category()) } diff --git a/src/commands/schema.rs b/src/commands/schema.rs index 7bc946b..298b346 100644 --- a/src/commands/schema.rs +++ b/src/commands/schema.rs @@ -7,7 +7,7 @@ use crate::commands::category; use crate::convert::schema_to_nu; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::dataframe_type; +use crate::values::NuDataFusionType; pub struct SchemaCmd; @@ -24,7 +24,7 @@ impl PluginCommand for SchemaCmd { fn signature(&self) -> Signature { Signature::build(self.name()) - .input_output_type(dataframe_type(), Type::table()) + .input_output_type(NuDataFusionType::DataFrame.nu_type(), Type::table()) .input_output_type(Type::table(), Type::table()) .category(category()) } diff --git a/src/commands/select.rs b/src/commands/select.rs index 9cc3ab7..da2d5c9 100644 --- a/src/commands/select.rs +++ b/src/commands/select.rs @@ -5,7 +5,7 @@ use crate::commands::category; use crate::error::from_datafusion; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{cache_and_value, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Select; @@ -27,8 +27,11 @@ impl PluginCommand for Select { SyntaxShape::String, "Column names or SQL expressions (\"a + 1 as b\")", ) - .input_output_type(dataframe_type(), dataframe_type()) - .input_output_type(Type::table(), dataframe_type()) + .input_output_type( + NuDataFusionType::DataFrame.nu_type(), + NuDataFusionType::DataFrame.nu_type(), + ) + .input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -55,7 +58,7 @@ impl PluginCommand for Select { .select_exprs(&refs) .map_err(|e| from_datafusion(e, span))?; Ok(PipelineData::value( - cache_and_value(plugin, engine, out, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/sort.rs b/src/commands/sort.rs index dfded37..32e1d46 100644 --- a/src/commands/sort.rs +++ b/src/commands/sort.rs @@ -6,7 +6,7 @@ use crate::commands::category; use crate::error::from_datafusion; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{cache_and_value, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Sort; @@ -26,8 +26,11 @@ impl PluginCommand for Sort { .rest("columns", SyntaxShape::String, "Columns to sort by") .switch("reverse", "Sort descending", Some('r')) .switch("nulls-last", "Place nulls last", None) - .input_output_type(dataframe_type(), dataframe_type()) - .input_output_type(Type::table(), dataframe_type()) + .input_output_type( + NuDataFusionType::DataFrame.nu_type(), + NuDataFusionType::DataFrame.nu_type(), + ) + .input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -57,7 +60,7 @@ impl PluginCommand for Sort { .collect(); let out = df.sort(exprs).map_err(|e| from_datafusion(e, span))?; Ok(PipelineData::value( - cache_and_value(plugin, engine, out, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/sql.rs b/src/commands/sql.rs index 7df11d9..5fe7f08 100644 --- a/src/commands/sql.rs +++ b/src/commands/sql.rs @@ -5,7 +5,7 @@ use crate::commands::category; use crate::input::resolve_df; use crate::plugin::DfPlugin; use crate::session::{ThisGuard, inject_from_this}; -use crate::values::{cache_and_value, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Sql; @@ -29,9 +29,12 @@ Registered tables (see `df tables`) are visible to every `df sql` call in this p fn signature(&self) -> Signature { Signature::build(self.name()) .required("query", SyntaxShape::String, "SQL query") - .input_output_type(dataframe_type(), dataframe_type()) - .input_output_type(Type::Nothing, dataframe_type()) - .input_output_type(Type::table(), dataframe_type()) + .input_output_type( + NuDataFusionType::DataFrame.nu_type(), + NuDataFusionType::DataFrame.nu_type(), + ) + .input_output_type(Type::Nothing, NuDataFusionType::DataFrame.nu_type()) + .input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -70,7 +73,7 @@ Registered tables (see `df tables`) are visible to every `df sql` call in this p } let out = result?; Ok(PipelineData::value( - cache_and_value(plugin, engine, out, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/union.rs b/src/commands/union.rs index 726164c..07a77b3 100644 --- a/src/commands/union.rs +++ b/src/commands/union.rs @@ -5,7 +5,7 @@ use crate::commands::category; use crate::error::{from_datafusion, shell}; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{cache_and_value, dataframe_from_custom, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Union; @@ -28,8 +28,11 @@ impl PluginCommand for Union { "Other dataframe handle or catalog table name", ) .switch("distinct", "Drop duplicate rows (SQL UNION)", Some('d')) - .input_output_type(dataframe_type(), dataframe_type()) - .input_output_type(Type::table(), dataframe_type()) + .input_output_type( + NuDataFusionType::DataFrame.nu_type(), + NuDataFusionType::DataFrame.nu_type(), + ) + .input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -52,7 +55,7 @@ impl PluginCommand for Union { let left = resolve_df(plugin, input, span)?; let other: Value = call.req(0)?; let right = match &other { - Value::Custom { .. } => dataframe_from_custom(&plugin.cache, &other, span)?, + Value::Custom { .. } => NuDataFrame::try_from_value(plugin, &other)?.into_df(), Value::String { val, .. } => plugin.block_on(plugin.ctx.table(val.as_str()), span)?, _ => { return Err(shell( @@ -70,7 +73,7 @@ impl PluginCommand for Union { } .map_err(|e| from_datafusion(e, span))?; Ok(PipelineData::value( - cache_and_value(plugin, engine, out, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/with_column.rs b/src/commands/with_column.rs index 7d1ea01..22ac68b 100644 --- a/src/commands/with_column.rs +++ b/src/commands/with_column.rs @@ -6,7 +6,7 @@ use crate::error::{from_datafusion, shell}; use crate::expr::parse_sql_expr; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{cache_and_value, dataframe_type}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct WithColumn; @@ -34,8 +34,11 @@ impl PluginCommand for WithColumn { "Column name if the expression has no alias", Some('a'), ) - .input_output_type(dataframe_type(), dataframe_type()) - .input_output_type(Type::table(), dataframe_type()) + .input_output_type( + NuDataFusionType::DataFrame.nu_type(), + NuDataFusionType::DataFrame.nu_type(), + ) + .input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type()) .category(category()) } @@ -63,7 +66,7 @@ impl PluginCommand for WithColumn { .with_column(&name, expr) .map_err(|e| from_datafusion(e, span))?; Ok(PipelineData::value( - cache_and_value(plugin, engine, out, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/input.rs b/src/input.rs index abe1118..3395a13 100644 --- a/src/input.rs +++ b/src/input.rs @@ -4,7 +4,7 @@ use nu_protocol::{PipelineData, ShellError, Span, Value}; use crate::convert::values_to_dataframe; use crate::error::shell; use crate::plugin::DfPlugin; -use crate::values::dataframe_from_custom; +use crate::values::{CustomValueSupport, NuDataFrame}; /// Resolve pipeline input to a DataFrame. /// Custom dataframe handles are loaded from the cache. @@ -30,7 +30,7 @@ pub fn resolve_df( pub fn resolve_value(plugin: &DfPlugin, value: Value, span: Span) -> Result { match &value { - Value::Custom { .. } => dataframe_from_custom(&plugin.cache, &value, span), + Value::Custom { .. } => Ok(NuDataFrame::try_from_value(plugin, &value)?.into_df()), _ => values_to_dataframe(&plugin.ctx, value, span), } } diff --git a/src/plugin.rs b/src/plugin.rs index b396d1b..20d73d3 100644 --- a/src/plugin.rs +++ b/src/plugin.rs @@ -9,10 +9,9 @@ use tokio::runtime::Runtime; use crate::cache::Cache; use crate::commands; -use crate::convert::collect_to_nu; use crate::error::from_datafusion; use crate::session::Catalog; -use crate::values::{PREVIEW_ROWS, id_from_custom_box}; +use crate::values::CustomValueType; pub trait EngineWrapper { fn set_gc_disabled(&self, disabled: bool) -> Result<(), ShellError>; @@ -81,25 +80,8 @@ impl Plugin for DfPlugin { custom_value: Spanned>, ) -> Result { let span = custom_value.span; - let id = id_from_custom_box(custom_value.item.as_ref()).ok_or_else(|| { - LabeledError::from(crate::error::shell( - span, - "not a dataframe", - custom_value.item.type_name(), - )) - })?; - let df = self.cache.get(&id)?.ok_or_else(|| { - LabeledError::from(crate::error::shell( - span, - "stale dataframe handle", - "this dataframe is no longer in the plugin cache", - )) - })?; - let preview = df - .limit(0, Some(PREVIEW_ROWS)) - .map_err(|e| from_datafusion(e, span))?; - let (value, _) = collect_to_nu(self, preview, span, Some(PREVIEW_ROWS))?; - Ok(value) + CustomValueType::try_from_custom_value(custom_value.item.as_ref(), span)? + .custom_value_to_base_value(self, span) } fn custom_value_dropped( @@ -110,9 +92,9 @@ impl Plugin for DfPlugin { if self.disable_cache_drop { return Ok(()); } - if let Some(id) = id_from_custom_box(custom_value.as_ref()) { - self.cache.remove(engine, &id, false)?; - } + let id = + CustomValueType::try_from_custom_value(custom_value.as_ref(), Span::unknown())?.id(); + self.cache.remove(engine, &id, false)?; Ok(()) } } diff --git a/src/values/dataframe.rs b/src/values/dataframe.rs index 39ad6ee..1751785 100644 --- a/src/values/dataframe.rs +++ b/src/values/dataframe.rs @@ -1,16 +1,88 @@ -use nu_protocol::{CustomValue, ShellError, Span, Type, Value}; +use std::sync::Arc; + +use datafusion::dataframe::DataFrame; +use nu_protocol::{CustomValue, LabeledError, ShellError, Span, Value}; use serde::{Deserialize, Serialize}; use uuid::Uuid; -use super::TYPE_NAME; +use crate::cache::Cacheable; +use crate::convert::collect_to_nu; +use crate::error::from_datafusion; +use crate::plugin::DfPlugin; +use crate::values::{ + CustomValueSupport, NuDataFusionCustomValue, NuDataFusionObject, NuDataFusionType, PREVIEW_ROWS, +}; + +#[derive(Debug, Clone)] +pub struct NuDataFrame { + pub id: Uuid, + pub inner: Arc, +} + +impl NuDataFrame { + pub fn new(df: DataFrame) -> Self { + Self { + id: Uuid::new_v4(), + inner: Arc::new(df), + } + } + + /// Take the underlying DataFrame, cloning it only if the Arc is shared. + pub fn into_df(self) -> DataFrame { + Arc::unwrap_or_clone(self.inner) + } +} #[derive(Debug, Clone, Deserialize, Serialize)] pub struct NuDataFrameCustomValue { pub id: Uuid, } -pub fn dataframe_type() -> Type { - Type::Custom(TYPE_NAME.into()) +impl Cacheable for NuDataFrame { + fn cache_id(&self) -> &Uuid { + &self.id + } + + fn to_cache_value(&self) -> NuDataFusionObject { + NuDataFusionObject::DataFrame(self.clone()) + } + + fn from_cache_value(value: NuDataFusionObject) -> Result { + match value { + NuDataFusionObject::DataFrame(df) => Ok(df), + // Add once NuDataFusionObject has more variants: + // other => Err(LabeledError::new(format!("cache value is not a dataframe: {other:?}"))), + } + } +} + +impl CustomValueSupport for NuDataFrame { + type CV = NuDataFrameCustomValue; + + fn get_type_static() -> NuDataFusionType { + NuDataFusionType::DataFrame + } + + fn custom_value(self) -> Self::CV { + NuDataFrameCustomValue { id: self.id } + } + + fn base_value(self, plugin: &DfPlugin, span: Span) -> Result { + let preview = self + .into_df() + .limit(0, Some(PREVIEW_ROWS)) + .map_err(|e| from_datafusion(e, span))?; + let (value, _) = collect_to_nu(plugin, preview, span, Some(PREVIEW_ROWS))?; + Ok(value) + } +} + +impl NuDataFusionCustomValue for NuDataFrameCustomValue { + type ObjectType = NuDataFrame; + + fn id(&self) -> &Uuid { + &self.id + } } #[typetag::serde] @@ -20,7 +92,7 @@ impl CustomValue for NuDataFrameCustomValue { } fn type_name(&self) -> String { - TYPE_NAME.to_string() + NuDataFusionType::DataFrame.name().to_string() } fn to_base_value(&self, span: Span) -> Result { diff --git a/src/values/mod.rs b/src/values/mod.rs index 033cb8d..bc3fc07 100644 --- a/src/values/mod.rs +++ b/src/values/mod.rs @@ -1,68 +1,142 @@ mod dataframe; -pub use dataframe::{NuDataFrameCustomValue, dataframe_type}; +pub use dataframe::{NuDataFrame, NuDataFrameCustomValue}; -use datafusion::prelude::DataFrame; use nu_plugin::EngineInterface; -use nu_protocol::{CustomValue, ShellError, Span, Value}; +use nu_protocol::{CustomValue, LabeledError, Span, Type, Value}; use uuid::Uuid; -use crate::cache::Cache; -use crate::error::shell; +use crate::cache::Cacheable; use crate::plugin::DfPlugin; -pub const TYPE_NAME: &str = "datafusion_dataframe"; pub const PREVIEW_ROWS: usize = 20; pub const COLLECT_DEFAULT: usize = 10_000; -pub fn cache_and_value( - plugin: &DfPlugin, - engine: &EngineInterface, - df: DataFrame, - span: Span, -) -> Result { - let id = Uuid::new_v4(); - plugin.cache.insert(engine, id, df, span)?; - Ok(Value::custom(Box::new(NuDataFrameCustomValue { id }), span)) +pub enum NuDataFusionType { + DataFrame, } -pub fn dataframe_from_custom( - cache: &Cache, - value: &Value, - span: Span, -) -> Result { - let custom = match value { - Value::Custom { val, .. } => val, - _ => { - return Err(shell( - span, - "expected dataframe", - format!("found {}", value.get_type()), - )); +impl NuDataFusionType { + pub fn name(&self) -> &'static str { + match self { + NuDataFusionType::DataFrame => "datafusion_dataframe", } - }; - let handle = custom - .as_any() - .downcast_ref::() - .ok_or_else(|| { - shell( - span, - "expected dataframe", - format!("found custom value '{}'", custom.type_name()), - ) - })?; - cache.get(&handle.id)?.ok_or_else(|| { - shell( - span, - "stale dataframe handle", - "this dataframe is no longer in the plugin cache", + } + + pub fn nu_type(&self) -> Type { + Type::Custom(self.name().into()) + } +} + +/// Every kind of object the plugin can hold in its cache. +#[derive(Debug, Clone)] +pub enum NuDataFusionObject { + DataFrame(NuDataFrame), +} + +/// Plugin-side object that is handed to Nushell as a custom value. +/// +/// Implementors provide the cache plumbing (via [`Cacheable`]) plus the +/// mapping to their custom value type; lookup, caching and conversion to +/// a Nushell [`Value`] are provided. +pub trait CustomValueSupport: Cacheable { + type CV: NuDataFusionCustomValue + 'static; + + fn get_type_static() -> NuDataFusionType; + + fn custom_value(self) -> Self::CV; + + /// The plain Nushell value shown when the custom value is displayed. + fn base_value(self, plugin: &DfPlugin, span: Span) -> Result; + + fn into_value(self, span: Span) -> Value { + Value::custom(Box::new(self.custom_value()), span) + } + + fn try_from_custom_value( + plugin: &DfPlugin, + cv: &Self::CV, + span: Span, + ) -> Result { + Self::get_cached(plugin, cv.id())?.ok_or_else(|| { + LabeledError::new(format!("stale {} handle", Self::get_type_static().name())) + .with_label("this value is no longer in the plugin cache", span) + }) + } + + fn try_from_value(plugin: &DfPlugin, value: &Value) -> Result { + let span = value.span(); + let expected = Self::get_type_static().name(); + let found = match value { + Value::Custom { val, .. } => match val.as_any().downcast_ref::() { + Some(cv) => return Self::try_from_custom_value(plugin, cv, span), + None => format!("custom value '{}'", val.type_name()), + }, + _ => value.get_type().to_string(), + }; + Err( + LabeledError::new(format!("expected {expected}, found {found}")) + .with_label(format!("expected {expected}"), span), ) - }) + } + + /// Caches the object and returns the custom value that refers to it. + fn cache_and_to_value( + self, + plugin: &DfPlugin, + engine: &EngineInterface, + span: Span, + ) -> Result { + Ok(self.cache(plugin, engine, span)?.into_value(span)) + } } -pub fn id_from_custom_box(custom: &dyn CustomValue) -> Option { - custom - .as_any() - .downcast_ref::() - .map(|v| v.id) +/// The custom value Nushell holds: a handle into the plugin cache. +pub trait NuDataFusionCustomValue: CustomValue { + type ObjectType: CustomValueSupport; + + fn id(&self) -> &Uuid; + + fn custom_value_to_base_value( + &self, + plugin: &DfPlugin, + span: Span, + ) -> Result { + Self::ObjectType::try_from_custom_value(plugin, self, span)?.base_value(plugin, span) + } +} + +/// Dispatches plugin-level custom value hooks to the concrete type. +pub enum CustomValueType { + DataFrame(NuDataFrameCustomValue), +} + +impl CustomValueType { + pub fn try_from_custom_value(val: &dyn CustomValue, span: Span) -> Result { + let any = val.as_any(); + if let Some(cv) = any.downcast_ref::() { + Ok(Self::DataFrame(cv.clone())) + } else { + Err( + LabeledError::new(format!("unsupported custom value '{}'", val.type_name())) + .with_label("not a DataFusion plugin value", span), + ) + } + } + + pub fn id(&self) -> Uuid { + match self { + Self::DataFrame(cv) => cv.id, + } + } + + pub fn custom_value_to_base_value( + &self, + plugin: &DfPlugin, + span: Span, + ) -> Result { + match self { + Self::DataFrame(cv) => cv.custom_value_to_base_value(plugin, span), + } + } }