pigeonhole 1.3.2

Embedded, single-file, wide-column store: BigTable's data model with SQLite's deployment model.
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
use std::ops::{Bound, RangeBounds};
use std::sync::Arc;

use pigeonhole_engine::{FamilyId, TableInfo};

use crate::db::Db;

use crate::cell::CellRef;
use crate::{Error, ErrorCode, Family, Pigeonhole, Result, RowMutation, RowRead, Scan, Snapshot};

/// Defines or opens a table. Returned by [`Pigeonhole::table`].
///
/// ```
/// use pigeonhole::{days, ErrorCode, Family, Options, Pigeonhole};
///
/// # fn main() -> pigeonhole::Result<()> {
/// # let dir = pigeonhole::doc_support::temp_dir();
/// let db = Pigeonhole::open(dir.join("app.phdb"), Options::default().shards(1))?;
/// let events = db
///     .table("events")?
///     .family("ev", Family::default().ttl(days(7)))
///     .create()?;
/// assert_eq!(events.families(), ["ev"]);
///
/// // Creating it again fails; opening it (and adding a family) works.
/// let again = db.table("events")?.family("ev", Family::default()).create();
/// assert_eq!(again.unwrap_err().code(), ErrorCode::TableExists);
/// let events = db.table("events")?.family("meta", Family::default()).open()?;
/// assert_eq!(events.families(), ["ev", "meta"]);
/// # db.close()?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct TableBuilder<'db> {
    db: &'db Pigeonhole,
    name: String,
    families: Vec<(String, Family)>,
}

impl<'db> TableBuilder<'db> {
    pub(crate) fn new(db: &'db Pigeonhole, name: &str) -> Self {
        Self {
            db,
            name: name.to_owned(),
            families: Vec::new(),
        }
    }
}

/// What a builder does when the table exists or is missing.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Finish {
    CreateIfMissing,
    Create,
    Open,
}

impl TableBuilder<'_> {
    /// Declares a family. On an existing table, a family not yet present is added (cheap);
    /// one that exists keeps its stored options.
    pub fn family(mut self, name: &str, family: Family) -> Self {
        self.families.push((name.to_owned(), family));
        self
    }

    /// Opens the table, creating it (and any missing declared families) if needed. Creating
    /// a table needs at least one declared family; an empty name or a new table without one
    /// fails with [`ErrorCode::InvalidArgument`].
    pub fn create_if_missing(self) -> Result<Table> {
        self.finish(Finish::CreateIfMissing)
    }

    /// Creates the table; fails with `TableExists` if it exists, and with `InvalidArgument`
    /// for an empty name or no declared family.
    pub fn create(self) -> Result<Table> {
        self.finish(Finish::Create)
    }

    /// Opens an existing table; fails with `TableNotFound`. Declared families that the table
    /// does not have yet are added.
    pub fn open(self) -> Result<Table> {
        self.finish(Finish::Open)
    }

    fn finish(self, how: Finish) -> Result<Table> {
        let db = &self.db.db;
        db.check_open()?;
        if self.name.is_empty() {
            return Err(Error::new(ErrorCode::InvalidArgument, "empty table name"));
        }
        let engine = self.db.engine();
        let mut defs = Vec::with_capacity(self.families.len());
        for (name, family) in &self.families {
            if !defs.iter().any(|(n, _)| n == name) {
                defs.push((name.clone(), family.to_engine()));
            }
        }
        let mut info = match engine.table(&self.name) {
            Some(info) if how == Finish::Create => {
                return Err(pigeonhole_engine::Error::TableExists(info.name.clone()).into());
            }
            Some(info) => info,
            None if how == Finish::Open => {
                return Err(pigeonhole_engine::Error::TableNotFound(self.name).into());
            }
            None if defs.is_empty() => {
                return Err(Error::new(
                    ErrorCode::InvalidArgument,
                    format!(
                        "table {:?} needs at least one family: declare one with .family(..)",
                        self.name
                    ),
                ));
            }
            None => match db.retry_closed(|| {
                self.db
                    .engine()
                    .create_table(&self.name, &defs)
                    .map_err(Error::from)
            }) {
                Ok(info) => info,
                // Another thread created it first: open it as it is.
                Err(e) if e.code() == ErrorCode::TableExists && how != Finish::Create => engine
                    .table(&self.name)
                    .ok_or_else(|| pigeonhole_engine::Error::TableNotFound(self.name.clone()))?,
                Err(e) => return Err(e),
            },
        };
        for (name, options) in defs {
            if info.family(&name).is_some() {
                continue;
            }
            let id = info.id;
            info = match db.retry_closed(|| {
                self.db
                    .engine()
                    .add_family(id, &name, options.clone())
                    .map_err(Error::from)
            }) {
                Ok(info) => info,
                // Added concurrently: it keeps the options it was created with.
                Err(e) if e.code() == ErrorCode::FamilyExists => engine
                    .table(&self.name)
                    .ok_or_else(|| pigeonhole_engine::Error::TableNotFound(self.name.clone()))?,
                Err(e) => return Err(e),
            };
        }
        Ok(Table {
            core: Arc::new(TableCore::new(
                Arc::clone(db),
                info,
                self.db.cached.fresh(db),
            )),
        })
    }
}

