-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathpipelined.rs
More file actions
1641 lines (1565 loc) · 53.2 KB
/
pipelined.rs
File metadata and controls
1641 lines (1565 loc) · 53.2 KB
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
use std::{
collections::{HashMap, HashSet},
ops::Bound,
};
use anyhow::Result;
use itertools::Either;
use spacetimedb_expr::expr::AggType;
use spacetimedb_lib::{metrics::ExecutionMetrics, query::Delta, sats::size_of::SizeOf, AlgebraicValue, ProductValue};
use spacetimedb_physical_plan::plan::{
HashJoin, IxJoin, IxScan, PhysicalExpr, PhysicalPlan, ProjectField, ProjectListPlan, ProjectPlan, Sarg, Semi,
TableScan, TupleField,
};
use spacetimedb_primitives::{ColId, ColList, IndexId, TableId};
use spacetimedb_sats::product;
use crate::{Datastore, DeltaStore, Row, Tuple};
/// An executor for explicit column projections.
/// Note, this plan can only be constructed from the http api,
/// which is not considered performance critical.
/// Hence this operator is not particularly optimized.
pub enum ProjectListExecutor {
Name(Vec<PipelinedProject>),
View(Vec<ViewProject>),
List(Vec<PipelinedExecutor>, Vec<TupleField>),
Limit(Box<ProjectListExecutor>, u64),
Agg(Vec<PipelinedExecutor>, AggType),
}
impl From<ProjectListPlan> for ProjectListExecutor {
fn from(plan: ProjectListPlan) -> Self {
/// A helper that checks if a [`ProjectListPlan`] returns an unprojected view table
fn returns_view_table(plans: &[ProjectPlan]) -> bool {
plans.first().is_some_and(|plan| plan.returns_view_table())
}
/// A helper that returns the number of columns returned by this [`ProjectListPlan`]
fn num_cols(plans: &[ProjectPlan]) -> usize {
plans
.first()
.and_then(|plan| plan.return_table())
.map(|schema| schema.num_cols())
.unwrap_or_default()
}
/// A helper that returns the number of private columns returned by this [`ProjectListPlan`]
fn num_private_cols(plans: &[ProjectPlan]) -> usize {
plans
.first()
.and_then(|plan| plan.return_table())
.map(|schema| schema.num_private_cols())
.unwrap_or_default()
}
match plan {
ProjectListPlan::Name(plans) if returns_view_table(&plans) => {
let num_cols = num_cols(&plans);
let num_private_cols = num_private_cols(&plans);
Self::View(
plans
.into_iter()
.map(PipelinedProject::from)
.map(|plan| ViewProject::new(plan, num_cols, num_private_cols))
.collect(),
)
}
ProjectListPlan::Name(plan) => Self::Name(plan.into_iter().map(PipelinedProject::from).collect()),
ProjectListPlan::List(plan, fields) => {
Self::List(plan.into_iter().map(PipelinedExecutor::from).collect(), fields)
}
ProjectListPlan::Limit(plan, n) => Self::Limit(Box::new((*plan).into()), n),
ProjectListPlan::Agg(plan, AggType::Count) => {
Self::Agg(plan.into_iter().map(PipelinedExecutor::from).collect(), AggType::Count)
}
}
}
}
impl ProjectListExecutor {
pub fn execute<Tx: Datastore + DeltaStore>(
&self,
tx: &Tx,
metrics: &mut ExecutionMetrics,
f: &mut dyn FnMut(ProductValue) -> Result<()>,
) -> Result<()> {
let mut n = 0;
let mut bytes_scanned = 0;
match self {
Self::Name(plans) => {
for plan in plans {
plan.execute(tx, metrics, &mut |row| {
n += 1;
let row = row.to_product_value();
bytes_scanned += row.size_of();
f(row)
})?;
}
}
Self::View(plans) => {
for plan in plans {
plan.execute(tx, metrics, &mut |row| {
n += 1;
f(row)
})?;
}
}
Self::List(plans, fields) => {
for plan in plans {
plan.execute(tx, metrics, &mut |t| {
n += 1;
let row = ProductValue::from_iter(fields.iter().map(|field| t.project(field)));
bytes_scanned += row.size_of();
f(row)
})?;
}
}
Self::Limit(plan, limit) => {
plan.execute(tx, metrics, &mut |row| {
n += 1;
if n <= *limit as usize {
f(row)?;
}
Ok(())
})?;
}
Self::Agg(plans, AggType::Count) => {
for plan in plans {
match plan {
// TODO: This is a hack that needs to be removed.
// We check if this is a COUNT on a physical table,
// and if so, we retrieve the count from table metadata.
// It's a valid optimization but one that should be done by the optimizer.
// There should be no optimizations performed during execution.
PipelinedExecutor::TableScan(table_scan) => {
n += tx.row_count(table_scan.table) as usize;
}
_ => {
plan.execute(tx, metrics, &mut |_| {
n += 1;
Ok(())
})?;
}
}
}
f(product![n as u64])?;
}
}
metrics.rows_scanned += n;
metrics.bytes_scanned += bytes_scanned;
Ok(())
}
}
/// An executor for a query that returns rows from a view.
/// Essentially just a projection that drops the view's private columns.
///
/// Unlike user tables, view tables can have private columns.
/// For example, if a view is not anonymous, its backing table will have a `sender` column.
/// This column tracks which rows belong to which caller of the view.
/// However we must remove this column before sending rows from the view to a client.
///
/// See `TableSchema::from_view_def_for_datastore` for more details.
#[derive(Debug)]
pub struct ViewProject {
num_cols: usize,
num_private_cols: usize,
inner: PipelinedProject,
}
impl ViewProject {
pub fn new(inner: PipelinedProject, num_cols: usize, num_private_cols: usize) -> Self {
Self {
inner,
num_cols,
num_private_cols,
}
}
pub fn execute<Tx: Datastore + DeltaStore>(
&self,
tx: &Tx,
metrics: &mut ExecutionMetrics,
f: &mut dyn FnMut(ProductValue) -> Result<()>,
) -> Result<()> {
let mut n = 0;
let mut bytes_scanned = 0;
self.inner.execute(tx, metrics, &mut |row| match row {
Row::Ptr(ptr) => {
n += 1;
let col_list = ColList::from_iter(self.num_private_cols..self.num_cols);
let row = ptr.project_product(&col_list)?;
bytes_scanned += row.size_of();
f(row)
}
Row::Ref(val) => {
n += 1;
let col_list = ColList::from_iter(self.num_private_cols..self.num_cols);
let row = val.project_product(&col_list)?;
bytes_scanned += row.size_of();
f(row)
}
})?;
metrics.rows_scanned += n;
Ok(())
}
}
/// Implements a projection on top of a pipelined executor
#[derive(Debug)]
pub enum PipelinedProject {
None(PipelinedExecutor),
Some(PipelinedExecutor, usize),
}
impl From<ProjectPlan> for PipelinedProject {
fn from(plan: ProjectPlan) -> Self {
match plan {
ProjectPlan::None(plan) => Self::None(plan.into()),
ProjectPlan::Name(plan, _, None) => Self::None(plan.into()),
ProjectPlan::Name(plan, _, Some(i)) => Self::Some(plan.into(), i),
}
}
}
impl PipelinedProject {
/// Walks and visits each executor in the tree
pub fn visit(&self, f: &mut impl FnMut(&PipelinedExecutor)) {
match self {
Self::Some(plan, _) | Self::None(plan) => {
plan.visit(f);
}
}
}
/// Does this operation contain an empty delta scan?
pub fn is_empty(&self, tx: &impl DeltaStore) -> bool {
match self {
Self::None(plan) | Self::Some(plan, _) => plan.is_empty(tx),
}
}
pub fn execute<'a, Tx: Datastore + DeltaStore>(
&self,
tx: &'a Tx,
metrics: &mut ExecutionMetrics,
f: &mut dyn FnMut(Row<'a>) -> Result<()>,
) -> Result<()> {
let mut n = 0;
match self {
Self::None(plan) => {
// No explicit projection.
// This means the input does not return tuples.
// It returns either row ids or product values.
plan.execute(tx, metrics, &mut |t| {
n += 1;
if let Tuple::Row(row) = t {
f(row)?;
}
Ok(())
})?;
}
Self::Some(plan, i) => {
// The contrary is true for explicit projections.
// They return a tuple of row ids or product values.
plan.execute(tx, metrics, &mut |t| {
n += 1;
if let Some(row) = t.select(*i) {
f(row)?;
}
Ok(())
})?;
}
}
metrics.rows_scanned += n;
Ok(())
}
}
/// Executes a query plan in a streaming fashion.
/// Avoids materializing intermediate results when possible.
/// Note that unlike a tuple at a time iterator,
/// the caller has no way to interrupt its forward progress.
#[derive(Debug)]
pub enum PipelinedExecutor {
TableScan(PipelinedScan),
IxScanEq(PipelinedIxScanEq),
IxScanRange(PipelinedIxScanRange),
IxJoin(PipelinedIxJoin),
IxDeltaScanEq(PipelinedIxDeltaScanEq),
IxDeltaScanRange(PipelinedIxDeltaScanRange),
IxDeltaJoin(PipelinedIxDeltaJoin),
HashJoin(BlockingHashJoin),
NLJoin(BlockingNLJoin),
Filter(PipelinedFilter),
Limit(PipelinedLimit),
}
impl From<PhysicalPlan> for PipelinedExecutor {
fn from(plan: PhysicalPlan) -> Self {
match plan {
PhysicalPlan::TableScan(TableScan { schema, limit, delta }, _) => Self::TableScan(PipelinedScan {
table: schema.table_id,
limit,
delta,
}),
PhysicalPlan::IxScan(
scan @ IxScan {
delta: None,
arg: Sarg::Eq(..),
..
},
_,
) => Self::IxScanEq(scan.into()),
PhysicalPlan::IxScan(
scan @ IxScan {
delta: None,
arg: Sarg::Range(..),
..
},
_,
) => Self::IxScanRange(scan.into()),
PhysicalPlan::IxScan(
scan @ IxScan {
delta: Some(_),
arg: Sarg::Eq(..),
..
},
_,
) => Self::IxDeltaScanEq(scan.into()),
PhysicalPlan::IxScan(
scan @ IxScan {
delta: Some(_),
arg: Sarg::Range(..),
..
},
_,
) => Self::IxDeltaScanRange(scan.into()),
PhysicalPlan::IxJoin(
IxJoin {
lhs,
rhs,
rhs_index,
rhs_prefix,
rhs_field,
unique,
lhs_field,
rhs_delta: None,
..
},
semijoin,
) => Self::IxJoin(PipelinedIxJoin {
lhs: Box::new(Self::from(*lhs)),
rhs_table: rhs.table_id,
rhs_index,
rhs_prefix,
rhs_field,
lhs_field,
unique,
semijoin,
}),
PhysicalPlan::IxJoin(
IxJoin {
lhs,
rhs,
rhs_index,
rhs_prefix,
rhs_field,
unique,
lhs_field,
rhs_delta: Some(rhs_delta),
..
},
semijoin,
) => Self::IxDeltaJoin(PipelinedIxDeltaJoin {
lhs: Box::new(Self::from(*lhs)),
rhs_table: rhs.table_id,
rhs_index,
rhs_prefix,
rhs_field,
rhs_delta,
lhs_field,
unique,
semijoin,
}),
PhysicalPlan::HashJoin(
HashJoin {
lhs,
rhs,
lhs_field,
rhs_field,
unique,
},
semijoin,
) => Self::HashJoin(BlockingHashJoin {
lhs: Box::new(PipelinedExecutor::from(*lhs)),
rhs: Box::new(PipelinedExecutor::from(*rhs)),
lhs_field,
rhs_field,
unique,
semijoin,
}),
PhysicalPlan::NLJoin(lhs, rhs) => Self::NLJoin(BlockingNLJoin {
lhs: Box::new(PipelinedExecutor::from(*lhs)),
rhs: Box::new(PipelinedExecutor::from(*rhs)),
}),
PhysicalPlan::Filter(input, expr) => Self::Filter(PipelinedFilter {
input: Box::new(PipelinedExecutor::from(*input)),
expr,
}),
}
}
}
impl PipelinedExecutor {
/// Walks and visits each executor in the tree
pub fn visit(&self, f: &mut impl FnMut(&Self)) {
f(self);
match self {
Self::IxJoin(PipelinedIxJoin { lhs: input, .. })
| Self::IxDeltaJoin(PipelinedIxDeltaJoin { lhs: input, .. })
| Self::Filter(PipelinedFilter { input, .. })
| Self::Limit(PipelinedLimit { input, .. }) => {
input.visit(f);
}
Self::NLJoin(BlockingNLJoin { lhs, rhs }) | Self::HashJoin(BlockingHashJoin { lhs, rhs, .. }) => {
lhs.visit(f);
rhs.visit(f);
}
Self::TableScan(..)
| Self::IxScanEq(..)
| Self::IxScanRange(..)
| Self::IxDeltaScanEq(..)
| Self::IxDeltaScanRange(..) => {}
}
}
/// Does this operation contain an empty delta scan?
pub fn is_empty(&self, tx: &impl DeltaStore) -> bool {
match self {
Self::TableScan(scan) => scan.is_empty(tx),
Self::IxScanEq(scan) => scan.is_empty(tx),
Self::IxScanRange(scan) => scan.is_empty(tx),
Self::IxDeltaScanEq(scan) => scan.is_empty(tx),
Self::IxDeltaScanRange(scan) => scan.is_empty(tx),
Self::IxJoin(join) => join.is_empty(tx),
Self::IxDeltaJoin(join) => join.is_empty(tx),
Self::HashJoin(join) => join.is_empty(tx),
Self::NLJoin(join) => join.is_empty(tx),
Self::Filter(filter) => filter.is_empty(tx),
Self::Limit(limit) => limit.is_empty(tx),
}
}
pub fn execute<'a, Tx: Datastore + DeltaStore>(
&self,
tx: &'a Tx,
metrics: &mut ExecutionMetrics,
f: &mut dyn FnMut(Tuple<'a>) -> Result<()>,
) -> Result<()> {
match self {
Self::TableScan(scan) => scan.execute(tx, metrics, f),
Self::IxScanEq(scan) => scan.execute(tx, metrics, f),
Self::IxScanRange(scan) => scan.execute(tx, metrics, f),
Self::IxDeltaScanEq(scan) => scan.execute(tx, metrics, f),
Self::IxDeltaScanRange(scan) => scan.execute(tx, metrics, f),
Self::IxJoin(join) => join.execute(tx, metrics, f),
Self::IxDeltaJoin(join) => join.execute(tx, metrics, f),
Self::HashJoin(join) => join.execute(tx, metrics, f),
Self::NLJoin(join) => join.execute(tx, metrics, f),
Self::Filter(filter) => filter.execute(tx, metrics, f),
Self::Limit(limit) => limit.execute(tx, metrics, f),
}
}
}
/// A pipelined executor for scanning both physical and delta tables
#[derive(Debug)]
pub struct PipelinedScan {
pub table: TableId,
pub limit: Option<u64>,
pub delta: Option<Delta>,
}
impl PipelinedScan {
/// Is this an empty delta scan?
pub fn is_empty(&self, tx: &impl DeltaStore) -> bool {
match self.delta {
Some(Delta::Inserts) => !tx.has_inserts(self.table),
Some(Delta::Deletes) => !tx.has_deletes(self.table),
None => false,
}
}
pub fn execute<'a, Tx: Datastore + DeltaStore>(
&self,
tx: &'a Tx,
metrics: &mut ExecutionMetrics,
f: &mut dyn FnMut(Tuple<'a>) -> Result<()>,
) -> Result<()> {
// A physical table scan
let table_scan = || tx.table_scan(self.table);
// A physical table scan with optional row limit
let table_limit_scan = |limit| match limit {
None => table_scan().map(Either::Left),
Some(n) => table_scan().map(|iter| iter.take(n)).map(Either::Right),
};
// A delta table scan
let delta_scan = |inserts| tx.delta_scan(self.table, inserts);
// A delta table scan with optional row limit
let delta_limit_scan = |limit, inserts| match limit {
None => Either::Left(delta_scan(inserts)),
Some(n) => Either::Right(delta_scan(inserts).take(n)),
};
let mut n = 0;
let mut f = |t| {
n += 1;
f(t)
};
match self.delta {
None => {
for tuple in table_limit_scan(self.limit.map(|n| n as usize))?
.map(Row::Ptr)
.map(Tuple::Row)
{
f(tuple)?;
}
}
Some(Delta::Inserts) => {
for tuple in delta_limit_scan(self.limit.map(|n| n as usize), true)
.map(Row::Ref)
.map(Tuple::Row)
{
f(tuple)?;
}
}
Some(Delta::Deletes) => {
for tuple in delta_limit_scan(self.limit.map(|n| n as usize), false)
.map(Row::Ref)
.map(Tuple::Row)
{
f(tuple)?;
}
}
}
metrics.rows_scanned += n;
Ok(())
}
}
/// A range index scan executor for a delta table.
///
/// TODO: There is much overlap between this executor and [PipelinedIxScanRange].
/// But merging them requires merging the [Datastore] and [DeltaStore] traits,
/// since the index scan interface is right now split between both.
#[derive(Debug)]
pub struct PipelinedIxDeltaScanRange {
/// The table id
pub table_id: TableId,
/// The index id
pub index_id: IndexId,
/// An equality prefix for multi-column scans
pub prefix: Vec<AlgebraicValue>,
/// The lower index bound
pub lower: Bound<AlgebraicValue>,
/// The upper index bound
pub upper: Bound<AlgebraicValue>,
/// Inserts or deletes?
pub delta: Delta,
}
impl From<IxScan> for PipelinedIxDeltaScanRange {
fn from(scan: IxScan) -> Self {
match scan {
IxScan {
schema,
index_id,
prefix,
arg: Sarg::Eq(_, v),
delta: Some(delta),
..
} => Self {
table_id: schema.table_id,
index_id,
prefix: prefix.into_iter().map(|(_, v)| v).collect(),
lower: Bound::Included(v.clone()),
upper: Bound::Included(v),
delta,
},
IxScan {
schema,
index_id,
prefix,
arg: Sarg::Range(_, lower, upper),
delta: Some(delta),
..
} => Self {
table_id: schema.table_id,
index_id,
prefix: prefix.into_iter().map(|(_, v)| v).collect(),
lower,
upper,
delta,
},
IxScan { delta: None, .. } => unreachable!(),
}
}
}
impl PipelinedIxDeltaScanRange {
/// Is the delta table empty?
pub fn is_empty(&self, tx: &impl DeltaStore) -> bool {
match self.delta {
Delta::Inserts => !tx.has_inserts(self.table_id),
Delta::Deletes => !tx.has_deletes(self.table_id),
}
}
pub fn execute<'a, Tx: Datastore + DeltaStore>(
&self,
tx: &'a Tx,
metrics: &mut ExecutionMetrics,
f: &mut dyn FnMut(Tuple<'a>) -> Result<()>,
) -> Result<()> {
let mut n = 0;
let mut f = |t| {
n += 1;
f(t)
};
match self.prefix.as_slice() {
[] => {
for ptr in tx
.index_scan_range_for_delta(
self.table_id,
self.index_id,
self.delta,
(self.lower.as_ref(), self.upper.as_ref()),
)
.map(Tuple::Row)
{
f(ptr)?;
}
}
prefix => {
for ptr in tx
.index_scan_range_for_delta(
self.table_id,
self.index_id,
self.delta,
(
self.lower
.as_ref()
.map(std::iter::once)
.map(|iter| prefix.iter().chain(iter))
.map(|iter| iter.cloned())
.map(ProductValue::from_iter)
.map(AlgebraicValue::Product),
self.upper
.as_ref()
.map(std::iter::once)
.map(|iter| prefix.iter().chain(iter))
.map(|iter| iter.cloned())
.map(ProductValue::from_iter)
.map(AlgebraicValue::Product),
),
)
.map(Tuple::Row)
{
f(ptr)?;
}
}
}
metrics.index_seeks += 1;
metrics.rows_scanned += n;
Ok(())
}
}
/// An equality index scan executor for a delta table.
///
/// TODO: There is much overlap between this executor and [PipelinedIxScanEq].
/// But merging them requires merging the [Datastore] and [DeltaStore] traits,
/// since the index scan interface is right now split between both.
#[derive(Debug)]
pub struct PipelinedIxDeltaScanEq {
/// The table id
pub table_id: TableId,
/// The index id
pub index_id: IndexId,
/// The point to scan the index for.
pub point: AlgebraicValue,
/// Inserts or deletes?
pub delta: Delta,
}
impl From<IxScan> for PipelinedIxDeltaScanEq {
fn from(scan: IxScan) -> Self {
match scan {
IxScan {
schema,
index_id,
prefix,
arg: Sarg::Eq(_, last),
delta: Some(delta),
..
} => Self {
table_id: schema.table_id,
index_id,
point: combine_prefix_and_last(prefix, last),
delta,
},
IxScan { .. } => unreachable!(),
}
}
}
impl PipelinedIxDeltaScanEq {
/// Is the delta table empty?
pub fn is_empty(&self, tx: &impl DeltaStore) -> bool {
match self.delta {
Delta::Inserts => !tx.has_inserts(self.table_id),
Delta::Deletes => !tx.has_deletes(self.table_id),
}
}
pub fn execute<'a, Tx: Datastore + DeltaStore>(
&self,
tx: &'a Tx,
metrics: &mut ExecutionMetrics,
f: &mut dyn FnMut(Tuple<'a>) -> Result<()>,
) -> Result<()> {
let mut n = 0;
let mut f = |t| {
n += 1;
f(t)
};
for ptr in tx
.index_scan_point_for_delta(self.table_id, self.index_id, self.delta, &self.point)
.map(Tuple::Row)
{
f(ptr)?;
}
metrics.index_seeks += 1;
metrics.rows_scanned += n;
Ok(())
}
}
/// A pipelined executor for range scanning an index
#[derive(Debug)]
pub struct PipelinedIxScanRange {
/// The table id
pub table_id: TableId,
/// The index id
pub index_id: IndexId,
pub limit: Option<u64>,
/// An equality prefix for multi-column scans
pub prefix: Vec<AlgebraicValue>,
/// The lower index bound
pub lower: Bound<AlgebraicValue>,
/// The upper index bound
pub upper: Bound<AlgebraicValue>,
}
impl From<IxScan> for PipelinedIxScanRange {
fn from(scan: IxScan) -> Self {
match scan {
IxScan {
schema,
limit,
delta: None,
index_id,
prefix,
arg: Sarg::Eq(_, v),
} => Self {
table_id: schema.table_id,
index_id,
limit,
prefix: prefix.into_iter().map(|(_, v)| v).collect(),
lower: Bound::Included(v.clone()),
upper: Bound::Included(v),
},
IxScan {
schema,
limit,
delta: None,
index_id,
prefix,
arg: Sarg::Range(_, lower, upper),
} => Self {
table_id: schema.table_id,
index_id,
limit,
prefix: prefix.into_iter().map(|(_, v)| v).collect(),
lower,
upper,
},
IxScan { .. } => unreachable!(),
}
}
}
impl PipelinedIxScanRange {
/// We don't know statically if an index scan will return rows
pub fn is_empty(&self, _: &impl DeltaStore) -> bool {
false
}
pub fn execute<'a, Tx: Datastore + DeltaStore>(
&self,
tx: &'a Tx,
metrics: &mut ExecutionMetrics,
f: &mut dyn FnMut(Tuple<'a>) -> Result<()>,
) -> Result<()> {
// A single column index scan
let single_col_scan = || {
tx.index_scan_range(
self.table_id,
self.index_id,
&(self.lower.as_ref(), self.upper.as_ref()),
)
};
// A single column index scan with optional row limit
let single_col_limit_scan = |limit| match limit {
None => single_col_scan().map(Either::Left),
Some(n) => single_col_scan().map(|iter| iter.take(n)).map(Either::Right),
};
// A multi-column index scan
let multi_col_scan = |prefix: &[AlgebraicValue]| {
tx.index_scan_range(
self.table_id,
self.index_id,
&(
self.lower
.as_ref()
.map(std::iter::once)
.map(|iter| prefix.iter().chain(iter))
.map(|iter| iter.cloned())
.map(ProductValue::from_iter)
.map(AlgebraicValue::Product),
self.upper
.as_ref()
.map(std::iter::once)
.map(|iter| prefix.iter().chain(iter))
.map(|iter| iter.cloned())
.map(ProductValue::from_iter)
.map(AlgebraicValue::Product),
),
)
};
// A multi-column index scan with optional row limit
let multi_col_limit_scan = |prefix, limit| match limit {
None => multi_col_scan(prefix).map(Either::Left),
Some(n) => multi_col_scan(prefix).map(|iter| iter.take(n)).map(Either::Right),
};
let mut n = 0;
let mut f = |t| {
n += 1;
f(t)
};
match self.prefix.as_slice() {
[] => {
for ptr in single_col_limit_scan(self.limit.map(|n| n as usize))?
.map(Row::Ptr)
.map(Tuple::Row)
{
f(ptr)?;
}
}
prefix => {
for ptr in multi_col_limit_scan(prefix, self.limit.map(|n| n as usize))?
.map(Row::Ptr)
.map(Tuple::Row)
{
f(ptr)?;
}
}
}
metrics.index_seeks += 1;
metrics.rows_scanned += n;
Ok(())
}
}
/// A pipelined executor for equality scanning an index
#[derive(Debug)]
pub struct PipelinedIxScanEq {
/// The table id
pub table_id: TableId,
/// The index id
pub index_id: IndexId,
pub limit: Option<u64>,
/// The point to scan the index for.
pub point: AlgebraicValue,
}
impl From<IxScan> for PipelinedIxScanEq {
fn from(scan: IxScan) -> Self {
match scan {
IxScan {
schema,
limit,
delta: None,
index_id,
prefix,
arg: Sarg::Eq(_, last),
} => Self {
table_id: schema.table_id,
index_id,
limit,
point: combine_prefix_and_last(prefix, last),
},
IxScan { .. } => unreachable!(),
}
}
}
fn combine_prefix_and_last(prefix: Vec<(ColId, AlgebraicValue)>, last: AlgebraicValue) -> AlgebraicValue {
if prefix.is_empty() {
last
} else {
let mut elems = Vec::with_capacity(prefix.len() + 1);
elems.extend(prefix.into_iter().map(|(_, v)| v));
elems.push(last);
AlgebraicValue::product(elems)
}
}
fn combine_probe_prefix_and_last(prefix: &[AlgebraicValue], last: AlgebraicValue) -> AlgebraicValue {
if prefix.is_empty() {
last
} else {
AlgebraicValue::product(ProductValue::from_iter(
prefix.iter().cloned().chain(std::iter::once(last)),
))
}
}
impl PipelinedIxScanEq {
/// We don't know statically if an index scan will return rows
pub fn is_empty(&self, _: &impl DeltaStore) -> bool {
false
}
pub fn execute<'a, Tx: Datastore + DeltaStore>(
&self,
tx: &'a Tx,
metrics: &mut ExecutionMetrics,
f: &mut dyn FnMut(Tuple<'a>) -> Result<()>,
) -> Result<()> {
// Scan without a row limit.
let scan = || tx.index_scan_point(self.table_id, self.index_id, &self.point);
// Scan with an optional row limit.
let scan_opt_limit = |limit| match limit {
None => scan().map(Either::Left),
Some(n) => scan().map(|iter| iter.take(n)).map(Either::Right),
};
let mut n = 0;
let mut f = |t| {
n += 1;
f(t)
};
for ptr in scan_opt_limit(self.limit.map(|n| n as usize))?
.map(Row::Ptr)
.map(Tuple::Row)
{
f(ptr)?;
}
metrics.index_seeks += 1;
metrics.rows_scanned += n;
Ok(())
}
}
/// A pipelined index join executor
#[derive(Debug)]
pub struct PipelinedIxJoin {
/// The executor for the lhs of the join
pub lhs: Box<PipelinedExecutor>,
/// The rhs table
pub rhs_table: TableId,
/// The rhs index
pub rhs_index: IndexId,
/// Constant prefix values for multi-column index probes.
pub rhs_prefix: Vec<AlgebraicValue>,
/// The rhs join field
pub rhs_field: ColId,
/// The lhs join field
pub lhs_field: TupleField,
/// Is the index unique?
pub unique: bool,
/// Is this a semijoin?
pub semijoin: Semi,
}
impl PipelinedIxJoin {
/// Does this operation contain an empty delta scan?
pub fn is_empty(&self, tx: &impl DeltaStore) -> bool {