2020-04-27 02:04:54 +00:00
|
|
|
use crate::commands::WholeStreamCommand;
|
2019-12-05 20:15:41 +00:00
|
|
|
use crate::context::CommandRegistry;
|
|
|
|
use crate::prelude::*;
|
|
|
|
use nu_errors::ShellError;
|
2020-04-27 02:04:54 +00:00
|
|
|
use nu_protocol::{ColumnPath, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value};
|
2019-12-09 18:52:01 +00:00
|
|
|
use nu_value_ext::ValueExt;
|
2019-12-05 20:15:41 +00:00
|
|
|
|
|
|
|
pub struct Insert;
|
|
|
|
|
2020-04-27 02:04:54 +00:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
pub struct InsertArgs {
|
|
|
|
column: ColumnPath,
|
|
|
|
value: Value,
|
|
|
|
}
|
|
|
|
|
2020-05-29 08:22:52 +00:00
|
|
|
#[async_trait]
|
2020-04-27 02:04:54 +00:00
|
|
|
impl WholeStreamCommand for Insert {
|
2019-12-05 20:15:41 +00: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 02:04:54 +00:00
|
|
|
"Insert a new column with a given value."
|
2019-12-05 20:15:41 +00:00
|
|
|
}
|
|
|
|
|
2020-05-29 08:22:52 +00:00
|
|
|
async fn run(
|
2019-12-05 20:15:41 +00:00
|
|
|
&self,
|
2020-04-27 02:04:54 +00:00
|
|
|
args: CommandArgs,
|
|
|
|
registry: &CommandRegistry,
|
2019-12-05 20:15:41 +00:00
|
|
|
) -> Result<OutputStream, ShellError> {
|
2020-06-13 04:03:39 +00:00
|
|
|
insert(args, registry).await
|
2020-04-27 02:04:54 +00:00
|
|
|
}
|
|
|
|
}
|
2019-12-05 20:15:41 +00:00
|
|
|
|
2020-06-13 04:03:39 +00:00
|
|
|
async fn insert(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
|
2020-05-16 03:18:24 +00:00
|
|
|
let registry = registry.clone();
|
2020-04-27 02:04:54 +00:00
|
|
|
|
2020-06-13 04:03:39 +00:00
|
|
|
let (InsertArgs { column, value }, input) = args.process(®istry).await?;
|
2019-12-05 20:15:41 +00:00
|
|
|
|
2020-06-13 04:03:39 +00:00
|
|
|
Ok(input
|
|
|
|
.map(move |row| match row {
|
|
|
|
Value {
|
|
|
|
value: UntaggedValue::Row(_),
|
|
|
|
..
|
2020-07-18 01:12:06 +00:00
|
|
|
} => Ok(ReturnSuccess::Value(
|
|
|
|
row.insert_data_at_column_path(&column, value.clone())?,
|
|
|
|
)),
|
2020-04-27 02:04:54 +00:00
|
|
|
|
2020-06-13 04:03:39 +00:00
|
|
|
Value { tag, .. } => Err(ShellError::labeled_error(
|
|
|
|
"Unrecognized type in stream",
|
|
|
|
"original value",
|
|
|
|
tag,
|
|
|
|
)),
|
|
|
|
})
|
|
|
|
.to_output_stream())
|
2019-12-05 20:15:41 +00:00
|
|
|
}
|
2020-05-18 12:56:01 +00:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::Insert;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn examples_work_as_expected() {
|
|
|
|
use crate::examples::test as test_examples;
|
|
|
|
|
|
|
|
test_examples(Insert {})
|
|
|
|
}
|
|
|
|
}
|