/// A typed operand a write resolves its family for ([`TableCore::operand_family_id`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Operand {
    /// `incr`: a counter, or a 0.1.0 family's add.
    Incr,
    /// `aggregate`: an `i64` input to an aggregate family (D294).
    Aggregate,
    /// `aggregate_u64`: an input to a bitwise family (D298).
    U64,
    /// `aggregate_f64`: an input to an `f64` family (D298).
    F64,
    /// `aggregate_bytes`: a bytes element for an HLL or bloom family (D298).
    Bytes,
    /// `set_add` / `set_remove`: an element for a set family (D298).
    Set,
}

/// What every table handle shares: the database and the catalog entry it was opened with.
#[derive(Debug)]
pub(crate) struct TableCore {
    pub(crate) db: Arc<Db>,
    pub(crate) info: Arc<TableInfo>,
    pub(crate) cached: crate::db::Cached,
    /// Its rows' sizes, for a point read's buffers (#1558 item 1).
    pub(crate) row_shape: crate::cell::RowShape,
}

impl TableCore {
    pub(crate) fn new(db: Arc<Db>, info: Arc<TableInfo>, cached: crate::db::Cached) -> Self {
        Self {
            db,
            info,
            cached,
            row_shape: crate::cell::RowShape::default(),
        }
    }

