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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
//! `InboxSpec`, the typed builder of a queue table's description, and `InboxTable`, the trait a
//! table described by hand implements.

use std::fmt::{self, Debug, Formatter};
use std::marker::PhantomData;

use ruststream_sqlx_dialect::{Column, Form, KeyPart, Opening, Role, TableSpec};

use super::{
    Advisory, Attempt, AttemptFrom, Clock, Declaration, Fifo, HeaderFields, Headers, Key, Lease,
    OpeningLevel, Opens, OwnEvent, Payload, ProcessedAt, Push, RetryAfter, Valid,
};
use crate::TimeSource;

/// A queue table described by hand.
///
/// A struct implements it with the table's description in `TABLE`, built by [`InboxSpec`], and
/// the builder's final type in `type Table`. The typed setters of the chain decide the type, and
/// the compiler holds the chain to it, so the time types of the chain come from `type Table`.
///
/// # Examples
///
/// ```
/// # #[cfg(all(feature = "sqlite", feature = "chrono"))]
/// # mod demo {
/// use chrono::{DateTime, Utc};
/// use std::time::Duration;
///
/// use ruststream_sqlx::dialect::Column;
/// use ruststream_sqlx::prelude::*;
/// use ruststream_sqlx::spec::{Attempt, Lease, Payload, ProcessedAt, RetryAfter};
/// use ruststream_sqlx::{AttemptRow, InboxSpec, InboxTable, PayloadRow};
/// use serde::Deserialize;
/// use sqlx::{Sqlite, SqlitePool};
///
/// #[derive(sqlx::FromRow)]
/// pub struct EmailJob {
///     job_id: i64,
///     attempt: i16,
///     payload: Vec<u8>,
/// }
///
/// impl InboxTable for EmailJob {
///     type Id = i64;
///     type Table = InboxSpec<(
///         Lease<DateTime<Utc>>,
///         Payload,
///         Attempt,
///         RetryAfter<DateTime<Utc>>,
///         ProcessedAt<DateTime<Utc>>,
///     )>;
///     const TABLE: Self::Table = InboxSpec::new("email_jobs", Column::new("job_id").generated())
///         .group(Column::new("name"))
///         .lease(Column::new("locked_until"))
///         .payload(Column::new("payload"))
///         .attempt(Column::new("attempt").generated())
///         .retry_after(Column::new("retry_after"))
///         .processed_at(Column::new("processed_at"));
///
///     fn id(&self) -> &i64 {
///         &self.job_id
///     }
/// }
///
/// impl PayloadRow for EmailJob {
///     type Column = Vec<u8>;
///
///     fn payload(&self) -> &[u8] {
///         &self.payload
///     }
/// }
///
/// impl AttemptRow for EmailJob {
///     type Attempt = i16;
///
///     fn attempt(&self) -> &i16 {
///         &self.attempt
///     }
/// }
///
/// #[derive(Deserialize)]
/// struct Email {
///     to: String,
/// }
///
/// // An address the mail server refuses comes back a minute later.
/// #[subscriber(InboxQueue::<EmailJob>::new("emails"))]
/// async fn send(email: &Email) -> HandlerOutcome {
///     if email.to.ends_with("@example.com") {
///         HandlerOutcome::ack()
///     } else {
///         HandlerOutcome::retry_after(Duration::from_secs(60))
///     }
/// }
///
/// pub fn app(pool: SqlitePool) -> RustStream {
///     RustStream::new(AppInfo::new("mailer", "1.0.0")).with_broker(
///         SqlxBroker::<Sqlite>::new(pool),
///         |b| {
///             b.include(send);
///         },
///     )
/// }
/// # }
/// # fn main() {}
/// ```
pub trait InboxTable: Sized + Send + Sync + 'static {
    /// The type of the column that identifies a row.
    type Id: Clone + Debug + Send + Sync + 'static;

    /// The table's description as a type: `InboxSpec<(..)>`, listing the markers the chain of
    /// `TABLE` sets, in the order it sets them.
    type Table: Valid;

    /// The table's description.
    const TABLE: Self::Table;

    /// The row's id.
    fn id(&self) -> &Self::Id;
}

/// The description of a queue table, with its settings as types.
///
/// `new` starts a table in the row lock form, in row mode. The column-only setters (`within`,
/// `group`, `priority`, `data`, `fetching`, `selecting_all`) keep the type. Each typed setter
/// adds its marker of [`spec`](crate::spec) to `Settings`, so a table's `type Table` lists the
/// markers its chain sets, in that order. A setting set twice does not compile. Every setter is a
/// `const fn`, and [`spec`](Self::spec) hands back the dialect's [`TableSpec`].
///
/// # Examples
///
/// ```
/// # #[cfg(all(feature = "sqlite", feature = "chrono"))]
/// # mod demo {
/// use chrono::{DateTime, Utc};
/// use ruststream_sqlx::dialect::{Column, KeyPart, level};
/// use ruststream_sqlx::prelude::*;
/// use ruststream_sqlx::spec::{Advisory, Clock, Opens, Payload, RetryAfter};
/// use ruststream_sqlx::{DatabaseClock, InboxSpec, InboxTable, PayloadRow};
/// use serde::Deserialize;
/// use sqlx::{Sqlite, SqlitePool};
///
/// #[derive(sqlx::FromRow)]
/// pub struct SyncJob {
///     id: i64,
///     payload: Vec<u8>,
/// }
///
/// impl InboxTable for SyncJob {
///     type Id = i64;
///     type Table = InboxSpec<(
///         Advisory,
///         Clock<DatabaseClock>,
///         Opens<level::Immediate>,
///         RetryAfter<DateTime<Utc>>,
///         Payload,
///     )>;
///     const TABLE: Self::Table = InboxSpec::new("sync_jobs", Column::new("id").generated())
///         .advisory(&[KeyPart::Literal("sync-"), KeyPart::Column("tenant")])
///         .clock::<DatabaseClock>()
///         .opens::<level::Immediate>()
///         .retry_after(Column::new("retry_after"))
///         .payload(Column::new("payload"));
///
///     fn id(&self) -> &i64 {
///         &self.id
///     }
/// }
///
/// impl PayloadRow for SyncJob {
///     type Column = Vec<u8>;
///
///     fn payload(&self) -> &[u8] {
///         &self.payload
///     }
/// }
///
/// #[derive(Deserialize)]
/// struct Sync {
///     tenant: String,
/// }
///
/// // One tenant syncs at a time: the lock key holds the tenant.
/// #[subscriber(InboxQueue::<SyncJob>::new("sync"))]
/// async fn sync(job: &Sync) -> HandlerOutcome {
///     tracing::info!(tenant = %job.tenant, "syncing");
///     HandlerOutcome::ack()
/// }
///
/// pub fn app(pool: SqlitePool) -> RustStream {
///     RustStream::new(AppInfo::new("sync", "1.0.0")).with_broker(
///         SqlxBroker::<Sqlite>::new(pool),
///         |b| {
///             b.include(sync);
///         },
///     )
/// }
/// # }
/// # fn main() {}
/// ```
pub struct InboxSpec<Settings = ()> {
    spec: TableSpec<'static>,
    settings: PhantomData<fn() -> Settings>,
}

