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
use std::collections::{BTreeMap, HashMap, HashSet};
use std::convert::TryFrom;
use std::fmt;
use std::iter::{self, FromIterator};
use std::marker::PhantomData;
use std::sync::Arc;

use async_trait::async_trait;
use destream::de;
use futures::future::{self, join_all, try_join_all, TryFutureExt};
use futures::stream::TryStreamExt;
use log::debug;

use tc_btree::{BTreeFile, BTreeInstance, BTreeWrite, Node, NodeId};
use tc_error::*;
use tc_transact::fs::{CopyFrom, Dir, DirCreateFile, DirReadFile, File, Persist, Restore};
use tc_transact::lock::{TxnLock, TxnLockCommit};
use tc_transact::{Transact, Transaction, TxnId};
use tc_value::Value;
use tcgeneric::{label, Id, Instance, Label, TCBoxTryStream, Tuple};

use super::view::{Limited, MergeSource, Merged, Selection, TableSlice as Slice};
use super::{
    Bounds, Column, ColumnBound, IndexSchema, IndexSlice, Key, Row, Table, TableInstance,
    TableOrder, TableRead, TableSchema, TableSlice, TableStream, TableType, TableWrite, Values,
};

const PRIMARY_INDEX: Label = label("primary");

#[derive(Clone)]
pub struct Index<F, D, Txn> {
    btree: BTreeFile<F, D, Txn>,
    schema: IndexSchema,
}

impl<F, D, Txn> Index<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node>,
    D: Dir,
    Txn: Transaction<D>,
{
    pub fn btree(&'_ self) -> &'_ BTreeFile<F, D, Txn> {
        &self.btree
    }

    pub async fn is_empty(&self, txn: &Txn) -> TCResult<bool> {
        self.btree.is_empty(*txn.id()).await
    }

    pub fn index_slice(self, bounds: Bounds) -> TCResult<IndexSlice<F, D, Txn>> {
        debug!("Index::index_slice");
        let bounds = bounds.validate(&self.schema.columns())?;
        IndexSlice::new(self.btree, self.schema, bounds)
    }

    pub fn schema(&'_ self) -> &'_ IndexSchema {
        &self.schema
    }

    pub fn validate_slice_bounds(&self, outer: Bounds, inner: Bounds) -> TCResult<()> {
        let columns = &self.schema.columns();
        let outer = outer.validate(columns)?.into_btree_range(columns)?;
        let inner = inner.validate(columns)?.into_btree_range(columns)?;

        if outer.contains(&inner, self.btree.collator()) {
            Ok(())
        } else {
            Err(TCError::unsupported(
                "slice does not contain requested bounds",
            ))
        }
    }

    pub async fn slice_rows<'a>(
        self,
        txn_id: TxnId,
        bounds: Bounds,
        reverse: bool,
    ) -> TCResult<TCBoxTryStream<'a, Vec<Value>>> {
        self.validate_bounds(&bounds)?;
        let range = bounds.into_btree_range(&self.schema.columns())?;
        self.btree.slice(range, reverse)?.keys(txn_id).await
    }

    async fn delete_inner(&self, txn_id: TxnId, key: Key) -> TCResult<()> {
        debug!("Index::delete {:?}", key);
        let range = tc_btree::Range::with_prefix(key.to_vec());
        self.btree.delete(txn_id, range).await
    }

    async fn delete(&self, txn_id: TxnId, mut row: Row) -> TCResult<()> {
        let key = self
            .schema
            .key()
            .iter()
            .map(|col| {
                row.remove(&col.name)
                    .ok_or_else(|| TCError::bad_request("missing value for column", &col.name))
            })
            .collect::<TCResult<Key>>()?;

        self.delete_inner(txn_id, key).await
    }

    async fn replace(&self, txn_id: TxnId, mut row: Row, mut update: Row) -> TCResult<()> {
        debug!("Index::replace {} with updated values {}", row, update);

        let old_key = self
            .schema
            .key()
            .iter()
            .map(|col| {
                row.get(&col.name)
                    .cloned()
                    .ok_or_else(|| TCError::bad_request("missing value for column", &col.name))
            })
            .collect::<TCResult<Key>>()?;

        let new_key = BTreeInstance::schema(&self.btree)
            .iter()
            .map(|col| {
                if let Some(value) = update.remove(&col.name) {
                    Ok(value)
                } else if let Some(value) = row.remove(&col.name) {
                    Ok(value)
                } else {
                    Err(TCError::bad_request("missing value for column", &col.name))
                }
            })
            .collect::<TCResult<Key>>()?;

        self.delete_inner(txn_id, old_key).await?;
        self.btree.insert(txn_id, new_key).await
    }
}