    /// The engine for one operation: the handle's cached one while it is current.
    #[inline]
    pub(crate) fn engine(&self) -> crate::db::EngineRef<'_> {
        self.cached.get(&self.db)
    }

    /// `f` on the engine for one operation (the hot paths: no guard materialized).
    #[inline(always)]
    pub(crate) fn with<R>(&self, f: impl FnOnce(&pigeonhole_engine::Engine) -> R) -> R {
        self.cached.with(&self.db, f)
    }

    fn family_info(&self, family: &str) -> Option<crate::FamilyInfo> {
        self.info.family(family).map(crate::FamilyInfo::from_engine)
    }

    /// The catalog entry as of now: a family added through another handle shows up here.
    /// Falls back to the handle's own entry if the table was dropped or replaced.
    pub(crate) fn current_info(&self) -> Arc<TableInfo> {
        // By id: a table dropped, or dropped and created again under its name (a new id),
        // is not this handle's.
        self.with(|e| e.table_by_id(self.info.id))
            .unwrap_or_else(|| Arc::clone(&self.info))
    }

    /// The table as `snapshot` saw it, which names every family a read at it can return; the
    /// current entry if the table did not exist then (#892).
    pub(crate) fn info_at(&self, snapshot: &pigeonhole_engine::Snapshot) -> Arc<TableInfo> {
        snapshot
            .table(self.info.id)
            .map_or_else(|| self.current_info(), Arc::clone)
    }

    /// Resolves a family name for a read at `snapshot`: as the snapshot saw it, so a family
    /// dropped (or dropped and created again) since still reads what the snapshot holds; a
    /// family created since resolves as now and reads nothing at the snapshot (#892).
    pub(crate) fn family_id_at(
        &self,
        snapshot: &pigeonhole_engine::Snapshot,
        name: &str,
    ) -> Result<FamilyId> {
        if let Some(info) = snapshot.table(self.info.id)
            && let Some(f) = info.family(name)
        {
            return Ok(f.id);
        }
        self.family_id(name)
    }

    /// [`family_id`](Self::family_id) for a typed operand, refused where its type isn't the
    /// family's inputs (D294, D298): `incr` outside a counter (and a 0.1.0 family's add),
    /// `aggregate` outside an `i64`-input aggregate family, `aggregate_u64` outside a bitwise
    /// family and `aggregate_f64` outside an `f64` family, each naming the method to use.
    /// One lookup, the one the write does anyway.
    pub(crate) fn operand_family_id(&self, name: &str, operand: Operand) -> Result<FamilyId> {
        use pigeonhole_engine::FamilyKind as K;
        let current;
        let f = match self.info.family(name) {
            Some(f) => f,
            None => {
                current = self.current_info();
                current
                    .family(name)
                    .ok_or_else(|| family_not_found(&self.info.name, name))?
            }
        };
        let kind = f.options.kind;
        let accepted = match operand {
            // A standard family's `incr` is the engine's to judge (D41).
            Operand::Incr => matches!(kind, K::Standard | K::Counter),
            Operand::Aggregate => {
                kind.is_aggregate()
                    && !matches!(
                        kind,
                        K::MinF64
                            | K::MaxF64
                            | K::SumF64
                            | K::MeanVar
                            | K::Histogram
                            | K::Quantiles
                            | K::Set
                    )
            }
            Operand::U64 => matches!(kind, K::BitOr | K::BitAnd | K::BitXor),
            Operand::Bytes => matches!(kind, K::Hll | K::Bloom),
            Operand::Set => kind == K::Set,
            Operand::F64 => matches!(
                kind,
                K::MinF64 | K::MaxF64 | K::SumF64 | K::MeanVar | K::Histogram | K::Quantiles
            ),
        };
        if accepted {
            return Ok(f.id);
        }
        let used = match operand {
            Operand::Incr => "incr",
            Operand::Aggregate => "aggregate",
            Operand::U64 => "aggregate_u64",
            Operand::F64 => "aggregate_f64",
            Operand::Bytes => "aggregate_bytes",
            Operand::Set => "set_add / set_remove",
        };
        let (what, method) = match kind {
            K::Standard | K::Vector => {
                return Err(Error::new(
                    ErrorCode::InvalidArgument,
                    format!(
                        "family {name:?} of table {:?} is not an aggregate family: {used} \
                         needs Family::aggregate or Family::counter",
                        self.info.name
                    ),
                ));
            }
            K::Counter => ("a counter", "incr"),
            K::Min => ("a min", "aggregate"),
            K::Max => ("a max", "aggregate"),
            K::Hll => ("an hll", "aggregate"),
            K::BitOr => ("a bit_or", "aggregate_u64"),
            K::BitAnd => ("a bit_and", "aggregate_u64"),
            K::BitXor => ("a bit_xor", "aggregate_u64"),
            K::MinF64 => ("a min_f64", "aggregate_f64"),
            K::MaxF64 => ("a max_f64", "aggregate_f64"),
            K::SumF64 => ("a sum_f64", "aggregate_f64"),
            K::MeanVar => ("a mean_var", "aggregate_f64"),
            K::Histogram => ("a histogram", "aggregate_f64"),
            K::Quantiles => ("a quantiles", "aggregate_f64"),
            K::Bloom => ("a bloom", "aggregate or aggregate_bytes"),
            K::Set => ("a set", "set_add or set_remove"),
        };
        Err(Error::new(
            ErrorCode::InvalidArgument,
            format!(
                "family {name:?} of table {:?} is {what} family: write its inputs with \
                 {method}, not {used}",
                self.info.name
            ),
        ))
    }

    /// Checks a vector put's value against its family (D303): a vector family, and a vector
    /// of its spec, encoded into `out`. Returns the family's parameters for the value.
    pub(crate) fn vector_payload(
        &self,
        name: &str,
        q: pigeonhole_format::vector::Query<'_>,
        out: &mut Vec<u8>,
    ) -> Result<pigeonhole_format::vector::Params> {
        let current;
        let f = match self.info.family(name) {
            Some(f) => f,
            None => {
                current = self.current_info();
                current
                    .family(name)
                    .ok_or_else(|| family_not_found(&self.info.name, name))?
            }
        };
        let spec = (f.options.kind == pigeonhole_engine::FamilyKind::Vector)
            .then(|| crate::VectorSpec::from_kind_params(&f.options.kind_params))
            .flatten()
            .ok_or_else(|| {
                Error::new(
                    ErrorCode::InvalidArgument,
                    format!(
                        "family {name:?} of table {:?} is not a vector family: put_vector_* \
                         needs Family::vector",
                        self.info.name
                    ),
                )
            })?;
        crate::vector::payload(&spec, q, out).map_err(|e| {
            Error::new(
                e.code(),
                format!(
                    "family {name:?} of table {:?} ({} {:?}, {:?}): {}",
                    self.info.name,
                    spec.dim(),
                    spec.element(),
                    spec.metric(),
                    e.message()
                ),
            )
        })?;
        Ok(*spec.params())
    }

    /// Resolves a family name: from the handle's entry (no allocation), else from the
    /// current catalog.
    #[inline]
    pub(crate) fn family_id(&self, name: &str) -> Result<FamilyId> {
        if let Some(f) = self.info.family(name) {
            return Ok(f.id);
        }
        self.current_info()
            .family(name)
            .map(|f| f.id)
            .ok_or_else(|| family_not_found(&self.info.name, name))
    }

    /// `get` as of now with a supervisor: run again on the recovered engine if it got
    /// `Closed`. Out of line, and called before `get`'s match (see there).
    #[cold]
    #[inline(never)]
    fn get_latest_supervised(
        &self,
        table: pigeonhole_engine::TableId,
        family: FamilyId,
        row: &[u8],
        qualifier: &[u8],
    ) -> Result<Option<pigeonhole_engine::CellData>> {
        self.db.retry_closed(|| {
            self.with(|e| e.get_latest(table, family, row, qualifier))
                .map_err(Error::from)
        })
    }

    /// A snapshot with a supervisor (see `get_latest_supervised`).
    #[cold]
    #[inline(never)]
    pub(crate) fn snapshot_supervised(&self) -> Result<pigeonhole_engine::Snapshot> {
        self.db
            .retry_closed(|| self.engine().snapshot().map_err(Error::from))
    }

    /// The newest version of one cell, as of `snapshot` or now.
    #[inline]
    pub(crate) fn get(
        &self,
        snapshot: Option<&Snapshot>,
        row: &[u8],
        family: &str,
        qualifier: &[u8],
    ) -> Result<Option<CellRef<'_>>> {
        self.db.check_open()?;
        if let Some(s) = snapshot {
            return self.get_at(s, row, family, qualifier);
        }
        let family = self.family_id(family)?;
        let table = self.info.id;
        // With a supervisor, a read as of now is run again on the recovered engine if it
        // got `Closed`: out of line, and before the match below, so the match stays the one
        // main compiles (a second arm yielding into `data` moved the engine's result once
        // more: about 50 instructions per get on callgrind, #836 rounds 6 and 7).
        if snapshot.is_none() && self.db.supervised() {
            return self
                .get_latest_supervised(table, family, row, qualifier)
                .map(|data| data.map(CellRef::owned));
        }
        let data = self.with(|e| e.get_latest(table, family, row, qualifier))?;
        Ok(data.map(CellRef::owned))
    }

    /// [`get`](Self::get) as of `snapshot`: the family resolved as the snapshot saw it
    /// (#892). Out of line, so the read as of now keeps its shape.
    #[inline(never)]
    fn get_at(
        &self,
        snapshot: &Snapshot,
        row: &[u8],
        family: &str,
        qualifier: &[u8],
    ) -> Result<Option<CellRef<'_>>> {
        self.db.check_snapshot(snapshot)?;
        let family = self.family_id_at(&snapshot.inner, family)?;
        let table = self.info.id;
        let data = self.with(|e| e.get(&snapshot.inner, table, family, row, qualifier))?;
        Ok(data.map(CellRef::owned))
    }

    /// A get as a future; errors found before any read (closed, unknown family, a snapshot
    /// of another database) resolve on the first poll.
    #[cfg(feature = "async")]
    pub(crate) fn get_async(
        &self,
        snapshot: Option<&Snapshot>,
        row: &[u8],
        family: &str,
        qualifier: &[u8],
    ) -> crate::nonblocking::GetFuture {
        let started = self.db.check_open().and_then(|()| {
            let table = self.info.id;
            Ok(match snapshot {
                None => {
                    let family = self.family_id(family)?;
                    self.with(|e| e.get_latest_async(table, family, row, qualifier))
                }
                Some(s) => {
                    self.db.check_snapshot(s)?;
                    // The family as the snapshot saw it (#892).
                    let family = self.family_id_at(&s.inner, family)?;
                    self.with(|e| e.get_async(&s.inner, table, family, row, qualifier))
                }
            })
        });
        crate::nonblocking::GetFuture::new(started)
    }

    fn scan(self: &Arc<Self>, start: Bound<&[u8]>, end: Bound<&[u8]>) -> Scan<'_> {
        Scan::new(self, start.map(<[u8]>::to_vec), end.map(<[u8]>::to_vec))
    }

    fn scan_range<'k, K: AsRef<[u8]> + ?Sized + 'k>(
        self: &Arc<Self>,
        range: impl RangeBounds<&'k K>,
    ) -> Scan<'_> {
        self.scan(
            range.start_bound().map(|k| k.as_ref()),
            range.end_bound().map(|k| k.as_ref()),
        )
    }

    fn scan_prefix(self: &Arc<Self>, prefix: &[u8]) -> Scan<'_> {
        let end = match prefix_end(prefix) {
            Some(end) => Bound::Excluded(end),
            None => Bound::Unbounded,
        };
        Scan::new(self, Bound::Included(prefix.to_vec()), end)
    }
}

