ruststream-sqlx 0.7.0

SQL databases for the RustStream messaging framework through sqlx: a transactional outbox over any RustStream broker and task queues in Postgres, MySQL/MariaDB and SQLite tables.
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! How a by-name row binds its statements: its id, its times on the host's clock and its lease,
//! and the events it leaves to the crate.

use std::mem;
use std::time::Duration;

#[cfg(feature = "chrono")]
use chrono::{DateTime, Utc};
use ruststream::HeaderMap;
use ruststream_sqlx_dialect::Param;
#[cfg(any(feature = "chrono", feature = "time"))]
use sqlx::Database;
use sqlx::{Column, Error, Row};
#[cfg(feature = "time")]
use time::OffsetDateTime;

use super::{NamedBytes, NamedId, NamedRow, NamedTime, attempt_fits, hold_to};
use crate::inbox::database::QueueDatabase;
use crate::inbox::engine::{
    self, Claimed, Claiming, Event, Events, Leasing, Now, Settled, Settling, Shape, Values,
};
use crate::inbox::form::advisory::events::{self as advisory, Candidates};
use crate::inbox::named::by_name::ByName;
use crate::inbox::named::database::RoleColumns;
use crate::inbox::named::kinds::Kinds;
#[cfg(any(feature = "chrono", feature = "time"))]
use crate::inbox::named::kinds::{ClockKind, TimeKind};
use crate::inbox::queue::Queue;
#[cfg(any(feature = "chrono", feature = "time"))]
use crate::inbox::time::{QueueTime, SystemClock};

/// Binds now on the host's clock, or `delay` later, in the time `column` holds; `false` where
/// the table has no such column or reads the database's clock.
#[cfg(any(feature = "chrono", feature = "time"))]
fn bind_now<DB, D>(
    arguments: &mut DB::Arguments,
    values: &Values<'_, DB, NamedRow<D>>,
    column: fn(Kinds) -> Option<TimeKind>,
    delay: Option<Duration>,
) -> Result<bool, Error>
where
    DB: QueueDatabase + RoleColumns,
    D: ByName<DB> + 'static,
{
    let Some(kinds) = values.queue.kinds else {
        return Ok(false);
    };
    let (Some(kind), ClockKind::System) = (column(kinds), kinds.clock) else {
        return Ok(false);
    };
    match kind {
        #[cfg(feature = "chrono")]
        TimeKind::Chrono => {
            bind_at::<DB, D, DateTime<Utc>>(arguments, values, delay, NamedTime::Chrono)
        }
        #[cfg(feature = "time")]
        TimeKind::Time => {
            bind_at::<DB, D, OffsetDateTime>(arguments, values, delay, NamedTime::Time)
        }
    }
}

/// Binds `lease`; `false` where the statement has no lease to bind.
#[cfg(any(feature = "chrono", feature = "time"))]
fn bind_lease<DB, D>(arguments: &mut DB::Arguments, lease: Option<NamedTime>) -> Result<bool, Error>
where
    DB: Database,
    D: ByName<DB>,
{
    let Some(lease) = lease else {
        return Ok(false);
    };
    D::bind_time(arguments, lease)?;
    Ok(true)
}

/// Binds now, or `delay` later, as a `Time`.
#[cfg(any(feature = "chrono", feature = "time"))]
fn bind_at<DB, D, Time>(
    arguments: &mut DB::Arguments,
    values: &Values<'_, DB, NamedRow<D>>,
    delay: Option<Duration>,
    named: fn(Time) -> NamedTime,
) -> Result<bool, Error>
where
    DB: QueueDatabase + RoleColumns,
    D: ByName<DB> + 'static,
    Time: QueueTime,
{
    let now = engine::now::<SystemClock, Time, DB, NamedRow<D>>(values)?;
    let at = delay.map_or(now, |delay| now.after(delay));
    D::bind_time(arguments, named(at))?;
    Ok(true)
}

