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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
use jiff::SignedDuration;

use super::SqlDurationComparison;
use crate::{DurationFilter, DurationOutOfRange};

/// The stored form a column past MySQL's 35-day `TIME` ceiling has to declare — and, since neither
/// live dialect stores an integer by default, the only remaining caller of `operand_nanos`.
fn nanos(value: SignedDuration) -> Result<i64, DurationOutOfRange> {
  DurationFilter::operand_nanos(value)
}

#[test]
fn a_parameterless_filter_crosses_into_a_parameterised_comparison() {
  let filter = DurationFilter::new()
    .with_gte(SignedDuration::from_millis(500))
    .with_in_([SignedDuration::from_secs(1), SignedDuration::ZERO]);
  let crossed = SqlDurationComparison::<i64, ()>::try_from_filter_with(filter, nanos).unwrap();

  assert_eq!(crossed.gte(), Some(&500_000_000));
  assert_eq!(crossed.in_(), Some(&[1_000_000_000i64, 0][..]));
}

/// The range check lands at the CROSSING, where a refusal is a typed error — never at the bind,
/// where it would be a driver failure, and never as an `as` cast, which would match wrong rows. It
/// is TWO-SIDED, because the operand is.
#[test]
fn an_unstorable_duration_is_refused_at_the_crossing() {
  // `i64::MAX` and `i64::MIN` nanoseconds exactly, and one nanosecond past each.
  let ceiling = SignedDuration::new(9_223_372_036, 854_775_807);
  let floor = SignedDuration::new(-9_223_372_036, -854_775_808);

  for (edge, stored) in [(ceiling, i64::MAX), (floor, i64::MIN)] {
    let crossed = SqlDurationComparison::<i64, ()>::try_from_filter_with(
      DurationFilter::new().with_eq(edge),
      nanos,
    );
    assert_eq!(crossed.unwrap().eq(), Some(&stored));
  }

  for past in [
    ceiling + SignedDuration::from_nanos(1),
    floor - SignedDuration::from_nanos(1),
  ] {
    let refused = SqlDurationComparison::<i64, ()>::try_from_filter_with(
      DurationFilter::new().with_eq(past),
      nanos,
    );
    assert_eq!(refused.unwrap_err(), DurationOutOfRange);
  }
}

/// The first refusal in a membership list is the answer, as it is for every other kind.
#[test]
fn a_list_crossing_stops_at_the_first_refusal() {
  let over = SignedDuration::new(9_223_372_036, 854_775_807) + SignedDuration::from_nanos(1);
  let filter =
    DurationFilter::new().with_in_([SignedDuration::from_secs(1), over, SignedDuration::ZERO]);
  let refused = SqlDurationComparison::<i64, ()>::try_from_filter_with(filter, nanos);
  assert_eq!(refused.unwrap_err(), DurationOutOfRange);
}

/// `in_: []` asks for no rows and is not an absent `in_`, which asks for all of them.
#[test]
fn an_empty_membership_list_stays_present() {
  let filter = DurationFilter::new().with_in_(Vec::<SignedDuration>::new());
  let crossed = SqlDurationComparison::<i64, ()>::try_from_filter_with(filter, nanos).unwrap();

  assert_eq!(crossed.in_(), Some(&[][..]));
  assert!(!crossed.is_empty());
  assert_eq!(crossed.conjuncts(), 1);
}

/// The dialect where a duration column needs no declaration at all: sqlx stores
/// [`Duration`](core::time::Duration) as a Postgres `INTERVAL`, so the crossing is jiff's own
/// conversion into it.
#[cfg(feature = "postgres")]
mod postgres {
  use core::time::Duration;

  use jiff::SignedDuration;
  use sqlx::postgres::types::PgInterval;

  use super::{SqlDurationComparison, nanos};
  use crate::{
    DurationFilter, PgDuration, PgDurationError,
    comparison::{
      TryFromFilter,
      sql::tests::{render, threaded},
    },
  };