pub(crate) fn family_not_found(table: &str, family: &str) -> Error {
    Error::new(
        ErrorCode::FamilyNotFound,
        format!("no such family {family:?} in table {table:?}"),
    )
}

/// The smallest key greater than every key starting with `prefix`, or `None` if there is
/// none (`prefix` is empty or all `0xff`).
pub(crate) fn prefix_end(prefix: &[u8]) -> Option<Vec<u8>> {
    let keep = prefix.iter().rposition(|&b| b != 0xff)?;
    let mut end = prefix[..=keep].to_vec();
    end[keep] += 1;
    Some(end)
}

/// A table handle for reads and writes. Cheap to clone; `Send + Sync`.
///
/// ```
/// use pigeonhole::{Family, Options, Pigeonhole};
///
/// # fn main() -> pigeonhole::Result<()> {
/// # let dir = pigeonhole::doc_support::temp_dir();
/// let db = Pigeonhole::open(dir.join("app.phdb"), Options::default().shards(1))?;
/// let pages = db
///     .table("pages")?
///     .family("meta", Family::default().max_versions(1))
///     .family("links", Family::default())
///     .family("stats", Family::counter())
///     .create_if_missing()?;
///
/// pages
///     .mutate(b"com.example/a")
///     .put("meta", b"status", b"200")
///     .put("links", b"com.example/b", b"")
///     .incr("stats", b"hits", 1)
///     .commit()?;
///
/// let status = pages.get(b"com.example/a", "meta", b"status")?.unwrap();
/// assert_eq!(status.value(), b"200");
/// let hits = pages.get(b"com.example/a", "stats", b"hits")?.and_then(|c| c.as_i64());
/// assert_eq!(hits, Some(1));
///
/// let row = pages.row(b"com.example/a").family("links").read()?.unwrap();
/// assert_eq!(row.len(), 1);
///
/// let keys: Vec<Vec<u8>> = pages
///     .scan_prefix(b"com.example/")
///     .iter()?
///     .map(|row| row.map(|r| r.key().to_vec()))
///     .collect::<pigeonhole::Result<_>>()?;
/// assert_eq!(keys, [b"com.example/a".to_vec()]);
/// # db.close()?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Table {
    pub(crate) core: Arc<TableCore>,
}

