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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
//! Row-write undo/redo history (step 28.1, item U14).
//!
//! The stack is per open database and bounded; it records **row writes
//! only** (`InsertRow`/`UpdateRow`/`DeleteRow`). Schema changes, journal
//! batches and file-level commands are barriers: they clear the history,
//! because their row effects cannot be expressed as row images. Undo and
//! redo are ordinary bus commands, so GUI, CLI and MCP share them.
//!
//! Operations address rows by their full value image, never by an index:
//! an undo that appends a deleted row shifts the indices behind it, so
//! image matching is the only deterministic way to keep redo correct.
use serde::{Deserialize, Serialize};
use crate::core::failed;
use crate::event::Event;
use crate::failure::FailureCode;
use crate::port::{DriverCapabilities, RowRange};
use crate::schema::FieldValue;
/// Maximum number of recorded row writes per open database.
pub const MAX_HISTORY: usize = 50;
/// One row operation of the history.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum HistoryOp {
/// Appends a row image verbatim, including engine-assigned AutoNumber
/// values ([`crate::port::StoragePort::restore_row`]).
Restore {
/// The exact row image.
values: Vec<FieldValue>,
},
/// Deletes the first row matching the image.
Delete {
/// The exact row image.
values: Vec<FieldValue>,
},
/// Replaces the first row matching `from` with `to`.
Update {
/// The image the row must currently carry.
from: Vec<FieldValue>,
/// The image to write.
to: Vec<FieldValue>,
},
}
/// One undoable row write.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HistoryEntry {
/// Canonical table name.
pub table: String,
/// Operations in undo order.
pub undo: Vec<HistoryOp>,
/// Operations in redo order.
pub redo: Vec<HistoryOp>,
}
impl crate::core::Core {
/// Undoes the last recorded row write (step 28.1, item U14).
pub(crate) fn undo(&mut self) -> Vec<Event> {
self.move_history(true)
}
/// Re-applies the last undone row write (step 28.1, item U14).
pub(crate) fn redo(&mut self) -> Vec<Event> {
self.move_history(false)
}
fn move_history(&mut self, undo: bool) -> Vec<Event> {
let Some(db) = self.state.database.as_ref() else {
return failed(
FailureCode::NoDatabase,
"no database is open — open a database first",
);
};
if !db.capabilities.write_rows {
return failed(
FailureCode::Capability(crate::availability::DisabledReason::WriteRows),
DriverCapabilities::unsupported(&db.driver, "write rows for this source"),
);
}
let entry = {
let db = self.state.database.as_mut().expect("checked above");
if undo { db.undo.pop() } else { db.redo.pop() }
};
let Some(entry) = entry else {
return failed(
FailureCode::Lifecycle,
if undo {
"nothing to undo"
} else {
"nothing to redo"
},
);
};
let ops = if undo {
entry.undo.clone()
} else {
entry.redo.clone()
};
match self.apply_history(&entry.table, &ops) {
Ok(()) => {
if let Some(db) = self.state.database.as_mut() {
if undo {
db.redo.push(entry.clone());
} else {
db.undo.push(entry.clone());
if db.undo.len() > MAX_HISTORY {
db.undo.remove(0);
}
}
}
vec![if undo {
Event::Undone { table: entry.table }
} else {
Event::Redone { table: entry.table }
}]
}
Err(reason) => {
// The stack did not change: a stale entry is retried once
// and then reported again instead of silently vanishing.
if let Some(db) = self.state.database.as_mut() {
if undo {
db.undo.push(entry);
} else {
db.redo.push(entry);
}
}
failed(FailureCode::Port, reason)
}
}
}
fn apply_history(&mut self, table: &str, ops: &[HistoryOp]) -> Result<(), String> {
let known = self
.state
.database
.as_ref()
.is_some_and(|db| db.tables.iter().any(|t| t.name.eq_ignore_ascii_case(table)));
if !known {
return Err(crate::port::PortError::TableNotFound(table.to_owned()).to_string());
}
for op in ops {
match op {
HistoryOp::Restore { values } => {
self.port
.restore_row(table, values)
.map_err(|e| e.to_string())?;
}
HistoryOp::Delete { values } => {
let index = self.find_row(table, values)?;
self.port
.delete_row(table, index)
.map_err(|e| e.to_string())?;
}
HistoryOp::Update { from, to } => {
let index = self.find_row(table, from)?;
self.port
.update_row(table, index, to)
.map_err(|e| e.to_string())?;
}
}
}
Ok(())
}
fn find_row(&self, table: &str, image: &[FieldValue]) -> Result<usize, String> {
let rows = self
.port
.read_rows(
table,
RowRange {
start: 0,
len: usize::MAX,
},
)
.map_err(|e| e.to_string())?;
rows.iter()
.position(|row| row == image)
.ok_or_else(|| format!("undo history is stale — no row matches {image:?} in {table:?}"))
}
/// Records a successful insert: the appended row is the last row of
/// the table (the port's insert contract), so its actual image — with
/// the engine-assigned AutoNumber — is read back.
pub(crate) fn record_insert(&mut self, table: &str) {
let rows = self.port.read_rows(
table,
RowRange {
start: 0,
len: usize::MAX,
},
);
let Ok(rows) = rows else {
self.clear_history();
return;
};
let Some(image) = rows.last().cloned() else {
self.clear_history();
return;
};
self.push_history(HistoryEntry {
table: table.to_owned(),
undo: vec![HistoryOp::Delete {
values: image.clone(),
}],
redo: vec![HistoryOp::Restore { values: image }],
});
}
/// Records a successful update (before/after images).
pub(crate) fn record_update(
&mut self,
table: &str,
before: &[FieldValue],
after: &[FieldValue],
) {
self.push_history(HistoryEntry {
table: table.to_owned(),
undo: vec![HistoryOp::Update {
from: after.to_vec(),
to: before.to_vec(),
}],
redo: vec![HistoryOp::Update {
from: before.to_vec(),
to: after.to_vec(),
}],
});
}
/// Records a successful delete (undo restores the before image).
pub(crate) fn record_delete(&mut self, table: &str, before: &[FieldValue]) {
self.push_history(HistoryEntry {
table: table.to_owned(),
undo: vec![HistoryOp::Restore {
values: before.to_vec(),
}],
redo: vec![HistoryOp::Delete {
values: before.to_vec(),
}],
});
}
fn push_history(&mut self, entry: HistoryEntry) {
if let Some(db) = self.state.database.as_mut() {
db.redo.clear();
db.undo.push(entry);
if db.undo.len() > MAX_HISTORY {
db.undo.remove(0);
}
}
}
/// Clears both stacks — the barrier for schema, batch and file-level
/// writes whose row effects are not row images.
pub(crate) fn clear_history(&mut self) {
if let Some(db) = self.state.database.as_mut() {
db.undo.clear();
db.redo.clear();
}
}
}
#[cfg(test)]
mod tests;