  #[test]
  fn every_operator_renders_its_own_conjunct() {
    let filter = DurationFilter::new()
      .with_eq(SignedDuration::from_secs(1))
      .with_ne(SignedDuration::from_secs(2))
      .with_gt(SignedDuration::from_secs(3))
      .with_gte(SignedDuration::from_secs(4))
      .with_lt(SignedDuration::from_secs(5))
      .with_lte(SignedDuration::from_secs(6))
      .with_in_([SignedDuration::from_secs(7), SignedDuration::from_secs(8)])
      .with_not_in([SignedDuration::from_secs(9)]);
    let crossed =
      SqlDurationComparison::<PgDuration, sqlx::Postgres>::try_from_filter(filter).unwrap();

    assert_eq!(crossed.conjuncts(), 8);
    assert_eq!(
      render::<sqlx::Postgres, _>("len", &crossed),
      (
        "\"len\" = $1 AND NOT ( \"len\" = $2 ) AND \"len\" > $3 AND \"len\" >= $4 AND \
         \"len\" < $5 AND \"len\" <= $6 AND \"len\" IN ($7, $8) AND NOT ( \"len\" IN ($9) )"
          .to_owned(),
        9
      )
    );
  }

  /// **The undeclared crossing carries the whole signed range**, which is what the newtype was
  /// minted for: an `INTERVAL` holds a negative span, and before this carrier the only type the
  /// crossing resolved to was `core::time::Duration`, which does not.
  ///
  /// The stored form is PURE MICROSECONDS — no `months`, no `days` — because the operand is an
  /// elapsed span with no calendar fields in it. See [`PgDuration`] for the measurement that says a
  /// pure-microseconds operand still compares exactly against a mixed-field column.
  #[test]
  fn a_native_interval_column_crosses_through_a_checked_conversion() {
    let crossed = SqlDurationComparison::<PgDuration, sqlx::Postgres>::try_from_filter(
      DurationFilter::new().with_lte(SignedDuration::from_secs(90)),
    )
    .expect("90 seconds is an interval");

    assert_eq!(
      crossed.lte().map(|stored| stored.get()),
      Some(PgInterval {
        months: 0,
        days: 0,
        microseconds: 90_000_000,
      })
    );
    assert_eq!(
      render::<sqlx::Postgres, _>("len", &crossed),
      ("\"len\" <= $1".to_owned(), 1)
    );

    // The half this dialect used to give up, now a value like any other — and negative in the field
    // rather than in a sign beside it, which is what `INTERVAL` has and `TIME` does not.
    let negative = SqlDurationComparison::<PgDuration, sqlx::Postgres>::try_from_filter(
      DurationFilter::new().with_gte(SignedDuration::from_secs(-2)),
    )
    .expect("an `INTERVAL` is signed");
    assert_eq!(
      negative.gte().map(|stored| stored.get().microseconds),
      Some(-2_000_000)
    );
  }

  /// The two refusals the carrier keeps, each landing at the CROSSING where every other refusal in
  /// this family lands.
  ///
  /// Precision, because `INTERVAL` is a microsecond type and the filter is a nanosecond one; and
  /// RANGE, because the interval's microsecond field is an `i64` and a [`SignedDuration`] reaches
  /// far past it. Neither rounds nor wraps: a substituted operand is a wrong result set reported as
  /// a right one, and it would leave no mark on the SQL.
  #[test]
  fn the_carrier_refuses_sub_microsecond_precision_and_a_count_past_the_field() {
    assert_eq!(
      PgDuration::try_from(SignedDuration::from_nanos(1_500)).unwrap_err(),
      PgDurationError::Nanoseconds(500)
    );
    // The remainder is taken off the magnitude, so the direction does not change the refusal.
    assert_eq!(
      PgDuration::try_from(SignedDuration::from_nanos(-1_500)).unwrap_err(),
      PgDurationError::Nanoseconds(500)
    );

    // `i64::MAX` microseconds exactly, and one microsecond past it in each direction.
    let ceiling = SignedDuration::new(9_223_372_036_854, 775_807_000);
    assert_eq!(
      PgDuration::try_from(ceiling).unwrap().get().microseconds,
      i64::MAX
    );
    let floor = SignedDuration::new(-9_223_372_036_854, -775_808_000);
    assert_eq!(
      PgDuration::try_from(floor).unwrap().get().microseconds,
      i64::MIN
    );
    for past in [
      ceiling + SignedDuration::from_micros(1),
      floor - SignedDuration::from_micros(1),
    ] {
      assert_eq!(
        PgDuration::try_from(past).unwrap_err(),
        PgDurationError::Range
      );
    }
    // The extreme, spelled as a whole microsecond so that RANGE is what it reaches. The checks are
    // ORDERED and precision runs first, so `SignedDuration::MAX` — whose nanoseconds are 999_999_999
    // — reports the precision refusal instead, which is the more specific thing wrong with it.
    assert_eq!(
      PgDuration::try_from(SignedDuration::new(i64::MAX, 999_999_000)).unwrap_err(),
      PgDurationError::Range
    );
    assert_eq!(
      PgDuration::try_from(SignedDuration::MAX).unwrap_err(),
      PgDurationError::Nanoseconds(999)
    );

    // …and the refusal reaches the whole filter through the crossing, not only the converter.
    let refused = SqlDurationComparison::<PgDuration, sqlx::Postgres>::try_from_filter(
      DurationFilter::new().with_in_([
        SignedDuration::from_secs(1),
        SignedDuration::from_nanos(1_500),
      ]),
    );
    assert_eq!(
      refused.unwrap_err(),
      PgDurationError::Nanoseconds(500),
      "the first refusal in a list is the answer"
    );
  }

