datacraft-core 0.2.0

Headless domain model, command bus and application state for DataCraft
Documentation
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! In-memory storage port for headless tests (split from `port.rs` to keep
//! every file under the size gate).

use std::collections::HashMap;

use crate::port::{
    DatabaseFormat, DriverCapabilities, DriverId, OpenedDatabase, PortError, Relationship,
    RowRange, StoragePort, window_slice,
};
use crate::schema::{FieldValue, TableDef};

/// In-memory backend for headless tests and early UI wiring (no filesystem
/// involvement).
#[derive(Debug, Default)]
pub struct MockPort {
    tables: Vec<TableDef>,
    rows: HashMap<String, Vec<Vec<FieldValue>>>,
    relationships: Vec<Relationship>,
    macros: Vec<crate::macro_def::MacroDef>,
    vba: Option<crate::vba::VbaProject>,
    vba_error: Option<String>,
    /// When set, `native_queries` fails with this reason (M10 tests).
    native_queries_error: Option<String>,
    /// Native query inventory (M3 surface; set by tests).
    native_queries: Vec<crate::port::NativeQuery>,
    /// File-owned views (phase 73, step 73.1; M90) — read-only.
    native_views: Vec<crate::port::NativeView>,
    /// Read-only index/trigger inventory (phase 73, step 73.2; M90).
    indexes: Vec<crate::port::SourceIndex>,
    triggers: Vec<crate::port::SourceTrigger>,
    /// Driver facts and the health verdict (phase 73, step 73.3; M91).
    source_facts: crate::port::SourceFacts,
    /// Native Access form/report inventory (phase 74, step 74.1; M87).
    native_objects: Vec<crate::port::NativeObject>,
    /// Column definitions of the native views, for read windows.
    view_defs: Vec<TableDef>,
    opened: Option<OpenedDatabase>,
    open_fail: Option<String>,
    write_fail: Option<String>,
    read_fail: Option<String>,
    /// When set, `open` requires this database password (M5 tests).
    password: Option<String>,
    /// Overrides the reported capabilities (phase 30, M17: restricted-
    /// driver simulations). `None` reports the honest mock default.
    reported_capabilities: Option<DriverCapabilities>,
    /// The lock-file name `open` reports (step 53.2, item M59 —
    /// simulated Access co-existence; combine with `with_capabilities`
    /// for the read-only shape).
    lock_file: Option<String>,
    /// Number of successful `open` calls (observability for tests).
    pub open_calls: usize,
    /// Number of `close` calls (observability for tests).
    pub close_calls: usize,
    /// Save-As calls recorded for core tests (path, password).
    pub save_as_calls: Vec<(std::path::PathBuf, Option<String>)>,
    /// Password-change calls recorded for core tests.
    pub change_password_calls: Vec<Option<String>>,
}

mod alter;
mod builders;
mod rename;

/// Out-of-range error for a single addressed row.
fn out_of_range(table: &str, row: usize, row_count: usize) -> PortError {
    PortError::OutOfRange {
        table: table.to_owned(),
        start: row,
        len: 1,
        row_count,
    }
}

impl StoragePort for MockPort {
    fn driver_id(&self) -> DriverId {
        DriverId::new("mock")
    }

    /// The honest mock default: everything DataCraft's commands can
    /// drive except atomic batches (the trait default applies batches
    /// one by one) and passwords (the mock ignores them).
    fn capabilities(&self) -> DriverCapabilities {
        self.reported_capabilities.unwrap_or_else(|| {
            let mut caps = DriverCapabilities::full();
            caps.passwords = false;
            caps
        })
    }

    fn open(
        &mut self,
        path: &std::path::Path,
        password: Option<&str>,
    ) -> Result<OpenedDatabase, PortError> {
        if let Some(detail) = &self.open_fail {
            return Err(PortError::OpenFailed {
                detail: detail.clone(),
            });
        }
        if let Some(expected) = &self.password {
            match password {
                None => {
                    return Err(PortError::PasswordRequired {
                        path: path.display().to_string(),
                    });
                }
                Some(given) if given != expected => {
                    return Err(PortError::WrongPassword {
                        path: path.display().to_string(),
                    });
                }
                Some(_) => {}
            }
        }
        self.open_calls += 1;
        let name = path
            .file_stem()
            .map_or_else(|| "mock".to_owned(), |s| s.to_string_lossy().into_owned());
        let opened = self
            .opened
            .get_or_insert(OpenedDatabase {
                name,
                format: DatabaseFormat::Jet4,
                lock_file: self.lock_file.clone(),
            })
            .clone();
        Ok(opened)
    }

    fn close(&mut self) {
        self.close_calls += 1;
        self.opened = None;
    }

    fn create_database(
        &mut self,
        path: &std::path::Path,
        format: DatabaseFormat,
    ) -> Result<(), PortError> {
        if let Some(detail) = &self.write_fail {
            return Err(PortError::WriteFailed {
                detail: detail.clone(),
            });
        }
        let _ = (path, format);
        Ok(())
    }

    fn save_as(&mut self, path: &std::path::Path, password: Option<&str>) -> Result<(), PortError> {
        if let Some(detail) = &self.write_fail {
            return Err(PortError::WriteFailed {
                detail: detail.clone(),
            });
        }
        self.save_as_calls
            .push((path.to_path_buf(), password.map(str::to_owned)));
        Ok(())
    }

    fn change_password(&mut self, new_password: Option<&str>) -> Result<(), PortError> {
        if let Some(detail) = &self.write_fail {
            return Err(PortError::WriteFailed {
                detail: detail.clone(),
            });
        }
        self.change_password_calls
            .push(new_password.map(str::to_owned));
        Ok(())
    }

    fn tables(&self) -> Vec<TableDef> {
        self.tables.clone()
    }

    fn native_views(&self) -> Result<Vec<crate::port::NativeView>, PortError> {
        Ok(self.native_views.clone())
    }

    fn indexes(&self) -> Result<Vec<crate::port::SourceIndex>, PortError> {
        Ok(self.indexes.clone())
    }

    fn triggers(&self) -> Result<Vec<crate::port::SourceTrigger>, PortError> {
        Ok(self.triggers.clone())
    }

    fn source_facts(&self) -> crate::port::SourceFacts {
        self.source_facts.clone()
    }

    fn native_objects(&self) -> Result<Vec<crate::port::NativeObject>, PortError> {
        Ok(self.native_objects.clone())
    }

    fn create_table(&mut self, definition: &TableDef) -> Result<(), PortError> {
        if let Some(detail) = &self.write_fail {
            return Err(PortError::WriteFailed {
                detail: detail.clone(),
            });
        }
        self.tables.push(definition.clone());
        Ok(())
    }

    fn drop_table(&mut self, name: &str) -> Result<String, PortError> {
        if let Some(detail) = &self.write_fail {
            return Err(PortError::WriteFailed {
                detail: detail.clone(),
            });
        }
        self.reject_view(name)?;
        let pos = self
            .tables
            .iter()
            .position(|t| t.name.to_lowercase() == name.to_lowercase())
            .ok_or_else(|| PortError::TableNotFound(name.to_owned()))?;
        Ok(self.tables.remove(pos).name)
    }

    fn alter_table(
        &mut self,
        table: &str,
        change: crate::port::SchemaChange,
    ) -> Result<(), PortError> {
        self.reject_view(table)?;
        alter::alter(self, table, change)
    }

    fn rename_table(&mut self, table: &str, new_name: &str) -> Result<String, PortError> {
        rename::rename(self, table, new_name)
    }

    fn read_rows(&self, table: &str, range: RowRange) -> Result<Vec<Vec<FieldValue>>, PortError> {
        if self.opened.is_none() {
            return Err(PortError::Unsupported {
                reason: "no database is open".to_owned(),
            });
        }
        if let Some(detail) = &self.read_fail {
            return Err(PortError::Unsupported {
                reason: detail.clone(),
            });
        }
        // A catalogued table without a row entry is an empty table.
        let def = self.table_def(table)?;
        let empty: Vec<Vec<FieldValue>> = Vec::new();
        let rows = self
            .rows
            .iter()
            .find(|(key, _)| key.eq_ignore_ascii_case(&def.name))
            .map(|(_, rows)| rows)
            .unwrap_or(&empty);
        let (start, end) = window_slice(table, range, rows.len())?;
        Ok(rows[start..end].to_vec())
    }

    fn insert_row(&mut self, table: &str, values: &[FieldValue]) -> Result<(), PortError> {
        if let Some(detail) = &self.write_fail {
            return Err(PortError::WriteFailed {
                detail: detail.clone(),
            });
        }
        self.reject_view(table)?;
        let Some(pos) = self
            .tables
            .iter()
            .position(|t| t.name.eq_ignore_ascii_case(table))
        else {
            return Err(PortError::TableNotFound(table.to_owned()));
        };
        let def = self.tables[pos].clone();
        if values.len() != def.fields.len() {
            return Err(PortError::WriteFailed {
                detail: format!(
                    "insert into {:?}: expected {} values, found {}",
                    def.name,
                    def.fields.len(),
                    values.len()
                ),
            });
        }
        self.rows.entry(def.name).or_default().push(values.to_vec());
        Ok(())
    }

    fn update_row(
        &mut self,
        table: &str,
        row: usize,
        values: &[FieldValue],
    ) -> Result<(), PortError> {
        if let Some(detail) = &self.write_fail {
            return Err(PortError::WriteFailed {
                detail: detail.clone(),
            });
        }
        self.reject_view(table)?;
        let def = self.table_def(table)?.clone();
        if values.len() != def.fields.len() {
            return Err(PortError::WriteFailed {
                detail: format!(
                    "update {:?}: expected {} values, found {}",
                    def.name,
                    def.fields.len(),
                    values.len()
                ),
            });
        }
        let rows = self
            .rows
            .iter_mut()
            .find(|(key, _)| key.eq_ignore_ascii_case(&def.name))
            .map(|(_, rows)| rows);
        let Some(rows) = rows else {
            return Err(out_of_range(table, row, 0));
        };
        let Some(target) = rows.get_mut(row) else {
            return Err(out_of_range(table, row, rows.len()));
        };
        *target = values.to_vec();
        Ok(())
    }

    fn delete_row(&mut self, table: &str, row: usize) -> Result<(), PortError> {
        if let Some(detail) = &self.write_fail {
            return Err(PortError::WriteFailed {
                detail: detail.clone(),
            });
        }
        self.reject_view(table)?;
        let def = self.table_def(table)?.clone();
        let rows = self
            .rows
            .iter_mut()
            .find(|(key, _)| key.eq_ignore_ascii_case(&def.name))
            .map(|(_, rows)| rows);
        let Some(rows) = rows else {
            return Err(out_of_range(table, row, 0));
        };
        if row >= rows.len() {
            return Err(out_of_range(table, row, rows.len()));
        }
        rows.remove(row);
        Ok(())
    }

    fn relationships(&self) -> Result<Vec<Relationship>, PortError> {
        Ok(self.relationships.clone())
    }

    fn create_relationship(&mut self, relationship: &Relationship) -> Result<(), PortError> {
        if let Some(detail) = &self.write_fail {
            return Err(PortError::WriteFailed {
                detail: detail.clone(),
            });
        }
        if self.relationships.iter().any(|entry| entry == relationship) {
            return Err(PortError::WriteFailed {
                detail: format!("duplicate relationship {relationship:?}"),
            });
        }
        self.relationships.push(relationship.clone());
        Ok(())
    }

    fn delete_relationship(&mut self, relationship: &Relationship) -> Result<(), PortError> {
        if let Some(detail) = &self.write_fail {
            return Err(PortError::WriteFailed {
                detail: detail.clone(),
            });
        }
        let Some(position) = self
            .relationships
            .iter()
            .position(|entry| entry == relationship)
        else {
            return Err(PortError::WriteFailed {
                detail: format!("relationship {relationship:?} not found"),
            });
        };
        self.relationships.remove(position);
        Ok(())
    }

    fn macros(&self) -> Result<Vec<crate::macro_def::MacroDef>, PortError> {
        Ok(self.macros.clone())
    }

    fn native_queries(&self) -> Result<Vec<crate::port::NativeQuery>, PortError> {
        if let Some(reason) = &self.native_queries_error {
            return Err(PortError::Unsupported {
                reason: reason.clone(),
            });
        }
        Ok(self.native_queries.clone())
    }

    fn vba_project(&self) -> Result<Option<crate::vba::VbaProject>, PortError> {
        if let Some(reason) = &self.vba_error {
            return Err(PortError::Unsupported {
                reason: reason.clone(),
            });
        }
        Ok(self.vba.clone())
    }
}

#[cfg(test)]
mod tests;