impl Table {
    /// The table name.
    pub fn name(&self) -> &str {
        &self.core.info.name
    }

    /// Family names, in creation order, as of when this handle was opened.
    pub fn families(&self) -> Vec<&str> {
        self.core
            .info
            .families
            .iter()
            .map(|f| f.name.as_str())
            .collect()
    }

    /// A family's stored options, as of when this handle was opened (ICR 0047); `None` if
    /// the table has no such family.
    pub fn family_info(&self, family: &str) -> Option<crate::FamilyInfo> {
        self.core.family_info(family)
    }

    /// The table's identity, as its change feed follows it (ICR 0114 amendment): ids are
    /// never reused, so a table dropped and created again under the same name has another.
    /// For a server that shares one feed among the clients of one set of tables
    /// (`phdb serve`'s hubs). Not part of the stable API.
    #[doc(hidden)]
    pub fn feed_id(&self) -> u64 {
        u64::from(self.core.info.id.0)
    }

    /// Starts a single-row atomic mutation.
    pub fn mutate<'t>(&'t self, row: &[u8]) -> RowMutation<'t> {
        RowMutation::new(self, row)
    }

    /// The newest version of one cell. Borrows from the cache: no allocation.
    #[inline]
    pub fn get(&self, row: &[u8], family: &str, qualifier: &[u8]) -> Result<Option<CellRef<'_>>> {
        self.core.get(None, row, family, qualifier)
    }

    /// The newest version of one cell as of `snapshot`.
    pub fn get_at(
        &self,
        snapshot: &Snapshot,
        row: &[u8],
        family: &str,
        qualifier: &[u8],
    ) -> Result<Option<CellRef<'_>>> {
        self.core.get(Some(snapshot), row, family, qualifier)
    }

    /// Subscribes to this table's committed changes (D310): [`FeedBuilder::open`] gives a
    /// [`Feed`] of whole commits, once each, in commit order. The database's change feed must
    /// be on and follow the table ([`Options::change_feed`](crate::Options::change_feed),
    /// [`Options::feed_tables`](crate::Options::feed_tables)). [`FeedBuilder::table`] adds
    /// more tables to the same feed.
    ///
    /// [`FeedBuilder::open`]: crate::FeedBuilder::open
    /// [`Feed`]: crate::Feed
    /// [`FeedBuilder::table`]: crate::FeedBuilder::table
    pub fn feed(&self) -> crate::FeedBuilder {
        crate::FeedBuilder::new(&self.core)
    }

    /// The shard that owns `row` right now ([`Shard::index`](crate::Shard::index)), for
    /// application-owned mode: a thread driving a shard can commit the rows that shard owns,
    /// so its writes run on its own shard with no handoff (the spec's inline local writes).
    /// A routing hint only (ICR 0022):
    /// - it reflects the current tablet map, which can change at any time after a split,
    ///   merge or move;
    /// - a commit from any thread is correct whatever shard owns its rows, merely routed
    ///   there.
    ///
    /// `None` if the table was dropped.
    ///
    /// ```
    /// use pigeonhole::{Family, Options, Pigeonhole};
    ///
    /// # fn main() -> pigeonhole::Result<()> {
    /// # let dir = pigeonhole::doc_support::temp_dir();
    /// let db = Pigeonhole::open(dir.join("app.phdb"), Options::default().shards(2))?;
    /// let t = db.table("t")?.family("f", Family::default()).create_if_missing()?;
    /// let shard = t.shard_of(b"user:1").expect("the table exists");
    /// assert!(shard < 2);
    /// # drop(t);
    /// # db.close()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn shard_of(&self, row: &[u8]) -> Option<usize> {
        self.core.engine().shard_of(self.core.info.id, row)
    }

    /// Splits this table's row space at `keys` (sorted) and spreads the pieces over the
    /// shards, piece `i` to shard `i % shards`, waiting until done. A bench hook (D213): the
    /// gate's group-commit table starts on every shard instead of waiting for the balancer.
    /// The balancer may still move the pieces later.
    #[cfg(feature = "__unstable-hooks")]
    #[doc(hidden)]
    pub fn split_over_shards(&self, keys: Vec<Vec<u8>>) -> Result<()> {
        let shards = self.core.engine().shard_stats().len().max(1);
        let owners: Vec<u16> = (0..=keys.len()).map(|i| (i % shards) as u16).collect();
        self.core
            .db
            .engine()
            .split_table(self.core.info.id, keys, &owners)
            .map_err(Into::into)
    }

    /// [`get`](Self::get) as a future resolving to an owned [`Cell`](crate::Cell): a memtable
    /// or cache hit is read at the call and resolves on the first poll, and a block the cache
    /// does not hold is read asynchronously (see [`nonblocking`](crate::nonblocking)).
    #[cfg(feature = "async")]
    pub fn get_async(
        &self,
        row: &[u8],
        family: &str,
        qualifier: &[u8],
    ) -> crate::nonblocking::GetFuture {
        self.core.get_async(None, row, family, qualifier)
    }

    /// [`get_at`](Self::get_at) as a future, as [`get_async`](Self::get_async).
    #[cfg(feature = "async")]
    pub fn get_at_async(
        &self,
        snapshot: &Snapshot,
        row: &[u8],
        family: &str,
        qualifier: &[u8],
    ) -> crate::nonblocking::GetFuture {
        self.core.get_async(Some(snapshot), row, family, qualifier)
    }

    /// Starts a row read.
    pub fn row<'t>(&'t self, row: &[u8]) -> RowRead<'t> {
        RowRead::new(&self.core, row)
    }

    /// Starts an ordered scan over a row range: `table.scan(b"a".."b")`.
    pub fn scan<'k, K: AsRef<[u8]> + ?Sized + 'k>(
        &self,
        range: impl RangeBounds<&'k K>,
    ) -> Scan<'_> {
        self.core.scan_range(range)
    }

    /// Starts a scan of every row starting with `prefix`.
    pub fn scan_prefix(&self, prefix: &[u8]) -> Scan<'_> {
        self.core.scan_prefix(prefix)
    }

    /// Starts a multi-get of `keys` ([`KeysRead`](crate::KeysRead), D299): their rows in key
    /// order under one snapshot, each tablet's read set up once for all of its keys.
    pub fn keys<'t>(&'t self, keys: &crate::KeySet) -> crate::KeysRead<'t> {
        crate::KeysRead::new(&self.core, keys)
    }

    /// Starts a breadth-first traversal from `seeds` ([`Traverse`](crate::Traverse), D304):
    /// hops over an edge family whose qualifiers name the destination rows, run in the
    /// engine under one snapshot.
    pub fn traverse<'t>(&'t self, seeds: &crate::KeySet) -> crate::Traverse<'t> {
        crate::Traverse::new(&self.core, seeds)
    }

    /// Starts a scan from explicit bounds (the form a C ABI exports).
    pub fn scan_bounds(&self, start: Bound<&[u8]>, end: Bound<&[u8]>) -> Scan<'_> {
        self.core.scan(start, end)
    }
}