  /// A raw [`PgInterval`] keeps its carrier row and its declared route, and what that route is FOR
  /// is now narrow: a MIXED-FIELD interval, which the crate's own carrier deliberately cannot build.
  ///
  /// The negative half used to be this test's subject and is not any more — the undeclared crossing
  /// carries it. What is left is the one thing `PgDuration` refuses to do: write `months` or `days`,
  /// which a column sharing a schema with something else may need to match on.
  #[test]
  fn a_declared_interval_converter_is_the_route_to_a_mixed_field_interval() {
    /// A converter that reads a span as CALENDAR fields — thirty days written as a month, which is
    /// the reading `PgDuration` will not choose on a caller's behalf.
    fn as_months(value: SignedDuration) -> Result<PgInterval, &'static str> {
      let days = value.as_secs() / 86_400;
      let months = i32::try_from(days / 30).map_err(|_| "too many months")?;
      Ok(PgInterval {
        months,
        days: i32::try_from(days % 30).map_err(|_| "too many days")?,
        microseconds: 0,
      })
    }

    let crossed = SqlDurationComparison::<PgInterval, sqlx::Postgres>::try_from_filter_with(
      DurationFilter::new().with_gte(SignedDuration::from_hours(24 * 31)),
      as_months,
    )
    .expect("the declared converter decides the fields");

    assert_eq!(
      crossed.gte(),
      Some(&PgInterval {
        months: 1,
        days: 1,
        microseconds: 0,
      })
    );
    assert_eq!(
      render::<sqlx::Postgres, _>("len", &crossed),
      ("\"len\" >= $1".to_owned(), 1)
    );

    // The crate's own carrier over the same operand fills microseconds ALONE, which is the whole
    // difference between the two routes.
    let plain = PgDuration::try_from(SignedDuration::from_hours(24 * 31)).unwrap();
    assert_eq!(plain.get().months, 0);
    assert_eq!(plain.get().days, 0);
    assert_eq!(plain.get().microseconds, 2_678_400_000_000);
  }

  /// The stored form is invisible in the SQL: a native interval and a declared nanosecond integer
  /// render the same text and bind the same count, so the crossing has to be asserted on the
  /// operand.
  #[test]
  fn a_declared_integer_renders_what_the_native_interval_does() {
    let native = SqlDurationComparison::<PgDuration, sqlx::Postgres>::try_from_filter(
      DurationFilter::new().with_lte(SignedDuration::from_secs(90)),
    )
    .unwrap();
    let declared = SqlDurationComparison::<i64, sqlx::Postgres>::try_from_filter_with(
      DurationFilter::new().with_lte(SignedDuration::from_secs(90)),
      nanos,
    )
    .unwrap();

    assert_eq!(declared.lte(), Some(&90_000_000_000));
    assert_eq!(
      render::<sqlx::Postgres, _>("len", &native),
      render::<sqlx::Postgres, _>("len", &declared)
    );
  }

  /// WHEN a sub-microsecond operand is refused is still a choice, and the two carriers make it
  /// differently — which is what keeps `core::time::Duration`'s row worth having now that it is no
  /// longer the default.
  ///
  /// The crate's own carrier refuses at the CROSSING, where this architecture puts every refusal.
  /// `core::time::Duration` crosses the same operand happily and leaves the refusal to sqlx's
  /// `Encode` at the BIND — the same answer, later, and reported as a driver failure rather than as
  /// a typed error.
  #[test]
  fn the_two_carriers_refuse_a_sub_microsecond_operand_at_different_moments() {
    let refused = SqlDurationComparison::<PgDuration, sqlx::Postgres>::try_from_filter(
      DurationFilter::new().with_eq(SignedDuration::from_nanos(1_500)),
    );
    assert_eq!(refused.unwrap_err(), PgDurationError::Nanoseconds(500));

    let whole = SqlDurationComparison::<PgDuration, sqlx::Postgres>::try_from_filter(
      DurationFilter::new().with_eq(SignedDuration::from_nanos(2_000)),
    )
    .unwrap();
    assert_eq!(
      render::<sqlx::Postgres, _>("len", &whole),
      ("\"len\" = $1".to_owned(), 1)
    );

    // The same operand crosses when `Duration` is the declared storage type — nothing is lost, the
    // refusal simply has not happened yet.
    assert!(
      SqlDurationComparison::<Duration, sqlx::Postgres>::try_from_filter(
        DurationFilter::new().with_eq(SignedDuration::from_nanos(1_500)),
      )
      .is_ok()
    );
  }

  /// The threaded lowering renders what the borrowed one does, and it exists on THIS dialect
  /// because `INTERVAL` does: SQLite has no duration and so has neither lowering, which is what
  /// makes a duration column on it an unsatisfied bound where its comparison is named at that
  /// dialect, rather than an integer this crate invented.
  #[test]
  fn the_threaded_lowering_renders_the_same_conjuncts() {
    let crossed = SqlDurationComparison::<PgDuration, sqlx::Postgres>::try_from_filter(
      DurationFilter::new()
        .with_gte(SignedDuration::from_secs(4))
        .with_lt(SignedDuration::from_secs(5)),
    )
    .unwrap();

    assert_eq!(
      threaded::<sqlx::Postgres, _>("len", &crossed),
      "SELECT \"id\" FROM \"t\" WHERE \"len\" >= $1 AND \"len\" < $2"
    );
  }
}