impl<F, D, Txn> Instance for Index<F, D, Txn>
where
    Self: Send + Sync,
{
    type Class = TableType;

    fn class(&self) -> TableType {
        TableType::Index
    }
}

impl<F, D, Txn> TableInstance for Index<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node>,
    D: Dir,
    Txn: Transaction<D>,
{
    fn key(&self) -> &[Column] {
        self.schema.key()
    }

    fn values(&self) -> &[Column] {
        self.schema.values()
    }

    fn schema(&self) -> TableSchema {
        self.schema.clone().into()
    }
}

impl<F, D, Txn> TableOrder for Index<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node>,
    D: Dir,
    Txn: Transaction<D>,
{
    type OrderBy = IndexSlice<F, D, Txn>;
    type Reverse = IndexSlice<F, D, Txn>;

    fn order_by(self, order: Vec<Id>, reverse: bool) -> TCResult<Self::OrderBy> {
        if self.schema.starts_with(&order) {
            Ok(IndexSlice::all(self.btree, self.schema, reverse))
        } else {
            Err(TCError::bad_request(
                &format!("Index with schema {} does not support order", self.schema),
                Value::from_iter(order),
            ))
        }
    }

    fn reverse(self) -> TCResult<Self::Reverse> {
        Ok(IndexSlice::all(self.btree, self.schema, true).into())
    }

    fn validate_order(&self, order: &[Id]) -> TCResult<()> {
        if !self.schema.starts_with(&order) {
            let order: Vec<String> = order.iter().map(|c| c.to_string()).collect();
            Err(TCError::bad_request(
                &format!("cannot order index with schema {} by", self.schema),
                order.join(", "),
            ))
        } else {
            Ok(())
        }
    }
}

#[async_trait]
impl<F, D, Txn> TableStream for Index<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node>,
    D: Dir,
    Txn: Transaction<D>,
{
    type Limit = Limited<F, D, Txn>;
    type Selection = Selection<F, D, Txn, Self>;

    async fn count(self, txn_id: TxnId) -> TCResult<u64> {
        self.btree.count(txn_id).await
    }

    fn limit(self, limit: u64) -> Self::Limit {
        Limited::new(self, limit)
    }

    fn select(self, columns: Vec<Id>) -> TCResult<Self::Selection> {
        Selection::new(self, columns)
    }

    async fn rows<'a>(self, txn_id: TxnId) -> TCResult<TCBoxTryStream<'a, Vec<Value>>> {
        debug!("Index::rows");
        self.btree.keys(txn_id).await
    }
}

impl<F, D, Txn> TableSlice for Index<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node>,
    D: Dir,
    Txn: Transaction<D>,
{
    type Slice = IndexSlice<F, D, Txn>;

    fn slice(self, bounds: Bounds) -> TCResult<IndexSlice<F, D, Txn>> {
        self.index_slice(bounds).map(|is| is.into())
    }

    fn validate_bounds(&self, bounds: &Bounds) -> TCResult<()> {
        if bounds.is_empty() {
            return Ok(());
        }

        let columns = self.schema.columns();
        let mut bounds = bounds.clone();
        let mut ordered_bounds = Vec::with_capacity(columns.len());
        for column in columns {
            let bound = bounds.remove(column.name()).unwrap_or_default();
            ordered_bounds.push(bound);

            if bounds.is_empty() {
                break;
            }
        }

        if !bounds.is_empty() {
            return Err(TCError::bad_request(
                "Index has no such columns: {}",
                Value::from_iter(bounds.keys().cloned()),
            ));
        }

        debug!(
            "ordered bounds: {}",
            Tuple::<&ColumnBound>::from_iter(&ordered_bounds)
        );

        if ordered_bounds[..ordered_bounds.len() - 1]
            .iter()
            .any(ColumnBound::is_range)
        {
            return Err(TCError::unsupported(
                "Index bounds must include a maximum of one range, only on the rightmost column",
            ));
        }

        Ok(())
    }
}

#[async_trait]
impl<F, D, Txn> Transact for Index<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node> + Transact,
    D: Dir,
    Txn: Transaction<D>,
{
    type Commit = <tc_btree::BTreeFile<F, D, Txn> as Transact>::Commit;

    async fn commit(&self, txn_id: TxnId) -> Self::Commit {
        self.btree.commit(txn_id).await
    }

    async fn rollback(&self, txn_id: &TxnId) {
        self.btree.rollback(txn_id).await
    }

    async fn finalize(&self, txn_id: &TxnId) {
        self.btree.finalize(txn_id).await
    }
}

