ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
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
//! Why a MongoDB query did not answer: [`MongoQueryError`], and the two refusals an EXTRACTION
//! makes — [`MongoExtractionError`], which names the field, and [`MongoTypeError`], which says what
//! the field held. Beside them, why a WRITE did not land: [`MongoWriteError`].

use super::{CrossingError, MongoSortError};
use crate::{CursorError, comparison::mongo::MongoLoweringError};

/// What a stored BSON value would not become.
///
/// # A closed vocabulary of THREE, because a document has exactly three ways to disappoint
///
/// The field is absent, the field is present at another BSON type, or the field is present at the
/// right type carrying a value the Rust type cannot hold — a `Binary` of the wrong length for a
/// fixed-width carrier, an `Int64` past `i32`. Nothing else can go wrong at a leaf: BSON is
/// self-describing, so there is no parse to fail and no width to guess.
///
/// # It names the BSON type it FOUND, and that is the sentence a caller can act on
///
/// A decode that says *expected i64* leaves the reader to go and look at the document. One that
/// says *expected i64, found String* is a schema report: a migration ran, a field was written by
/// another writer, a `type = "…"` in the declaration does not match what is stored.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MongoTypeError {
  /// The document has no such field, and the Rust type cannot be built from its absence.
  ///
  /// An `Option<T>` field never raises this — see the two-state reading in
  /// [`MongoExtract`](super::MongoExtract), which is where a missing field and a `null` become one
  /// answer.
  Absent,
  /// The field is present at another BSON type. Carries what was wanted and what was found, both as
  /// BSON's own type ALIAS — the same word `$type` takes, so the message and a query that would
  /// find the offending documents spell the type the same way.
  Type {
    /// The alias this Rust type reads.
    wanted: &'static str,
    /// The alias the document held.
    found: &'static str,
  },
  /// The field is present at the right BSON type and holds a value this Rust type cannot take: a
  /// blob of the wrong length, an integer past the width, a float outside a domain invariant.
  ///
  /// Carries the reason, as the row that refused states it.
  Range(&'static str),
}

impl MongoTypeError {
  /// The refusal for a value that arrived at the wrong BSON type.
  ///
  /// Both aliases are `$type`'s own words — see [`alias`](super::extract::alias), which is where a
  /// [`Bson`] is turned into one, so a row cannot invent a spelling the query language does not
  /// take.
  #[inline]
  #[must_use]
  pub const fn wrong_type(wanted: &'static str, found: &'static str) -> Self {
    Self::Type { wanted, found }
  }
}

impl core::fmt::Display for MongoTypeError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Absent => f.write_str("this field is not in the document"),
      Self::Type { wanted, found } => {
        write!(f, "this field holds a {found} where a {wanted} was stored")
      }
      Self::Range(why) => f.write_str(why),
    }
  }
}

impl core::error::Error for MongoTypeError {}

/// One field of one document that would not read, named.
///
/// # The field name is on EVERY failure, and that is the whole of what this type adds
///
/// A refusal that says *expected i64, found String* over a twenty-field document is a search. The
/// extraction knows which field it was reading, because it reads them one at a time under their own
/// names, so the context costs nothing to carry and is the difference between a report and a hunt.
///
/// # Why serde's decode was refused, which is what this type is the alternative to
///
/// `#[derive(Deserialize)]` over the emitted document would have given the read for free, and the
/// declaration's own conversions would have ridden `#[serde(deserialize_with = "…")]`. What that
/// costs is the typed cell: a `deserialize_with` function refuses through
/// `serde::de::Error::custom`, which takes a `Display` and returns the FORMAT's error — so every
/// declared refusal arrives at the caller as a `bson::de::Error` carrying a string, and the
/// `mongo(try_into(error = "…"))` cell a declaration wrote can hold nothing at all.
///
/// The framework's standing rule is that a declared error type is the one a caller matches on. An
/// emitted extraction keeps it: this refusal is an ordinary [`Error`](core::error::Error), so `?`
/// carries it into the boxed default and a declared cell absorbs it through its own `From` — which
/// is `E0277` at the declaration where it cannot, exactly as every other leg's cell is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MongoExtractionError {
  field: &'static str,
  cause: MongoTypeError,
}