impl<DB, D> Events<DB> for NamedRow<D>
where
    DB: QueueDatabase + RoleColumns,
    D: ByName<DB> + 'static,
{
    const SHAPE: Shape = Shape {
        custom_claim: false,
        custom_fetch: false,
        custom_ack: false,
        custom_retry: false,
        custom_retry_after: false,
        custom_discard: false,
        custom_dead_letter: false,
        custom_extend: false,
        custom_lock: false,
        custom_unlock: false,
    };

    // The lease in the type of the route's `locked_until` column, which the queue's kinds name.
    type Token = NamedTime;

    type Ids = ();

    type Headers = HeaderMap;

    fn kinds() -> Option<Kinds> {
        // The route's own row answers when the subscription opens.
        None
    }

    fn id(&self) -> &NamedId {
        &self.id
    }

    fn take_headers(&mut self) -> HeaderMap {
        mem::take(&mut self.headers)
    }

    fn unfit_header(headers: &HeaderMap) -> Option<&str> {
        // Nothing publishes through a by-name row: the route's own row writes the table.
        engine::first_header(headers)
    }

    fn partition_key(&self) -> Option<&[u8]> {
        self.key.as_ref().map(NamedBytes::as_bytes)
    }

    fn attempt(&self) -> Option<u64> {
        self.attempt
    }

    fn read_attempt(row: &DB::Row, queue: &'static Queue) -> Option<u64> {
        // The alias `ClaimShape::Roles` gives the column, held to the type the struct reads it as.
        let kind = queue.kinds?.attempt?;
        let column = row
            .columns()
            .iter()
            .find(|column| column.name() == "attempt")?;
        let (attempt, held) = DB::attempt(DB::value(row, column.ordinal()).ok()?).ok()?;
        attempt_fits(kind, held).then_some(attempt)
    }

    fn bind(
        param: Param,
        arguments: &mut DB::Arguments,
        values: &Values<'_, DB, Self>,
    ) -> Result<bool, Error> {
        Ok(match (param, values.event) {
            (Param::Id, _) => match values.id {
                Some(id) => {
                    DB::bind_id(arguments, id)?;
                    true
                }
                None => false,
            },
            (Param::Group, _) => {
                DB::bind_str(arguments, values.queue.name)?;
                true
            }
            (Param::Limit, _) => {
                DB::bind_i64(arguments, values.limit)?;
                true
            }
            (Param::Destination, Event::DeadLetter) => {
                DB::bind_str(arguments, values.destination)?;
                true
            }
            (Param::Delay, Event::RetryAfter) => {
                DB::bind_i64(arguments, engine::micros(values.delay))?;
                true
            }
            (Param::Key, _) => match values.key {
                Some(key) => {
                    DB::bind_str(arguments, key)?;
                    true
                }
                None => false,
            },
            // A time binds only where a time type is enabled: without one no table has a time
            // column, and these fall through to `false`.
            #[cfg(any(feature = "chrono", feature = "time"))]
            (Param::Now, Event::Claim | Event::Take) => {
                bind_now::<DB, D>(arguments, values, |kinds| kinds.retry_after, None)?
            }
            #[cfg(any(feature = "chrono", feature = "time"))]
            (Param::Now, Event::Ack | Event::Discard) => {
                bind_now::<DB, D>(arguments, values, |kinds| kinds.processed_at, None)?
            }
            #[cfg(any(feature = "chrono", feature = "time"))]
            (Param::RetryAfter, Event::RetryAfter) => bind_now::<DB, D>(
                arguments,
                values,
                |kinds| kinds.retry_after,
                Some(values.delay),
            )?,
            #[cfg(any(feature = "chrono", feature = "time"))]
            (Param::LeaseNow, _) => {
                bind_lease::<DB, D>(arguments, values.leasing.map(|leasing| leasing.now))?
            }
            #[cfg(any(feature = "chrono", feature = "time"))]
            (Param::Lease, _) => bind_lease::<DB, D>(arguments, values.lease)?,
            #[cfg(any(feature = "chrono", feature = "time"))]
            (Param::Held, _) => bind_lease::<DB, D>(arguments, values.held)?,
            _ => false,
        })
    }

    fn lease(queue: &'static Queue, now: Now) -> Result<Leasing<NamedTime>, Error> {
        #[cfg(any(feature = "chrono", feature = "time"))]
        if let Some(Kinds {
            locked_until: Some(kind),
            clock: ClockKind::System,
            ..
        }) = queue.kinds
        {
            return Ok(match kind {
                #[cfg(feature = "chrono")]
                TimeKind::Chrono => {
                    engine::lease::<SystemClock, DateTime<Utc>>(queue, now)?.map(NamedTime::Chrono)
                }
                #[cfg(feature = "time")]
                TimeKind::Time => {
                    engine::lease::<SystemClock, OffsetDateTime>(queue, now)?.map(NamedTime::Time)
                }
            });
        }
        let _ = (queue, now);
        // A table whose kinds name no lease has none for the role columns to bind.
        Err(engine::unbound(Param::Lease, Event::Claim))
    }

    async fn claim<'a>(
        conn: &'a mut DB::Connection,
        cx: &'a Claiming,
        lease: Option<&'a Leasing<NamedTime>>,
        _ids: &'a mut (),
        out: &'a mut Vec<Claimed<Self>>,
    ) -> Result<(), Error> {
        let claimed = out.len();
        engine::claim_rows::<DB, Self>(conn, cx, lease, out).await?;
        if let Some(kinds) = cx.queue.kinds {
            for row in &mut out[claimed..] {
                hold_to(kinds, row)?;
            }
        }
        Ok(())
    }

    fn ack<'a>(
        conn: &'a mut DB::Connection,
        cx: &'a Settling,
        id: &'a NamedId,
        held: Option<&'a NamedTime>,
    ) -> impl Future<Output = Result<Settled, Error>> + Send + 'a {
        engine::ack::<DB, Self>(conn, cx, id, held)
    }

    fn retry<'a>(
        conn: &'a mut DB::Connection,
        cx: &'a Settling,
        id: &'a NamedId,
        held: Option<&'a NamedTime>,
    ) -> impl Future<Output = Result<Settled, Error>> + Send + 'a {
        engine::retry::<DB, Self>(conn, cx, id, held)
    }

    fn retry_after<'a>(
        conn: &'a mut DB::Connection,
        cx: &'a Settling,
        id: &'a NamedId,
        held: Option<&'a NamedTime>,
        delay: Duration,
    ) -> impl Future<Output = Result<Settled, Error>> + Send + 'a {
        engine::retry_after::<DB, Self>(conn, cx, id, held, delay)
    }

    fn discard<'a>(
        conn: &'a mut DB::Connection,
        cx: &'a Settling,
        id: &'a NamedId,
        held: Option<&'a NamedTime>,
    ) -> impl Future<Output = Result<Settled, Error>> + Send + 'a {
        engine::discard::<DB, Self>(conn, cx, id, held)
    }

    fn dead_letter<'a>(
        conn: &'a mut DB::Connection,
        cx: &'a Settling,
        id: &'a NamedId,
        held: Option<&'a NamedTime>,
        destination: &'a str,
    ) -> impl Future<Output = Result<Settled, Error>> + Send + 'a {
        engine::dead_letter::<DB, Self>(conn, cx, id, held, destination)
    }

    fn extend<'a>(
        conn: &'a mut DB::Connection,
        cx: &'a Settling,
        id: &'a NamedId,
        held: &'a NamedTime,
        until: &'a NamedTime,
    ) -> impl Future<Output = Result<Settled, Error>> + Send + 'a {
        engine::extend::<DB, Self>(conn, cx, id, held, until)
    }

    fn lock<'a>(
        conn: &'a mut DB::Connection,
        cx: &'a Claiming,
        key: &'a str,
    ) -> impl Future<Output = Result<bool, Error>> + Send + 'a {
        advisory::lock::<DB, Self>(conn, cx, key)
    }

    fn unlock<'a>(
        conn: &'a mut DB::Connection,
        cx: &'a Settling,
        key: &'a str,
    ) -> impl Future<Output = Result<bool, Error>> + Send + 'a {
        advisory::unlock::<DB, Self>(conn, cx, key)
    }

    fn candidates<'a>(
        conn: &'a mut DB::Connection,
        cx: &'a Claiming,
        out: &'a mut Candidates<NamedId>,
    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
        advisory::candidates::<DB, Self>(conn, cx, out)
    }

    async fn take<'a>(
        conn: &'a mut DB::Connection,
        cx: &'a Claiming,
        id: &'a NamedId,
        out: &'a mut Vec<Claimed<Self>>,
    ) -> Result<bool, Error> {
        let taken = out.len();
        let found = advisory::take::<DB, Self>(conn, cx, id, out).await?;
        if let Some(kinds) = cx.queue.kinds {
            for row in &mut out[taken..] {
                hold_to(kinds, row)?;
            }
        }
        Ok(found)
    }
}