// By hand: a derive would require each marker of `Settings` to implement the trait, and the
// markers are never values.
impl<Settings> Debug for InboxSpec<Settings> {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("InboxSpec")
            .field("spec", &self.spec)
            .finish_non_exhaustive()
    }
}

impl<Settings> Clone for InboxSpec<Settings> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Settings> Copy for InboxSpec<Settings> {}

impl<Settings> PartialEq for InboxSpec<Settings> {
    fn eq(&self, other: &Self) -> bool {
        self.spec == other.spec
    }
}

impl<Settings> Eq for InboxSpec<Settings> {}

impl InboxSpec {
    /// A table in the connection's default schema, with the column that identifies a row: in the
    /// row lock form, in row mode, with no other setting.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # mod demo {
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::spec::Payload;
    /// use ruststream_sqlx::{InboxSpec, InboxTable, PayloadRow};
    /// # use ruststream_sqlx::prelude::*;
    /// # use serde::Deserialize;
    /// # use sqlx::PgPool;
    ///
    /// // webhooks: id BIGSERIAL PRIMARY KEY, body BYTEA NOT NULL
    /// #[derive(sqlx::FromRow)]
    /// pub struct Webhook {
    ///     id: i64,
    ///     body: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for Webhook {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(Payload,)>;
    ///     // The database numbers the rows, so an insert leaves `id` out.
    ///     const TABLE: Self::Table = InboxSpec::new("webhooks", Column::new("id").generated())
    ///         .payload(Column::new("body"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl PayloadRow for Webhook {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.body
    ///     }
    /// }
    /// # #[derive(Deserialize)]
    /// # struct Event { kind: String }
    /// # #[subscriber(InboxQueue::<Webhook>::new("webhooks"))]
    /// # async fn receive(event: &Event) -> HandlerOutcome {
    /// #     tracing::info!(kind = %event.kind, "received");
    /// #     HandlerOutcome::ack()
    /// # }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("hooks", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(receive);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn new(table: &'static str, id: Column<'static>) -> Self {
        Self {
            spec: TableSpec::new(table, id, Form::RowLock),
            settings: PhantomData,
        }
    }
}