impl<F, D, Txn> Persist<D> for Index<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node, Inner = D::Inner> + TryFrom<D::Store, Error = TCError>,
    D: Dir + TryFrom<D::Store, Error = TCError>,
    Txn: Transaction<D>,
    D::Store: From<F>,
{
    type Txn = Txn;
    type Schema = IndexSchema;

    fn create(txn_id: TxnId, schema: Self::Schema, store: D::Store) -> TCResult<Self> {
        BTreeFile::create(txn_id, schema.clone().into(), store).map(|btree| Self { schema, btree })
    }

    fn load(txn_id: TxnId, schema: Self::Schema, store: D::Store) -> TCResult<Self> {
        BTreeFile::load(txn_id, schema.clone().into(), store).map(|btree| Self { schema, btree })
    }

    fn dir(&self) -> F::Inner {
        BTreeFile::dir(&self.btree)
    }
}

#[async_trait]
impl<F, D, Txn> Restore<D> for Index<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node, Inner = D::Inner> + TryFrom<D::Store, Error = TCError>,
    D: Dir + TryFrom<D::Store, Error = TCError>,
    Txn: Transaction<D>,
    D::Store: From<F>,
{
    async fn restore(&self, txn_id: TxnId, backup: &Self) -> TCResult<()> {
        self.btree.restore(txn_id, &backup.btree).await
    }
}

impl<F, D, Txn> From<Index<F, D, Txn>> for Table<F, D, Txn> {
    fn from(index: Index<F, D, Txn>) -> Self {
        Table::Index(index)
    }
}

struct Inner<F, D, Txn> {
    schema: TableSchema,
    primary: Index<F, D, Txn>,
    auxiliary: Vec<(Id, Index<F, D, Txn>)>,
    dir: D,
}

/// The base type of a [`Table`].
#[derive(Clone)]
pub struct TableIndex<F, D, Txn> {
    inner: Arc<Inner<F, D, Txn>>,
}

impl<F, D, Txn> TableIndex<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node, Inner = D::Inner> + TryFrom<D::Store, Error = TCError>,
    D: Dir + TryFrom<D::Store, Error = TCError>,
    Txn: Transaction<D>,
    D::Write: DirCreateFile<F>,
    D::Store: From<F>,
{
    fn create_index(
        txn_id: TxnId,
        primary: &IndexSchema,
        file: F,
        key: Vec<Id>,
    ) -> TCResult<Index<F, D, Txn>> {
        let schema = primary.auxiliary(&key)?;
        Index::create(txn_id, schema, file.into())
    }
}

impl<F, D, Txn> TableIndex<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node>,
    D: Dir,
    Txn: Transaction<D>,
{
    /// Return `true` if this table has zero rows.
    pub async fn is_empty(&self, txn: &Txn) -> TCResult<bool> {
        self.inner.primary.is_empty(txn).await
    }

    /// Merge the given list of `Bounds` into a single `Bounds` instance.
    ///
    /// Returns an error in the case that later [`Bounds`] are larger than earlier [`Bounds`].
    pub fn merge_bounds(&self, all_bounds: Vec<Bounds>) -> TCResult<Bounds> {
        let collator = self.inner.primary.btree().collator();

        let mut merged = Bounds::default();
        for bounds in all_bounds {
            merged.merge(bounds, collator)?;
        }

        Ok(merged)
    }

    /// Borrow the primary `Index` of this `TableIndex`.
    pub fn primary(&self) -> &Index<F, D, Txn> {
        &self.inner.primary
    }

    /// Return an index which supports the given [`Bounds`], or an error if there is none.
    pub fn supporting_index(&self, bounds: &Bounds) -> TCResult<Index<F, D, Txn>> {
        if self.inner.primary.validate_bounds(bounds).is_ok() {
            return Ok(self.inner.primary.clone());
        }

        for (_, index) in &self.inner.auxiliary {
            if index.validate_bounds(bounds).is_ok() {
                return Ok(index.clone());
            }
        }

        Err(TCError::bad_request(
            "this table has no index which supports bounds",
            bounds,
        ))
    }

    /// Stream the rows within the given [`Bounds`] from the primary index of this `TableIndex`.
    pub async fn slice_rows<'a>(
        self,
        txn_id: TxnId,
        bounds: Bounds,
        reverse: bool,
    ) -> TCResult<TCBoxTryStream<'a, Vec<Value>>> {
        self.inner
            .primary
            .clone()
            .slice_rows(txn_id, bounds, reverse)
            .await
    }
}

