1use std::collections::HashMap;
2
3use crate::{
4 df::{ApplyStatError, DfExecutor},
5 sql,
6};
7use polars::lazy::frame::LazyFrame;
8
9pub struct LineExecutor {
10 history: Vec<String>,
11 original_df_name: String,
12 original_input: HashMap<String, LazyFrame>,
13 executor: DfExecutor,
14}
15
16impl LineExecutor {
17 pub fn new(executor: DfExecutor) -> Self {
18 let original_df_name = executor.df_name().clone();
19 let original_input = executor.input().clone();
20 Self {
21 history: vec![],
22 original_df_name,
23 original_input,
24 executor,
25 }
26 }
27
28 pub fn reset(&mut self) {
29 self.executor =
30 DfExecutor::new(self.original_df_name.clone(), self.original_input.clone()).unwrap();
31 self.history.clear();
32 }
33
34 pub fn undo(&mut self) -> anyhow::Result<()> {
35 self.executor =
36 DfExecutor::new(self.original_df_name.clone(), self.original_input.clone()).unwrap();
37 self.history.pop();
38 let sql = self.history.iter().map(|s| sql::parse(s).unwrap());
39 apply_history(sql, &mut self.executor)?;
40 Ok(())
41 }
42
43 pub fn execute(&mut self, line: String) -> anyhow::Result<()> {
44 let s = sql::parse(&line)?;
45 self.executor.execute(&s)?;
46 if !line.trim().is_empty() {
47 self.history.push(line);
48 }
49 Ok(())
50 }
51
52 pub fn df(&self) -> &LazyFrame {
53 self.executor.df()
54 }
55 pub fn df_mut(&mut self) -> &mut LazyFrame {
56 self.executor.df_mut()
57 }
58
59 pub fn history(&self) -> &Vec<String> {
60 &self.history
61 }
62}
63
64fn apply_history(
65 sql: impl Iterator<Item = sql::S>,
66 executor: &mut DfExecutor,
67) -> Result<(), ApplyStatError> {
68 for s in sql {
69 executor.execute(&s)?;
70 }
71 Ok(())
72}