2020-04-27 04:04:54 +02:00
|
|
|
use crate::commands::WholeStreamCommand;
|
2019-12-05 21:15:41 +01:00
|
|
|
use crate::context::CommandRegistry;
|
|
|
|
use crate::prelude::*;
|
|
|
|
use nu_errors::ShellError;
|
2020-04-27 04:04:54 +02:00
|
|
|
use nu_protocol::{ColumnPath, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value};
|
2019-12-09 19:52:01 +01:00
|
|
|
use nu_value_ext::ValueExt;
|
2019-12-05 21:15:41 +01:00
|
|
|
|
|
|
|
pub struct Insert;
|
|
|
|
|
2020-04-27 04:04:54 +02:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
pub struct InsertArgs {
|
|
|
|
column: ColumnPath,
|
|
|
|
value: Value,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl WholeStreamCommand for Insert {
|
2019-12-05 21:15:41 +01:00
|
|
|
fn name(&self) -> &str {
|
|
|
|
"insert"
|
|
|
|
}
|
|
|
|
|
|
|
|
fn signature(&self) -> Signature {
|
|
|
|
Signature::build("insert")
|
|
|
|
.required(
|
|
|
|
"column",
|
|
|
|
SyntaxShape::ColumnPath,
|
|
|
|
"the column name to insert",
|
|
|
|
)
|
|
|
|
.required(
|
|
|
|
"value",
|
|
|
|
SyntaxShape::String,
|
|
|
|
"the value to give the cell(s)",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn usage(&self) -> &str {
|
2020-04-27 04:04:54 +02:00
|
|
|
"Insert a new column with a given value."
|
2019-12-05 21:15:41 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fn run(
|
|
|
|
&self,
|
2020-04-27 04:04:54 +02:00
|
|
|
args: CommandArgs,
|
|
|
|
registry: &CommandRegistry,
|
2019-12-05 21:15:41 +01:00
|
|
|
) -> Result<OutputStream, ShellError> {
|
2020-04-27 04:04:54 +02:00
|
|
|
args.process(registry, insert)?.run()
|
|
|
|
}
|
|
|
|
}
|
2019-12-05 21:15:41 +01:00
|
|
|
|
2020-04-27 04:04:54 +02:00
|
|
|
fn insert(
|
|
|
|
InsertArgs { column, value }: InsertArgs,
|
|
|
|
RunnableContext { input, .. }: RunnableContext,
|
|
|
|
) -> Result<OutputStream, ShellError> {
|
|
|
|
let mut input = input;
|
|
|
|
|
|
|
|
let stream = async_stream! {
|
|
|
|
match input.next().await {
|
|
|
|
Some(obj @ Value {
|
2019-12-05 21:15:41 +01:00
|
|
|
value: UntaggedValue::Row(_),
|
|
|
|
..
|
2020-04-27 04:04:54 +02:00
|
|
|
}) => match obj.insert_data_at_column_path(&column, value.clone()) {
|
|
|
|
Ok(v) => yield Ok(ReturnSuccess::Value(v)),
|
|
|
|
Err(err) => yield Err(err),
|
2019-12-05 21:15:41 +01:00
|
|
|
},
|
|
|
|
|
2020-04-27 04:04:54 +02:00
|
|
|
Some(Value { tag, ..}) => {
|
|
|
|
yield Err(ShellError::labeled_error(
|
2019-12-05 21:15:41 +01:00
|
|
|
"Unrecognized type in stream",
|
|
|
|
"original value",
|
2020-04-27 04:04:54 +02:00
|
|
|
tag,
|
|
|
|
));
|
2019-12-05 21:15:41 +01:00
|
|
|
}
|
2020-04-27 04:04:54 +02:00
|
|
|
|
|
|
|
None => {}
|
2019-12-05 21:15:41 +01:00
|
|
|
};
|
|
|
|
|
2020-04-27 04:04:54 +02:00
|
|
|
};
|
|
|
|
Ok(stream.to_output_stream())
|
2019-12-05 21:15:41 +01:00
|
|
|
}
|