impl<F, D, Txn> Instance for TableIndex<F, D, Txn>
where
    Self: Send + Sync,
{
    type Class = TableType;

    fn class(&self) -> TableType {
        TableType::Table
    }
}

#[async_trait]
impl<F, D, Txn> TableInstance for TableIndex<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node>,
    D: Dir,
    Txn: Transaction<D>,
{
    fn key(&self) -> &[Column] {
        self.inner.primary.key()
    }

    fn values(&self) -> &[Column] {
        self.inner.primary.values()
    }

    fn schema(&self) -> TableSchema {
        self.inner.schema.clone()
    }
}

impl<F, D, Txn> TableOrder for TableIndex<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node>,
    D: Dir,
    Txn: Transaction<D>,
{
    type OrderBy = Merged<F, D, Txn>;
    type Reverse = Merged<F, D, Txn>;

    fn order_by(self, columns: Vec<Id>, reverse: bool) -> TCResult<Self::OrderBy> {
        self.validate_order(&columns)?;

        let selection = Slice::new(self.clone(), Bounds::default())?;
        let merge_source = MergeSource::Table(selection);

        if self.primary().validate_order(&columns).is_ok() {
            debug!("primary key can order by {}", Tuple::from(columns.clone()));

            let index_slice = self.primary().clone().index_slice(Bounds::default())?;
            let merged = Merged::new(merge_source, index_slice)?;
            return if reverse {
                merged.reverse()
            } else {
                Ok(merged.into())
            };
        } else {
            for (name, index) in &self.inner.auxiliary {
                if index.validate_order(&columns).is_ok() {
                    debug!(
                        "index {} can order by {}",
                        name,
                        Tuple::from(columns.clone())
                    );

                    let index_slice = index.clone().index_slice(Bounds::default())?;
                    let merged = Merged::new(merge_source, index_slice)?;
                    return if reverse {
                        merged.reverse()
                    } else {
                        Ok(merged.into())
                    };
                }
            }
        }

        Err(TCError::bad_request(
            "table has no index to order by",
            Tuple::<Id>::from_iter(columns),
        ))
    }

    fn reverse(self) -> TCResult<Self::Reverse> {
        Err(TCError::unsupported(
            "cannot reverse a Table itself, consider reversing a slice of the table instead",
        ))
    }

    fn validate_order(&self, mut order: &[Id]) -> TCResult<()> {
        while !order.is_empty() {
            let initial = order.to_vec();
            let mut i = order.len();
            loop {
                let subset = &order[..i];

                if self.inner.primary.validate_order(subset).is_ok() {
                    order = &order[i..];
                    break;
                }

                for (_, index) in &self.inner.auxiliary {
                    if index.validate_order(subset).is_ok() {
                        order = &order[i..];
                        break;
                    }
                }

                if order.is_empty() {
                    break;
                } else {
                    i = i - 1;
                }
            }

            if order == &initial[..] {
                let order: Vec<String> = order.iter().map(|id| id.to_string()).collect();
                return Err(TCError::bad_request(
                    "This table has no index to support the order",
                    order.join(", "),
                ));
            }
        }

        Ok(())
    }
}

#[async_trait]
impl<F, D, Txn> TableRead for TableIndex<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node>,
    D: Dir,
    Txn: Transaction<D>,
{
    async fn read(&self, txn_id: &TxnId, key: &Key) -> TCResult<Option<Vec<Value>>> {
        let slice = self
            .inner
            .primary
            .btree
            .clone()
            .slice(tc_btree::Range::with_prefix(key.to_vec()), false)?;

        let mut keys = slice.keys(*txn_id).await?;
        keys.try_next().await
    }
}

#[async_trait]
impl<F, D, Txn> TableStream for TableIndex<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node>,
    D: Dir,
    Txn: Transaction<D>,
{
    type Limit = Limited<F, D, Txn>;
    type Selection = Selection<F, D, Txn, Self>;

    async fn count(self, txn_id: TxnId) -> TCResult<u64> {
        self.inner.primary.clone().count(txn_id).await
    }

    fn limit(self, limit: u64) -> Self::Limit {
        Limited::new(self, limit)
    }

    fn select(self, columns: Vec<Id>) -> TCResult<Self::Selection> {
        Selection::new(self, columns)
    }

    async fn rows<'a>(self, txn_id: TxnId) -> TCResult<TCBoxTryStream<'a, Vec<Value>>> {
        self.inner.primary.clone().rows(txn_id).await
    }
}

