Skip to main content

nu_command/stor/
reset.rs

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