forked from timescale/timescaledb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqual_pushdown.c
More file actions
1797 lines (1603 loc) · 50.8 KB
/
Copy pathqual_pushdown.c
File metadata and controls
1797 lines (1603 loc) · 50.8 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
/* * This file and its contents are licensed under the Timescale License.
* Please see the included NOTICE for copyright information and
* LICENSE-TIMESCALE for a copy of the license.
*/
#include <postgres.h>
#include <nodes/makefuncs.h>
#include <nodes/nodeFuncs.h>
#include <optimizer/optimizer.h>
#include <optimizer/restrictinfo.h>
#include <parser/parse_func.h>
#include <parser/parsetree.h>
#include <utils/builtins.h>
#include <utils/typcache.h>
#include "columnar_scan.h"
#include "compression/batch_metadata_builder.h"
#include "compression/create.h"
#include "compression/sparse_index_bloom1.h"
#include "custom_type_cache.h"
#include "guc.h"
#include "ts_catalog/array_utils.h"
#include "utils.h"
#include "qual_pushdown.h"
typedef struct QualPushdownContext
{
PlannerInfo *root;
RelOptInfo *chunk_rel;
RelOptInfo *compressed_rel;
RangeTblEntry *chunk_rte;
RangeTblEntry *compressed_rte;
CompressionSettings *settings;
/*
* This is actually the result, not the static input context like above, but
* there's no way to separate this properly using the expression tree mutator
* interface.
*/
bool can_pushdown;
bool needs_recheck;
} QualPushdownContext;
static QualPushdownContext
copy_context(const QualPushdownContext *source)
{
QualPushdownContext copy;
copy = *source;
copy.can_pushdown = true;
copy.needs_recheck = false;
return copy;
}
static Node *qual_pushdown_mutator(Node *node, QualPushdownContext *context);
/*
* Result of validating an OpExpr as a potential bloom filter candidate.
* Does NOT make decisions about which operand to use.
*/
typedef struct HashableEqualityInfo
{
Var *left_var; /* NULL if left is not a Var on chunk_rel */
Var *right_var; /* NULL if right is not a Var on chunk_rel */
Expr *left_expr; /* Original left operand (after unwrapping RelabelType) */
Expr *right_expr; /* Original right operand (after unwrapping RelabelType) */
Oid opno; /* Original operator OID */
bool left_hashable; /* Is operator in left_var's hash opfamily? */
bool right_hashable; /* Is operator in right_var's hash opfamily? */
bool valid; /* Is this a valid hashable equality? */
} HashableEqualityInfo;
static HashableEqualityInfo validate_hashable_equality(OpExpr *opexpr,
QualPushdownContext *context);
static Var *extract_var_for_bloom1(OpExpr *opexpr, QualPushdownContext *context, Expr **value_out,
Oid *op_oid_out);
static Var *extract_var_for_composite_bloom(OpExpr *opexpr, QualPushdownContext *context,
Expr **value_out, Oid *op_oid_out);
static void pushdown_composite_blooms(PlannerInfo *root, QualPushdownContext *context);
static Node *make_bloom1_hash_array(PlannerInfo *root, List *exprs, Oid input_collation);
static FuncExpr *make_bloom1_check(Var *bloom_var, Node *hash_array);
static List *deconstruct_array_const(Const *array_const);
bool
columnar_scan_filter_pushdown(PlannerInfo *root, CompressionSettings *settings,
RelOptInfo *chunk_rel, RelOptInfo *compressed_rel, bool chunk_partial)
{
ListCell *lc;
List *decompress_clauses = NIL;
bool all_pushed_down = true;
QualPushdownContext base_context = {
.root = root,
.chunk_rel = chunk_rel,
.compressed_rel = compressed_rel,
.chunk_rte = planner_rt_fetch(chunk_rel->relid, root),
.compressed_rte = planner_rt_fetch(compressed_rel->relid, root),
.settings = settings,
};
/*
* Collect composite bloom candidates first.
* This looks at ALL equality predicates together to find composite bloom matches
* and push down the composite bloom filters.
*/
if (ts_guc_enable_sparse_index_bloom && settings != NULL && settings->fd.index != NULL &&
ts_guc_enable_composite_bloom_indexes)
{
pushdown_composite_blooms(root, &base_context);
}
foreach (lc, chunk_rel->baserestrictinfo)
{
RestrictInfo *ri = lfirst(lc);
QualPushdownContext clause_context = copy_context(&base_context);
Node *pushed_down = qual_pushdown_mutator((Node *) ri->clause, &clause_context);
if (clause_context.can_pushdown)
{
/*
* We have to call eval_const_expressions after pushing down
* the quals, to normalize the bool expressions. Namely, we might add an
* AND boolexpr on minmax metadata columns, but the normal form is not
* allowed to have nested AND boolexprs. They break some functions like
* generate_bitmap_or_paths().
*/
pushed_down = eval_const_expressions(root, pushed_down);
if (IsA(pushed_down, BoolExpr) && castNode(BoolExpr, pushed_down)->boolop == AND_EXPR)
{
/* have to separate out and expr into different restrict infos */
ListCell *lc_and;
BoolExpr *bool_expr = castNode(BoolExpr, pushed_down);
foreach (lc_and, bool_expr->args)
{
compressed_rel->baserestrictinfo =
lappend(compressed_rel->baserestrictinfo,
make_simple_restrictinfo(root, lfirst(lc_and)));
}
}
else
{
compressed_rel->baserestrictinfo =
lappend(compressed_rel->baserestrictinfo,
make_simple_restrictinfo(root, (Expr *) pushed_down));
}
}
/*
* We need to check the restriction clause on the decompress node if the clause can't be
* pushed down or needs re-checking.
*/
if (!clause_context.can_pushdown || clause_context.needs_recheck || chunk_partial)
{
decompress_clauses = lappend(decompress_clauses, ri);
}
if (!clause_context.can_pushdown || clause_context.needs_recheck)
{
all_pushed_down = false;
}
}
chunk_rel->baserestrictinfo = decompress_clauses;
return all_pushed_down;
}
static OpExpr *
make_segment_meta_opexpr(QualPushdownContext *context, Oid opno, AttrNumber meta_column_attno,
Var *uncompressed_var, Expr *compare_to_expr, StrategyNumber strategy)
{
Var *meta_var = makeVar(context->compressed_rel->relid,
meta_column_attno,
uncompressed_var->vartype,
-1,
InvalidOid,
0);
return (OpExpr *) make_opclause(opno,
BOOLOID,
false,
(Expr *) meta_var,
copyObject(compare_to_expr),
InvalidOid,
uncompressed_var->varcollid);
}
/*
* Locate the lower/upper boundary metadata columns for a Var on the chunk.
* Returns InvalidAttrNumber via the out params when the expression is not a
* sound pushdown target.
*
* For the leading orderby column under a firstlast-shaped compressed chunk
* index, we prefer the first/last metadata when the column is NOT NULL:
* those columns are part of the compressed chunk btree index, so the
* pushed-down predicate can become an index condition. Every other case
* (nullable leading orderby, secondary orderbys, non-orderby columns
* with an explicit minmax sparse index, and any orderby on a legacy
* minmax-shaped compressed chunk index) falls back to minmax, which
* is always available for orderby columns.
*/
static void
expr_fetch_orderby_range_metadata(QualPushdownContext *context, Expr *expr, AttrNumber *lower_attno,
AttrNumber *upper_attno)
{
*lower_attno = InvalidAttrNumber;
*upper_attno = InvalidAttrNumber;
if (!IsA(expr, Var))
{
return;
}
Var *var = castNode(Var, expr);
/*
* Not on the chunk we expect. This doesn't really happen because we don't
* push down the join quals, only the baserestrictinfo.
*/
if ((Index) var->varno != context->chunk_rel->relid)
{
return;
}
/* ignore system attributes or whole row references */
if (var->varattno <= 0)
{
return;
}
char *attname = get_attname(context->chunk_rte->relid, var->varattno, true);
if (attname == NULL)
{
return;
}
if (ts_array_is_member(context->settings->fd.orderby, attname))
{
int orderby_pos = ts_array_position(context->settings->fd.orderby, attname);
if (orderby_sparse_kind(context->settings, orderby_pos) == ORDERBY_SPARSE_FIRSTLAST &&
orderby_pos == 1 && ts_get_attnotnull(context->chunk_rte->relid, var->varattno))
{
orderby_sparse_metadata_attnos(context->settings,
context->compressed_rte->relid,
orderby_pos,
lower_attno,
upper_attno);
return;
}
/* Fall through to minmax (always available for orderby columns). */
}
*lower_attno = compressed_column_metadata_attno(context->settings,
context->chunk_rte->relid,
var->varattno,
context->compressed_rte->relid,
"min");
*upper_attno = compressed_column_metadata_attno(context->settings,
context->chunk_rte->relid,
var->varattno,
context->compressed_rte->relid,
"max");
}
static void *
pushdown_op_to_orderby_range_metadata(QualPushdownContext *context, OpExpr *orig_opexpr)
{
/*
* This always requires rechecking the decompressed data.
*/
context->needs_recheck = true;
List *expr_args = orig_opexpr->args;
Assert(list_length(expr_args) == 2);
Expr *orig_leftop = linitial(expr_args);
Expr *orig_rightop = lsecond(expr_args);
if (IsA(orig_leftop, RelabelType))
{
orig_leftop = ((RelabelType *) orig_leftop)->arg;
}
if (IsA(orig_rightop, RelabelType))
{
orig_rightop = ((RelabelType *) orig_rightop)->arg;
}
/* Find the side that has var with segment meta set expr to the other side */
Oid op_oid = orig_opexpr->opno;
AttrNumber lower_attno;
AttrNumber upper_attno;
expr_fetch_orderby_range_metadata(context, orig_leftop, &lower_attno, &upper_attno);
if (lower_attno == InvalidAttrNumber || upper_attno == InvalidAttrNumber)
{
/* No metadata for the left operand, try to commute the operator. */
op_oid = get_commutator(op_oid);
Expr *tmp = orig_leftop;
orig_leftop = orig_rightop;
orig_rightop = tmp;
expr_fetch_orderby_range_metadata(context, orig_leftop, &lower_attno, &upper_attno);
}
if (lower_attno == InvalidAttrNumber || upper_attno == InvalidAttrNumber)
{
/* No metadata for either operand. */
context->can_pushdown = false;
return orig_opexpr;
}
Var *var_with_segment_meta = castNode(Var, orig_leftop);
/* May be able to allow non-strict operations as well.
* Next steps: Think through edge cases, either allow and write tests or figure out why we must
* block strict operations
*/
if (!OidIsValid(op_oid) || !op_strict(op_oid))
{
context->can_pushdown = false;
return orig_opexpr;
}
/* If the collation to be used by the OP doesn't match the column's collation do not push down
* as the materialized min/max value do not match the semantics of what we need here */
Oid op_collation = orig_opexpr->inputcollid;
if (var_with_segment_meta->varcollid != op_collation)
{
context->can_pushdown = false;
return orig_opexpr;
}
TypeCacheEntry *tce =
lookup_type_cache(var_with_segment_meta->vartype, TYPECACHE_BTREE_OPFAMILY);
const int strategy = get_op_opfamily_strategy(op_oid, tce->btree_opf);
if (strategy == InvalidStrategy)
{
context->can_pushdown = false;
return orig_opexpr;
}
/*
* Check if the righthand expression is safe to push down. We cannot combine
* it with the original operator if there can be false negatives.
*/
QualPushdownContext tmp_context = copy_context(context);
Expr *pushed_down_rightop = (Expr *) qual_pushdown_mutator((Node *) orig_rightop, &tmp_context);
if (!tmp_context.can_pushdown || tmp_context.needs_recheck)
{
context->can_pushdown = false;
return orig_opexpr;
}
Assert(pushed_down_rightop != NULL);
const Oid expr_type_id = exprType((Node *) pushed_down_rightop);
switch (strategy)
{
case BTEqualStrategyNumber:
{
/* var = expr implies lower <= expr and upper >= expr */
Oid opno_le = get_opfamily_member(tce->btree_opf,
tce->type_id,
expr_type_id,
BTLessEqualStrategyNumber);
Oid opno_ge = get_opfamily_member(tce->btree_opf,
tce->type_id,
expr_type_id,
BTGreaterEqualStrategyNumber);
if (!OidIsValid(opno_le) || !OidIsValid(opno_ge))
{
/*
* Shouldn't be possible if we managed to create the sparse
* index, but defend against catalog corruption.
*/
context->can_pushdown = false;
return orig_opexpr;
}
return make_andclause(
list_make2(make_segment_meta_opexpr(context,
opno_le,
lower_attno,
var_with_segment_meta,
pushed_down_rightop,
BTLessEqualStrategyNumber),
make_segment_meta_opexpr(context,
opno_ge,
upper_attno,
var_with_segment_meta,
pushed_down_rightop,
BTGreaterEqualStrategyNumber)));
}
case BTLessStrategyNumber:
case BTLessEqualStrategyNumber:
/* var < expr implies lower < expr */
{
Oid opno =
get_opfamily_member(tce->btree_opf, tce->type_id, expr_type_id, strategy);
if (!OidIsValid(opno))
{
/*
* Shouldn't be possible if we managed to create the
* sparse index, but defend against catalog corruption.
*/
context->can_pushdown = false;
return orig_opexpr;
}
return (Expr *) make_segment_meta_opexpr(context,
opno,
lower_attno,
var_with_segment_meta,
pushed_down_rightop,
strategy);
}
case BTGreaterStrategyNumber:
case BTGreaterEqualStrategyNumber:
/* var > expr implies upper > expr */
{
Oid opno =
get_opfamily_member(tce->btree_opf, tce->type_id, expr_type_id, strategy);
if (!OidIsValid(opno))
{
/*
* Shouldn't be possible if we managed to create the
* sparse index, but defend against catalog corruption.
*/
context->can_pushdown = false;
return orig_opexpr;
}
return (Expr *) make_segment_meta_opexpr(context,
opno,
upper_attno,
var_with_segment_meta,
pushed_down_rightop,
strategy);
}
default:
context->can_pushdown = false;
return orig_opexpr;
}
}
static void
expr_fetch_bloom1_metadata(QualPushdownContext *context, Expr *expr, AttrNumber *bloom1_attno)
{
*bloom1_attno = InvalidAttrNumber;
if (!IsA(expr, Var))
{
return;
}
Var *var = castNode(Var, expr);
/*
* Not on the chunk we expect. This doesn't really happen because we don't
* push down the join quals, only the baserestrictinfo.
*/
if ((Index) var->varno != context->chunk_rel->relid)
{
return;
}
/* ignore system attributes or whole row references */
if (var->varattno <= 0)
{
return;
}
*bloom1_attno = compressed_column_metadata_attno(context->settings,
context->chunk_rte->relid,
var->varattno,
context->compressed_rte->relid,
bloom1_column_prefix);
if (*bloom1_attno == InvalidAttrNumber && ts_guc_read_legacy_bloom1_v1)
{
/*
* The version 1 of bloom1 indexes is disabled by default because its
* hashing was dependent on build options leading to corrupt indexes,
* but can be enabled manually.
*/
*bloom1_attno = compressed_column_metadata_attno(context->settings,
context->chunk_rte->relid,
var->varattno,
context->compressed_rte->relid,
"bloom1");
}
}
/*
* Validate an OpExpr as a hashable equality predicate.
*
* Does NOT:
* - Decide which operand is "column" vs "value"
* - Check bloom metadata
* - Check collation (Caller's responsibility - depends on which Var is chosen)
* - Commute the operator
*
* DOES validate:
* - OpExpr structure
* - Var identification on chunk_rel
* - Hash operator validity for each Var
*
* Returns info about both operands with validation flags.
* Caller decides which Var to use and validates collation.
*/
static HashableEqualityInfo
validate_hashable_equality(OpExpr *opexpr, QualPushdownContext *context)
{
Assert(opexpr != NULL);
Assert(context != NULL);
HashableEqualityInfo info = { 0 };
info.valid = false;
info.left_hashable = false;
info.right_hashable = false;
if (list_length(opexpr->args) != 2)
{
return info;
}
Expr *left = linitial(opexpr->args);
Expr *right = lsecond(opexpr->args);
/* Unwrap RelabelType */
if (IsA(left, RelabelType))
{
left = ((RelabelType *) left)->arg;
}
if (IsA(right, RelabelType))
{
right = ((RelabelType *) right)->arg;
}
info.left_expr = left;
info.right_expr = right;
info.opno = opexpr->opno;
/* Must have valid operator OID */
if (!OidIsValid(info.opno))
{
return info;
}
/* Identify Vars on our relation and validate hash operator for each */
if (IsA(left, Var))
{
Var *left_var = (Var *) left;
if ((Index) left_var->varno == context->chunk_rel->relid && left_var->varattno > 0)
{
info.left_var = left_var;
/* Check if operator is hashable equality for this type */
TypeCacheEntry *tce = lookup_type_cache(left_var->vartype, TYPECACHE_HASH_OPFAMILY);
if (OidIsValid(tce->hash_opf))
{
int strategy = get_op_opfamily_strategy(info.opno, tce->hash_opf);
if (strategy == HTEqualStrategyNumber)
{
info.left_hashable = true;
}
}
}
}
if (IsA(right, Var))
{
Var *right_var = (Var *) right;
if ((Index) right_var->varno == context->chunk_rel->relid && right_var->varattno > 0)
{
info.right_var = right_var;
/* Check if operator is hashable equality for this type */
TypeCacheEntry *tce = lookup_type_cache(right_var->vartype, TYPECACHE_HASH_OPFAMILY);
if (OidIsValid(tce->hash_opf))
{
int strategy = get_op_opfamily_strategy(info.opno, tce->hash_opf);
if (strategy == HTEqualStrategyNumber)
{
info.right_hashable = true;
}
}
}
}
/* Must have at least one Var on our relation */
if (info.left_var == NULL && info.right_var == NULL)
{
return info;
}
/* Must have at least one Var that passes hashable equality check */
if (!info.left_hashable && !info.right_hashable)
{
return info;
}
info.valid = true;
return info;
}
/*
* Extract Var for single-column bloom filter pushdown.
* Uses bloom metadata presence to decide which operand to use.
*
* This handles cases like:
* - bloom_col = 5 (left has bloom)
* - 5 = bloom_col (right has bloom, commute)
* - bloom_col = segmentby_col (left has bloom, caller validates segmentby)
* - segmentby_col = bloom_col (right has bloom, commute, caller validates)
* - bloom_col1 = bloom_col2 (left has bloom, caller validates bloom_col2: FAILS)
*
* Returns the Var that has single-column bloom metadata, along with
* the value expression and (possibly commuted) operator.
*/
static Var *
extract_var_for_bloom1(OpExpr *opexpr, QualPushdownContext *context, Expr **value_out,
Oid *op_oid_out)
{
Assert(value_out != NULL);
Assert(op_oid_out != NULL);
Assert(opexpr != NULL);
Assert(context != NULL);
*value_out = NULL;
*op_oid_out = InvalidOid;
/* Validate the expression */
HashableEqualityInfo info = validate_hashable_equality(opexpr, context);
if (!info.valid)
{
return NULL;
}
/* Try to find a Var with bloom metadata that passes hash operator validation. */
Var *chosen_var = NULL;
Expr *value_expr_tmp = NULL;
Oid op_oid_tmp;
AttrNumber bloom1_attno = InvalidAttrNumber;
if (info.left_var != NULL && info.left_hashable)
{
expr_fetch_bloom1_metadata(context, (Expr *) info.left_var, &bloom1_attno);
if (bloom1_attno != InvalidAttrNumber)
{
/* Left has bloom metadata and valid hash operator. */
chosen_var = info.left_var;
value_expr_tmp = info.right_expr;
op_oid_tmp = info.opno;
}
}
/* If left didn't qualify, try right. */
if (chosen_var == NULL && info.right_var != NULL && info.right_hashable)
{
expr_fetch_bloom1_metadata(context, (Expr *) info.right_var, &bloom1_attno);
if (bloom1_attno != InvalidAttrNumber)
{
/* Right has bloom metadata and valid hash operator. Need commutation. */
chosen_var = info.right_var;
value_expr_tmp = info.left_expr;
op_oid_tmp = get_commutator(info.opno);
}
}
if (chosen_var == NULL)
{
/* No Var with both bloom metadata and valid hash operator */
return NULL;
}
/* Validate collation for the chosen Var */
Oid op_collation = opexpr->inputcollid;
if (chosen_var->varcollid != op_collation)
{
/* Collation mismatch - bloom filter hash won't match operator hash */
return NULL;
}
/* Cannot use non-deterministic collations */
if (OidIsValid(op_collation) && !get_collation_isdeterministic(op_collation))
{
return NULL;
}
*value_out = value_expr_tmp;
*op_oid_out = op_oid_tmp;
return chosen_var;
}
static Node *
make_bloom1_hash_array(PlannerInfo *root, List *exprs, Oid input_collation)
{
static Oid bloom1_hash_oid = InvalidOid;
if (!OidIsValid(bloom1_hash_oid))
{
bloom1_hash_oid = LookupFuncName(list_make2(makeString("_timescaledb_functions"),
makeString("bloom1_hash")),
-1,
(void *) -1,
false);
}
List *hash_elements = NIL;
ListCell *lc;
foreach (lc, exprs)
{
FuncExpr *h = makeFuncExpr(bloom1_hash_oid,
INT8OID,
list_make1(lfirst(lc)),
/* funccollid = */ InvalidOid,
/* inputcollid = */ input_collation,
COERCE_EXPLICIT_CALL);
hash_elements = lappend(hash_elements, h);
}
ArrayExpr *hash_array = makeNode(ArrayExpr);
hash_array->array_typeid = INT8ARRAYOID;
hash_array->element_typeid = INT8OID;
hash_array->elements = hash_elements;
hash_array->multidims = false;
hash_array->location = -1;
return estimate_expression_value(root, (Node *) hash_array);
}
static FuncExpr *
make_bloom1_check(Var *bloom_var, Node *hash_array)
{
static Oid func_oid = InvalidOid;
if (!OidIsValid(func_oid))
{
func_oid = LookupFuncName(list_make2(makeString("_timescaledb_functions"),
makeString("bloom1_contains_any_hashes")),
/* nargs = */ -1,
/* argtypes = */ (void *) -1,
/* missing_ok = */ false);
}
return makeFuncExpr(func_oid,
BOOLOID,
list_make2(bloom_var, hash_array),
/* funccollid = */ InvalidOid,
/* inputcollid = */ InvalidOid,
COERCE_EXPLICIT_CALL);
}
static void *
pushdown_op_to_segment_meta_bloom1(QualPushdownContext *context, OpExpr *orig_opexpr)
{
/*
* This always requires rechecking the decompressed data.
*/
context->needs_recheck = true;
/*
* Use single-column bloom helper to find Var with bloom metadata.
* Helper returns first Var with bloom metadata.
*/
Expr *orig_rightop = NULL;
Oid op_oid;
Var *var = extract_var_for_bloom1(orig_opexpr, context, &orig_rightop, &op_oid);
if (var == NULL)
{
context->can_pushdown = false;
return orig_opexpr;
}
/* Get bloom metadata. */
AttrNumber bloom1_attno = InvalidAttrNumber;
expr_fetch_bloom1_metadata(context, (Expr *) var, &bloom1_attno);
Assert(bloom1_attno != InvalidAttrNumber);
/*
* The hash equality operators are supposed to be strict.
*/
Assert(op_strict(op_oid));
/*
* Check if the righthand expression is safe to push down. We cannot combine
* it with the original operator if there can be false negatives.
*/
QualPushdownContext tmp_context = copy_context(context);
Expr *pushed_down_rightop = (Expr *) qual_pushdown_mutator((Node *) orig_rightop, &tmp_context);
if (!tmp_context.can_pushdown || tmp_context.needs_recheck)
{
context->can_pushdown = false;
return orig_opexpr;
}
Assert(pushed_down_rightop != NULL);
/*
* We can have cross-type equality operator, but in this case the our hashes
* or Postgres hashes for the respective types are guaranteed to have the
* same result for both types, so we don't need any type conversion here.
* The only special case is composite types. The right-hand constant would
* have the anonymous type "record" and would be compared polymorphically
* at runtime with the record_eq() function. However, this type doesn't have
* an extended hash function. Just refuse to work with it.
*/
const Oid compared_type = exprType((Node *) pushed_down_rightop);
if (compared_type == RECORDOID)
{
context->can_pushdown = false;
return orig_opexpr;
}
/*
* var = expr implies bloom1_contains(var_bloom, expr).
*/
Var *bloom_var = makeVar(context->compressed_rel->relid,
bloom1_attno,
ts_custom_type_cache_get(CUSTOM_TYPE_BLOOM1)->type_oid,
-1,
InvalidOid,
0);
Node *hash_array = make_bloom1_hash_array(context->root,
list_make1(pushed_down_rightop),
orig_opexpr->inputcollid);
return (Expr *) make_bloom1_check(bloom_var, hash_array);
}
/*
* Try to transform x = any(array[]) into bloom1_contains_any(bloom_x, array[]).
*/
static void *
pushdown_saop_bloom1(QualPushdownContext *context, ScalarArrayOpExpr *orig_saop)
{
/*
* This always requires rechecking the decompressed data.
*/
context->needs_recheck = true;
if (!orig_saop->useOr)
{
context->can_pushdown = false;
return orig_saop;
}
List *expr_args = orig_saop->args;
Assert(list_length(expr_args) == 2);
Expr *orig_leftop = linitial(expr_args);
Expr *orig_rightop = lsecond(expr_args);
if (IsA(orig_leftop, RelabelType))
{
orig_leftop = ((RelabelType *) orig_leftop)->arg;
}
if (IsA(orig_rightop, RelabelType))
{
orig_rightop = ((RelabelType *) orig_rightop)->arg;
}
/*
* For scalar array operation, we expect a var on the left side.
*/
AttrNumber bloom1_attno = InvalidAttrNumber;
expr_fetch_bloom1_metadata(context, orig_leftop, &bloom1_attno);
if (bloom1_attno == InvalidAttrNumber)
{
/* No metadata for left operand. */
context->can_pushdown = false;
return orig_saop;
}
Var *var_with_segment_meta = castNode(Var, orig_leftop);
/*
* Play it safe and don't push down if the operator collation doesn't match
* the column collation.
*/
Oid op_collation = orig_saop->inputcollid;
if (var_with_segment_meta->varcollid != op_collation)
{
context->can_pushdown = false;
return orig_saop;
}
/*
* We cannot use bloom filters for non-deterministic collations.
*/
if (OidIsValid(op_collation) && !get_collation_isdeterministic(op_collation))
{
context->can_pushdown = false;
return orig_saop;
}
/*
* We only support hashable equality operators.
*/
const Oid op_oid = orig_saop->opno;
TypeCacheEntry *tce =
lookup_type_cache(var_with_segment_meta->vartype, TYPECACHE_HASH_OPFAMILY);
const int strategy = get_op_opfamily_strategy(op_oid, tce->hash_opf);
if (strategy != HTEqualStrategyNumber)
{
context->can_pushdown = false;
return orig_saop;
}
/*
* The hash equality operators are supposed to be strict.
*/
Assert(op_strict(op_oid));
/*
* Check if the righthand expression is safe to push down. We cannot combine
* it with the original operator if there can be false negatives.
*/
QualPushdownContext tmp_context = copy_context(context);
Expr *pushed_down_rightop = (Expr *) qual_pushdown_mutator((Node *) orig_rightop, &tmp_context);
if (!tmp_context.can_pushdown || tmp_context.needs_recheck)
{
context->can_pushdown = false;
return orig_saop;
}
Assert(pushed_down_rightop != NULL);
/*
* var = any(array) implies bloom1_contains_any(var_bloom, array).
*/
Var *bloom_var = makeVar(context->compressed_rel->relid,
bloom1_attno,
ts_custom_type_cache_get(CUSTOM_TYPE_BLOOM1)->type_oid,
-1,
InvalidOid,
0);
if ((IsA(pushed_down_rightop, Const) && !castNode(Const, pushed_down_rightop)->constisnull) ||
IsA(pushed_down_rightop, ArrayExpr))
{
List *elements;
if (IsA(pushed_down_rightop, Const))
{
elements = deconstruct_array_const(castNode(Const, pushed_down_rightop));
}
else
{
elements = castNode(ArrayExpr, pushed_down_rightop)->elements;
}
Node *hash_array = make_bloom1_hash_array(context->root, elements, orig_saop->inputcollid);
return (Expr *) make_bloom1_check(bloom_var, hash_array);
}
/* Fallback: non-deconstructable array: bloom1_contains_any */
Oid func = LookupFuncName(list_make2(makeString("_timescaledb_functions"),
makeString("bloom1_contains_any")),
/* nargs = */ -1,
/* argtypes = */ (void *) -1,
/* missing_ok = */ false);
return makeFuncExpr(func,
BOOLOID,
list_make2(bloom_var, pushed_down_rightop),
/* funccollid = */ InvalidOid,
/* inputcollid = */ InvalidOid,
COERCE_EXPLICIT_CALL);
}
/*
* Extract Var for composite bloom filter pushdown.
* Uses segmentby membership as a heuristic for Var-to-Var cases.
* Does NOT check bloom metadata (composite bloom is checked later by name matching).
*
* This handles cases like:
* - col = 5 (obvious)
* - 5 = col (commute)
* - col = segmentby_col (prefer non-segmentby col)
* - col1 = col2 (prefer non-segmentby, but caller validates value)
*
* IMPORTANT: For col1 = col2 where both are non-segmentby, returns col1 but
* the caller (pushdown_composite_blooms) will reject col2 during value validation.
* Composite bloom requires value expressions to be constants, params, or segmentby Vars.
*
* Returns a Var along with the value expression and (possibly commuted) operator.
*/
static Var *
extract_var_for_composite_bloom(OpExpr *opexpr, QualPushdownContext *context, Expr **value_out,
Oid *op_oid_out)
{
Assert(opexpr != NULL);
Assert(context != NULL);
Assert(value_out != NULL);
Assert(op_oid_out != NULL);
*value_out = NULL;