impl<F, D, Txn> TableSlice for TableIndex<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node>,
    D: Dir,
    Txn: Transaction<D>,
{
    type Slice = Merged<F, D, Txn>;

    fn slice(self, bounds: Bounds) -> TCResult<Merged<F, D, Txn>> {
        debug!("TableIndex::slice {}", bounds);

        let primary = &self.inner.primary;
        let auxiliary = &self.inner.auxiliary;

        let columns: Vec<Id> = primary
            .schema()
            .columns()
            .iter()
            .map(|c| c.name())
            .cloned()
            .collect();

        let bounds: Vec<(Id, ColumnBound)> = columns
            .into_iter()
            .filter_map(|name| bounds.get(&name).map(|bound| (name, bound.clone())))
            .collect();

        let selection = Slice::new(self.clone(), Bounds::default())?;
        let mut merge_source = MergeSource::Table(selection);

        let mut bounds = &bounds[..];
        loop {
            let initial = bounds.len();
            let mut i = bounds.len();
            while i > 0 {
                let subset: HashMap<Id, ColumnBound> = bounds[..i].to_vec().into_iter().collect();
                let subset = Bounds::from(subset);

                if primary.validate_bounds(&subset).is_ok() {
                    debug!("primary key can slice {}", subset);

                    let index_slice = primary.clone().index_slice(subset)?;
                    let merged = Merged::new(merge_source, index_slice)?;

                    bounds = &bounds[i..];
                    if bounds.is_empty() {
                        return Ok(merged);
                    }

                    merge_source = MergeSource::Merge(Box::new(merged));
                    break;
                } else {
                    let mut supported = false;
                    for (name, index) in auxiliary {
                        debug!("checking index {} with schema {}", name, index.schema());

                        match index.validate_bounds(&subset) {
                            Ok(()) => {
                                debug!("index {} can slice {}", name, subset);
                                supported = true;

                                let index_slice = index.clone().index_slice(subset)?;
                                let merged = Merged::new(merge_source, index_slice)?;

                                bounds = &bounds[i..];
                                if bounds.is_empty() {
                                    return Ok(merged);
                                }

                                merge_source = MergeSource::Merge(Box::new(merged));
                                break;
                            }
                            Err(cause) => {
                                debug!("index {} cannot slice {}: {}", name, subset, cause);
                            }
                        }
                    }

                    if supported {
                        break;
                    }
                };

                i = i - 1;
            }

            if bounds.len() == initial {
                return Err(TCError::unsupported(
                    "this Table has no Index to support the requested selection bounds",
                ));
            }
        }
    }

    fn validate_bounds(&self, bounds: &Bounds) -> TCResult<()> {
        let primary = &self.inner.primary;
        let auxiliary = &self.inner.auxiliary;

        if primary.validate_bounds(bounds).is_ok() {
            return Ok(());
        }

        let bounds: Vec<(Id, ColumnBound)> = primary
            .schema()
            .columns()
            .iter()
            .filter_map(|c| {
                bounds
                    .get(c.name())
                    .map(|bound| (c.name().clone(), bound.clone()))
            })
            .collect();

        let mut bounds = &bounds[..];
        while !bounds.is_empty() {
            let initial = bounds.len();

            let mut i = bounds.len();
            loop {
                let subset: HashMap<Id, ColumnBound> = bounds[..i].iter().cloned().collect();
                let subset = Bounds::from(subset);

                if primary.validate_bounds(&subset).is_ok() {
                    bounds = &bounds[i..];
                    break;
                }

                for (_, index) in auxiliary {
                    if index.validate_bounds(&subset).is_ok() {
                        bounds = &bounds[i..];
                        break;
                    }
                }

                if bounds.is_empty() {
                    break;
                } else {
                    i = i - 1;
                }
            }

            if bounds.len() == initial {
                let bounds = Tuple::<String>::from_iter(
                    bounds
                        .into_iter()
                        .map(|(id, bound)| format!("{}: {}", id, bound)),
                );

                return Err(TCError::unsupported(format!("this table has no index to support selection bounds on {}--available indices are {}", bounds, Tuple::<&Id>::from_iter(auxiliary.iter().map(|(id, _)| id)))));
            }
        }

        Ok(())
    }
}