/// MySQL's `TIME` is the other native duration column, and the dialect whose sqlx conversion had to
/// be replaced rather than used.
#[cfg(feature = "mysql")]
mod mysql {
  use core::time::Duration;

  use jiff::SignedDuration;
  use sqlx::mysql::types::{MySqlTime, MySqlTimeSign};

  use super::SqlDurationComparison;
  use crate::{
    DurationFilter, MySqlDuration, MySqlDurationError,
    comparison::{
      TryFromFilter,
      sql::tests::{render, threaded},
    },
  };

  #[test]
  fn every_operator_renders_its_own_conjunct() {
    let filter = DurationFilter::new()
      .with_eq(SignedDuration::from_secs(1))
      .with_ne(SignedDuration::from_secs(2))
      .with_gt(SignedDuration::from_secs(3))
      .with_gte(SignedDuration::from_secs(4))
      .with_lt(SignedDuration::from_secs(5))
      .with_lte(SignedDuration::from_secs(6))
      .with_in_([SignedDuration::from_secs(7), SignedDuration::from_secs(8)])
      .with_not_in([SignedDuration::from_secs(9)]);
    let crossed =
      SqlDurationComparison::<MySqlDuration, sqlx::MySql>::try_from_filter(filter).unwrap();

    assert_eq!(crossed.conjuncts(), 8);
    assert_eq!(
      render::<sqlx::MySql, _>("len", &crossed),
      (
        "`len` = ? AND NOT ( `len` = ? ) AND `len` > ? AND `len` >= ? AND `len` < ? AND \
         `len` <= ? AND `len` IN (?, ?) AND NOT ( `len` IN (?) )"
          .to_owned(),
        9
      )
    );
  }

  /// The measurement the newtype exists for. sqlx's own `TryFrom<Duration> for MySqlTime` reads
  /// `subsec_micros()`, so `1500ns` and `1000ns` become the SAME `TIME` and no error is raised —
  /// a rounded operand, invisible in the rendered SQL. This crate's conversion refuses instead.
  ///
  /// sqlx's conversion is from `core::time::Duration`, not from the filter's operand: it has none
  /// from a `SignedDuration` at all, which is the other half of why the newtype is here.
  #[test]
  fn sqlx_rounds_a_sub_microsecond_operand_and_this_crate_refuses_it() {
    let rounded = MySqlTime::try_from(Duration::from_nanos(1_500)).expect("sqlx accepts it");
    let whole = MySqlTime::try_from(Duration::from_nanos(1_000)).expect("sqlx accepts it");
    assert_eq!(
      rounded, whole,
      "sqlx's conversion divides by 1000, so the nanoseconds are gone with no error"
    );

    assert_eq!(
      MySqlDuration::try_from(SignedDuration::from_nanos(1_500)).unwrap_err(),
      MySqlDurationError::Nanoseconds(500)
    );
    assert_eq!(
      MySqlDuration::try_from(SignedDuration::from_nanos(1_000))
        .unwrap()
        .get(),
      whole
    );
  }

