Skip to main content

nu_command/stor/
reset.rs

1use crate::database::{MEMORY_DB, SQLiteDatabase};
2use nu_engine::command_prelude::*;
3use nu_protocol::Signals;
4use nu_protocol::shell_error::generic::GenericError;
5
6#[derive(Clone)]
7pub struct StorReset;
8
9impl Command for StorReset {
10    fn name(&self) -> &str {
11        "stor reset"
12    }
13
14    fn signature(&self) -> Signature {
15        Signature::build("stor reset")
16            .input_output_types(vec![(Type::Nothing, Type::table())])
17            .allow_variants_without_examples(true)
18            .category(Category::Database)
19    }
20
21    fn description(&self) -> &str {
22        "Reset the in-memory database by dropping all tables."
23    }
24
25    fn search_terms(&self) -> Vec<&str> {
26        vec!["sqlite", "remove", "table", "saving", "drop"]
27    }
28
29    fn examples(&self) -> Vec<Example<'_>> {
30        vec![Example {
31            description: "Reset the in-memory sqlite database",
32            example: "stor reset",
33            result: None,
34        }]
35    }
36
37    fn run(
38        &self,
39        _engine_state: &EngineState,
40        _stack: &mut Stack,
41        call: &Call,
42        _input: PipelineData,
43    ) -> Result<PipelineData, ShellError> {
44        let span = call.head;
45
46        // Open the in-mem database
47        let db = Box::new(SQLiteDatabase::new(
48            std::path::Path::new(MEMORY_DB),
49            Signals::empty(),
50        ));
51
52        if let Ok(conn) = db.open_connection() {
53            conn.execute("PRAGMA foreign_keys = OFF", [])
54                .map_err(|err| {
55                    ShellError::Generic(GenericError::new_internal(
56                        "Failed to turn off foreign_key protections for reset",
57                        err.to_string(),
58                    ))
59                })?;
60            db.drop_all_tables(&conn).map_err(|err| {
61                ShellError::Generic(GenericError::new_internal(
62                    "Failed to drop all tables in memory from reset",
63                    err.to_string(),
64                ))
65            })?;
66            conn.execute("PRAGMA foreign_keys = ON", [])
67                .map_err(|err| {
68                    ShellError::Generic(GenericError::new_internal(
69                        "Failed to turn on foreign_key protections for reset",
70                        err.to_string(),
71                    ))
72                })?;
73        }
74        // dbg!(db.clone());
75        Ok(Value::custom(db, span).into_pipeline_data())
76    }
77}
78
79#[cfg(test)]
80mod test {
81    use super::*;
82
83    #[test]
84    fn test_examples() -> nu_test_support::Result {
85        nu_test_support::test().examples(StorReset)
86    }
87}