impl MongoExtractionError {
  /// `field` would not read, because `cause`.
  #[inline]
  #[must_use]
  pub const fn new(field: &'static str, cause: MongoTypeError) -> Self {
    Self { field, cause }
  }

  /// The field that would not read, under the name the document spells it — `_id` for the id, which
  /// is what a reader would go and look for.
  #[inline]
  #[must_use]
  pub const fn field(&self) -> &'static str {
    self.field
  }

  /// What the field held instead.
  #[inline]
  #[must_use]
  pub const fn cause(&self) -> &MongoTypeError {
    &self.cause
  }
}

impl core::fmt::Display for MongoExtractionError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    let Self { field, cause } = self;
    write!(f, "`{field}` did not read: {cause}")
  }
}

impl core::error::Error for MongoExtractionError {
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    Some(&self.cause)
  }
}

/// Why a MongoDB query did not answer.
///
/// # A lowering refusal is carried VERBATIM
///
/// [`SqlQueryError`](crate::query::sql::SqlQueryError)'s rule, and it holds for the same reason: a
/// filter this backend refuses — a relation with no `$lookup` behind it yet, an element scope that
/// cannot hold what was written into it — has said something specific about the query being asked,
/// and a lane reporting *the query failed* would throw away the only sentence a caller can act on.
///
/// # The DRIVER's variant rides a feature, and the rest do not
///
/// Everything above the driver is the package builder's, which compiles under `mongo` alone. Only
/// [`Driver`](Self::Driver) needs the crate that opens connections, so it is the one variant gated
/// — which is what lets a build that renders packages and executes nothing still name this type.
#[derive(Debug)]
#[non_exhaustive]
pub enum MongoQueryError {
  /// The driver refused, or the server did.
  #[cfg(feature = "mongodb")]
  Driver(mongodb::error::Error),
  /// A comparison would not lower for this backend — carried as the backend stated it.
  Lowering(MongoLoweringError),
  /// The written order cannot be rendered.
  Order(MongoSortError),
  /// The cursor is not this query's — see [`CursorError`] for which of the ways.
  Cursor(CursorError),
  /// A `skip` past what `$skip` can hold.
  ///
  /// `$skip` takes a non-negative 64-bit integer and the driver binds an `i64`, so the ceiling is
  /// [`i64::MAX`] — the same number the SQL family's `OFFSET` refuses past, arrived at from the
  /// other backend's own wire type. Carries what was asked for.
  Skip(u64),
  /// A returned document is not a row.
  Extraction(MongoExtractionError),
  /// A row is not a record, or an id is not this database's stored value.
  Crossing(CrossingError),
}