#[async_trait]
impl<F, D, Txn> TableWrite for TableIndex<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node>,
    D: Dir,
    Txn: Transaction<D>,
{
    async fn delete(&self, txn_id: TxnId, key: Key) -> TCResult<()> {
        let primary = &self.inner.primary;
        let aux = &self.inner.auxiliary;

        let key = primary.schema.validate_key(key)?;
        let row = match self.read(&txn_id, &key).await? {
            Some(row) => row,
            None => return Ok(()),
        };

        let row = primary.schema.row_from_values(row)?;

        let mut deletes = Vec::with_capacity(aux.len() + 1);
        for (_, index) in aux {
            deletes.push(index.delete(txn_id, row.clone()));
        }

        deletes.push(primary.delete(txn_id, row));
        try_join_all(deletes).await?;

        Ok(())
    }

    async fn update(&self, txn_id: TxnId, key: Key, values: Row) -> TCResult<()> {
        let columns_updated: HashSet<Id> = values.keys().cloned().collect();

        let primary = &self.inner.primary;
        let aux = &self.inner.auxiliary;

        let key = primary.schema.validate_key(key)?;
        let row = match self.read(&txn_id, &key).await? {
            Some(values) => primary.schema.row_from_values(values)?,
            None => return Ok(()),
        };

        let mut updates = Vec::with_capacity(aux.len() + 1);
        for (_, index) in aux {
            if !index
                .schema
                .column_names()
                .any(|name| columns_updated.contains(name))
            {
                continue;
            }

            updates.push(index.replace(txn_id, row.clone(), values.clone()));
        }

        updates.push(primary.replace(txn_id, row, values));
        try_join_all(updates).await?;

        Ok(())
    }

    async fn upsert(&self, txn_id: TxnId, key: Key, values: Values) -> TCResult<()> {
        let primary = &self.inner.primary;
        let aux = &self.inner.auxiliary;

        let key = primary.schema.validate_key(key)?;
        let values = primary.schema.validate_values(values)?;

        let columns: HashSet<Id> = primary
            .schema
            .values()
            .iter()
            .map(|col| &col.name)
            .cloned()
            .collect();

        let row = primary.schema.row_from_key_values(key, values)?;
        let update: Row = row
            .clone()
            .into_iter()
            .filter(|(id, _)| columns.contains(id))
            .collect();

        let mut upserts = Vec::with_capacity(aux.len() + 1);
        for (_name, index) in aux {
            upserts.push(index.replace(txn_id, row.clone(), update.clone()));
        }

        upserts.push(primary.replace(txn_id, row, update));
        try_join_all(upserts).await?;

        Ok(())
    }
}

#[async_trait]
impl<F, D, Txn> Transact for TableIndex<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node>
        + Transact<Commit = Option<TxnLockCommit<BTreeMap<NodeId, TxnLock<TxnId>>>>>,
    D: Dir,
    Txn: Transaction<D>,
{
    type Commit = <BTreeFile<F, D, Txn> as Transact>::Commit;

    async fn commit(&self, txn_id: TxnId) -> Self::Commit {
        let guard = self.inner.primary.commit(txn_id).await?;

        let index_commits = self
            .inner
            .auxiliary
            .iter()
            .map(|(_, index)| index.commit(txn_id));

        join_all(index_commits).await;

        Some(guard)
    }

    async fn rollback(&self, txn_id: &TxnId) {
        let index_rollbacks = self
            .inner
            .auxiliary
            .iter()
            .map(|(_, index)| index.rollback(txn_id));

        join_all(iter::once(self.inner.primary.rollback(txn_id)).chain(index_rollbacks)).await;
    }

    async fn finalize(&self, txn_id: &TxnId) {
        let index_cleanups = self
            .inner
            .auxiliary
            .iter()
            .map(|(_, index)| index.finalize(txn_id));

        join_all(iter::once(self.inner.primary.finalize(txn_id)).chain(index_cleanups)).await;
    }
}