/// A table handle on a [`PigeonholeReader`](crate::PigeonholeReader): reads only.
///
/// See [`PigeonholeReader`](crate::PigeonholeReader) for an example.
#[derive(Debug, Clone)]
pub struct ReadTable {
    pub(crate) core: Arc<TableCore>,
}

impl ReadTable {
    /// Subscribes to this table's committed changes from a reader process (D310 PR 4): the
    /// same [`Feed`](crate::Feed) a writer's [`Table::feed`] gives, following the writer's
    /// feed through shared memory. The writer must feed the table. Across a writer restart
    /// the feed resubscribes from its own token on the new writer: a durable feed continues,
    /// and a visible one that delivered what a power loss took expires.
    pub fn feed(&self) -> crate::FeedBuilder {
        crate::FeedBuilder::new(&self.core)
    }

    /// The table name.
    pub fn name(&self) -> &str {
        &self.core.info.name
    }

    /// Family names, in creation order, as of when this handle was opened (ICR 0047).
    pub fn families(&self) -> Vec<&str> {
        self.core
            .info
            .families
            .iter()
            .map(|f| f.name.as_str())
            .collect()
    }

    /// As [`Table::family_info`].
    pub fn family_info(&self, family: &str) -> Option<crate::FamilyInfo> {
        self.core.family_info(family)
    }