#[cfg(all(test, feature = "postgres", feature = "chrono"))]
mod tests {
    //! How a by-name row binds its statements on Postgres.

    use std::time::Duration;

    use chrono::{DateTime, TimeDelta, Utc};
    use ruststream::HeaderMap;
    use ruststream_sqlx_dialect::{Column, Form, Param, TableSpec};
    use sqlx::postgres::PgArguments;
    use sqlx::{Arguments, Postgres};

    use super::super::tests::{FITTING, KINDS, row};
    use super::super::{NamedId, NamedRow, NamedTime};
    use crate::inbox::engine::{Event, Events, IdAt, Leasing, Now, Prepared, Shape, Values};
    use crate::inbox::named::kinds::{ClockKind, Kinds, TimeKind};
    use crate::inbox::queue::Queue;
    use crate::inbox::time::QueueTime;
    use crate::inbox::{BuiltIn, PayloadRow};

    /// The row of a by-name subscription on Postgres, read and bound by its built-in dialect.
    type Named = NamedRow<BuiltIn<Postgres>>;

    const SPEC: TableSpec<'static> =
        TableSpec::new("email_jobs", Column::new("job_id"), Form::RowLock)
            .payload(Column::new("payload"));

    /// The subscription `emails` of a table read with `kinds`.
    fn queue(kinds: Option<Kinds>) -> &'static Queue {
        Box::leak(Box::new(Queue {
            name: "emails",
            table: "email_jobs",
            row: "SendEmail",
            spec: SPEC,
            id_at: IdAt::First,
            native_retry_after: true,
            kinds,
            prepared: Prepared::default(),
            begin_claim: None,
            counted_attempt: false,
            one_writer: false,
            poll_interval: Duration::from_secs(1),
            lease: None,
            cap: None,
        }))
    }

    /// The subscription `emails` of a lease table read with `kinds`, with a lease of thirty
    /// seconds.
    fn leased(kinds: Option<Kinds>) -> &'static Queue {
        Box::leak(Box::new(Queue {
            spec: TableSpec::new(
                "email_jobs",
                Column::new("job_id"),
                Form::Lease(Column::new("locked_until")),
            )
            .payload(Column::new("payload")),
            lease: Some(Duration::from_secs(30)),
            ..*queue(kinds)
        }))
    }

    /// Binds `param` for `event`, and says whether it bound and how many values are bound.
    fn bind(
        param: Param,
        event: Event,
        queue: &'static Queue,
        id: Option<&NamedId>,
    ) -> Result<(bool, usize), sqlx::Error> {
        bind_leased(param, event, queue, id, None)
    }

    /// Binds `param` for `event` where the statement takes `leasing`, and writes and matches
    /// its expiry.
    fn bind_leased(
        param: Param,
        event: Event,
        queue: &'static Queue,
        id: Option<&NamedId>,
        leasing: Option<&Leasing<NamedTime>>,
    ) -> Result<(bool, usize), sqlx::Error> {
        let lease = leasing.map(|leasing| leasing.expiry);
        let values = Values {
            event,
            queue,
            limit: 10,
            id,
            ids: &[],
            delay: Duration::from_secs(30),
            destination: "emails.dead",
            now: Now::default(),
            lease,
            leasing,
            held: lease,
            key: None,
        };
        let mut arguments = PgArguments::default();
        let bound = <Named as Events<Postgres>>::bind(param, &mut arguments, &values)?;
        Ok((bound, arguments.len()))
    }

    #[test]
    fn a_lock_key_binds_as_text_where_the_statement_names_one() -> Result<(), sqlx::Error> {
        let queue = queue(Some(KINDS));
        let bind_key = |event, key| {
            let values = Values {
                event,
                queue,
                limit: 10,
                id: None,
                ids: &[],
                delay: Duration::ZERO,
                destination: "",
                now: Now::default(),
                lease: None,
                leasing: None,
                held: None,
                key,
            };
            let mut arguments = PgArguments::default();
            let bound = <Named as Events<Postgres>>::bind(Param::Key, &mut arguments, &values)?;
            Ok::<_, sqlx::Error>((bound, arguments.len()))
        };
        assert_eq!(bind_key(Event::Lock, Some("email_jobs-7"))?, (true, 1));
        assert_eq!(bind_key(Event::Unlock, Some("email_jobs-7"))?, (true, 1));
        // A statement outside the lock and the unlock has no key to bind.
        assert_eq!(bind_key(Event::Ack, None)?, (false, 0));
        Ok(())
    }

    #[test]
    fn a_lease_is_taken_and_bound_in_the_type_of_its_column() -> Result<(), sqlx::Error> {
        let queue = leased(Some(Kinds {
            locked_until: Some(TimeKind::Chrono),
            ..KINDS
        }));
        let before = Utc::now();
        let lease = <Named as Events<Postgres>>::lease(queue, Now::default())?;
        assert!(
            matches!(
                lease,
                Leasing {
                    at,
                    now: NamedTime::Chrono(now),
                    expiry: NamedTime::Chrono(expiry),
                } if now == DateTime::<Utc>::from(at)
                    && expiry.timestamp_subsec_nanos() == 0
                    && expiry >= before + TimeDelta::seconds(30)
                    && expiry == now.after(Duration::from_secs(30)).rounded_up()
            ),
            "a whole second, a lease from the claim's now: {lease:?}"
        );
        for param in [Param::Lease, Param::Held, Param::LeaseNow] {
            assert_eq!(
                bind_leased(param, Event::Extend, queue, None, Some(&lease))?,
                (true, 1),
                "{param:?}"
            );
        }
        // A claim holds no lease yet, and a statement outside the lease form writes none.
        assert_eq!(
            bind_leased(Param::Held, Event::Claim, queue, None, None)?,
            (false, 0)
        );
        // A queue whose kinds name no lease cannot tell one.
        let refused = <Named as Events<Postgres>>::lease(leased(Some(KINDS)), Now::default());
        assert!(
            matches!(refused, Err(sqlx::Error::Configuration(_))),
            "{refused:?}"
        );
        assert_eq!(
            bind(Param::LeaseNow, Event::Claim, leased(Some(KINDS)), None)?,
            (false, 0)
        );
        Ok(())
    }

    fn timed(clock: ClockKind) -> Kinds {
        Kinds {
            clock,
            retry_after: Some(TimeKind::Chrono),
            processed_at: Some(TimeKind::Chrono),
            ..KINDS
        }
    }

    #[test]
    fn every_id_binds_as_its_column_holds_it() -> Result<(), sqlx::Error> {
        let queue = queue(Some(KINDS));
        for id in [
            NamedId::I16(1),
            NamedId::I32(2),
            NamedId::I64(3),
            NamedId::Text("job-4".to_owned()),
            NamedId::Bytes(vec![5]),
        ] {
            assert_eq!(bind(Param::Id, Event::Ack, queue, Some(&id))?, (true, 1));
        }
        assert_eq!(bind(Param::Id, Event::Ack, queue, None)?, (false, 0));
        Ok(())
    }

    #[test]
    fn the_queue_binds_its_name_limit_destination_and_delay() -> Result<(), sqlx::Error> {
        let queue = queue(Some(KINDS));
        assert_eq!(bind(Param::Group, Event::Claim, queue, None)?, (true, 1));
        assert_eq!(bind(Param::Limit, Event::Claim, queue, None)?, (true, 1));
        assert_eq!(
            bind(Param::Destination, Event::DeadLetter, queue, None)?,
            (true, 1)
        );
        assert_eq!(
            bind(Param::Destination, Event::Ack, queue, None)?,
            (false, 0)
        );
        assert_eq!(
            bind(Param::Delay, Event::RetryAfter, queue, None)?,
            (true, 1)
        );
        assert_eq!(bind(Param::Ids, Event::Fetch, queue, None)?, (false, 0));
        Ok(())
    }

    #[test]
    fn times_bind_on_the_hosts_clock_in_their_columns_type() -> Result<(), sqlx::Error> {
        let host = queue(Some(timed(ClockKind::System)));
        assert_eq!(bind(Param::Now, Event::Claim, host, None)?, (true, 1));
        // The take of an advisory claim checks the row is still due, as the claim does.
        assert_eq!(bind(Param::Now, Event::Take, host, None)?, (true, 1));
        assert_eq!(bind(Param::Now, Event::Ack, host, None)?, (true, 1));
        assert_eq!(bind(Param::Now, Event::Discard, host, None)?, (true, 1));
        assert_eq!(
            bind(Param::RetryAfter, Event::RetryAfter, host, None)?,
            (true, 1)
        );
        // The database's clock is read by the statement itself; a table without the column,
        // or a queue that never described its kinds, has no time to bind.
        let database = queue(Some(timed(ClockKind::Database)));
        assert_eq!(bind(Param::Now, Event::Claim, database, None)?, (false, 0));
        let untimed = queue(Some(KINDS));
        assert_eq!(bind(Param::Now, Event::Ack, untimed, None)?, (false, 0));
        assert_eq!(
            bind(Param::Now, Event::Claim, queue(None), None)?,
            (false, 0)
        );
        Ok(())
    }

    #[cfg(feature = "time")]
    #[test]
    fn time_crate_columns_bind_too() -> Result<(), sqlx::Error> {
        let kinds = Some(Kinds {
            retry_after: Some(TimeKind::Time),
            ..KINDS
        });
        assert_eq!(
            bind(Param::RetryAfter, Event::RetryAfter, queue(kinds), None)?,
            (true, 1)
        );
        Ok(())
    }

    #[test]
    fn a_named_row_lends_its_parts_and_leaves_every_event_to_the_crate() {
        let mut row = row(FITTING);
        assert_eq!(row.payload(), b"{}");
        assert_eq!(<Named as Events<Postgres>>::id(&row), &NamedId::I64(7));
        assert_eq!(
            <Named as Events<Postgres>>::partition_key(&row),
            Some(b"acme".as_slice())
        );
        assert_eq!(<Named as Events<Postgres>>::attempt(&row), Some(2));
        let mut headers = HeaderMap::new();
        headers.insert("x-tenant", "acme");
        row.headers = headers.clone();
        // The delivery takes the headers once: they move out of the row.
        assert_eq!(<Named as Events<Postgres>>::take_headers(&mut row), headers);
        assert!(<Named as Events<Postgres>>::take_headers(&mut row).is_empty());
        assert_eq!(<Named as Events<Postgres>>::SHAPE, Shape::default());
        assert_eq!(<Named as Events<Postgres>>::kinds(), None);
        assert_eq!(
            <Named as Events<Postgres>>::unfit_header(&headers),
            Some("x-tenant")
        );
    }
}