-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
upsert.rs
211 lines (184 loc) · 7.38 KB
/
upsert.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::{Call, CellPath, PathMember};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, FromValue, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
ShellError, Signature, Span, SyntaxShape, Type, Value,
};
#[derive(Clone)]
pub struct Upsert;
impl Command for Upsert {
fn name(&self) -> &str {
"upsert"
}
fn signature(&self) -> Signature {
Signature::build("upsert")
.input_output_types(vec![(Type::Table(vec![]), Type::Table(vec![]))])
.required(
"field",
SyntaxShape::CellPath,
"the name of the column to update or insert",
)
.required(
"replacement value",
SyntaxShape::Any,
"the new value to give the cell(s), or a block to create the value",
)
.category(Category::Filters)
}
fn usage(&self) -> &str {
"Update an existing column to have a new value, or insert a new column."
}
fn search_terms(&self) -> Vec<&str> {
vec!["add"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
upsert(engine_state, stack, call, input)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Update a record's value",
example: "{'name': 'nu', 'stars': 5} | upsert name 'Nushell'",
result: Some(Value::Record { cols: vec!["name".into(), "stars".into()], vals: vec![Value::test_string("Nushell"), Value::test_int(5)], span: Span::test_data()}),
}, Example {
description: "Insert a new entry into a single record",
example: "{'name': 'nu', 'stars': 5} | upsert language 'Rust'",
result: Some(Value::Record { cols: vec!["name".into(), "stars".into(), "language".into()], vals: vec![Value::test_string("nu"), Value::test_int(5), Value::test_string("Rust")], span: Span::test_data()}),
}, Example {
description: "Use in closure form for more involved updating logic",
example: "[[count fruit]; [1 'apple']] | upsert count {|row index| ($row.fruit | str length) + $index }",
result: Some(Value::List { vals: vec![Value::Record { cols: vec!["count".into(), "fruit".into()], vals: vec![Value::test_int(5), Value::test_string("apple")], span: Span::test_data()}], span: Span::test_data()}),
},
Example {
description: "Upsert an int into a list, updating an existing value based on the index",
example: "[1 2 3] | upsert 0 2",
result: Some(Value::List {
vals: vec![Value::test_int(2), Value::test_int(2), Value::test_int(3)],
span: Span::test_data(),
}),
},
Example {
description: "Upsert an int into a list, inserting a new value based on the index",
example: "[1 2 3] | upsert 3 4",
result: Some(Value::List {
vals: vec![
Value::test_int(1),
Value::test_int(2),
Value::test_int(3),
Value::test_int(4),
],
span: Span::test_data(),
}),
},
]
}
}
fn upsert(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let span = call.head;
let cell_path: CellPath = call.req(engine_state, stack, 0)?;
let replacement: Value = call.req(engine_state, stack, 1)?;
let redirect_stdout = call.redirect_stdout;
let redirect_stderr = call.redirect_stderr;
let engine_state = engine_state.clone();
let ctrlc = engine_state.ctrlc.clone();
// Replace is a block, so set it up and run it instead of using it as the replacement
if replacement.as_block().is_ok() {
let capture_block: Closure = FromValue::from_value(&replacement)?;
let block = engine_state.get_block(capture_block.block_id).clone();
let mut stack = stack.captures_to_stack(&capture_block.captures);
let orig_env_vars = stack.env_vars.clone();
let orig_env_hidden = stack.env_hidden.clone();
// enumerate() can't be used here because it converts records into tables
// when combined with into_pipeline_data(). Hence, the index is tracked manually like so.
let mut idx: i64 = 0;
input.map(
move |mut input| {
// with_env() is used here to ensure that each iteration uses
// a different set of environment variables.
// Hence, a 'cd' in the first loop won't affect the next loop.
stack.with_env(&orig_env_vars, &orig_env_hidden);
if let Some(var) = block.signature.get_positional(0) {
if let Some(var_id) = &var.var_id {
stack.add_var(*var_id, input.clone())
}
}
// Optional index argument
if let Some(var) = block.signature.get_positional(1) {
if let Some(var_id) = &var.var_id {
stack.add_var(*var_id, Value::Int { val: idx, span });
}
idx += 1;
}
let output = eval_block(
&engine_state,
&mut stack,
&block,
input.clone().into_pipeline_data(),
redirect_stdout,
redirect_stderr,
);
match output {
Ok(pd) => {
if let Err(e) =
input.upsert_data_at_cell_path(&cell_path.members, pd.into_value(span))
{
return Value::Error { error: e };
}
input
}
Err(e) => Value::Error { error: e },
}
},
ctrlc,
)
} else {
if let Some(PathMember::Int { val, span }) = cell_path.members.get(0) {
let mut input = input.into_iter();
let mut pre_elems = vec![];
for idx in 0..*val {
if let Some(v) = input.next() {
pre_elems.push(v);
} else {
return Err(ShellError::AccessBeyondEnd(idx - 1, *span));
}
}
// Skip over the replaced value
let _ = input.next();
return Ok(pre_elems
.into_iter()
.chain(vec![replacement])
.chain(input)
.into_pipeline_data(ctrlc));
}
input.map(
move |mut input| {
let replacement = replacement.clone();
if let Err(e) = input.upsert_data_at_cell_path(&cell_path.members, replacement) {
return Value::Error { error: e };
}
input
},
ctrlc,
)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Upsert {})
}
}