From a8226a56f2326dd4e6dd6bf7eae261f257664d37 Mon Sep 17 00:00:00 2001 From: Jack Wright Date: Thu, 3 Dec 2026 18:38:34 -0800 Subject: [PATCH 1/9] Set lto to thin --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 25b56d3..5b443aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,5 +56,5 @@ debug = 1 [profile.release] strip = true -lto = true +lto = "thin" codegen-units = 1 From 5ea64c2ecf8a4eb823ff615801915643bcfe5634 Mon Sep 17 00:00:00 2001 From: Jack Wright <56345+ayax79@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:14:54 -0800 Subject: [PATCH 2/9] flakehub publishing (#1) --- .github/dependabot.yml | 7 ++++++ .github/workflows/ci.yml | 36 +++++++++++++++++++++++++++++ .github/workflows/fh.yml | 29 +++++++++++++++++++++++ .github/workflows/flake-checker.yml | 24 +++++++++++++++++++ .github/workflows/lock-updater.yml | 29 +++++++++++++++++++++++ 5 files changed, 125 insertions(+) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/fh.yml create mode 100644 .github/workflows/flake-checker.yml create mode 100644 .github/workflows/lock-updater.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..d202a33 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,7 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + # Check for updates to GitHub Actions every week + interval: "weekly" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..6ecfb2b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,36 @@ +on: [push, pull_request] + +name: CI + +jobs: + check: + name: Rust project + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + # Installs the toolchain from rust-toolchain.toml + # (the "default" profile includes rustfmt and clippy) + - uses: actions-rust-lang/setup-rust-toolchain@v2 + + - name: Check formatting + run: cargo fmt --all --check + + - name: Run cargo check + run: cargo check + + - name: Run clippy + run: cargo clippy --all-targets -- -D warnings + + audit: + name: Security audit + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + - uses: taiki-e/install-action@v2 + with: + tool: cargo-audit + + - name: Run cargo audit + run: cargo audit diff --git a/.github/workflows/fh.yml b/.github/workflows/fh.yml new file mode 100644 index 0000000..da561b4 --- /dev/null +++ b/.github/workflows/fh.yml @@ -0,0 +1,29 @@ +name: Build 🏗️ and Cache ❄️ +on: + workflow_dispatch: + pull_request: + push: + branches: + - main + tags: + - "v?[0-9]+.[0-9]+.[0-9]+*" + paths-ignore: + - "**/README.md" + - "LICENSE" + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +env: + RUST_BACKTRACE: full + +jobs: + DeterminateCI: + name: Determinate CI 👷 + uses: DeterminateSystems/ci/.github/workflows/workflow.yml@main + permissions: + id-token: "write" + contents: "read" + with: + visibility: public diff --git a/.github/workflows/flake-checker.yml b/.github/workflows/flake-checker.yml new file mode 100644 index 0000000..56543e6 --- /dev/null +++ b/.github/workflows/flake-checker.yml @@ -0,0 +1,24 @@ +name: Flake ❄️ Checker ✅ + +on: + schedule: + # l33t o'clock + - cron: '37 13 * * *' + workflow_dispatch: + +jobs: + flake-checker: + name: Flake Checker + runs-on: ubuntu-22.04 + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + - uses: DeterminateSystems/nix-installer-action@main + with: + determinate: true + - uses: DeterminateSystems/flakehub-cache-action@main + - uses: DeterminateSystems/flake-checker-action@main diff --git a/.github/workflows/lock-updater.yml b/.github/workflows/lock-updater.yml new file mode 100644 index 0000000..c7ca9af --- /dev/null +++ b/.github/workflows/lock-updater.yml @@ -0,0 +1,29 @@ +name: Flake ❄️ Lock 🔒️ Updater ✨ + +on: + schedule: + # Pi o'clock + - cron: '3 14 * * 1,5' + workflow_dispatch: + +jobs: + lock-updater: + name: Flake Lock Updater + runs-on: ubuntu-22.04 + permissions: + contents: write + id-token: write + pull-requests: write + steps: + - uses: actions/checkout@v7 + - uses: DeterminateSystems/nix-installer-action@main + with: + determinate: true + - uses: DeterminateSystems/flakehub-cache-action@main + - uses: DeterminateSystems/update-flake-lock@main + with: + pr-title: "chore: update flake.lock" + # Labels to be set on the PR + pr-labels: | + dependencies + automated From e80659103141e8d244b1ff1512eec39cfb5ea5a2 Mon Sep 17 00:00:00 2001 From: Jack Wright Date: Fri, 4 Dec 2026 19:34:39 -0800 Subject: [PATCH 3/9] first stage of refactoring.. doesn't compile yet. --- src/cache.rs | 46 +++++++++++------- src/commands/select.rs | 4 +- src/values/dataframe.rs | 68 ++++++++++++++++++++++++-- src/values/mod.rs | 104 +++++++++++++++++++++------------------- 4 files changed, 148 insertions(+), 74 deletions(-) diff --git a/src/cache.rs b/src/cache.rs index f5a13f2..1b65fde 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -1,14 +1,15 @@ use std::collections::HashMap; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; -use datafusion::prelude::DataFrame; -use nu_protocol::{LabeledError, ShellError, Span, shell_error::generic::GenericError}; +use log::debug; +use nu_protocol::{LabeledError, ShellError, Span}; use uuid::Uuid; use crate::plugin::EngineWrapper; +use crate::values::NuDataFusionObject; pub struct CacheEntry { - pub df: DataFrame, + pub value: Arc, pub reference_count: i16, } @@ -18,37 +19,48 @@ 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}"))) } pub fn insert( &self, engine: impl EngineWrapper, id: Uuid, - df: DataFrame, + dfo: NuDataFusionObject, _span: Span, - ) -> Result<(), ShellError> { + ) -> Result<(), LabeledError> { let mut lock = self.lock()?; engine.set_gc_disabled(true).map_err(LabeledError::from)?; + + debug!( + "DataFusion plugin: Inserting cache entry with ID: {id} value: {:?}", + dfo + ); + lock.insert( id, CacheEntry { - df, + value: Arc::new(dfo), reference_count: 1, }, ); + Ok(()) } - pub fn get(&self, id: &Uuid) -> Result, ShellError> { - let lock = self.lock()?; - Ok(lock.get(id).map(|entry| entry.df.clone())) + pub fn get(&self, id: &Uuid) -> Result, LabeledError> { + let mut lock = self.lock()?; + Ok(lock.get_mut(id).map(|entry| { + debug!( + "DataFusion plugin: Incrementing reference count for cache entry with ID: {id} value: {:?}", + entry.value + ); + entry.reference_count += 1; + entry.value.as_ref().clone() + })) } pub fn remove( diff --git a/src/commands/select.rs b/src/commands/select.rs index 9cc3ab7..03cbd95 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::NuDataFusionType; pub struct Select; @@ -27,7 +27,7 @@ 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(NuDataFusionType::DataFrame.nu_type(), dataframe_type()) .input_output_type(Type::table(), dataframe_type()) .category(category()) } diff --git a/src/values/dataframe.rs b/src/values/dataframe.rs index 39ad6ee..fcc7478 100644 --- a/src/values/dataframe.rs +++ b/src/values/dataframe.rs @@ -1,16 +1,74 @@ -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::plugin::DfPlugin; +use crate::values::{NuDataFusionObject, NuDataFusionObjectSupport, NuDataFusionType}; + +#[derive(Debug, Clone)] +pub struct NuDataFrame { + pub id: Uuid, + pub inner: Arc, +} #[derive(Debug, Clone, Deserialize, Serialize)] pub struct NuDataFrameCustomValue { pub id: Uuid, } -pub fn dataframe_type() -> Type { - Type::Custom(TYPE_NAME.into()) +impl NuDataFusionObjectSupport for NuDataFrame { + type InnerType = DataFrame; + fn nu_datafusion_type(&self) -> NuDataFusionType { + NuDataFusionType::DataFrame + } + + fn nu_datafusion_object(&self) -> crate::values::NuDataFusionObject { + crate::values::NuDataFusionObject::DataFrame(self.clone()) + } + + fn custom_value(&self, span: Span) -> Value { + Value::custom(Box::new(NuDataFrameCustomValue { id: self.id }), span) + } + + fn inner(&self) -> &DataFrame { + self.inner.as_ref() + } + + fn id(&self) -> &Uuid { + &self.id + } + + fn from_value(plugin: &DfPlugin, value: &Value, span: Span) -> Result { + let id = match value { + Value::Custom { val, .. } => val + .as_any() + .downcast_ref::() + .map(|cv| cv.id) + .ok_or_else(|| { + LabeledError::new(format!( + "expected dataframe, found custom value '{}'", + val.type_name() + )) + .with_label("expected dataframe", span) + })?, + _ => { + return Err(LabeledError::new(format!( + "expected dataframe, found {}", + value.get_type() + )) + .with_label("expected dataframe", span)); + } + }; + + match plugin.cache.get(&id)? { + Some(NuDataFusionObject::DataFrame(df)) => Ok(df), + None => Err(LabeledError::new("stale dataframe handle") + .with_label("this dataframe is no longer in the plugin cache", span)), + } + } } #[typetag::serde] @@ -20,7 +78,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..0e598d8 100644 --- a/src/values/mod.rs +++ b/src/values/mod.rs @@ -1,68 +1,72 @@ mod dataframe; -pub use dataframe::{NuDataFrameCustomValue, dataframe_type}; +pub use dataframe::{NuDataFrame, dataframe_type}; use datafusion::prelude::DataFrame; use nu_plugin::EngineInterface; -use nu_protocol::{CustomValue, ShellError, Span, Value}; +use nu_protocol::{CustomValue, LabeledError, ShellError, Span, Type, Value}; use uuid::Uuid; -use crate::cache::Cache; -use crate::error::shell; 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 trait HasId { + fn id(&self) -> &Uuid; } -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()), - )); +pub enum NuDataFusionType { + DataFrame, +} + +impl NuDataFusionType { + pub fn name(&self) -> &'static str { + match self { + NuDataFusionType::DataFrame => "datafusion_dataframe", + } + } + + pub fn nu_type(&self) -> Type { + match self { + NuDataFusionType::DataFrame => Type::Custom(self.name().into()), } - }; - 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 id_from_custom_box(custom: &dyn CustomValue) -> Option { - custom - .as_any() - .downcast_ref::() - .map(|v| v.id) +#[derive(Debug, Clone)] +pub enum NuDataFusionObject { + DataFrame(NuDataFrame), +} + +impl NuDataFusionObject {} + +pub trait NuDataFusionObjectSupport { + type InnerType; + + fn id(&self) -> &Uuid; + + fn nu_datafusion_type(&self) -> NuDataFusionType; + + fn nu_datafusion_object(&self) -> NuDataFusionObject; + + fn custom_value(&self, span: Span) -> Value; + + fn inner(&self) -> &Self::InnerType; + + fn from_value(plugin: &DfPlugin, value: &Value, span: Span) -> Result + where + Self: Sized; + + fn cache_and_value( + &self, + plugin: &DfPlugin, + engine: &EngineInterface, + span: Span, + ) -> Result { + plugin + .cache + .insert(engine, *self.id(), self.nu_datafusion_object(), span)?; + Ok(self.custom_value(span)) + } } From 81f3d835ab465dfd9d4ae669acd442e7e787cb16 Mon Sep 17 00:00:00 2001 From: Jack Wright Date: Fri, 4 Dec 2026 19:38:37 -0800 Subject: [PATCH 4/9] Addressing refactoring errors --- src/commands/aggregate.rs | 8 ++++---- src/commands/cast.rs | 8 ++++---- src/commands/collect.rs | 4 ++-- src/commands/count.rs | 4 ++-- src/commands/describe.rs | 4 ++-- src/commands/distinct.rs | 8 ++++---- src/commands/drop.rs | 8 ++++---- src/commands/explain.rs | 4 ++-- src/commands/filter.rs | 8 ++++---- src/commands/from_nu.rs | 6 +++--- src/commands/join.rs | 10 +++++----- src/commands/limit.rs | 8 ++++---- src/commands/open.rs | 6 +++--- src/commands/register.rs | 8 ++++---- src/commands/rename.rs | 8 ++++---- src/commands/sample.rs | 8 ++++---- src/commands/save.rs | 4 ++-- src/commands/schema.rs | 4 ++-- src/commands/select.rs | 8 ++++---- src/commands/sort.rs | 8 ++++---- src/commands/sql.rs | 10 +++++----- src/commands/union.rs | 10 +++++----- src/commands/with_column.rs | 8 ++++---- src/input.rs | 4 ++-- src/plugin.rs | 4 +++- src/values/dataframe.rs | 14 ++++++++++++++ src/values/mod.rs | 13 ++++++++++--- 27 files changed, 110 insertions(+), 87 deletions(-) diff --git a/src/commands/aggregate.rs b/src/commands/aggregate.rs index 6b88ab7..639abd9 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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; pub struct Aggregate; @@ -36,8 +36,8 @@ 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 +69,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_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/cast.rs b/src/commands/cast.rs index d185c45..a71d77f 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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; pub struct Cast; @@ -26,8 +26,8 @@ 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 +62,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_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..29aa8b0 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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; pub struct Distinct; @@ -28,8 +28,8 @@ 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 +59,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_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/drop.rs b/src/commands/drop.rs index 9fd2925..1afbc04 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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; pub struct DropCols; @@ -23,8 +23,8 @@ 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 +50,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_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..c1e29db 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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; pub struct Filter; @@ -28,8 +28,8 @@ 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 +54,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_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/from_nu.rs b/src/commands/from_nu.rs index bebccca..e251ead 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::{NuDataFrame, NuDataFusionObjectSupport, 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_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/join.rs b/src/commands/join.rs index 82802a4..88e7836 100644 --- a/src/commands/join.rs +++ b/src/commands/join.rs @@ -6,7 +6,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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; pub struct Join; @@ -52,8 +52,8 @@ impl PluginCommand for Join { "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 +76,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::from_value(plugin, &right_val, span)?.into_df(), Value::String { val, .. } => plugin.block_on(plugin.ctx.table(val.as_str()), span)?, _ => { return Err(shell( @@ -95,7 +95,7 @@ impl PluginCommand for Join { .join(right, join_type, &left_refs, &right_refs, None) .map_err(|e| from_datafusion(e, span))?; Ok(PipelineData::value( - cache_and_value(plugin, engine, out, span)?, + NuDataFrame::new(out).cache_and_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/limit.rs b/src/commands/limit.rs index c6cdf43..ceb8b3f 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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; pub struct Limit; @@ -24,8 +24,8 @@ 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 +52,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_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/open.rs b/src/commands/open.rs index b7386ac..dea123e 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::{NuDataFrame, NuDataFusionObjectSupport, 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_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/register.rs b/src/commands/register.rs index a42f5e8..124ed4f 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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; pub struct Register; @@ -28,8 +28,8 @@ 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 +62,7 @@ impl PluginCommand for Register { span, )?; Ok(PipelineData::value( - cache_and_value(plugin, engine, df, span)?, + NuDataFrame::new(df).cache_and_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/rename.rs b/src/commands/rename.rs index 91fe57f..958f121 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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; pub struct Rename; @@ -27,8 +27,8 @@ 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 +61,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_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/sample.rs b/src/commands/sample.rs index bc170bb..2c50525 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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; pub struct Sample; @@ -33,8 +33,8 @@ 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 +62,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_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 03cbd95..793a683 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::NuDataFusionType; +use crate::values::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; pub struct Select; @@ -27,8 +27,8 @@ impl PluginCommand for Select { SyntaxShape::String, "Column names or SQL expressions (\"a + 1 as b\")", ) - .input_output_type(NuDataFusionType::DataFrame.nu_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 +55,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_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/sort.rs b/src/commands/sort.rs index dfded37..30cda97 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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; pub struct Sort; @@ -26,8 +26,8 @@ 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 +57,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_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/sql.rs b/src/commands/sql.rs index 7df11d9..68173ec 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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; pub struct Sql; @@ -29,9 +29,9 @@ 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 +70,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_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/union.rs b/src/commands/union.rs index 726164c..9a7e5ab 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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; pub struct Union; @@ -28,8 +28,8 @@ 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 +52,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::from_value(plugin, &other, span)?.into_df(), Value::String { val, .. } => plugin.block_on(plugin.ctx.table(val.as_str()), span)?, _ => { return Err(shell( @@ -70,7 +70,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_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/with_column.rs b/src/commands/with_column.rs index 7d1ea01..df5e4ad 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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; pub struct WithColumn; @@ -34,8 +34,8 @@ 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 +63,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_value(plugin, engine, span)?, None, )) } diff --git a/src/input.rs b/src/input.rs index abe1118..ab99582 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::{NuDataFrame, NuDataFusionObjectSupport}; /// 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::from_value(plugin, &value, span)?.into_df()), _ => values_to_dataframe(&plugin.ctx, value, span), } } diff --git a/src/plugin.rs b/src/plugin.rs index b396d1b..2cd8ea6 100644 --- a/src/plugin.rs +++ b/src/plugin.rs @@ -12,7 +12,7 @@ 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::{NuDataFusionObject, PREVIEW_ROWS, id_from_custom_box}; pub trait EngineWrapper { fn set_gc_disabled(&self, disabled: bool) -> Result<(), ShellError>; @@ -95,7 +95,9 @@ impl Plugin for DfPlugin { "this dataframe is no longer in the plugin cache", )) })?; + let NuDataFusionObject::DataFrame(df) = df; let preview = df + .into_df() .limit(0, Some(PREVIEW_ROWS)) .map_err(|e| from_datafusion(e, span))?; let (value, _) = collect_to_nu(self, preview, span, Some(PREVIEW_ROWS))?; diff --git a/src/values/dataframe.rs b/src/values/dataframe.rs index fcc7478..c34d354 100644 --- a/src/values/dataframe.rs +++ b/src/values/dataframe.rs @@ -14,6 +14,20 @@ pub struct NuDataFrame { 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, diff --git a/src/values/mod.rs b/src/values/mod.rs index 0e598d8..703b959 100644 --- a/src/values/mod.rs +++ b/src/values/mod.rs @@ -1,10 +1,9 @@ mod dataframe; -pub use dataframe::{NuDataFrame, dataframe_type}; +pub use dataframe::{NuDataFrame, NuDataFrameCustomValue}; -use datafusion::prelude::DataFrame; use nu_plugin::EngineInterface; -use nu_protocol::{CustomValue, LabeledError, ShellError, Span, Type, Value}; +use nu_protocol::{CustomValue, LabeledError, Span, Type, Value}; use uuid::Uuid; use crate::plugin::DfPlugin; @@ -70,3 +69,11 @@ pub trait NuDataFusionObjectSupport { Ok(self.custom_value(span)) } } + +/// Extract the cache id from any of this plugin's custom values. +pub fn id_from_custom_box(custom: &dyn CustomValue) -> Option { + custom + .as_any() + .downcast_ref::() + .map(|v| v.id) +} From 47b848d0653b378c4e3b7bc007eb97c05312df6d Mon Sep 17 00:00:00 2001 From: Jack Wright Date: Fri, 4 Dec 2026 19:41:17 -0800 Subject: [PATCH 5/9] Removed unused HasId --- src/values/mod.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/values/mod.rs b/src/values/mod.rs index 703b959..97bf6e6 100644 --- a/src/values/mod.rs +++ b/src/values/mod.rs @@ -11,10 +11,6 @@ use crate::plugin::DfPlugin; pub const PREVIEW_ROWS: usize = 20; pub const COLLECT_DEFAULT: usize = 10_000; -pub trait HasId { - fn id(&self) -> &Uuid; -} - pub enum NuDataFusionType { DataFrame, } From 65b56e8aebf8d0a5ea089123ac4c95c4613d72f1 Mon Sep 17 00:00:00 2001 From: Jack Wright Date: Fri, 4 Dec 2026 19:54:09 -0800 Subject: [PATCH 6/9] More refactoring to enable supporting more types --- src/cache.rs | 216 ++++++++++++++++++++++++++++++------ src/commands/aggregate.rs | 9 +- src/commands/cast.rs | 9 +- src/commands/distinct.rs | 9 +- src/commands/drop.rs | 9 +- src/commands/filter.rs | 9 +- src/commands/from_nu.rs | 4 +- src/commands/join.rs | 11 +- src/commands/limit.rs | 9 +- src/commands/open.rs | 4 +- src/commands/register.rs | 9 +- src/commands/rename.rs | 9 +- src/commands/sample.rs | 9 +- src/commands/select.rs | 9 +- src/commands/sort.rs | 9 +- src/commands/sql.rs | 9 +- src/commands/union.rs | 11 +- src/commands/with_column.rs | 9 +- src/input.rs | 4 +- src/plugin.rs | 32 +----- src/values/dataframe.rs | 80 ++++++------- src/values/mod.rs | 119 +++++++++++++++----- 22 files changed, 420 insertions(+), 178 deletions(-) diff --git a/src/cache.rs b/src/cache.rs index 1b65fde..41787bf 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -1,15 +1,22 @@ use std::collections::HashMap; -use std::sync::{Arc, Mutex, MutexGuard}; +use std::sync::{Mutex, MutexGuard}; +use std::time::SystemTime; +use chrono::{DateTime, Utc}; use log::debug; -use nu_protocol::{LabeledError, ShellError, Span}; +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 value: Arc, + pub id: Uuid, + pub value: NuDataFusionObject, + pub created: DateTime, + pub span: Span, pub reference_count: i16, } @@ -25,61 +32,204 @@ impl Cache { .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, - dfo: NuDataFusionObject, - _span: Span, - ) -> Result<(), LabeledError> { + value: NuDataFusionObject, + span: Span, + ) -> Result, LabeledError> { let mut lock = self.lock()?; + debug!("DataFusion plugin: inserting {id} into cache: {value:?}"); engine.set_gc_disabled(true).map_err(LabeledError::from)?; - - debug!( - "DataFusion plugin: Inserting cache entry with ID: {id} value: {:?}", - dfo - ); - - lock.insert( + let entry = CacheEntry { id, - CacheEntry { - value: Arc::new(dfo), - 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, LabeledError> { + /// 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| { - debug!( - "DataFusion plugin: Incrementing reference count for cache entry with ID: {id} value: {:?}", - entry.value - ); - entry.reference_count += 1; - entry.value.as_ref().clone() + if increment { + entry.reference_count += 1; + debug!( + "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); + debug!("DataFusion plugin: removed {id} from cache: {removed:?}"); + removed + } else { + debug!("DataFusion plugin: decremented reference count for {id}"); + None + }; + if lock.is_empty() { + debug!("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 639abd9..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Aggregate; @@ -36,7 +36,10 @@ impl PluginCommand for Aggregate { "SQL aggregates, e.g. [\"sum(amount) as total\" \"count(*) as n\"]", Some('a'), ) - .input_output_type(NuDataFusionType::DataFrame.nu_type(), NuDataFusionType::DataFrame.nu_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( - NuDataFrame::new(out).cache_and_value(plugin, engine, 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 a71d77f..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Cast; @@ -26,7 +26,10 @@ 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(NuDataFusionType::DataFrame.nu_type(), NuDataFusionType::DataFrame.nu_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( - NuDataFrame::new(out).cache_and_value(plugin, engine, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/distinct.rs b/src/commands/distinct.rs index 29aa8b0..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Distinct; @@ -28,7 +28,10 @@ impl PluginCommand for Distinct { SyntaxShape::String, "Columns that define uniqueness (default: all)", ) - .input_output_type(NuDataFusionType::DataFrame.nu_type(), NuDataFusionType::DataFrame.nu_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( - NuDataFrame::new(out).cache_and_value(plugin, engine, 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 1afbc04..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct DropCols; @@ -23,7 +23,10 @@ impl PluginCommand for DropCols { fn signature(&self) -> Signature { Signature::build(self.name()) .rest("columns", SyntaxShape::String, "Column names to drop") - .input_output_type(NuDataFusionType::DataFrame.nu_type(), NuDataFusionType::DataFrame.nu_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( - NuDataFrame::new(out).cache_and_value(plugin, engine, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/filter.rs b/src/commands/filter.rs index c1e29db..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Filter; @@ -28,7 +28,10 @@ impl PluginCommand for Filter { SyntaxShape::String, "SQL boolean expression, e.g. \"amount > 1000\"", ) - .input_output_type(NuDataFusionType::DataFrame.nu_type(), NuDataFusionType::DataFrame.nu_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( - NuDataFrame::new(out).cache_and_value(plugin, engine, 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 e251ead..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct FromNu; @@ -47,7 +47,7 @@ impl PluginCommand for FromNu { let span = call.head; let df = resolve_df(plugin, input, span)?; Ok(PipelineData::value( - NuDataFrame::new(df).cache_and_value(plugin, engine, 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 88e7836..e648a0c 100644 --- a/src/commands/join.rs +++ b/src/commands/join.rs @@ -6,7 +6,7 @@ use crate::commands::category; use crate::error::{from_datafusion, shell}; use crate::input::resolve_df; use crate::plugin::DfPlugin; -use crate::values::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Join; @@ -52,7 +52,10 @@ impl PluginCommand for Join { "inner, left, right, full, semi, anti (default inner)", Some('t'), ) - .input_output_type(NuDataFusionType::DataFrame.nu_type(), NuDataFusionType::DataFrame.nu_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 +79,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 { .. } => NuDataFrame::from_value(plugin, &right_val, span)?.into_df(), + 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( @@ -95,7 +98,7 @@ impl PluginCommand for Join { .join(right, join_type, &left_refs, &right_refs, None) .map_err(|e| from_datafusion(e, span))?; Ok(PipelineData::value( - NuDataFrame::new(out).cache_and_value(plugin, engine, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/limit.rs b/src/commands/limit.rs index ceb8b3f..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Limit; @@ -24,7 +24,10 @@ 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(NuDataFusionType::DataFrame.nu_type(), NuDataFusionType::DataFrame.nu_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( - NuDataFrame::new(out).cache_and_value(plugin, engine, 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 dea123e..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Open; @@ -85,7 +85,7 @@ impl PluginCommand for Open { )?; } Ok(PipelineData::value( - NuDataFrame::new(df).cache_and_value(plugin, engine, 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 124ed4f..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Register; @@ -28,7 +28,10 @@ impl PluginCommand for Register { "Replace an existing table with this name", Some('f'), ) - .input_output_type(NuDataFusionType::DataFrame.nu_type(), NuDataFusionType::DataFrame.nu_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( - NuDataFrame::new(df).cache_and_value(plugin, engine, 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 958f121..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Rename; @@ -27,7 +27,10 @@ impl PluginCommand for Rename { SyntaxShape::Record(vec![].into()), "Record of old names to new names", ) - .input_output_type(NuDataFusionType::DataFrame.nu_type(), NuDataFusionType::DataFrame.nu_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( - NuDataFrame::new(df).cache_and_value(plugin, engine, 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 2c50525..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Sample; @@ -33,7 +33,10 @@ impl PluginCommand for Sample { "Number of rows to sample (default 10)", Some('n'), ) - .input_output_type(NuDataFusionType::DataFrame.nu_type(), NuDataFusionType::DataFrame.nu_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( - NuDataFrame::new(out).cache_and_value(plugin, engine, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/commands/select.rs b/src/commands/select.rs index 793a683..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Select; @@ -27,7 +27,10 @@ impl PluginCommand for Select { SyntaxShape::String, "Column names or SQL expressions (\"a + 1 as b\")", ) - .input_output_type(NuDataFusionType::DataFrame.nu_type(), NuDataFusionType::DataFrame.nu_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( - NuDataFrame::new(out).cache_and_value(plugin, engine, 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 30cda97..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Sort; @@ -26,7 +26,10 @@ 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(NuDataFusionType::DataFrame.nu_type(), NuDataFusionType::DataFrame.nu_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( - NuDataFrame::new(out).cache_and_value(plugin, engine, 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 68173ec..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Sql; @@ -29,7 +29,10 @@ 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(NuDataFusionType::DataFrame.nu_type(), NuDataFusionType::DataFrame.nu_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( - NuDataFrame::new(out).cache_and_value(plugin, engine, 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 9a7e5ab..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct Union; @@ -28,7 +28,10 @@ impl PluginCommand for Union { "Other dataframe handle or catalog table name", ) .switch("distinct", "Drop duplicate rows (SQL UNION)", Some('d')) - .input_output_type(NuDataFusionType::DataFrame.nu_type(), NuDataFusionType::DataFrame.nu_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 { .. } => NuDataFrame::from_value(plugin, &other, span)?.into_df(), + 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( - NuDataFrame::new(out).cache_and_value(plugin, engine, 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 df5e4ad..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::{NuDataFrame, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType}; pub struct WithColumn; @@ -34,7 +34,10 @@ impl PluginCommand for WithColumn { "Column name if the expression has no alias", Some('a'), ) - .input_output_type(NuDataFusionType::DataFrame.nu_type(), NuDataFusionType::DataFrame.nu_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( - NuDataFrame::new(out).cache_and_value(plugin, engine, span)?, + NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, None, )) } diff --git a/src/input.rs b/src/input.rs index ab99582..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::{NuDataFrame, NuDataFusionObjectSupport}; +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 { .. } => Ok(NuDataFrame::from_value(plugin, &value, span)?.into_df()), + 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 2cd8ea6..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::{NuDataFusionObject, PREVIEW_ROWS, id_from_custom_box}; +use crate::values::CustomValueType; pub trait EngineWrapper { fn set_gc_disabled(&self, disabled: bool) -> Result<(), ShellError>; @@ -81,27 +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 NuDataFusionObject::DataFrame(df) = df; - let preview = df - .into_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( @@ -112,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 c34d354..1751785 100644 --- a/src/values/dataframe.rs +++ b/src/values/dataframe.rs @@ -5,8 +5,13 @@ use nu_protocol::{CustomValue, LabeledError, ShellError, Span, Value}; use serde::{Deserialize, Serialize}; use uuid::Uuid; +use crate::cache::Cacheable; +use crate::convert::collect_to_nu; +use crate::error::from_datafusion; use crate::plugin::DfPlugin; -use crate::values::{NuDataFusionObject, NuDataFusionObjectSupport, NuDataFusionType}; +use crate::values::{ + CustomValueSupport, NuDataFusionCustomValue, NuDataFusionObject, NuDataFusionType, PREVIEW_ROWS, +}; #[derive(Debug, Clone)] pub struct NuDataFrame { @@ -33,55 +38,50 @@ pub struct NuDataFrameCustomValue { pub id: Uuid, } -impl NuDataFusionObjectSupport for NuDataFrame { - type InnerType = DataFrame; - fn nu_datafusion_type(&self) -> NuDataFusionType { - NuDataFusionType::DataFrame +impl Cacheable for NuDataFrame { + fn cache_id(&self) -> &Uuid { + &self.id } - fn nu_datafusion_object(&self) -> crate::values::NuDataFusionObject { - crate::values::NuDataFusionObject::DataFrame(self.clone()) + fn to_cache_value(&self) -> NuDataFusionObject { + NuDataFusionObject::DataFrame(self.clone()) } - fn custom_value(&self, span: Span) -> Value { - Value::custom(Box::new(NuDataFrameCustomValue { id: self.id }), span) + 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:?}"))), + } } +} - fn inner(&self) -> &DataFrame { - self.inner.as_ref() +impl CustomValueSupport for NuDataFrame { + type CV = NuDataFrameCustomValue; + + fn get_type_static() -> NuDataFusionType { + NuDataFusionType::DataFrame } - fn id(&self) -> &Uuid { - &self.id + fn custom_value(self) -> Self::CV { + NuDataFrameCustomValue { id: self.id } } - fn from_value(plugin: &DfPlugin, value: &Value, span: Span) -> Result { - let id = match value { - Value::Custom { val, .. } => val - .as_any() - .downcast_ref::() - .map(|cv| cv.id) - .ok_or_else(|| { - LabeledError::new(format!( - "expected dataframe, found custom value '{}'", - val.type_name() - )) - .with_label("expected dataframe", span) - })?, - _ => { - return Err(LabeledError::new(format!( - "expected dataframe, found {}", - value.get_type() - )) - .with_label("expected dataframe", span)); - } - }; - - match plugin.cache.get(&id)? { - Some(NuDataFusionObject::DataFrame(df)) => Ok(df), - None => Err(LabeledError::new("stale dataframe handle") - .with_label("this dataframe is no longer in the plugin cache", span)), - } + 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 } } diff --git a/src/values/mod.rs b/src/values/mod.rs index 97bf6e6..bc3fc07 100644 --- a/src/values/mod.rs +++ b/src/values/mod.rs @@ -6,6 +6,7 @@ use nu_plugin::EngineInterface; use nu_protocol::{CustomValue, LabeledError, Span, Type, Value}; use uuid::Uuid; +use crate::cache::Cacheable; use crate::plugin::DfPlugin; pub const PREVIEW_ROWS: usize = 20; @@ -23,53 +24,119 @@ impl NuDataFusionType { } pub fn nu_type(&self) -> Type { - match self { - NuDataFusionType::DataFrame => Type::Custom(self.name().into()), - } + Type::Custom(self.name().into()) } } +/// Every kind of object the plugin can hold in its cache. #[derive(Debug, Clone)] pub enum NuDataFusionObject { DataFrame(NuDataFrame), } -impl NuDataFusionObject {} +/// 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; -pub trait NuDataFusionObjectSupport { - type InnerType; + fn get_type_static() -> NuDataFusionType; - fn id(&self) -> &Uuid; + fn custom_value(self) -> Self::CV; - fn nu_datafusion_type(&self) -> NuDataFusionType; + /// The plain Nushell value shown when the custom value is displayed. + fn base_value(self, plugin: &DfPlugin, span: Span) -> Result; - fn nu_datafusion_object(&self) -> NuDataFusionObject; + fn into_value(self, span: Span) -> Value { + Value::custom(Box::new(self.custom_value()), span) + } - fn custom_value(&self, span: Span) -> Value; + 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 inner(&self) -> &Self::InnerType; + 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), + ) + } - fn from_value(plugin: &DfPlugin, value: &Value, span: Span) -> Result - where - Self: Sized; + /// 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)) + } +} + +/// The custom value Nushell holds: a handle into the plugin cache. +pub trait NuDataFusionCustomValue: CustomValue { + type ObjectType: CustomValueSupport; + + fn id(&self) -> &Uuid; - fn cache_and_value( + fn custom_value_to_base_value( &self, plugin: &DfPlugin, - engine: &EngineInterface, span: Span, ) -> Result { - plugin - .cache - .insert(engine, *self.id(), self.nu_datafusion_object(), span)?; - Ok(self.custom_value(span)) + Self::ObjectType::try_from_custom_value(plugin, self, span)?.base_value(plugin, span) } } -/// Extract the cache id from any of this plugin's custom values. -pub fn id_from_custom_box(custom: &dyn CustomValue) -> Option { - custom - .as_any() - .downcast_ref::() - .map(|v| v.id) +/// 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), + } + } } From 155a33d39ccc47090e68b918135c3d9b0416877e Mon Sep 17 00:00:00 2001 From: Jack Wright Date: Fri, 4 Dec 2026 19:55:44 -0800 Subject: [PATCH 7/9] moved debug logs to trace --- src/cache.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cache.rs b/src/cache.rs index 41787bf..782aa40 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -3,7 +3,7 @@ use std::sync::{Mutex, MutexGuard}; use std::time::SystemTime; use chrono::{DateTime, Utc}; -use log::debug; +use log::trace; use nu_plugin::EngineInterface; use nu_protocol::{LabeledError, Span}; use uuid::Uuid; @@ -42,7 +42,7 @@ impl Cache { span: Span, ) -> Result, LabeledError> { let mut lock = self.lock()?; - debug!("DataFusion plugin: inserting {id} into cache: {value:?}"); + trace!("DataFusion plugin: inserting {id} into cache: {value:?}"); engine.set_gc_disabled(true).map_err(LabeledError::from)?; let entry = CacheEntry { id, @@ -64,7 +64,7 @@ impl Cache { Ok(lock.get_mut(id).map(|entry| { if increment { entry.reference_count += 1; - debug!( + trace!( "DataFusion plugin: incremented reference count for {id} to {}", entry.reference_count ); @@ -91,15 +91,15 @@ impl Cache { let removed = if force || remaining.unwrap_or_default() < 1 { let removed = lock.remove(id); - debug!("DataFusion plugin: removed {id} from cache: {removed:?}"); + trace!("DataFusion plugin: removed {id} from cache: {removed:?}"); removed } else { - debug!("DataFusion plugin: decremented reference count for {id}"); + trace!("DataFusion plugin: decremented reference count for {id}"); None }; if lock.is_empty() { - debug!("DataFusion plugin: cache is empty, enabling GC"); + trace!("DataFusion plugin: cache is empty, enabling GC"); engine.set_gc_disabled(false).map_err(LabeledError::from)?; } Ok(removed) From 9892784d600da3d4450ba7aa3792c5c858ff157e Mon Sep 17 00:00:00 2001 From: Jack Wright Date: Fri, 4 Dec 2026 19:58:43 -0800 Subject: [PATCH 8/9] fixed an issue with df join --- src/commands/join.rs | 199 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 194 insertions(+), 5 deletions(-) diff --git a/src/commands/join.rs b/src/commands/join.rs index e648a0c..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}; @@ -46,6 +47,12 @@ 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, @@ -92,10 +99,10 @@ 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( NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?, @@ -104,6 +111,96 @@ impl PluginCommand for Join { } } +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, @@ -149,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]); + } +} From debc986daf5e56656c7c8c4a7d38c4850c5be4f6 Mon Sep 17 00:00:00 2001 From: Jack Wright Date: Fri, 4 Dec 2026 20:01:28 -0800 Subject: [PATCH 9/9] Don't run the build and cache workflow on PRs --- .github/workflows/fh.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) 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: