Skip to content

Commit

Permalink
Add example for LogicalPlanBuilder::insert_into
Browse files Browse the repository at this point in the history
  • Loading branch information
alamb committed Feb 14, 2025
1 parent 715781e commit 09a6d8c
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
9 changes: 4 additions & 5 deletions datafusion/core/src/dataframe/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1538,18 +1538,17 @@ impl DataFrame {
};

let table_ref: TableReference = table_name.into();
let table = table_ref.table().to_string();
let table_schema = self.session_state.schema_for_ref(table_ref)?;
let target = match table_schema.table(&table).await? {
let table_schema = self.session_state.schema_for_ref(table_ref.clone())?;
let target = match table_schema.table(table_ref.table()).await? {
Some(ref provider) => Ok(Arc::clone(provider)),
_ => plan_err!("No table named '{table}'"),
_ => plan_err!("No table named '{table_name}'"),
}?;

let target = Arc::new(DefaultTableSource::new(target));

let plan = LogicalPlanBuilder::insert_into(
plan,
table_name.to_owned(),
table_ref,
target,
write_options.insert_op,
)?
Expand Down
35 changes: 34 additions & 1 deletion datafusion/expr/src/logical_plan/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,40 @@ impl LogicalPlanBuilder {
})))
}

/// Create a [DmlStatement] for inserting the contents of this builder into the named table
/// Create a [DmlStatement] for inserting the contents of this builder into the named table.
///
/// Note, use a [`DefaultTableSource`] to insert into a [`TableProvider`]
///
/// [`DefaultTableSource`]: https://docs.rs/datafusion/latest/datafusion/datasource/default_table_source/struct.DefaultTableSource.html
/// [`TableProvider`]: https://docs.rs/datafusion/latest/datafusion/catalog/trait.TableProvider.html
///
/// # Example:
/// ```
/// # use datafusion_expr::{lit, LogicalPlanBuilder,
/// # logical_plan::builder::LogicalTableSource,
/// # };
/// # use std::sync::Arc;
/// # use arrow::datatypes::{Schema, DataType, Field};
/// # use datafusion_expr::dml::InsertOp;
/// #
/// # fn test() -> datafusion_common::Result<()> {
/// # let employee_schema = Arc::new(Schema::new(vec![
/// # Field::new("id", DataType::Int32, false),
/// # ])) as _;
/// # let table_source = Arc::new(LogicalTableSource::new(employee_schema));
/// // VALUES (1), (2)
/// let input = LogicalPlanBuilder::values(vec![vec![lit(1)], vec![lit(2)]])?
/// .build()?;
/// // INSERT INTO MyTable VALUES (1), (2)
/// let insert_plan = LogicalPlanBuilder::insert_into(
/// input,
/// "MyTable",
/// table_source,
/// InsertOp::Append,
/// )?;
/// # Ok(())
/// # }
/// ```
pub fn insert_into(
input: LogicalPlan,
table_name: impl Into<TableReference>,
Expand Down

0 comments on commit 09a6d8c

Please sign in to comment.