/// Why a write did not land.
///
/// # It is [`SqlWriteError`](crate::query::sql::SqlWriteError)'s roster with ONE seat added
///
/// The four the SQL family carries are here under the same names and for the same reasons — the
/// driver's own refusal, a predicate that will not lower, a record that will not cross, and the
/// unscoped delete. What a query's type has that a write's has not is likewise the same three:
/// nothing here names a cursor, writes an order or takes a `skip`, and a refusal that cannot be
/// spelled needs no variant. [`Extraction`](MongoQueryError::Extraction) is a fourth absence of the
/// same kind: a write reads no document back.
///
/// # The seat that is this BACKEND's alone — [`Joined`](Self::Joined)
///
/// A SQL delete carries its relation predicates INSIDE the statement, as correlated subqueries, so a
/// filter that asks about a neighbour is one more `WHERE` clause. MongoDB answers a relation with a
/// `$lookup`, which is a PIPELINE STAGE — and `delete_many` takes a filter document and has no
/// pipeline to put one in. So a filter that lowered to join stages has said something the command
/// cannot carry.
///
/// Dropping the stages and sending the `$match` alone is the failure this variant exists to refuse:
/// the remaining predicate is WIDER than the one the caller wrote — every conjunct the join
/// contributed is gone — so the delete would remove documents the filter never named, and report
/// success. That is [`Unscoped`](Self::Unscoped)'s own wound at one step less severe, and it gets the
/// same answer: refuse by name, before anything runs, carrying how many stages had no place to go.
///
/// The SQL family's nearest hazard is recorded rather than refused — MySQL's error 1093, at
/// [`query::sql::write`](crate::query::sql) — and the difference is who notices: there the ENGINE
/// rejects the statement, loudly, so the honest thing is to write the hazard down; here nothing would
/// reject anything, so the honest thing is to be the party that says no.
///
/// # It is a REFUSAL rather than a two-phase delete, which is the purge's own doctrine
///
/// The lane could run the aggregation, collect the `_id`s it matched and delete by that set — and
/// that is the gather the SQL removal already declined, for a reason a page does not have: a gather's
/// membership is bounded by the page size and a PURGE is bounded by nothing, so materializing the set
/// would put the whole verb under a ceiling and a re-index dropping forty thousand documents would be
/// refused for being large. It would also stop being one command, which is the whole of what makes
/// this backend's write atomic without a bracket. So the verb says no and the caller — who knows what
/// the set is for — spends the read lane and the id door.
#[derive(Debug)]
#[non_exhaustive]
pub enum MongoWriteError {
  /// The driver refused, or the server did — a DUPLICATE KEY among them, which is what a plain
  /// [`insert`](super::insert) onto an address that is already stored answers with.
  ///
  /// Carried whole rather than narrowed into a variant of this crate's own, which is
  /// [`SqlWriteError::Sql`](crate::query::sql::SqlWriteError::Sql)'s argument on the other backend:
  /// the framework cannot know WHICH index fired. `_id` is unique by the server's own construction
  /// and a collection may carry any number of other unique indexes a declaration asked the schema
  /// lane for, so a lane that reported all of them as *this already exists* would tell a caller the
  /// wrong story about most of them. A caller who means *store this whatever was there* has
  /// [`upsert`](super::upsert) and never has to read an error to get it.
  ///
  /// A caller who does mean to act on which index fired reads the driver's own answer: `11000` is
  /// MongoDB's duplicate-key code, reachable through
  /// `mongodb::error::ErrorKind::Write`. Nothing in `ingraph`
  /// re-derives that judgment — the SERVER decided, and this variant is the deciding answer surfaced
  /// rather than read.
  #[cfg(feature = "mongodb")]
  Driver(mongodb::error::Error),
  /// A comparison would not lower for this backend — carried as the backend stated it.
  Lowering(MongoLoweringError),
  /// A record is not this database's document: whatever the declaration's own write conversion
  /// refused with.
  Crossing(CrossingError),
  /// A DELETE's filter lowered to `$lookup` stages, which the command has nowhere to carry — see the
  /// type's own note. Carries how many stages were left over.
  Joined(usize),
  /// A DELETE was handed a filter naming no document at all. Carries the collection the command
  /// would have emptied, which is the sentence a caller needs: *which* collection was about to go.
  ///
  /// A [`FieldName`](crate::FieldName) rather than a string, because that is what a
  /// [`RecordAddress`](crate::RecordAddress) holds and what
  /// [`SqlWriteError::Unscoped`](crate::query::sql::SqlWriteError::Unscoped) carries one backend
  /// over.
  Unscoped(&'static crate::FieldName),
}

#[cfg(feature = "mongodb")]
impl From<mongodb::error::Error> for MongoWriteError {
  #[inline]
  fn from(error: mongodb::error::Error) -> Self {
    Self::Driver(error)
  }
}

impl From<MongoLoweringError> for MongoWriteError {
  #[inline]
  fn from(error: MongoLoweringError) -> Self {
    Self::Lowering(error)
  }
}

impl From<CrossingError> for MongoWriteError {
  #[inline]
  fn from(error: CrossingError) -> Self {
    Self::Crossing(error)
  }
}

impl core::fmt::Display for MongoWriteError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      #[cfg(feature = "mongodb")]
      Self::Driver(error) => write!(f, "this write did not run: {error}"),
      Self::Lowering(error) => write!(f, "this write's predicate does not lower here: {error}"),
      Self::Crossing(error) => write!(f, "this record and its document do not cross: {error}"),
      Self::Joined(stages) => write!(
        f,
        "this delete's filter needs {stages} `$lookup` stage(s), and a delete command carries no \
         pipeline — a predicate that reaches another collection is refused rather than run without \
         it"
      ),
      // `as_str` rather than the name itself: this family of borrowed names carries no `Display`,
      // by design — see [`borrowed_name`](crate::name).
      Self::Unscoped(collection) => write!(
        f,
        "this delete names no document, so it would empty `{}` — a filter that lowers to `{{}}` is \
         refused rather than run",
        collection.as_str()
      ),
    }
  }
}