    /// The newest version of one cell.
    pub fn get(&self, row: &[u8], family: &str, qualifier: &[u8]) -> Result<Option<CellRef<'_>>> {
        self.core.get(None, row, family, qualifier)
    }

    /// The newest version of one cell as of `snapshot`.
    pub fn get_at(
        &self,
        snapshot: &Snapshot,
        row: &[u8],
        family: &str,
        qualifier: &[u8],
    ) -> Result<Option<CellRef<'_>>> {
        self.core.get(Some(snapshot), row, family, qualifier)
    }

    /// [`get`](Self::get) as a future resolving to an owned [`Cell`](crate::Cell): a memtable
    /// or cache hit is read at the call and resolves on the first poll, and a block the cache
    /// does not hold is read asynchronously (see [`nonblocking`](crate::nonblocking)).
    #[cfg(feature = "async")]
    pub fn get_async(
        &self,
        row: &[u8],
        family: &str,
        qualifier: &[u8],
    ) -> crate::nonblocking::GetFuture {
        self.core.get_async(None, row, family, qualifier)
    }

    /// [`get_at`](Self::get_at) as a future, as [`get_async`](Self::get_async).
    #[cfg(feature = "async")]
    pub fn get_at_async(
        &self,
        snapshot: &Snapshot,
        row: &[u8],
        family: &str,
        qualifier: &[u8],
    ) -> crate::nonblocking::GetFuture {
        self.core.get_async(Some(snapshot), row, family, qualifier)
    }

    /// Starts a row read.
    pub fn row<'t>(&'t self, row: &[u8]) -> RowRead<'t> {
        RowRead::new(&self.core, row)
    }

    /// Starts an ordered scan over a row range.
    pub fn scan<'k, K: AsRef<[u8]> + ?Sized + 'k>(
        &self,
        range: impl RangeBounds<&'k K>,
    ) -> Scan<'_> {
        self.core.scan_range(range)
    }

    /// Starts a scan of every row starting with `prefix`.
    pub fn scan_prefix(&self, prefix: &[u8]) -> Scan<'_> {
        self.core.scan_prefix(prefix)
    }

    /// Starts a multi-get of `keys` ([`KeysRead`](crate::KeysRead), D299): their rows in key
    /// order under one snapshot, each tablet's read set up once for all of its keys.
    pub fn keys<'t>(&'t self, keys: &crate::KeySet) -> crate::KeysRead<'t> {
        crate::KeysRead::new(&self.core, keys)
    }

    /// Starts a breadth-first traversal from `seeds` ([`Traverse`](crate::Traverse), D304):
    /// hops over an edge family whose qualifiers name the destination rows, run in the
    /// engine under one snapshot.
    pub fn traverse<'t>(&'t self, seeds: &crate::KeySet) -> crate::Traverse<'t> {
        crate::Traverse::new(&self.core, seeds)
    }

    /// Starts a scan from explicit bounds.
    pub fn scan_bounds(&self, start: Bound<&[u8]>, end: Bound<&[u8]>) -> Scan<'_> {
        self.core.scan(start, end)
    }
}

#[cfg(test)]
mod tests {
    use super::prefix_end;

    #[test]
    fn prefix_end_is_the_next_key_after_the_prefix() {
        assert_eq!(prefix_end(b"user:"), Some(b"user;".to_vec()));
        assert_eq!(prefix_end(b"a\xff\xff"), Some(b"b".to_vec()));
        assert_eq!(prefix_end(b"\xff\xff"), None);
        assert_eq!(prefix_end(b""), None);
    }
}