impl<Settings> InboxSpec<Settings> {
    /// The table's description, which every statement is built from.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # mod demo {
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::dialect::insert::{self, Sql};
    /// use ruststream_sqlx::spec::Payload;
    /// use ruststream_sqlx::{InboxSpec, InboxTable, PayloadRow};
    /// use sqlx::PgConnection;
    /// # use ruststream_sqlx::prelude::*;
    /// # use serde::Deserialize;
    /// # use sqlx::PgPool;
    ///
    /// #[derive(sqlx::FromRow)]
    /// pub struct ReceiptJob {
    ///     id: i64,
    ///     payload: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for ReceiptJob {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(Payload,)>;
    ///     const TABLE: Self::Table = InboxSpec::new("receipt_jobs", Column::new("id").generated())
    ///         .group(Column::new("name"))
    ///         .payload(Column::new("payload"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl PayloadRow for ReceiptJob {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.payload
    ///     }
    /// }
    ///
    /// // INSERT INTO "receipt_jobs" ("name", "payload") VALUES ($1, $2)
    /// const INSERT: Sql<128> = insert::postgres(&ReceiptJob::TABLE.spec());
    ///
    /// /// Queues a receipt in the order's transaction, so the two commit together.
    /// pub async fn enqueue(tx: &mut PgConnection, receipt: &[u8]) -> Result<(), sqlx::Error> {
    ///     sqlx::query(INSERT.as_str())
    ///         .bind("receipts")
    ///         .bind(receipt)
    ///         .execute(tx)
    ///         .await?;
    ///     Ok(())
    /// }
    /// # #[derive(Deserialize)]
    /// # struct Receipt { order: i64 }
    /// # #[subscriber(InboxQueue::<ReceiptJob>::new("receipts"))]
    /// # async fn send(receipt: &Receipt) -> HandlerOutcome {
    /// #     tracing::info!(order = receipt.order, "sending a receipt");
    /// #     HandlerOutcome::ack()
    /// # }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("shop", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(send);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn spec(&self) -> TableSpec<'static> {
        self.spec
    }

    /// The same table, inside `schema`.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # mod demo {
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::spec::Payload;
    /// use ruststream_sqlx::{InboxSpec, InboxTable, PayloadRow};
    /// # use ruststream_sqlx::prelude::*;
    /// # use serde::Deserialize;
    /// # use sqlx::PgPool;
    ///
    /// #[derive(sqlx::FromRow)]
    /// pub struct InvoiceJob {
    ///     id: i64,
    ///     payload: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for InvoiceJob {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(Payload,)>;
    ///     // The queue lives beside the tables it serves: `billing.invoice_jobs`.
    ///     const TABLE: Self::Table = InboxSpec::new("invoice_jobs", Column::new("id").generated())
    ///         .within("billing")
    ///         .payload(Column::new("payload"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl PayloadRow for InvoiceJob {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.payload
    ///     }
    /// }
    /// # #[derive(Deserialize)]
    /// # struct Invoice { number: String }
    /// # #[subscriber(InboxQueue::<InvoiceJob>::new("invoices"))]
    /// # async fn issue(invoice: &Invoice) -> HandlerOutcome {
    /// #     tracing::info!(number = %invoice.number, "issuing");
    /// #     HandlerOutcome::ack()
    /// # }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("billing", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(issue);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn within(self, schema: &'static str) -> Self {
        Self {
            spec: self.spec.within(schema),
            ..self
        }
    }

    /// The same table, split into groups by `column`; a subscription reads one group.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # mod demo {
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::prelude::*;
    /// use ruststream_sqlx::spec::Payload;
    /// use ruststream_sqlx::{InboxSpec, InboxTable, PayloadRow};
    /// use serde::Deserialize;
    /// # use sqlx::PgPool;
    ///
    /// #[derive(sqlx::FromRow)]
    /// pub struct MediaJob {
    ///     id: i64,
    ///     payload: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for MediaJob {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(Payload,)>;
    ///     // One table holds two queues: the `kind` column names the queue of each row.
    ///     const TABLE: Self::Table = InboxSpec::new("media_jobs", Column::new("id").generated())
    ///         .group(Column::new("kind"))
    ///         .payload(Column::new("payload"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl PayloadRow for MediaJob {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.payload
    ///     }
    /// }
    ///
    /// #[derive(Deserialize)]
    /// struct Upload {
    ///     file: String,
    /// }
    ///
    /// #[subscriber(InboxQueue::<MediaJob>::new("thumbnails"))]
    /// async fn thumbnail(upload: &Upload) -> HandlerOutcome {
    ///     tracing::info!(file = %upload.file, "drawing a thumbnail");
    ///     HandlerOutcome::ack()
    /// }
    ///
    /// #[subscriber(InboxQueue::<MediaJob>::new("transcodes"))]
    /// async fn transcode(upload: &Upload) -> HandlerOutcome {
    ///     tracing::info!(file = %upload.file, "transcoding");
    ///     HandlerOutcome::ack()
    /// }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("media", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(thumbnail);
    /// #         b.include(transcode);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn group(self, column: Column<'static>) -> Self {
        Self {
            spec: self.spec.group(column),
            ..self
        }
    }

    /// The same table, with rows claimed in the order of `column`, a smaller value first.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # mod demo {
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::spec::Payload;
    /// use ruststream_sqlx::{InboxSpec, InboxTable, PayloadRow};
    /// # use ruststream_sqlx::prelude::*;
    /// # use serde::Deserialize;
    /// # use sqlx::PgPool;
    ///
    /// // tickets: id BIGSERIAL PRIMARY KEY, severity SMALLINT NOT NULL, payload BYTEA NOT NULL
    /// #[derive(sqlx::FromRow)]
    /// pub struct Ticket {
    ///     id: i64,
    ///     payload: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for Ticket {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(Payload,)>;
    ///     // An outage (severity 0) is answered before a question (severity 3).
    ///     const TABLE: Self::Table = InboxSpec::new("tickets", Column::new("id").generated())
    ///         .priority(Column::new("severity"))
    ///         .payload(Column::new("payload"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl PayloadRow for Ticket {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.payload
    ///     }
    /// }
    /// # #[derive(Deserialize)]
    /// # struct Request { subject: String }
    /// # #[subscriber(InboxQueue::<Ticket>::new("support"))]
    /// # async fn triage(request: &Request) -> HandlerOutcome {
    /// #     tracing::info!(subject = %request.subject, "triaging");
    /// #     HandlerOutcome::ack()
    /// # }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("support", "1.0.0"))
    /// #         .with_broker(SqlxBroker::new(pool), |b| {
    /// #             b.include(triage);
    /// #         })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn priority(self, column: Column<'static>) -> Self {
        Self {
            spec: self.spec.priority(column),
            ..self
        }
    }

    /// The same table, with the columns of the message's own data: the columns without a role.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # mod demo {
    /// use ruststream::runtime::{Input, SoloCarried};
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::prelude::*;
    /// use ruststream_sqlx::{InboxSpec, InboxTable};
    /// # use sqlx::PgPool;
    ///
    /// // shipments: id BIGSERIAL PRIMARY KEY, carrier TEXT NOT NULL, tracking TEXT NOT NULL
    /// #[derive(Debug, Clone, sqlx::FromRow)]
    /// pub struct Shipment {
    ///     id: i64,
    ///     carrier: String,
    ///     tracking: String,
    /// }
    ///
    /// impl InboxTable for Shipment {
    ///     type Id = i64;
    ///     type Table = InboxSpec;
    ///     // Row mode: the claim reads these columns, and the handler takes the row.
    ///     const TABLE: Self::Table = InboxSpec::new("shipments", Column::new("id").generated())
    ///         .data(&[Column::new("carrier"), Column::new("tracking")]);
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl Input for Shipment {
    ///     type Axis = SoloCarried<Self>;
    /// }
    ///
    /// #[subscriber(InboxQueue::<Shipment>::new("shipments"))]
    /// async fn track(shipment: &Shipment) -> HandlerOutcome {
    ///     tracing::info!(carrier = %shipment.carrier, tracking = %shipment.tracking, "tracking");
    ///     HandlerOutcome::ack()
    /// }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("logistics", "1.0.0"))
    /// #         .with_broker(SqlxBroker::new(pool), |b| {
    /// #             b.include(track);
    /// #         })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn data(self, columns: &'static [Column<'static>]) -> Self {
        Self {
            spec: self.spec.data(columns),
            ..self
        }
    }

    /// The same table, with the columns a message assembled from header fields reads beside
    /// them.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # mod demo {
    /// use ruststream::HeaderMap;
    /// use ruststream::runtime::{Input, SoloCarried};
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::spec;
    /// use ruststream_sqlx::{HeaderFields, InboxSpec, InboxTable, put_header};
    /// # use ruststream_sqlx::prelude::*;
    /// # use sqlx::PgPool;
    ///
    /// #[derive(Debug, Clone, sqlx::FromRow)]
    /// pub struct RefundHeaders {
    ///     id: i64,
    ///     tenant: String,
    ///     order_id: i64,
    /// }
    ///
    /// #[derive(Debug, Clone, sqlx::FromRow)]
    /// pub struct Refund {
    ///     #[sqlx(flatten)]
    ///     headers: RefundHeaders,
    ///     reason: Option<String>,
    /// }
    ///
    /// impl InboxTable for Refund {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(spec::HeaderFields,)>;
    ///     // `tenant` and `order_id` become headers; the claim reads `reason` for the message.
    ///     const TABLE: Self::Table = InboxSpec::new("refunds", Column::new("id").generated())
    ///         .data(&[Column::new("tenant"), Column::new("order_id")])
    ///         .fetching(&[Column::new("reason")])
    ///         .header_fields();
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.headers.id
    ///     }
    /// }
    ///
    /// impl Input for Refund {
    ///     type Axis = SoloCarried<Self>;
    /// }
    ///
    /// impl HeaderFields for Refund {
    ///     const NAMES: &'static [&'static str] = &["tenant", "order_id"];
    ///
    ///     fn header_map(&self) -> HeaderMap {
    ///         let mut headers = HeaderMap::with_capacity(Self::NAMES.len());
    ///         put_header(&mut headers, "tenant", &self.headers.tenant);
    ///         put_header(&mut headers, "order_id", &self.headers.order_id);
    ///         headers
    ///     }
    /// }
    /// # #[subscriber(InboxQueue::<Refund>::new("refunds"))]
    /// # async fn pay_back(job: &Refund) -> HandlerOutcome {
    /// #     tracing::info!(order = job.headers.order_id, reason = ?job.reason, "refunding");
    /// #     HandlerOutcome::ack()
    /// # }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("payments", "1.0.0"))
    /// #         .with_broker(SqlxBroker::new(pool), |b| {
    /// #             b.include(pay_back);
    /// #         })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn fetching(self, columns: &'static [Column<'static>]) -> Self {
        Self {
            spec: self.spec.fetching(columns),
            ..self
        }
    }

    /// The same table, read with `*`: the row flattens another struct, so the columns are not
    /// all known.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # mod demo {
    /// use ruststream::runtime::{Input, SoloCarried};
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::{InboxSpec, InboxTable};
    /// # use ruststream_sqlx::prelude::*;
    /// # use sqlx::PgPool;
    ///
    /// /// The address type the service shares with its other tables.
    /// #[derive(Debug, Clone, sqlx::FromRow)]
    /// pub struct Address {
    ///     street: String,
    ///     city: String,
    /// }
    ///
    /// #[derive(Debug, Clone, sqlx::FromRow)]
    /// pub struct Parcel {
    ///     id: i64,
    ///     #[sqlx(flatten)]
    ///     address: Address,
    /// }
    ///
    /// impl InboxTable for Parcel {
    ///     type Id = i64;
    ///     type Table = InboxSpec;
    ///     // The claim reads every column, whatever `Address` holds.
    ///     const TABLE: Self::Table =
    ///         InboxSpec::new("parcels", Column::new("id").generated()).selecting_all();
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl Input for Parcel {
    ///     type Axis = SoloCarried<Self>;
    /// }
    /// # #[subscriber(InboxQueue::<Parcel>::new("parcels"))]
    /// # async fn route(parcel: &Parcel) -> HandlerOutcome {
    /// #     tracing::info!(street = %parcel.address.street, city = %parcel.address.city, "routing");
    /// #     HandlerOutcome::ack()
    /// # }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("logistics", "1.0.0"))
    /// #         .with_broker(SqlxBroker::new(pool), |b| {
    /// #             b.include(route);
    /// #         })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn selecting_all(self) -> Self {
        Self {
            spec: self.spec.selecting_all(),
            ..self
        }
    }

    /// The same table in the lease form: a claim sets `column`, the lease's expiry in `Time`, and
    /// commits. Adds [`Lease<Time>`](Lease).
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(all(feature = "postgres", feature = "chrono"))]
    /// # mod demo {
    /// use chrono::{DateTime, Utc};
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::spec::{Lease, Payload};
    /// use ruststream_sqlx::{InboxSpec, InboxTable, PayloadRow};
    /// # use ruststream_sqlx::prelude::*;
    /// # use serde::Deserialize;
    /// # use sqlx::PgPool;
    ///
    /// // report_jobs: id BIGSERIAL PRIMARY KEY, locked_until TIMESTAMPTZ NULL, payload BYTEA NOT NULL
    /// #[derive(sqlx::FromRow)]
    /// pub struct ReportJob {
    ///     id: i64,
    ///     payload: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for ReportJob {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(Lease<DateTime<Utc>>, Payload)>;
    ///     // A render that takes minutes holds its row by `locked_until`, not by an open transaction.
    ///     const TABLE: Self::Table = InboxSpec::new("report_jobs", Column::new("id").generated())
    ///         .lease(Column::new("locked_until"))
    ///         .payload(Column::new("payload"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl PayloadRow for ReportJob {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.payload
    ///     }
    /// }
    /// # #[derive(Deserialize)]
    /// # struct Report { month: String }
    /// # #[subscriber(InboxQueue::<ReportJob>::new("reports"))]
    /// # async fn render(report: &Report) -> HandlerOutcome {
    /// #     tracing::info!(month = %report.month, "rendering");
    /// #     HandlerOutcome::ack()
    /// # }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("reports", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(render);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn lease<Time>(
        self,
        column: Column<'static>,
    ) -> InboxSpec<<Settings as Push<Lease<Time>>>::Out>
    where
        Settings: Push<Lease<Time>>,
        <Settings as Push<Lease<Time>>>::Out: Declaration,
    {
        Self::with(&self.reformed(Form::Lease(column)))
    }

    /// The same table in the advisory lock form: a session lock on the key these parts build from
    /// the row holds the row. Adds [`Advisory`].
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # mod demo {
    /// use ruststream_sqlx::dialect::{Column, KeyPart};
    /// use ruststream_sqlx::spec::{Advisory, Payload};
    /// use ruststream_sqlx::{InboxSpec, InboxTable, PayloadRow};
    /// # use ruststream_sqlx::prelude::*;
    /// # use serde::Deserialize;
    /// # use sqlx::PgPool;
    ///
    /// // postings: id BIGSERIAL PRIMARY KEY, account TEXT NOT NULL, payload BYTEA NOT NULL
    /// #[derive(sqlx::FromRow)]
    /// pub struct Posting {
    ///     id: i64,
    ///     payload: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for Posting {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(Advisory, Payload)>;
    ///     // One account's postings run one at a time across every process: the key is `ledger-<account>`.
    ///     const TABLE: Self::Table = InboxSpec::new("postings", Column::new("id").generated())
    ///         .advisory(&[KeyPart::Literal("ledger-"), KeyPart::Column("account")])
    ///         .payload(Column::new("payload"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl PayloadRow for Posting {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.payload
    ///     }
    /// }
    /// # #[derive(Deserialize)]
    /// # struct Entry { amount: i64 }
    /// # #[subscriber(InboxQueue::<Posting>::new("ledger"))]
    /// # async fn post(entry: &Entry) -> HandlerOutcome {
    /// #     tracing::info!(amount = entry.amount, "posting");
    /// #     HandlerOutcome::ack()
    /// # }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("ledger", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(post);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn advisory(
        self,
        key: &'static [KeyPart<'static>],
    ) -> InboxSpec<<Settings as Push<Advisory>>::Out>
    where
        Settings: Push<Advisory>,
        <Settings as Push<Advisory>>::Out: Declaration,
    {
        Self::with(&self.reformed(Form::Advisory(key)))
    }

    /// The same table in payload mode, the message's bytes read from `column`. Adds [`Payload`].
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "mysql")]
    /// # mod demo {
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::spec::Payload;
    /// use ruststream_sqlx::{InboxSpec, InboxTable, PayloadRow};
    /// # use ruststream_sqlx::prelude::*;
    /// # use serde::Deserialize;
    /// # use sqlx::{MySql, MySqlPool};
    ///
    /// // audit_events: id BIGINT AUTO_INCREMENT PRIMARY KEY, body TEXT NOT NULL
    /// #[derive(sqlx::FromRow)]
    /// pub struct AuditEvent {
    ///     id: i64,
    ///     body: String,
    /// }
    ///
    /// impl InboxTable for AuditEvent {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(Payload,)>;
    ///     // The message is the JSON text in `body`, which the subscription's codec decodes.
    ///     const TABLE: Self::Table = InboxSpec::new("audit_events", Column::new("id").generated())
    ///         .payload(Column::new("body"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl PayloadRow for AuditEvent {
    ///     type Column = String;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         self.body.as_bytes()
    ///     }
    /// }
    /// # #[derive(Deserialize)]
    /// # struct Login { user: String }
    /// # #[subscriber(InboxQueue::<AuditEvent>::new("logins"))]
    /// # async fn record(login: &Login) -> HandlerOutcome {
    /// #     tracing::info!(user = %login.user, "logged in");
    /// #     HandlerOutcome::ack()
    /// # }
    /// # pub fn app(pool: MySqlPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("audit", "1.0.0")).with_broker(
    /// #         SqlxBroker::<MySql>::new(pool),
    /// #         |b| {
    /// #             b.include(record);
    /// #         },
    /// #     )
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn payload(
        self,
        column: Column<'static>,
    ) -> InboxSpec<<Settings as Push<Payload>>::Out>
    where
        Settings: Push<Payload>,
        <Settings as Push<Payload>>::Out: Declaration,
    {
        Self::with(&self.spec.payload(column))
    }

    /// The same table, with the delivery's partition key read from `column`. Adds [`Key`].
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # mod demo {
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::spec::{Key, Payload};
    /// use ruststream_sqlx::{InboxSpec, InboxTable, KeyRow, PayloadRow};
    /// # use ruststream_sqlx::prelude::*;
    /// # use serde::Deserialize;
    /// # use sqlx::PgPool;
    ///
    /// // export_jobs: id BIGSERIAL PRIMARY KEY, customer TEXT NOT NULL, payload BYTEA NOT NULL
    /// #[derive(sqlx::FromRow)]
    /// pub struct ExportJob {
    ///     id: i64,
    ///     customer: String,
    ///     payload: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for ExportJob {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(Key, Payload)>;
    ///     // Each delivery carries its customer as the partition key, which the dispatch keeps in order.
    ///     const TABLE: Self::Table = InboxSpec::new("export_jobs", Column::new("id").generated())
    ///         .partition_key(Column::new("customer"))
    ///         .payload(Column::new("payload"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl KeyRow for ExportJob {
    ///     type Key = String;
    ///
    ///     fn partition_key(&self) -> &String {
    ///         &self.customer
    ///     }
    /// }
    ///
    /// impl PayloadRow for ExportJob {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.payload
    ///     }
    /// }
    /// # #[derive(Deserialize)]
    /// # struct Export { file: String }
    /// # #[subscriber(InboxQueue::<ExportJob>::new("exports"))]
    /// # async fn export(job: &Export) -> HandlerOutcome {
    /// #     tracing::info!(file = %job.file, "exporting");
    /// #     HandlerOutcome::ack()
    /// # }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("exports", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(export);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn partition_key(
        self,
        column: Column<'static>,
    ) -> InboxSpec<<Settings as Push<Key>>::Out>
    where
        Settings: Push<Key>,
        <Settings as Push<Key>>::Out: Declaration,
    {
        Self::with(&self.spec.partition_key(column))
    }

    /// The same table, counting a row's attempts in `column`. Adds [`Attempt`].
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # mod demo {
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::prelude::*;
    /// use ruststream_sqlx::spec::{Attempt, Payload};
    /// use ruststream_sqlx::{AttemptRow, InboxSpec, InboxTable, PayloadRow};
    /// use serde::Deserialize;
    /// # use sqlx::PgPool;
    ///
    /// // downloads: id BIGSERIAL PRIMARY KEY, tries INT NOT NULL DEFAULT 1, payload BYTEA NOT NULL
    /// #[derive(sqlx::FromRow)]
    /// pub struct Download {
    ///     id: i64,
    ///     tries: i32,
    ///     payload: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for Download {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(Attempt, Payload)>;
    ///     // A retry counts in `tries`, and the handler reads the count.
    ///     const TABLE: Self::Table = InboxSpec::new("downloads", Column::new("id").generated())
    ///         .attempt(Column::new("tries").generated())
    ///         .payload(Column::new("payload"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl AttemptRow for Download {
    ///     type Attempt = i32;
    ///
    ///     fn attempt(&self) -> &i32 {
    ///         &self.tries
    ///     }
    /// }
    ///
    /// impl PayloadRow for Download {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.payload
    ///     }
    /// }
    ///
    /// #[derive(Deserialize)]
    /// struct Image {
    ///     url: String,
    /// }
    ///
    /// # async fn fetch(_: &str) -> bool { true }
    /// // An image the fifth attempt cannot fetch is given up.
    /// #[subscriber(InboxQueue::<Download>::new("images"))]
    /// async fn download(image: &Image, Ctx(attempt): Ctx<keys::Attempt>) -> HandlerOutcome {
    ///     if fetch(&image.url).await {
    ///         HandlerOutcome::ack()
    ///     } else if attempt.unwrap_or(1) >= 5 {
    ///         HandlerOutcome::drop()
    ///     } else {
    ///         HandlerOutcome::retry()
    ///     }
    /// }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("images", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(download);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn attempt(
        self,
        column: Column<'static>,
    ) -> InboxSpec<<Settings as Push<Attempt>>::Out>
    where
        Settings: Push<Attempt>,
        <Settings as Push<Attempt>>::Out: Declaration,
    {
        Self::with(&self.spec.attempt(column))
    }

    /// The same table, with `column` counting the row's attempts, decoded as `Decoded` and
    /// converted into the row's attempt field: what `#[sqlx(try_from = "..")]` on the derive's
    /// `attempt` field spells. Adds [`AttemptFrom`].
    #[doc(hidden)]
    #[must_use]
    pub const fn attempt_from<Decoded>(
        self,
        column: Column<'static>,
    ) -> InboxSpec<<Settings as Push<AttemptFrom<Decoded>>>::Out>
    where
        Settings: Push<AttemptFrom<Decoded>>,
        <Settings as Push<AttemptFrom<Decoded>>>::Out: Declaration,
    {
        Self::with(&self.spec.attempt(column))
    }

    /// The same table, with the delivery's headers read from `column`. Adds [`Headers`].
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(all(feature = "postgres", feature = "json"))]
    /// # mod demo {
    /// use std::collections::BTreeMap;
    ///
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::prelude::*;
    /// use ruststream_sqlx::spec::{Headers, Payload};
    /// use ruststream_sqlx::{HeaderRow, InboxSpec, InboxTable, PayloadRow};
    /// use serde::Deserialize;
    /// use sqlx::types::Json;
    /// # use sqlx::PgPool;
    ///
    /// // pushes: id BIGSERIAL PRIMARY KEY, meta JSONB NULL, payload BYTEA NOT NULL
    /// #[derive(sqlx::FromRow)]
    /// pub struct PushJob {
    ///     id: i64,
    ///     meta: Option<Json<BTreeMap<String, String>>>,
    ///     payload: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for PushJob {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(Headers, Payload)>;
    ///     // The JSON object in `meta` becomes the delivery's headers.
    ///     const TABLE: Self::Table = InboxSpec::new("pushes", Column::new("id").generated())
    ///         .headers(Column::new("meta"))
    ///         .payload(Column::new("payload"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl HeaderRow for PushJob {
    ///     type Column = Option<Json<BTreeMap<String, String>>>;
    ///
    ///     fn headers_mut(&mut self) -> &mut Self::Column {
    ///         &mut self.meta
    ///     }
    /// }
    ///
    /// impl PayloadRow for PushJob {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.payload
    ///     }
    /// }
    ///
    /// #[derive(Deserialize)]
    /// struct Notification {
    ///     title: String,
    /// }
    ///
    /// #[subscriber(InboxQueue::<PushJob>::new("pushes"))]
    /// async fn push(note: &Notification, ctx: &mut Context<'_>) -> HandlerOutcome {
    ///     let device = ctx.headers().get_str("device").unwrap_or("all");
    ///     tracing::info!(title = %note.title, device, "pushing");
    ///     HandlerOutcome::ack()
    /// }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("push", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(push);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn headers(
        self,
        column: Column<'static>,
    ) -> InboxSpec<<Settings as Push<Headers>>::Out>
    where
        Settings: Push<Headers>,
        <Settings as Push<Headers>>::Out: Declaration,
    {
        Self::with(&self.spec.headers(column))
    }

    /// The same table, with the delivery's headers built from the row's header fields, whose
    /// columns [`data`](Self::data) and [`fetching`](Self::fetching) name. Adds
    /// [`HeaderFields`].
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # mod demo {
    /// use ruststream::HeaderMap;
    /// use ruststream::runtime::{Input, SoloCarried};
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::prelude::*;
    /// use ruststream_sqlx::spec;
    /// use ruststream_sqlx::{HeaderFields, InboxSpec, InboxTable, put_header};
    /// # use sqlx::PgPool;
    ///
    /// // sms_jobs: id BIGSERIAL PRIMARY KEY, phone TEXT NOT NULL, locale TEXT NOT NULL, text TEXT NOT NULL
    /// #[derive(Debug, Clone, sqlx::FromRow)]
    /// pub struct Sms {
    ///     id: i64,
    ///     phone: String,
    ///     locale: String,
    ///     text: String,
    /// }
    ///
    /// impl InboxTable for Sms {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(spec::HeaderFields,)>;
    ///     // The `locale` column reads as a header, as it would on any other broker.
    ///     const TABLE: Self::Table = InboxSpec::new("sms_jobs", Column::new("id").generated())
    ///         .data(&[Column::new("phone"), Column::new("locale"), Column::new("text")])
    ///         .header_fields();
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl Input for Sms {
    ///     type Axis = SoloCarried<Self>;
    /// }
    ///
    /// impl HeaderFields for Sms {
    ///     const NAMES: &'static [&'static str] = &["locale"];
    ///
    ///     fn header_map(&self) -> HeaderMap {
    ///         let mut headers = HeaderMap::with_capacity(Self::NAMES.len());
    ///         put_header(&mut headers, "locale", &self.locale);
    ///         headers
    ///     }
    /// }
    ///
    /// #[subscriber(InboxQueue::<Sms>::new("sms"))]
    /// async fn send(sms: &Sms, ctx: &mut Context<'_>) -> HandlerOutcome {
    ///     let locale = ctx.headers().get_str("locale").unwrap_or("en");
    ///     tracing::info!(phone = %sms.phone, locale, len = sms.text.len(), "sending");
    ///     HandlerOutcome::ack()
    /// }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("sms", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(send);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn header_fields(self) -> InboxSpec<<Settings as Push<HeaderFields>>::Out>
    where
        Settings: Push<HeaderFields>,
        <Settings as Push<HeaderFields>>::Out: Declaration,
    {
        Self::with(&self.spec)
    }

    /// The same table, with the time a retried row is due in `column`, in `Time`. Adds
    /// [`RetryAfter<Time>`](RetryAfter).
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(all(feature = "postgres", feature = "chrono"))]
    /// # mod demo {
    /// use std::time::Duration;
    ///
    /// use chrono::{DateTime, Utc};
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::prelude::*;
    /// use ruststream_sqlx::spec::{Payload, RetryAfter};
    /// use ruststream_sqlx::{InboxSpec, InboxTable, PayloadRow};
    /// use serde::Deserialize;
    /// # use sqlx::PgPool;
    ///
    /// // crm_pushes: id BIGSERIAL PRIMARY KEY, due TIMESTAMPTZ NOT NULL DEFAULT now(),
    /// // payload BYTEA NOT NULL
    /// #[derive(sqlx::FromRow)]
    /// pub struct CrmPush {
    ///     id: i64,
    ///     payload: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for CrmPush {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(RetryAfter<DateTime<Utc>>, Payload)>;
    ///     // A row is claimed once `due` has passed, so a delayed retry waits in the table.
    ///     const TABLE: Self::Table = InboxSpec::new("crm_pushes", Column::new("id").generated())
    ///         .retry_after(Column::new("due").generated())
    ///         .payload(Column::new("payload"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl PayloadRow for CrmPush {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.payload
    ///     }
    /// }
    ///
    /// #[derive(Deserialize)]
    /// struct Contact {
    ///     email: String,
    /// }
    ///
    /// # async fn upsert(_: &str) -> Result<(), Duration> { Ok(()) }
    /// #[subscriber(InboxQueue::<CrmPush>::new("crm"))]
    /// async fn sync(contact: &Contact) -> HandlerOutcome {
    ///     match upsert(&contact.email).await {
    ///         Ok(()) => HandlerOutcome::ack(),
    ///         // The CRM's rate limit says how long to wait.
    ///         Err(wait) => HandlerOutcome::retry_after(wait),
    ///     }
    /// }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("crm", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(sync);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn retry_after<Time>(
        self,
        column: Column<'static>,
    ) -> InboxSpec<<Settings as Push<RetryAfter<Time>>>::Out>
    where
        Settings: Push<RetryAfter<Time>>,
        <Settings as Push<RetryAfter<Time>>>::Out: Declaration,
    {
        Self::with(&self.spec.retry_after(column))
    }

    /// The same table, with the time a row was processed written into `column`, in `Time`, so a
    /// processed row stays in the table. Adds [`ProcessedAt<Time>`](ProcessedAt).
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(all(feature = "postgres", feature = "time"))]
    /// # mod demo {
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::spec::{Payload, ProcessedAt};
    /// use ruststream_sqlx::{InboxSpec, InboxTable, PayloadRow};
    /// use time::OffsetDateTime;
    /// # use ruststream_sqlx::prelude::*;
    /// # use serde::Deserialize;
    /// # use sqlx::PgPool;
    ///
    /// // payments: id BIGSERIAL PRIMARY KEY, processed_at TIMESTAMPTZ NULL, payload BYTEA NOT NULL
    /// #[derive(sqlx::FromRow)]
    /// pub struct PaymentJob {
    ///     id: i64,
    ///     payload: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for PaymentJob {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(ProcessedAt<OffsetDateTime>, Payload)>;
    ///     // A settled payment stays in the table for the auditors, stamped in `processed_at`.
    ///     const TABLE: Self::Table = InboxSpec::new("payments", Column::new("id").generated())
    ///         .processed_at(Column::new("processed_at").generated())
    ///         .payload(Column::new("payload"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl PayloadRow for PaymentJob {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.payload
    ///     }
    /// }
    /// # #[derive(Deserialize)]
    /// # struct Payment { cents: i64 }
    /// # #[subscriber(InboxQueue::<PaymentJob>::new("payments"))]
    /// # async fn settle(payment: &Payment) -> HandlerOutcome {
    /// #     tracing::info!(cents = payment.cents, "settling");
    /// #     HandlerOutcome::ack()
    /// # }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("payments", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(settle);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn processed_at<Time>(
        self,
        column: Column<'static>,
    ) -> InboxSpec<<Settings as Push<ProcessedAt<Time>>>::Out>
    where
        Settings: Push<ProcessedAt<Time>>,
        <Settings as Push<ProcessedAt<Time>>>::Out: Declaration,
    {
        Self::with(&self.spec.processed_at(column))
    }

    /// The same table, split into groups by `column`, with each group in order: at most one row
    /// of a group is in work, taken in claim order. Adds [`Fifo`].
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # mod demo {
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::prelude::*;
    /// use ruststream_sqlx::spec::{Fifo, Payload};
    /// use ruststream_sqlx::{InboxSpec, InboxTable, PayloadRow};
    /// use serde::Deserialize;
    /// # use sqlx::PgPool;
    ///
    /// // stock_updates: id BIGSERIAL PRIMARY KEY, warehouse TEXT NOT NULL, payload BYTEA NOT NULL
    /// #[derive(sqlx::FromRow)]
    /// pub struct StockUpdate {
    ///     id: i64,
    ///     payload: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for StockUpdate {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(Fifo, Payload)>;
    ///     // Each warehouse is a group, and its updates arrive one at a time, in the order written.
    ///     const TABLE: Self::Table = InboxSpec::new("stock_updates", Column::new("id").generated())
    ///         .fifo_group(Column::new("warehouse"))
    ///         .payload(Column::new("payload"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl PayloadRow for StockUpdate {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.payload
    ///     }
    /// }
    ///
    /// #[derive(Deserialize)]
    /// struct Level {
    ///     sku: String,
    ///     count: i64,
    /// }
    ///
    /// #[subscriber(InboxQueue::<StockUpdate>::new("berlin"))]
    /// async fn berlin(level: &Level) -> HandlerOutcome {
    ///     tracing::info!(sku = %level.sku, level.count, "berlin stock");
    ///     HandlerOutcome::ack()
    /// }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("stock", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(berlin);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn fifo_group(
        self,
        column: Column<'static>,
    ) -> InboxSpec<<Settings as Push<Fifo>>::Out>
    where
        Settings: Push<Fifo>,
        <Settings as Push<Fifo>>::Out: Declaration,
    {
        Self::with(&self.spec.fifo_group(column))
    }

    /// The same table, reading now from `Source`: the statements read the database's own clock
    /// where `Source` is [`DatabaseClock`](crate::DatabaseClock). Adds
    /// [`Clock<Source>`](Clock).
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(all(feature = "postgres", feature = "chrono"))]
    /// # mod demo {
    /// use chrono::{DateTime, Utc};
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::spec::{Clock, Payload, RetryAfter};
    /// use ruststream_sqlx::{DatabaseClock, InboxSpec, InboxTable, PayloadRow};
    /// # use std::time::Duration;
    /// # use ruststream_sqlx::prelude::*;
    /// # use serde::Deserialize;
    /// # use sqlx::PgPool;
    ///
    /// // reminders: id BIGSERIAL PRIMARY KEY, retry_after TIMESTAMPTZ NOT NULL DEFAULT now(),
    /// // payload BYTEA NOT NULL
    /// #[derive(sqlx::FromRow)]
    /// pub struct Reminder {
    ///     id: i64,
    ///     payload: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for Reminder {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(Clock<DatabaseClock>, RetryAfter<DateTime<Utc>>, Payload)>;
    ///     // Due times count from the database's `now()`, so hosts whose clocks drift still agree.
    ///     const TABLE: Self::Table = InboxSpec::new("reminders", Column::new("id").generated())
    ///         .clock::<DatabaseClock>()
    ///         .retry_after(Column::new("retry_after").generated())
    ///         .payload(Column::new("payload"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl PayloadRow for Reminder {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.payload
    ///     }
    /// }
    /// # #[derive(Deserialize)]
    /// # struct Note { text: String }
    /// # #[subscriber(InboxQueue::<Reminder>::new("reminders"))]
    /// # async fn remind(note: &Note) -> HandlerOutcome {
    /// #     tracing::info!(text = %note.text, "reminding");
    /// #     HandlerOutcome::retry_after(Duration::from_secs(3600))
    /// # }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("reminders", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(remind);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn clock<Source: TimeSource>(
        self,
    ) -> InboxSpec<<Settings as Push<Clock<Source>>>::Out>
    where
        Settings: Push<Clock<Source>>,
        <Settings as Push<Clock<Source>>>::Out: Declaration,
    {
        if Source::DATABASE {
            Self::with(&self.spec.database_clock())
        } else {
            Self::with(&self.spec)
        }
    }

    /// The same table, with its transactions opened at `Level`, an isolation level or a SQLite
    /// mode. Adds [`Opens<Level>`](Opens).
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # mod demo {
    /// use ruststream_sqlx::dialect::{Column, level};
    /// use ruststream_sqlx::spec::{Opens, Payload};
    /// use ruststream_sqlx::{InboxSpec, InboxTable, PayloadRow};
    /// # use ruststream_sqlx::prelude::*;
    /// # use serde::Deserialize;
    /// # use sqlx::PgPool;
    ///
    /// #[derive(sqlx::FromRow)]
    /// pub struct PayoutJob {
    ///     id: i64,
    ///     payload: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for PayoutJob {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(Opens<level::ReadCommitted>, Payload)>;
    ///     // The claim's transaction runs at READ COMMITTED on a database whose default is SERIALIZABLE.
    ///     const TABLE: Self::Table = InboxSpec::new("payout_jobs", Column::new("id").generated())
    ///         .opens::<level::ReadCommitted>()
    ///         .payload(Column::new("payload"));
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl PayloadRow for PayoutJob {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.payload
    ///     }
    /// }
    /// # #[derive(Deserialize)]
    /// # struct Payout { cents: i64 }
    /// # #[subscriber(InboxQueue::<PayoutJob>::new("payouts"))]
    /// # async fn pay(payout: &Payout) -> HandlerOutcome {
    /// #     tracing::info!(cents = payout.cents, "paying out");
    /// #     HandlerOutcome::ack()
    /// # }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("payouts", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(pay);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn opens<Level: OpeningLevel>(
        self,
    ) -> InboxSpec<<Settings as Push<Opens<Level>>>::Out>
    where
        Settings: Push<Opens<Level>>,
        <Settings as Push<Opens<Level>>>::Out: Declaration,
    {
        Self::with(&opened(&self.spec, Level::OPENING))
    }

    /// The same table, with `Event` written by the service itself: the row implements the
    /// event's trait. Adds `Event`, a marker of [`own`](super::own).
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "postgres")]
    /// # mod demo {
    /// use ruststream_sqlx::dialect::Column;
    /// use ruststream_sqlx::spec::{Payload, own};
    /// use ruststream_sqlx::{Discard, InboxSpec, InboxTable, PayloadRow};
    /// use sqlx::{PgConnection, Postgres};
    /// # use ruststream_sqlx::prelude::*;
    /// # use serde::Deserialize;
    /// # use sqlx::PgPool;
    ///
    /// // signups: id BIGSERIAL PRIMARY KEY, name TEXT NOT NULL, payload BYTEA NOT NULL
    /// #[derive(sqlx::FromRow)]
    /// pub struct Signup {
    ///     id: i64,
    ///     payload: Vec<u8>,
    /// }
    ///
    /// impl InboxTable for Signup {
    ///     type Id = i64;
    ///     type Table = InboxSpec<(Payload, own::Discard)>;
    ///     const TABLE: Self::Table = InboxSpec::new("signups", Column::new("id").generated())
    ///         .group(Column::new("name"))
    ///         .payload(Column::new("payload"))
    ///         .own::<own::Discard>();
    ///
    ///     fn id(&self) -> &i64 {
    ///         &self.id
    ///     }
    /// }
    ///
    /// impl PayloadRow for Signup {
    ///     type Column = Vec<u8>;
    ///
    ///     fn payload(&self) -> &[u8] {
    ///         &self.payload
    ///     }
    /// }
    ///
    /// // A dropped signup moves to the `rejected` group, where support reviews it.
    /// impl Discard<Postgres> for Signup {
    ///     async fn discard(conn: &mut PgConnection, id: &i64) -> Result<(), sqlx::Error> {
    ///         sqlx::query("UPDATE signups SET name = 'rejected' WHERE id = $1")
    ///             .bind(id)
    ///             .execute(conn)
    ///             .await?;
    ///         Ok(())
    ///     }
    /// }
    /// # #[derive(Deserialize)]
    /// # struct Form { email: String }
    /// # #[subscriber(InboxQueue::<Signup>::new("signups"))]
    /// # async fn check(form: &Form) -> HandlerOutcome {
    /// #     if form.email.contains('@') { HandlerOutcome::ack() } else { HandlerOutcome::drop() }
    /// # }
    /// # pub fn app(pool: PgPool) -> RustStream {
    /// #     RustStream::new(AppInfo::new("signup", "1.0.0")).with_broker(SqlxBroker::new(pool), |b| {
    /// #         b.include(check);
    /// #     })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    #[must_use]
    pub const fn own<Event: OwnEvent>(self) -> InboxSpec<<Settings as Push<Event>>::Out>
    where
        Settings: Push<Event>,
        <Settings as Push<Event>>::Out: Declaration,
    {
        Self::with(&self.spec)
    }

    /// The same columns as `spec`, under the settings `Next`.
    const fn with<Next>(spec: &TableSpec<'static>) -> InboxSpec<Next> {
        InboxSpec {
            spec: *spec,
            settings: PhantomData,
        }
    }

    /// The same table in `form`: `TableSpec` takes its form when it is built, so the description
    /// is built again with every column set so far.
    const fn reformed(self, form: Form<'static>) -> TableSpec<'static> {
        let old = self.spec;
        let mut spec = TableSpec::new(old.table(), old.id(), form);
        if let Some(schema) = old.schema() {
            spec = spec.within(schema);
        }
        if let Some(column) = old.column(Role::Group) {
            spec = if old.is_fifo() {
                spec.fifo_group(column)
            } else {
                spec.group(column)
            };
        }
        if let Some(column) = old.column(Role::PartitionKey) {
            spec = spec.partition_key(column);
        }
        if let Some(column) = old.column(Role::Priority) {
            spec = spec.priority(column);
        }
        if let Some(column) = old.column(Role::RetryAfter) {
            spec = spec.retry_after(column);
        }
        if let Some(column) = old.column(Role::Attempt) {
            spec = spec.attempt(column);
        }
        if let Some(column) = old.column(Role::ProcessedAt) {
            spec = spec.processed_at(column);
        }
        if let Some(column) = old.column(Role::Headers) {
            spec = spec.headers(column);
        }
        if let Some(column) = old.column(Role::Payload) {
            spec = spec.payload(column);
        }
        if !old.data_columns().is_empty() {
            spec = spec.data(old.data_columns());
        }
        if !old.fetched_columns().is_empty() {
            spec = spec.fetching(old.fetched_columns());
        }
        if old.selects_all() {
            spec = spec.selecting_all();
        }
        if old.uses_database_clock() {
            spec = spec.database_clock();
        }
        opened(&spec, old.opening())
    }
}

/// `spec`, opening its transactions at `opening`.
const fn opened(spec: &TableSpec<'static>, opening: Opening) -> TableSpec<'static> {
    let spec = *spec;
    match opening {
        Opening::Isolation(isolation) => spec.isolation(isolation),
        Opening::Mode(mode) => spec.mode(mode),
        _ => spec,
    }
}