impl<F, D, Txn> Persist<D> for TableIndex<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node, Inner = D::Inner> + TryFrom<D::Store, Error = TCError>,
    D: Dir + TryFrom<D::Store, Error = TCError>,
    Txn: Transaction<D>,
    D::Read: DirReadFile<F>,
    D::Write: DirCreateFile<F>,
    D::Store: From<F>,
{
    type Txn = Txn;
    type Schema = TableSchema;

    fn create(txn_id: TxnId, schema: Self::Schema, store: D::Store) -> TCResult<Self> {
        let dir = D::try_from(store)?;
        let mut dir_lock = dir.try_write(txn_id)?;

        let primary_file = dir_lock.create_file(PRIMARY_INDEX.into())?;
        let primary = Index::create(txn_id, schema.primary().clone(), primary_file.into())?;

        let primary_schema = schema.primary();
        let mut auxiliary = Vec::with_capacity(schema.indices().len());
        for (name, column_names) in schema.indices() {
            if name == &PRIMARY_INDEX {
                return Err(TCError::bad_request(
                    "cannot create an auxiliary index with reserved name",
                    PRIMARY_INDEX,
                ));
            }

            let file = dir_lock.create_file(name.clone())?;
            let index = Self::create_index(txn_id, primary_schema, file, column_names.to_vec())
                .map(move |index| (name.clone(), index))?;

            auxiliary.push(index);
        }

        Ok(Self {
            inner: Arc::new(Inner {
                schema,
                primary,
                auxiliary,
                dir,
            }),
        })
    }

    fn load(txn_id: TxnId, schema: Self::Schema, store: D::Store) -> TCResult<Self> {
        let dir = D::try_from(store)?;
        let dir_lock = dir.try_read(txn_id)?;

        let file = dir_lock
            .get_file(&PRIMARY_INDEX.into())?
            .ok_or_else(|| TCError::internal("cannot load Table: primary index is missing"))?;

        let primary = Index::load(txn_id, schema.primary().clone(), file.into())?;

        let mut auxiliary = Vec::with_capacity(schema.indices().len());
        for (name, columns) in schema.indices() {
            let file = dir_lock.get_file(name)?.ok_or_else(|| {
                TCError::internal(format!("cannot load Table: missing index {}", name))
            })?;

            let index_schema = schema.primary().auxiliary(columns)?;

            let index = Index::load(txn_id, index_schema, file.into())?;
            auxiliary.push((name.clone(), index));
        }

        Ok(Self {
            inner: Arc::new(Inner {
                schema,
                primary,
                auxiliary,
                dir,
            }),
        })
    }

    fn dir(&self) -> D::Inner {
        self.inner.dir.clone().into_inner()
    }
}

#[async_trait]
impl<F, D, Txn> Restore<D> for TableIndex<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node, Inner = D::Inner> + TryFrom<D::Store, Error = TCError>,
    D: Dir + TryFrom<D::Store, Error = TCError>,
    Txn: Transaction<D>,
    D::Read: DirReadFile<F>,
    D::Write: DirCreateFile<F>,
    D::Store: From<F>,
{
    async fn restore(&self, txn_id: TxnId, backup: &Self) -> TCResult<()> {
        if self.inner.schema != backup.inner.schema {
            return Err(TCError::unsupported(
                "cannot restore a Table using a backup with a different schema",
            ));
        }

        let mut restores = Vec::with_capacity(self.inner.auxiliary.len() + 1);
        restores.push(self.inner.primary.restore(txn_id, &backup.inner.primary));

        let mut backup_indices = BTreeMap::from_iter(
            backup
                .inner
                .auxiliary
                .iter()
                .map(|(name, index)| (name, index)),
        );

        for (name, index) in &self.inner.auxiliary {
            restores.push(index.restore(txn_id, backup_indices.remove(name).unwrap()));
        }

        try_join_all(restores).await?;

        Ok(())
    }
}

#[async_trait]
impl<F, D, Txn, I> CopyFrom<D, I> for TableIndex<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node, Inner = D::Inner> + TryFrom<D::Store, Error = TCError>,
    D: Dir + TryFrom<D::Store, Error = TCError>,
    Txn: Transaction<D>,
    I: TableStream + 'static,
    D::Read: DirReadFile<F>,
    D::Write: DirCreateFile<F>,
    D::Store: From<F>,
{
    async fn copy_from(txn: &Txn, store: D::Store, source: I) -> TCResult<Self> {
        let txn_id = *txn.id();
        let schema = source.schema();
        let key_len = schema.primary().key().len();
        let table = Self::create(txn_id, schema, store)?;

        let rows = source.rows(txn_id).await?;

        rows.map_ok(|mut row| (row.drain(..key_len).collect(), row))
            .map_ok(|(key, values)| table.upsert(txn_id, key, values))
            .try_buffer_unordered(num_cpus::get())
            .try_fold((), |(), ()| future::ready(Ok(())))
            .await?;

        Ok(table)
    }
}

