nu_command/stor/
delete.rs1use crate::database::{MEMORY_DB, SQLiteDatabase, get_shared_mem_conn};
2use nu_engine::command_prelude::*;
3use nu_protocol::shell_error::generic::GenericError;
4use std::fmt::Write;
5
6#[derive(Clone)]
7pub struct StorDelete;
8
9impl Command for StorDelete {
10 fn name(&self) -> &str {
11 "stor delete"
12 }
13
14 fn signature(&self) -> Signature {
15 Signature::build("stor delete")
16 .input_output_types(vec![(Type::Nothing, Type::table())])
17 .required_named(
18 "table-name",
19 SyntaxShape::String,
20 "Name of the table you want to delete or delete from.",
21 Some('t'),
22 )
23 .named(
24 "where-clause",
25 SyntaxShape::String,
26 "A sql string to use as a where clause without the WHERE keyword.",
27 Some('w'),
28 )
29 .allow_variants_without_examples(true)
30 .category(Category::Database)
31 }
32
33 fn description(&self) -> &str {
34 "Delete a table or specified rows in the in-memory sqlite database."
35 }
36
37 fn search_terms(&self) -> Vec<&str> {
38 vec!["sqlite", "remove", "table", "saving", "drop"]
39 }
40
41 fn examples(&self) -> Vec<Example<'_>> {
42 vec![
43 Example {
44 description: "Delete a table from the in-memory sqlite database",
45 example: "stor delete --table-name nudb",
46 result: None,
47 },
48 Example {
49 description: "Delete some rows from the in-memory sqlite database with a where clause",
50 example: "stor delete --table-name nudb --where-clause \"int1 == 5\"",
51 result: None,
52 },
53 ]
54 }
55
56 fn run(
57 &self,
58 engine_state: &EngineState,
59 stack: &mut Stack,
60 call: &Call,
61 _input: PipelineData,
62 ) -> Result<PipelineData, ShellError> {
63 let span = call.head;
64 let table_name_opt: Option<String> = call.get_flag(engine_state, stack, "table-name")?;
66
67 let where_clause_opt: Option<String> =
69 call.get_flag(engine_state, stack, "where-clause")?;
70
71 if table_name_opt.is_none() && where_clause_opt.is_none() {
72 return Err(ShellError::MissingParameter {
73 param_name: "requires at least one of table-name or where-clause".into(),
74 span,
75 });
76 }
77
78 if table_name_opt.is_none() && where_clause_opt.is_some() {
79 return Err(ShellError::MissingParameter {
80 param_name: "using the where-clause requires the use of a table-name".into(),
81 span,
82 });
83 }
84
85 if let Some(new_table_name) = table_name_opt {
86 let conn = get_shared_mem_conn()?;
87 let sql_stmt = match where_clause_opt {
88 None => {
89 format!("DROP TABLE {new_table_name}")
91 }
92 Some(where_clause) => {
93 let mut delete_stmt = format!("DELETE FROM {new_table_name} ");
95
96 write!(delete_stmt, "WHERE {where_clause}")
100 .expect("writing to a String is infallible");
101 delete_stmt
102 }
103 };
104
105 conn.execute(&sql_stmt, []).map_err(|err| {
107 ShellError::Generic(GenericError::new_internal(
108 "Failed to delete using the SQLite connection to the in-memory database from delete.rs.",
109 err.to_string(),
110 ))
111 })?;
112 }
113
114 let db = Box::new(SQLiteDatabase::new(
115 std::path::Path::new(MEMORY_DB),
116 engine_state.signals().clone(),
117 ));
118 Ok(Value::custom(db, span).into_pipeline_data())
119 }
120}
121
122#[cfg(test)]
123mod test {
124 use super::*;
125
126 #[test]
127 fn test_examples() -> nu_test_support::Result {
128 nu_test_support::test().examples(StorDelete)
129 }
130}