  /// …and it is refused at the CROSSING, which is where every other refusal in this family lands.
  #[test]
  fn the_crossing_carries_the_refusal() {
    let refused = SqlDurationComparison::<MySqlDuration, sqlx::MySql>::try_from_filter(
      DurationFilter::new().with_in_([
        SignedDuration::from_secs(1),
        SignedDuration::from_nanos(1_500),
      ]),
    );
    assert_eq!(
      refused.unwrap_err(),
      MySqlDurationError::Nanoseconds(500),
      "the first refusal in a list is the answer"
    );
  }

  /// `TIME` stops at `±838:59:59`, about 35 days — comfortable for a media duration and not for an
  /// accumulated total, which is what keeps `operand_nanos` alive. The ceiling is on the MAGNITUDE,
  /// so it stands at the same distance from zero in each direction.
  #[test]
  fn the_time_ceiling_is_a_refusal_and_not_a_wrap() {
    let at_ceiling = SignedDuration::from_secs(838 * 3600 + 59 * 60 + 59);
    let one = SignedDuration::from_secs(1);

    for edge in [at_ceiling, -at_ceiling] {
      assert!(MySqlDuration::try_from(edge).is_ok(), "{edge}");
    }
    for past in [at_ceiling + one, -at_ceiling - one] {
      assert_eq!(
        MySqlDuration::try_from(past).unwrap_err(),
        MySqlDurationError::Ceiling,
        "{past}"
      );
    }

    // The escape hatch: the same duration stored as `i64` nanoseconds, which has no such ceiling.
    assert_eq!(
      DurationFilter::operand_nanos(at_ceiling + one),
      Ok(3_020_400_000_000_000)
    );
  }

  /// **The SIGN reaches the column**, which sqlx's own conversion cannot carry: it hard-codes
  /// `Positive`, correctly, because a `core::time::Duration` has no other value. `TIME` does, and so
  /// does the operand, so the crossing splits magnitude from sign and puts the sign back.
  ///
  /// Read through `sign()` rather than `is_negative()`: sqlx 0.9.0's `MySqlTime::is_negative` is
  /// `self.sign.is_positive()`, which answers the opposite of its name, so a test written against it
  /// would pass for a conversion that lost the sign entirely.
  #[test]
  fn a_negative_operand_reaches_the_time_column_with_its_sign() {
    let negative = MySqlDuration::try_from(SignedDuration::from_secs(-90))
      .expect("`TIME` is a signed type")
      .get();
    assert_eq!(negative.sign(), MySqlTimeSign::Negative);
    assert_eq!(negative.hours(), 0);
    assert_eq!(negative.minutes(), 1);
    assert_eq!(negative.seconds(), 30);

    // …and the positive operand of the same magnitude is a DIFFERENT value, which is what makes the
    // sign load-bearing rather than decorative.
    let positive = MySqlDuration::try_from(SignedDuration::from_secs(90))
      .expect("the magnitude is inside the ceiling")
      .get();
    assert_eq!(positive.sign(), MySqlTimeSign::Positive);
    assert_ne!(negative, positive);
    assert!(negative < positive);

    // Zero has no sign to lose, and a `NegativeZero` is a value `MySqlTime::new` refuses outright —
    // so the guard has to be the operand's own `is_negative`, which is false at zero.
    let zero = MySqlDuration::try_from(SignedDuration::ZERO)
      .expect("zero is a duration")
      .get();
    assert_eq!(zero.sign(), MySqlTimeSign::Positive);
    assert_eq!(zero, MySqlTime::ZERO);

    // The refusal is on the MAGNITUDE, so a negative sub-microsecond operand is the same error the
    // positive one gets.
    assert_eq!(
      MySqlDuration::try_from(SignedDuration::from_nanos(-1_500)).unwrap_err(),
      MySqlDurationError::Nanoseconds(500)
    );
  }

  /// The threaded lowering renders what the borrowed one does, over the ONE storage type this
  /// dialect admits — a `core::time::Duration` has no carrier row here and so cannot reach this impl
  /// at all.
  #[test]
  fn the_threaded_lowering_renders_the_same_conjuncts() {
    let crossed = SqlDurationComparison::<MySqlDuration, sqlx::MySql>::try_from_filter(
      DurationFilter::new()
        .with_gte(SignedDuration::from_secs(4))
        .with_lt(SignedDuration::from_secs(5)),
    )
    .unwrap();

    assert_eq!(
      threaded::<sqlx::MySql, _>("len", &crossed),
      "SELECT \"id\" FROM \"t\" WHERE `len` >= ? AND `len` < ?"
    );
  }
}