struct TableVisitor<F: File<Key = NodeId, Block = Node>, D: Dir, Txn: Transaction<D>> {
    txn: Txn,
    phantom_file: PhantomData<F>,
    phantom_dir: PhantomData<D>,
}

#[async_trait]
impl<F, D, Txn> de::Visitor for TableVisitor<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node, Inner = D::Inner> + TryFrom<D::Store, Error = TCError>,
    D: Dir + TryFrom<D::Store, Error = TCError>,
    Txn: Transaction<D>,
    D::Read: DirReadFile<F>,
    D::Write: DirCreateFile<F>,
    D::Store: From<D> + From<F>,
{
    type Value = TableIndex<F, D, Txn>;

    fn expecting() -> &'static str {
        "a Table"
    }

    async fn visit_seq<A: de::SeqAccess>(self, mut seq: A) -> Result<Self::Value, A::Error> {
        let txn_id = *self.txn.id();
        let schema = seq
            .next_element(())
            .await?
            .ok_or_else(|| de::Error::invalid_length(0, "a Table schema"))?;

        let table = TableIndex::create(txn_id, schema, self.txn.context().clone().into())
            .map_err(de::Error::custom)?;

        if let Some(visitor) = seq
            .next_element::<RowVisitor<F, D, Txn>>((txn_id, table.clone()))
            .await?
        {
            Ok(visitor.table)
        } else {
            Ok(table)
        }
    }
}

struct RowVisitor<F: File<Key = NodeId, Block = Node>, D: Dir, Txn: Transaction<D>> {
    table: TableIndex<F, D, Txn>,
    txn_id: TxnId,
}

#[async_trait]
impl<F, D, Txn> de::Visitor for RowVisitor<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node, Inner = D::Inner> + TryFrom<D::Store, Error = TCError>,
    D: Dir + TryFrom<D::Store, Error = TCError>,
    Txn: Transaction<D>,
    D::Write: DirCreateFile<F>,
    D::Store: From<F>,
{
    type Value = Self;

    fn expecting() -> &'static str {
        "a sequence of table rows"
    }

    async fn visit_seq<A: de::SeqAccess>(self, mut seq: A) -> Result<Self::Value, A::Error> {
        let schema = self.table.primary().schema();

        while let Some(row) = seq.next_element(()).await? {
            let row = schema.row_from_values(row).map_err(de::Error::custom)?;
            let (key, values) = schema
                .key_values_from_row(row, true)
                .map_err(de::Error::custom)?;

            self.table
                .upsert(self.txn_id, key, values)
                .map_err(de::Error::custom)
                .await?;
        }

        Ok(self)
    }
}

#[async_trait]
impl<F, D, Txn> de::FromStream for RowVisitor<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node, Inner = D::Inner> + TryFrom<D::Store, Error = TCError>,
    D: Dir + TryFrom<D::Store, Error = TCError>,
    Txn: Transaction<D>,
    D::Write: DirCreateFile<F>,
    D::Store: From<F>,
{
    type Context = (TxnId, TableIndex<F, D, Txn>);

    async fn from_stream<De: de::Decoder>(
        cxt: Self::Context,
        decoder: &mut De,
    ) -> Result<Self, De::Error> {
        let (txn_id, table) = cxt;
        decoder.decode_seq(Self { txn_id, table }).await
    }
}

#[async_trait]
impl<F, D, Txn> de::FromStream for TableIndex<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node, Inner = D::Inner> + TryFrom<D::Store, Error = TCError>,
    D: Dir + TryFrom<D::Store, Error = TCError>,
    Txn: Transaction<D>,
    D::Read: DirReadFile<F>,
    D::Write: DirCreateFile<F>,
    D::Store: From<D> + From<F>,
{
    type Context = Txn;

    async fn from_stream<De: de::Decoder>(txn: Txn, decoder: &mut De) -> Result<Self, De::Error> {
        decoder
            .decode_seq(TableVisitor {
                txn,
                phantom_dir: PhantomData,
                phantom_file: PhantomData,
            })
            .await
    }
}

impl<F, D, Txn> From<TableIndex<F, D, Txn>> for Table<F, D, Txn>
where
    F: File<Key = NodeId, Block = Node>,
    D: Dir,
    Txn: Transaction<D>,
{
    fn from(table: TableIndex<F, D, Txn>) -> Self {
        Self::Table(table)
    }
}

impl<F: File<Key = NodeId, Block = Node>, D: Dir, Txn: Transaction<D>> fmt::Display
    for TableIndex<F, D, Txn>
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("a Table")
    }
}