impl core::error::Error for MongoWriteError {
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      #[cfg(feature = "mongodb")]
      Self::Driver(error) => Some(error),
      Self::Lowering(error) => Some(error),
      Self::Crossing(error) => Some(&**error),
      // No source: both are this lane's own findings about a value it was handed rather than
      // anything a driver or a lowering said.
      Self::Joined(_) | Self::Unscoped(_) => None,
    }
  }
}

/// The ceiling a `skip` is refused past — `$skip`'s own operand, which the driver binds as an
/// `i64`.
const SKIP_CEILING: u64 = i64::MAX as u64;

#[cfg(feature = "mongodb")]
impl From<mongodb::error::Error> for MongoQueryError {
  #[inline]
  fn from(error: mongodb::error::Error) -> Self {
    Self::Driver(error)
  }
}

impl From<MongoLoweringError> for MongoQueryError {
  #[inline]
  fn from(error: MongoLoweringError) -> Self {
    Self::Lowering(error)
  }
}

impl From<MongoSortError> for MongoQueryError {
  #[inline]
  fn from(error: MongoSortError) -> Self {
    Self::Order(error)
  }
}

impl From<CursorError> for MongoQueryError {
  #[inline]
  fn from(error: CursorError) -> Self {
    Self::Cursor(error)
  }
}

impl From<MongoExtractionError> for MongoQueryError {
  #[inline]
  fn from(error: MongoExtractionError) -> Self {
    Self::Extraction(error)
  }
}

impl From<CrossingError> for MongoQueryError {
  #[inline]
  fn from(error: CrossingError) -> Self {
    Self::Crossing(error)
  }
}

impl core::fmt::Display for MongoQueryError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      #[cfg(feature = "mongodb")]
      Self::Driver(error) => write!(f, "this query did not run: {error}"),
      Self::Lowering(error) => write!(f, "this query's predicate does not lower here: {error}"),
      Self::Order(error) => write!(f, "this query's order cannot be rendered here: {error}"),
      Self::Cursor(error) => write!(f, "this query cannot resume there: {error}"),
      Self::Skip(skip) => write!(
        f,
        "a skip of {skip} is past the {SKIP_CEILING} a `$skip` holds"
      ),
      Self::Extraction(error) => write!(f, "this document is not a row: {error}"),
      Self::Crossing(error) => write!(f, "this row and its record do not cross: {error}"),
    }
  }
}

impl core::error::Error for MongoQueryError {
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      #[cfg(feature = "mongodb")]
      Self::Driver(error) => Some(error),
      Self::Lowering(error) => Some(error),
      Self::Order(error) => Some(error),
      Self::Cursor(error) => Some(error),
      Self::Skip(_) => None,
      Self::Extraction(error) => Some(error),
      Self::Crossing(error) => Some(&**error),
    }
  }
}

/// `skip` as the operand `$skip` takes, or the refusal.
///
/// # Errors
///
/// [`MongoQueryError::Skip`] where the value is past [`i64::MAX`].
pub(super) fn offset(skip: u64) -> Result<i64, MongoQueryError> {
  i64::try_from(skip).map_err(|_| MongoQueryError::Skip(skip))
}

#[cfg(test)]
mod tests;