datacraft_core/port.rs
1//! Storage port (step 4.1, item H13).
2//!
3//! The command core performs storage I/O only through this core-owned
4//! trait: real Jet/ACE backends implement it (dependency direction
5//! `storage → core`), headless tests use [`MockPort`]. No storage type
6//! crosses into the core vocabulary.
7
8use serde::{Deserialize, Serialize};
9
10use crate::schema::{FieldValue, TableDef};
11
12mod capabilities;
13mod native_query;
14mod native_view;
15mod source_objects;
16mod write_op;
17
18pub use capabilities::{DriverCapabilities, DriverId, DriverInfo, Support};
19pub use native_query::{
20 NativeJoin, NativeJoinKind, NativeOrder, NativeQuery, NativeQueryColumn, NativeQueryKind,
21};
22pub use native_view::NativeView;
23pub use source_objects::{
24 NativeObject, NativeObjectKind, SourceFact, SourceFacts, SourceIndex, SourceTrigger,
25};
26
27/// Binary format family of an opened database (domain vocabulary; the
28/// backends map their physical version detection onto it).
29///
30/// `#[non_exhaustive]` (M32): ADR-7's server path adds format families;
31/// clients match with a wildcard arm.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34#[non_exhaustive]
35pub enum DatabaseFormat {
36 /// Jet 3.x (Access 97 and earlier).
37 Jet3,
38 /// Jet 4.x (Access 2000–2003).
39 Jet4,
40 /// ACE (Access 2007 and later, `.accdb`).
41 Ace,
42 /// SQLite 3 (`.sqlite`, `.db`) — the non-Jet source family (H35).
43 Sqlite,
44 /// A directory of `*.csv` files (phase 30, M18; ADR-7 driver proof).
45 Csv,
46}
47
48/// Errors a storage backend reports through the port.
49///
50/// `#[non_exhaustive]` (M22, ADR-7): adding a variant is not a breaking
51/// change for drivers or clients compiled against a published core —
52/// out-of-crate consumers match with a wildcard arm.
53#[derive(Debug)]
54#[non_exhaustive]
55pub enum PortError {
56 /// Opening the database file failed.
57 OpenFailed {
58 /// Concrete, locatable detail.
59 detail: String,
60 },
61 /// The requested table does not exist.
62 TableNotFound(String),
63 /// A write operation failed.
64 WriteFailed {
65 /// Concrete, locatable detail.
66 detail: String,
67 },
68 /// The file is valid but uses a feature the backend does not support.
69 Unsupported {
70 /// What is unsupported and why.
71 reason: String,
72 },
73 /// A row window starts beyond the table's rows.
74 OutOfRange {
75 /// Name of the table addressed.
76 table: String,
77 /// First requested row index.
78 start: usize,
79 /// Requested window length.
80 len: usize,
81 /// Actual row count of the table.
82 row_count: usize,
83 },
84 /// The database is password-protected and no password was supplied.
85 PasswordRequired {
86 /// Filesystem path of the database.
87 path: String,
88 },
89 /// The supplied password does not match the stored database password.
90 WrongPassword {
91 /// Filesystem path of the database.
92 path: String,
93 },
94}
95
96impl std::fmt::Display for PortError {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 match self {
99 Self::OpenFailed { detail } => write!(f, "database open failed: {detail}"),
100 Self::TableNotFound(name) => write!(f, "table {name:?} not found"),
101 Self::WriteFailed { detail } => write!(f, "write failed: {detail}"),
102 Self::Unsupported { reason } => write!(f, "unsupported: {reason}"),
103 Self::OutOfRange {
104 table,
105 start,
106 len,
107 row_count,
108 } => write!(
109 f,
110 "row window {start}+{len} of {table:?} is out of range ({row_count} rows)"
111 ),
112 Self::PasswordRequired { path } => {
113 write!(f, "{path}: the database is password-protected")
114 }
115 Self::WrongPassword { path } => {
116 write!(f, "{path}: the database password is wrong")
117 }
118 }
119 }
120}
121
122impl std::error::Error for PortError {}
123
124/// One referential-integrity relationship between two tables.
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct Relationship {
127 /// Table holding the referencing column.
128 pub table: String,
129 /// Referencing column.
130 pub column: String,
131 /// Referenced (one-side) table.
132 pub related_table: String,
133 /// Referenced column.
134 pub related_column: String,
135}
136
137/// Window selector for row reads.
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
139pub struct RowRange {
140 /// Zero-based index of the first row to read.
141 pub start: usize,
142 /// Maximum number of rows to read.
143 pub len: usize,
144}
145
146/// Metadata of a successfully opened database.
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
148pub struct OpenedDatabase {
149 /// Database name (file stem).
150 pub name: String,
151 /// Binary format family.
152 pub format: DatabaseFormat,
153 /// A sibling Access lock file detected at open (step 53.1, item M59):
154 /// the file NAME as data — Access may hold the database open, so the
155 /// session opened read-only. Language stays UI-owned (ADR-4); clients
156 /// localize the notice from this field. `None` = no lock file seen.
157 pub lock_file: Option<String>,
158}
159
160/// The storage seam of the command core. Implementors must be deterministic
161/// and must not block indefinitely.
162pub trait StoragePort {
163 /// Stable identity of this driver (phase 30, item M17; ADR-7).
164 /// Required (M22): a driver names itself — there is no default
165 /// identity, so a driver that forgets its declaration does not
166 /// compile instead of hiding behind `"generic"`.
167 fn driver_id(&self) -> DriverId;
168 /// Declarative capabilities of the open data source (phase 30, item
169 /// M17; ADR-7) — per opened session, because they depend on runtime
170 /// state. Required (M22): there is no default — the former
171 /// optimistic `DriverCapabilities::full()` fallback made a forgetful
172 /// driver *lie* about what it can do; now the compiler asks for the
173 /// declaration. Start from [`DriverCapabilities::none`] or
174 /// [`DriverCapabilities::full`] and state the deviations.
175 fn capabilities(&self) -> DriverCapabilities;
176 /// The source family this driver opens, when fixed for the driver
177 /// (M23). The default is `None` — a single-purpose driver names its
178 /// family; a multi-family driver (the Jet/ACE adapter) may too, with
179 /// its primary family. The detecting composite reads this for its
180 /// inventory's fallback entries.
181 fn source_format(&self) -> Option<DatabaseFormat> {
182 None
183 }
184 /// The driver inventory of this composition (M23): every driver it
185 /// can open with id, fixed family and offline capability summary.
186 /// The default is empty — a single-purpose port names itself via
187 /// [`StoragePort::driver_id`]; the detecting composite reports its
188 /// full registry so agents can pre-flight an open.
189 fn driver_inventory(&self) -> Vec<DriverInfo> {
190 Vec::new()
191 }
192 /// Opens the database at `path`; `password` is `None` for unprotected
193 /// files (step 16.2, M5). Backends without passwords ignore it.
194 fn open(
195 &mut self,
196 path: &std::path::Path,
197 password: Option<&str>,
198 ) -> Result<OpenedDatabase, PortError>;
199 /// Closes the open database (idempotent).
200 fn close(&mut self);
201 /// Creates a new, empty database file at `path` (phase 29, item H44).
202 /// The file must not exist yet; creating never opens the database —
203 /// the caller dispatches [`StoragePort::open`] afterwards. Backends
204 /// that cannot create files answer a precise `Unsupported` (the
205 /// default).
206 fn create_database(
207 &mut self,
208 path: &std::path::Path,
209 format: DatabaseFormat,
210 ) -> Result<(), PortError> {
211 let _ = (path, format);
212 Err(PortError::Unsupported {
213 reason: "creating database files is not supported by this backend".to_owned(),
214 })
215 }
216 /// Writes a copy of the open database to `path` (step 27.2, item
217 /// M14). `password` protects the copy; `None` writes an unencrypted
218 /// copy. The original stays untouched. Backends without a password
219 /// surface answer a precise `Unsupported` (the default).
220 fn save_as(&mut self, path: &std::path::Path, password: Option<&str>) -> Result<(), PortError> {
221 let _ = (path, password);
222 Err(PortError::Unsupported {
223 reason: "saving database copies is not supported by this backend".to_owned(),
224 })
225 }
226 /// Replaces the open database's password in place (step 27.2, item
227 /// M14); `None` removes the protection. Backends without a password
228 /// surface answer a precise `Unsupported` (the default).
229 fn change_password(&mut self, new_password: Option<&str>) -> Result<(), PortError> {
230 let _ = new_password;
231 Err(PortError::Unsupported {
232 reason: "changing database passwords is not supported by this backend".to_owned(),
233 })
234 }
235 /// Catalog of table definitions in storage order.
236 fn tables(&self) -> Vec<TableDef>;
237 /// Views that live in the opened file itself (phase 73, step 73.1;
238 /// item M90) — read-only, never DataCraft's design layer. The default
239 /// is empty: Jet/ACE and CSV carry none.
240 fn native_views(&self) -> Result<Vec<NativeView>, PortError> {
241 Ok(Vec::new())
242 }
243 /// Indexes that live in the opened file itself (phase 73, step 73.2;
244 /// item M90) — read-only inventory. The default is empty.
245 fn indexes(&self) -> Result<Vec<SourceIndex>, PortError> {
246 Ok(Vec::new())
247 }
248 /// Triggers that live in the opened file itself (phase 73, step 73.2;
249 /// item M90) — inventory only, never created or executed. The default
250 /// is empty.
251 fn triggers(&self) -> Result<Vec<SourceTrigger>, PortError> {
252 Ok(Vec::new())
253 }
254 /// Driver facts and the file's own health verdict (phase 73, step
255 /// 73.3; item M91). Read at open: the check is bounded and runs once.
256 /// The default reports no facts and a healthy file.
257 fn source_facts(&self) -> SourceFacts {
258 SourceFacts::default()
259 }
260 /// Native Access forms/reports named by the catalog (phase 74, step
261 /// 74.1; item M87) — read-only inventory, definitions never decoded.
262 /// The default is empty.
263 fn native_objects(&self) -> Result<Vec<NativeObject>, PortError> {
264 Ok(Vec::new())
265 }
266 /// Creates a table; errors on duplicate names.
267 fn create_table(&mut self, definition: &TableDef) -> Result<(), PortError>;
268 /// Drops a table; returns its canonical name.
269 fn drop_table(&mut self, name: &str) -> Result<String, PortError>;
270 /// Reads a window of rows as domain values. A window starting at
271 /// `row_count` is empty; anything beyond fails with
272 /// [`PortError::OutOfRange`].
273 fn read_rows(&self, table: &str, range: RowRange) -> Result<Vec<Vec<FieldValue>>, PortError>;
274 /// Appends one row (positional values, arity must match the table).
275 /// `Null` on an AutoNumber field means "engine-assigned".
276 fn insert_row(&mut self, table: &str, values: &[FieldValue]) -> Result<(), PortError>;
277 /// Appends a row image verbatim, including engine-assigned AutoNumber
278 /// values (step 28.1, item U14 — undo/redo restoration). The default
279 /// delegates to [`StoragePort::insert_row`]; backends that reject
280 /// user-supplied AutoNumbers override it with a validated restore path.
281 fn restore_row(&mut self, table: &str, values: &[FieldValue]) -> Result<(), PortError> {
282 self.insert_row(table, values)
283 }
284 /// Replaces the row at `row` (zero-based live-row index) with `values`
285 /// (step 11.10, H40). AutoNumber values are preserved by the caller.
286 fn update_row(
287 &mut self,
288 table: &str,
289 row: usize,
290 values: &[FieldValue],
291 ) -> Result<(), PortError>;
292 /// Deletes the row at `row` (zero-based live-row index).
293 fn delete_row(&mut self, table: &str, row: usize) -> Result<(), PortError>;
294 /// Applies a batch of row operations in order (step 11.11, M2). Indices
295 /// address the row set as it evolves through the batch. Backends apply
296 /// the batch atomically where they can (Jet does); the default applies
297 /// the operations one by one.
298 fn write_row_ops(&mut self, table: &str, ops: &[RowWriteOp]) -> Result<(), PortError> {
299 for op in ops {
300 match op {
301 RowWriteOp::Insert(values) => self.insert_row(table, values)?,
302 RowWriteOp::Update { row, values } => self.update_row(table, *row, values)?,
303 RowWriteOp::Delete { row } => self.delete_row(table, *row)?,
304 }
305 }
306 Ok(())
307 }
308 /// Alters one table's schema (step 24.3, item M9). Backends that cannot
309 /// rewrite their catalog answer a precise `Unsupported`.
310 fn alter_table(&mut self, table: &str, change: SchemaChange) -> Result<(), PortError> {
311 let _ = (table, change);
312 Err(PortError::Unsupported {
313 reason: "schema alteration is not supported by this backend".to_owned(),
314 })
315 }
316 /// Renames one table in place (phase 72, item M81); rows, indexes and
317 /// relationships follow the name. Gated on `alter_table` by the
318 /// dispatcher; backends that cannot rewrite their catalog answer a
319 /// precise `Unsupported` (the default).
320 fn rename_table(&mut self, table: &str, new_name: &str) -> Result<String, PortError> {
321 let _ = (table, new_name);
322 Err(PortError::Unsupported {
323 reason: "table renames are not supported by this backend".to_owned(),
324 })
325 }
326 /// Whether the backend can apply sidecar views natively (step 71.3,
327 /// item M93): SQLite compiles them to `CREATE VIEW`, while Jet/ACE/CSV
328 /// rely on the shadow SQL engine and answer `false`.
329 fn supports_native_views(&self) -> bool {
330 false
331 }
332 /// Creates one native view in the open database (step 71.3, M93).
333 /// Backends without a view engine answer a precise `Unsupported`.
334 fn create_native_view(&mut self, name: &str, sql: &str) -> Result<(), PortError> {
335 let _ = (name, sql);
336 Err(PortError::Unsupported {
337 reason: "native views are not supported by this backend".to_owned(),
338 })
339 }
340 /// Drops one native view (step 71.3, M93).
341 fn drop_native_view(&mut self, name: &str) -> Result<(), PortError> {
342 let _ = name;
343 Err(PortError::Unsupported {
344 reason: "native views are not supported by this backend".to_owned(),
345 })
346 }
347 /// Referential relationships of the open database.
348 fn relationships(&self) -> Result<Vec<Relationship>, PortError>;
349 /// Creates one referential relationship (step 32.3, item M16).
350 /// Backends without a relationship write path answer a precise
351 /// `Unsupported` (the default).
352 fn create_relationship(&mut self, relationship: &Relationship) -> Result<(), PortError> {
353 let _ = relationship;
354 Err(PortError::Unsupported {
355 reason: "creating relationships is not supported by this backend".to_owned(),
356 })
357 }
358 /// Deletes one referential relationship (step 32.3, item M16).
359 fn delete_relationship(&mut self, relationship: &Relationship) -> Result<(), PortError> {
360 let _ = relationship;
361 Err(PortError::Unsupported {
362 reason: "deleting relationships is not supported by this backend".to_owned(),
363 })
364 }
365 /// Native saved queries of the open database (step 15.3, M3).
366 /// Backends without native queries return an empty list.
367 fn native_queries(&self) -> Result<Vec<NativeQuery>, PortError> {
368 Ok(Vec::new())
369 }
370 /// Named macros of the open database (step 17.1, L4). Backends without
371 /// macros return an empty list; definitions are read-only.
372 fn macros(&self) -> Result<Vec<crate::macro_def::MacroDef>, PortError> {
373 Ok(Vec::new())
374 }
375 /// Extracted VBA project of the open database (step 17.2, L5).
376 /// Backends without a decoded project return `None`; extraction errors
377 /// are reported so the core can surface them without blocking the open.
378 fn vba_project(&self) -> Result<Option<crate::vba::VbaProject>, PortError> {
379 Ok(None)
380 }
381}
382
383/// One schema change of an `alter_table` call (step 24.3, item M9).
384///
385/// `#[non_exhaustive]` (M32): new alter operations are additive for
386/// out-of-crate drivers.
387#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
388#[non_exhaustive]
389pub enum SchemaChange {
390 /// Appends one field (the new last column).
391 AddField {
392 /// Full definition of the new field.
393 field: crate::schema::FieldDef,
394 },
395 /// Removes one field (name matched case-insensitively).
396 DropField {
397 /// Field name.
398 field: String,
399 },
400 /// Renames one field; row data is untouched.
401 RenameField {
402 /// Current field name (case-insensitive).
403 field: String,
404 /// New name.
405 new_name: String,
406 },
407 /// Replaces one field's properties (storage shape must not change).
408 SetFieldProperties {
409 /// Field name (case-insensitive).
410 field: String,
411 /// The new property set.
412 properties: crate::schema::FieldProperties,
413 },
414}
415
416pub use write_op::{RowWriteOp, window_slice};
417
418pub use crate::port_mock::MockPort;
419
420#[cfg(test)]
421mod tests;