forked from timescale/timescaledb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplanner.c
More file actions
1460 lines (1304 loc) · 43.4 KB
/
Copy pathplanner.c
File metadata and controls
1460 lines (1304 loc) · 43.4 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 <access/sysattr.h>
#include <nodes/extensible.h>
#include <nodes/makefuncs.h>
#include <nodes/nodeFuncs.h>
#include <nodes/pathnodes.h>
#include <optimizer/clauses.h>
#include <optimizer/cost.h>
#include <optimizer/optimizer.h>
#include <optimizer/pathnode.h>
#include <optimizer/paths.h>
#include <optimizer/planmain.h>
#include <optimizer/prep.h>
#include <optimizer/restrictinfo.h>
#include <optimizer/tlist.h>
#include <parser/parse_coerce.h>
#include <parser/parsetree.h>
#include <rewrite/rewriteManip.h>
#include <utils/syscache.h>
#include <utils/typcache.h>
#include "compat/compat.h"
#include "guc.h"
#include "nodes/chunk_append/chunk_append.h"
#include "nodes/columnar_scan/columnar_scan.h"
#include "nodes/constraint_aware_append/constraint_aware_append.h"
#include "nodes/skip_scan/skip_scan.h"
#include "utils.h"
#include <import/planner.h>
#include <math.h>
typedef struct SkipKeyInfo
{
/* Index clause which we'll use to skip past elements we've already seen */
RestrictInfo *skip_clause;
/* Is this key guaranteed to be not null? */
bool notnull;
/* attribute number of the distinct column on the table/chunk which provides comparison value
* for Skip qual */
AttrNumber distinct_attno;
/* attribute number of the Skip qual comparison column on the indexed table/chunk
* "indexed_column_attno = distinct_attno" for (SkipScan <- Index Scan) scenario,
* it can be different for (SkipScan <- ColumnarScan <- compressed Index Scan) scenario,
* in that case "indexed_column_attno" is the attribute number of the compressed chunk column
* corresponding to the distinct column "distinct_attno" on the decompressed chunk consumed by
* SkipScan
*/
AttrNumber indexed_column_attno;
/* The column offset on the index we are calling DISTINCT on */
AttrNumber scankey_attno;
int distinct_typ_len;
bool distinct_by_val;
/* InvalidOid for the last skip key, always invalid for one-key SkipScan
* For N-key SkipScan default quals are (sk1 = p1), (sk2 = p2), .. (sk_n > p_n),
* we'll switch to (sk_i > p_i) when no more values for (sk_i+1 > p_i+1),
* so we will store "=" along with ">" comparator for keys 1..N-1.
*/
Oid eqcomp;
} SkipKeyInfo;
typedef struct SkipScanPath
{
CustomPath cpath;
IndexPath *index_path;
/* List of skip column attributes for each skip key */
List *skipkeyinfo;
/* Vars referencing the distinct columns on the relation */
List *dvars;
} SkipScanPath;
typedef struct DistinctPathInfo
{
UpperRelationKind stage; /* What kind of Upper distinct path we are dealing with */
Path *unique_path; /* If not NULL, valid Upper distinct path */
List *
distinct_expr; /* If not NULL, list of valid distinct expressions for Upper distinct path */
} DistinctPathInfo;
static int get_idx_key(IndexOptInfo *idxinfo, AttrNumber attno);
static List *sort_indexquals(IndexOptInfo *indexinfo, List *quals);
static OpExpr *fix_indexqual(IndexOptInfo *index, RestrictInfo *rinfo, AttrNumber scankey_attno);
static bool build_skip_qual(PlannerInfo *root, SkipKeyInfo *skinfo, IndexPath *index_path, Var *var,
bool build_eqop);
static List *build_subpath(PlannerInfo *root, List *subpaths, DistinctPathInfo *dpinfo,
List *top_pathkeys);
static Var *get_distinct_var(PlannerInfo *root, Expr *tlexpr, IndexPath *index_path,
Path *child_path, SkipKeyInfo *skinfo);
static TargetEntry *tlist_member_match_var(Var *var, List *targetlist);
/**************************
* SkipScan Plan Creation *
**************************/
static CustomScanMethods skip_scan_plan_methods = {
.CustomName = "SkipScan",
.CreateCustomScanState = tsl_skip_scan_state_create,
};
void
_skip_scan_init(void)
{
TryRegisterCustomScanMethods(&skip_scan_plan_methods);
}
static Plan *
setup_index_plan(CustomScan *skip_plan, Plan *child_plan)
{
Plan *plan = child_plan;
if (IsA(child_plan, IndexScan))
{
skip_plan->scan = castNode(IndexScan, child_plan)->scan;
}
else if (IsA(child_plan, IndexOnlyScan))
{
skip_plan->scan = castNode(IndexOnlyScan, child_plan)->scan;
}
else if (ts_is_columnar_scan_plan(child_plan))
{
CustomScan *csplan = castNode(CustomScan, plan);
skip_plan->scan = csplan->scan;
plan = linitial(csplan->custom_plans);
}
else
{
elog(ERROR,
"unsupported subplan type for SkipScan: %s",
ts_get_node_name((Node *) child_plan));
}
return plan;
}
static Plan *
skip_scan_plan_create(PlannerInfo *root, RelOptInfo *relopt, CustomPath *best_path, List *tlist,
List *clauses, List *custom_plans)
{
SkipScanPath *path = (SkipScanPath *) best_path;
CustomScan *skip_plan = makeNode(CustomScan);
IndexPath *index_path = path->index_path;
Plan *child_plan = linitial(custom_plans);
Plan *plan = setup_index_plan(skip_plan, child_plan);
skip_plan->scan.plan.targetlist = tlist;
skip_plan->custom_scan_tlist = list_copy(tlist);
skip_plan->scan.plan.qual = NIL;
skip_plan->scan.plan.type = T_CustomScan;
skip_plan->methods = &skip_scan_plan_methods;
skip_plan->custom_plans = custom_plans;
/* Setup for SkipScan debug info */
StringInfoData debuginfo;
RangeTblEntry *indexed_rte = NULL;
char *sep = "";
if (ts_guc_debug_skip_scan_info)
{
initStringInfo(&debuginfo);
RelOptInfo *indexed_rel = index_path->path.parent;
indexed_rte = planner_rt_fetch(indexed_rel->relid, root);
Oid indrelid = InvalidOid;
if (IsA(plan, IndexScan))
{
IndexScan *idx_plan = castNode(IndexScan, plan);
indrelid = idx_plan->indexid;
}
else if (IsA(plan, IndexOnlyScan))
{
IndexOnlyScan *idx_plan = castNode(IndexOnlyScan, plan);
indrelid = idx_plan->indexid;
}
appendStringInfo(&debuginfo, "SkipScan used on %s(", get_rel_name(indrelid));
}
ListCell *lc, *lv;
/* List of N-1 equality op Oids for N-key skipscan, stays NIL for one-key skipscan */
List *eqcomps = NIL;
/* List of N skipkeyinfo Int lists for N-key skipscan */
List *skinfos = NIL;
forboth (lc, path->skipkeyinfo, lv, path->dvars)
{
SkipKeyInfo *skinfo = (SkipKeyInfo *) lfirst(lc);
Var *dvar = castNode(Var, lfirst(lv));
OpExpr *op =
fix_indexqual(index_path->indexinfo, skinfo->skip_clause, skinfo->scankey_attno);
if (OidIsValid(skinfo->eqcomp))
{
eqcomps = lappend_oid(eqcomps, skinfo->eqcomp);
}
if (IsA(plan, IndexScan))
{
IndexScan *idx_plan = castNode(IndexScan, plan);
/* we prepend skip qual here so sort_indexquals will put it as first qual for that
* column */
idx_plan->indexqual =
sort_indexquals(index_path->indexinfo, lcons(op, idx_plan->indexqual));
}
else if (IsA(plan, IndexOnlyScan))
{
IndexOnlyScan *idx_plan = castNode(IndexOnlyScan, plan);
/* we prepend skip qual here so sort_indexquals will put it as first qual for that
* column */
idx_plan->indexqual =
sort_indexquals(index_path->indexinfo, lcons(op, idx_plan->indexqual));
}
else
{
elog(ERROR,
"unsupported subplan type for SkipScan: %s",
ts_get_node_name((Node *) plan));
}
/* get position of distinct column in tuples produced by child scan */
TargetEntry *tle = tlist_member_match_var(dvar, child_plan->targetlist);
SkipKeyNullStatus sknulls;
if (skinfo->notnull)
{
sknulls = SK_NOT_NULL;
}
else
{
bool nulls_first = index_path->indexinfo->nulls_first[skinfo->scankey_attno - 1];
if (index_path->indexscandir == BackwardScanDirection)
{
nulls_first = !nulls_first;
}
sknulls = (nulls_first ? SK_NULLS_FIRST : SK_NULLS_LAST);
}
skinfos = lappend(skinfos,
list_make5_int(tle->resno,
skinfo->distinct_by_val,
skinfo->distinct_typ_len,
sknulls,
skinfo->scankey_attno));
/* Debug info about skip key */
if (ts_guc_debug_skip_scan_info)
{
char *attname = get_attname(indexed_rte->relid, skinfo->indexed_column_attno, false);
char *sknullstext;
switch (sknulls)
{
case SK_NOT_NULL:
sknullstext = "NOT NULL";
break;
case SK_NULLS_FIRST:
sknullstext = "NULLS FIRST";
break;
case SK_NULLS_LAST:
sknullstext = "NULLS LAST";
break;
default:
Assert(false);
}
appendStringInfo(&debuginfo, "%s%s %s", sep, attname, sknullstext);
sep = ", ";
}
}
if (ts_guc_debug_skip_scan_info)
{
appendStringInfoString(&debuginfo, ")");
elog(INFO, "%s", debuginfo.data);
}
skip_plan->custom_private = lappend(skip_plan->custom_private, skinfos);
/* Don't need equality ops for one-key skipscan */
if (eqcomps != NIL)
{
Assert(list_length(skinfos) > 1);
skip_plan->custom_private = lappend(skip_plan->custom_private, eqcomps);
}
return &skip_plan->scan.plan;
}
/*************************
* SkipScanPath Creation *
*************************/
static CustomPathMethods skip_scan_path_methods = {
.CustomName = "SkipScanPath",
.PlanCustomPath = skip_scan_plan_create,
};
static Expr *
get_distint_clause_expr(PlannerInfo *root, SortGroupClause *distinct_clause)
{
Node *expr = get_sortgroupclause_expr(distinct_clause, root->parse->targetList);
/* we ignore any columns that can be constified to allow for cases like DISTINCT 'abc',
* column */
if (IsA(estimate_expression_value(root, expr), Const))
{
return NULL;
}
/* We ignore binary-compatible relabeling */
Expr *tlexpr = (Expr *) expr;
while (tlexpr && IsA(tlexpr, RelabelType))
{
tlexpr = ((RelabelType *) tlexpr)->arg;
}
if (!IsA(tlexpr, Var))
{
return NULL;
}
return tlexpr;
}
/* We can get upper path Distinct expression once for upper path,
* rather than repeat this check for each child path of an upper path input
*/
static List *
get_upper_distinct_expr(PlannerInfo *root, UpperRelationKind stage)
{
ListCell *lc;
Expr *tlexpr = NULL;
List *result = NULL;
if (stage == UPPERREL_DISTINCT && root->parse->distinctClause)
{
/* Obtain Distinct key from the target list, we ruled out numkeys > 1 cases before.
* Examples of queries with 1 Distinct key but multiple target entries:
* SELECT dev, dev FROM t; SELECT 1, dev FROM t; SELECT dev, time FROM t WHERE time = 100;
*/
SortGroupClause *distinct_clause = NULL;
foreach (lc, root->processed_distinctClause)
{
distinct_clause = (SortGroupClause *) lfirst(lc);
tlexpr = get_distint_clause_expr(root, distinct_clause);
if (tlexpr)
{
result = lappend(result, tlexpr);
}
else
{
return NULL;
}
}
}
else if (stage == UPPERREL_GROUP_AGG)
{
/* Find all non-nested Aggref in the query target list */
List *aggrefs = ts_find_aggrefs((Node *) root->parse->targetList);
foreach (lc, aggrefs)
{
Aggref *agg = lfirst_node(Aggref, lc);
/* Only distinct aggs with 1 sorted argument are eligible*/
if (agg->aggdistinct && agg->aggpresorted && list_length(agg->args) == 1)
{
TargetEntry *tle = (TargetEntry *) linitial(agg->args);
Expr *expr = tle->expr;
/* We ignore binary-compatible relabeling */
while (expr && IsA(expr, RelabelType))
{
expr = ((RelabelType *) expr)->arg;
}
/* Distinct agg over a Const is OK */
if (IsA(estimate_expression_value(root, (Node *) expr), Const))
{
continue;
}
/* Don't support no-var arguments */
if (!IsA(expr, Var))
{
return NULL;
}
/* Don't support multiple distinct aggs over different columns */
if (tlexpr && !tlist_member_match_var((Var *) tlexpr, agg->args))
{
return NULL;
}
/* If Distinct agg path has a groupby column, it needs to match Distinct agg column
*/
if (root->processed_groupClause)
{
/* Should have bailed out on gby exprs > 1 earlier
* Only 1-key SkipScan is supported for distinct aggregates
*/
Assert(list_length(root->processed_groupClause) == 1);
SortGroupClause *sortcl =
(SortGroupClause *) linitial(root->processed_groupClause);
Expr *gbykey = (Expr *) get_sortgroupclause_expr(sortcl, root->processed_tlist);
if (!equal(gbykey, expr))
{
return NULL;
}
}
/* Found a valid distinct agg over a valid Var */
if (!tlexpr)
{
tlexpr = expr;
result = lappend(result, tlexpr);
}
}
else
{
return NULL;
}
}
}
return result;
}
static void
obtain_upper_distinct_path(PlannerInfo *root, RelOptInfo *output_rel, DistinctPathInfo *dpinfo)
{
ListCell *lc;
/*
* look for Unique Path so we dont have to repeat some of
* the calculations done by postgres and can also assume
* that the DISTINCT clause is eligible for sort based
* DISTINCT
*/
if (dpinfo->stage == UPPERREL_DISTINCT)
{
if (!ts_guc_enable_skip_scan)
{
return;
}
foreach (lc, output_rel->pathlist)
{
if (IsA(lfirst(lc), UniquePathCompat))
{
UniquePathCompat *unique = (UniquePathCompat *) lfirst_node(UniquePathCompat, lc);
/* We can handle DISTINCT on more than one key if all keys are guaranteed not-nulls.
* To do so, we break down the SkipScan into subproblems: first
* find the minimal tuple then for each prefix find all unique suffix
* tuples. For instance, if we are searching over (int, int), we would
* first find (0, 0) then find (0, N) for all N in the domain, then
* find (1, N), then (2, N), etc
*/
if (!ts_guc_enable_multikey_skip_scan && unique->numkeys > 1)
{
return;
}
Assert(unique->numkeys >= 1);
dpinfo->unique_path = (Path *) unique;
break;
}
}
}
/* Look for Aggpath with eligible Distinct aggregates */
else if (dpinfo->stage == UPPERREL_GROUP_AGG)
{
if (!ts_guc_enable_skip_scan_for_distinct_aggregates)
{
return;
}
/* Cannot apply SkipScan to distinct aggregates with more than one key */
if (list_length(root->group_pathkeys) > 1)
{
return;
}
foreach (lc, output_rel->pathlist)
{
if (IsA(lfirst(lc), AggPath))
{
AggPath *unique = (AggPath *) lfirst_node(AggPath, lc);
/* If Distinct agg path has a group key, it must match Distinct aggregate input sort
* key, otherwise cannot apply SkipScan
*/
if (unique->path.pathkeys &&
!pathkeys_contained_in(unique->path.pathkeys, unique->subpath->pathkeys))
{
return;
}
dpinfo->unique_path = (Path *) lfirst_node(AggPath, lc);
break;
}
}
}
else
{
return;
}
if (!dpinfo->unique_path)
{
return;
}
/* Check if we have valid distinct expression to source from the underlying index */
dpinfo->distinct_expr = get_upper_distinct_expr(root, dpinfo->stage);
if (!dpinfo->distinct_expr)
{
dpinfo->unique_path = NULL;
return;
}
/* Need to make a copy of the unique path here because add_path() in the
* pathlist loop below might prune it if the new unique path
* (SkipScanPath) dominates the old one. When the unique path is pruned,
* the pointer will no longer be valid in the next iteration of the
* pathlist loop. Fortunately, the Path object is not deeply freed, so a
* shallow copy is enough. */
if (dpinfo->stage == UPPERREL_DISTINCT)
{
UniquePathCompat *unique = makeNode(UniquePathCompat);
memcpy(unique, lfirst_node(UniquePathCompat, lc), sizeof(UniquePathCompat));
dpinfo->unique_path = (Path *) unique;
}
else if (dpinfo->stage == UPPERREL_GROUP_AGG)
{
AggPath *dist_agg_path = makeNode(AggPath);
memcpy(dist_agg_path, lfirst_node(AggPath, lc), sizeof(AggPath));
dpinfo->unique_path = (Path *) dist_agg_path;
}
}
static SkipScanPath *skip_scan_path_create(PlannerInfo *root, Path *child_path,
DistinctPathInfo *dpinfo);
/*
* Create SkipScan paths based on existing Unique paths.
* For a Unique path on a simple relation like the following
*
* Unique
* -> Index Scan using skip_scan_dev_name_idx on skip_scan
*
* a SkipScan path like this will be created:
*
* Unique
* -> Custom Scan (SkipScan) on skip_scan
* -> Index Scan using skip_scan_dev_name_idx on skip_scan
*
* For a Unique path on a hypertable with multiple chunks like the following
*
* Unique
* -> Merge Append
* Sort Key: _hyper_2_1_chunk.dev_name
* -> Index Scan using _hyper_2_1_chunk_idx on _hyper_2_1_chunk
* -> Index Scan using _hyper_2_2_chunk_idx on _hyper_2_2_chunk
*
* a SkipScan path like this will be created:
*
* Unique
* -> Merge Append
* Sort Key: _hyper_2_1_chunk.dev_name
* -> Custom Scan (SkipScan) on _hyper_2_1_chunk
* -> Index Scan using _hyper_2_1_chunk_idx on _hyper_2_1_chunk
* -> Custom Scan (SkipScan) on _hyper_2_2_chunk
* -> Index Scan using _hyper_2_2_chunk_idx on _hyper_2_2_chunk
*/
void
tsl_skip_scan_paths_add(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *output_rel,
UpperRelationKind stage)
{
DistinctPathInfo dpinfo = {
.stage = stage,
.unique_path = NULL,
.distinct_expr = NULL,
};
obtain_upper_distinct_path(root, output_rel, &dpinfo);
if (!dpinfo.unique_path)
{
return;
}
Assert(IsA(dpinfo.unique_path, UniquePathCompat) || IsA(dpinfo.unique_path, AggPath));
ListCell *lc;
foreach (lc, input_rel->pathlist)
{
bool has_caa = false;
Path *subpath = lfirst(lc);
List *top_pathkeys = NULL;
/* Unique path has to be sorted on at least DISTINCT ON key */
if (IsA(dpinfo.unique_path, UniquePathCompat))
{
if (!pathkeys_contained_in(dpinfo.unique_path->pathkeys, subpath->pathkeys))
{
continue;
}
}
/* AggPath with distinct aggs may not be sorted, but the input into distinct aggs needs to
* be sorted */
else if (IsA(dpinfo.unique_path, AggPath))
{
if (!subpath->pathkeys ||
!pathkeys_contained_in(dpinfo.unique_path->pathkeys, subpath->pathkeys))
{
continue;
}
/* Need to check sortedness for inputs of Distinct aggs, so we'll keep track of the
* input pathkeys */
top_pathkeys = subpath->pathkeys;
}
/* If path is a ProjectionPath we strip it off for processing
* but also add a ProjectionPath on top of the SKipScanPaths
* later.
*/
ProjectionPath *proj = NULL;
if (IsA(subpath, ProjectionPath))
{
proj = castNode(ProjectionPath, subpath);
subpath = proj->subpath;
}
/* Path might be wrapped in a ConstraintAwareAppendPath if this
* is a MergeAppend that could benefit from runtime exclusion.
* We treat this similar to ProjectionPath and add it back
* later
*/
if (ts_is_constraint_aware_append_path(subpath))
{
subpath = linitial(castNode(CustomPath, subpath)->custom_paths);
Assert(IsA(subpath, MergeAppendPath));
has_caa = true;
}
if (IsA(subpath, IndexPath) || ts_is_columnar_scan_path(subpath))
{
subpath = (Path *) skip_scan_path_create(root, subpath, &dpinfo);
if (!subpath)
{
continue;
}
}
else if (IsA(subpath, MergeAppendPath))
{
MergeAppendPath *merge_path = castNode(MergeAppendPath, subpath);
List *new_paths = build_subpath(root, merge_path->subpaths, &dpinfo, top_pathkeys);
/* build_subpath returns NULL when no SkipScanPath was created */
if (!new_paths)
{
continue;
}
subpath = (Path *) create_merge_append_path(root,
merge_path->path.parent,
new_paths,
#if PG19_GE
merge_path->child_append_relid_sets,
#endif
merge_path->path.pathkeys,
NULL);
subpath->pathtarget = copy_pathtarget(merge_path->path.pathtarget);
}
/* We may have Append over one input which will be removed from the plan later.
* Consider it when it is sorted correctly. #7778
*/
else if (IsA(subpath, AppendPath))
{
AppendPath *append_path = castNode(AppendPath, subpath);
if (list_length(append_path->subpaths) > 1)
{
continue;
}
List *new_paths = build_subpath(root, append_path->subpaths, &dpinfo, top_pathkeys);
/* build_subpath returns NULL when no SkipScanPath was created */
if (!new_paths)
{
continue;
}
subpath = (Path *)
create_append_path(/* root = */ root,
/* rel = */ append_path->path.parent,
#if PG19_GE
/* input = */
(AppendPathInput){ .subpaths = new_paths,
.child_append_relid_sets =
append_path->child_append_relid_sets },
#else
/* subpaths = */ new_paths,
/* partial_subpaths = */ NULL,
#endif
/* pathkeys = */ append_path->path.pathkeys,
/* required_outer = */ NULL,
/* parallel_workers = */ append_path->path.parallel_workers,
/* parallel_aware = */ append_path->path.parallel_aware,
/* rows = */ -1);
subpath->pathtarget = copy_pathtarget(append_path->path.pathtarget);
}
else if (ts_is_chunk_append_path(subpath))
{
ChunkAppendPath *ca = (ChunkAppendPath *) subpath;
List *new_paths = build_subpath(root, ca->cpath.custom_paths, &dpinfo, top_pathkeys);
/* ChunkAppend should never be wrapped in ConstraintAwareAppendPath */
Assert(!has_caa);
/* build_subpath returns NULL when no SkipScanPath was created */
if (!new_paths)
{
continue;
}
/* We copy the existing ChunkAppendPath here because we don't have all the
* information used for creating the original one and we don't want to
* duplicate all the checks done when creating the original one.
*/
subpath = (Path *) ts_chunk_append_path_copy(ca, new_paths, ca->cpath.path.pathtarget);
}
else
{
continue;
}
/* add ConstraintAwareAppendPath if the original path had one */
if (has_caa)
{
subpath = ts_constraint_aware_append_path_create(root, subpath);
}
Path *new_unique = NULL;
if (IsA(dpinfo.unique_path, UniquePathCompat))
{
UniquePathCompat *unique = (UniquePathCompat *) dpinfo.unique_path;
new_unique = (Path *)
create_unique_path(root, output_rel, subpath, unique->numkeys, unique->path.rows);
new_unique->pathtarget = unique->path.pathtarget;
if (proj)
{
new_unique =
(Path *) create_projection_path(root,
output_rel,
new_unique,
copy_pathtarget(new_unique->pathtarget));
}
}
else if (IsA(dpinfo.unique_path, AggPath))
{
AggPath *dist_agg_path = (AggPath *) dpinfo.unique_path;
if (proj)
{
proj->subpath = subpath;
subpath = (Path *) proj;
}
AggClauseCosts agg_costs;
MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
get_agg_clause_costs(root, dist_agg_path->aggsplit, &agg_costs);
new_unique = (Path *) create_agg_path(root,
output_rel,
subpath,
dist_agg_path->path.pathtarget,
dist_agg_path->aggstrategy,
dist_agg_path->aggsplit,
dist_agg_path->groupClause,
dist_agg_path->qual,
(const AggClauseCosts *) &agg_costs,
dist_agg_path->numGroups);
}
add_path(output_rel, new_unique);
}
}
/* Check if skip key is guaranteed not-null */
static void
check_notnull_skipkey(SkipKeyInfo *skinfo, Path *child_path, IndexPath *index_path)
{
ListCell *l;
/* Quickly look through index clauses on this skip key */
foreach (l, index_path->indexclauses)
{
IndexClause *ic = (IndexClause *) lfirst(l);
/* index quals are ordered by indexcol, nothing to see if we've passed our indexcol */
if (ic->indexcol > skinfo->scankey_attno - 1)
{
break;
}
/* We may have row comparison with skip key not being a leading col,
* like (col, skipcol) > (3, 5), but it can allow NULL skipcols to pass if (col>3) is true,
* so for row comparisons we will only look at leading "indexcol" and not at "indexcols".
*/
if (ic->indexcol == skinfo->scankey_attno - 1)
{
/* Any simple index qual but "isNull" filters out nulls,
* including "lossy" index quals extracted from index clauses.
*/
ListCell *lc;
foreach (lc, ic->indexquals)
{
RestrictInfo *iqual = (RestrictInfo *) lfirst(lc);
if (!(IsA(iqual->clause, NullTest) &&
((NullTest *) iqual->clause)->nulltesttype == IS_NULL))
{
skinfo->notnull = true;
return;
}
}
}
}
/* Otherwise look at all non-indexqual index filters on the key (like (key+1)>5) to see if they
* filter out NULLs */
RelOptInfo *indexed_rel = index_path->path.parent;
foreach (l, index_path->indexinfo->indrestrictinfo)
{
RestrictInfo *ri = castNode(RestrictInfo, lfirst(l));
Bitmapset *clause_attnos = NULL;
pull_varattnos((Node *) ri->clause, indexed_rel->relid, &clause_attnos);
if (bms_is_member(skinfo->indexed_column_attno - FirstLowInvalidHeapAttributeNumber,
clause_attnos))
{
if (!contain_nonstrict_functions((Node *) ri->clause))
{
skinfo->notnull = true;
return;
}
}
}
/* Failing that, look at filters not pushed down into index (like col1+col2>1) to see if they
* filter out NULLs */
RelOptInfo *child_rel = child_path->parent;
foreach (l, child_rel->baserestrictinfo)
{
RestrictInfo *ri = castNode(RestrictInfo, lfirst(l));
Bitmapset *clause_attnos = NULL;
pull_varattnos((Node *) ri->clause, child_rel->relid, &clause_attnos);
if (bms_is_member(skinfo->distinct_attno - FirstLowInvalidHeapAttributeNumber,
clause_attnos))
{
if (!contain_nonstrict_functions((Node *) ri->clause))
{
skinfo->notnull = true;
return;
}
}
}
}
static IndexPath *
get_compressed_index_path(ColumnarScanPath *dcpath)
{
Path *compressed_path = linitial(dcpath->custom_path.custom_paths);
if (IsA(compressed_path, IndexPath))
{
IndexPath *index_path = castNode(IndexPath, compressed_path);
if (!pathkeys_contained_in(dcpath->required_compressed_pathkeys, compressed_path->pathkeys))
{
return NULL;
}
return index_path;
}
return NULL;
}
static SkipScanPath *
skip_scan_path_create(PlannerInfo *root, Path *child_path, DistinctPathInfo *dpinfo)
{
IndexPath *index_path = NULL;
if (IsA(child_path, IndexPath))
{
index_path = castNode(IndexPath, child_path);
}
else if (ts_is_columnar_scan_path(child_path))
{
if (!ts_guc_enable_compressed_skip_scan)
{
return NULL;
}
ColumnarScanPath *dcpath = (ColumnarScanPath *) child_path;
index_path = get_compressed_index_path(dcpath);
}
if (!index_path)
{
return NULL;
}
/* cannot use SkipScan with non-orderable index or IndexPath without pathkeys */
if (!index_path->path.pathkeys || !index_path->indexinfo->sortopfamily)
{
return NULL;
}
/* orderbyops are not compatible with skipscan */
if (index_path->indexorderbys != NIL)
{
return NULL;
}
SkipScanPath *skip_scan_path = (SkipScanPath *) newNode(sizeof(SkipScanPath), T_CustomPath);
skip_scan_path->cpath.path.pathtype = T_CustomScan;
skip_scan_path->cpath.path.pathkeys = child_path->pathkeys;
skip_scan_path->cpath.path.pathtarget = child_path->pathtarget;
skip_scan_path->cpath.path.param_info = child_path->param_info;
skip_scan_path->cpath.path.parent = child_path->parent;
skip_scan_path->cpath.custom_paths = list_make1(child_path);
skip_scan_path->cpath.methods = &skip_scan_path_methods;
/* While add_path may pfree paths with higher costs
* it will never free IndexPaths and only ever do a shallow
* free so reusing the IndexPath here is safe. */
skip_scan_path->index_path = index_path;
ListCell *lc;
int sk_no = 0;
int num_skipkeys = list_length(dpinfo->distinct_expr);
foreach (lc, dpinfo->distinct_expr)
{
Expr *dexpr = (Expr *) lfirst(lc);
/* Placeholder for skip key attributes */
SkipKeyInfo *skinfo = palloc(sizeof(SkipKeyInfo));
Var *dvar = get_distinct_var(root, dexpr, index_path, child_path, skinfo);
if (!dvar)
{
pfree(skinfo);
return NULL;
}
/* build skip qual this may fail if we cannot look up the operator */
if (!build_skip_qual(root, skinfo, index_path, dvar, (++sk_no) < num_skipkeys))
{
pfree(skinfo);
return NULL;
}
if (!skinfo->notnull)
{
check_notnull_skipkey(skinfo, child_path, index_path);
}
/* Multikey SkipScan is only supported in not-null mode */
if (!skinfo->notnull && num_skipkeys > 1)
{
return NULL;
}
skip_scan_path->dvars = lappend(skip_scan_path->dvars, dvar);
skip_scan_path->skipkeyinfo = lappend(skip_scan_path->skipkeyinfo, skinfo);
}
/* We have valid SkipScanPath: now we can cost it */
double startup = child_path->startup_cost;
double total = child_path->total_cost;
double rows = child_path->rows;
double indexscan_rows = index_path->path.rows;
/* Also true for SkipScan over compressed chunks as can't have more distinct segmentby values
* than number of batches */
int ndistinct = indexscan_rows;
/* For SELECT DISTINCT path, #rows can cap "ndistinct",
* but for Distinct aggregates #rows = 1 usually, i.e. we can't cap "ndistinct" in this case.
*/
if (dpinfo->stage == UPPERREL_DISTINCT)
{
ndistinct = Min(ndistinct, dpinfo->unique_path->rows);
}
/* If we are on a chunk rather than on a PG table, we want to get "ndistinct" for this chunk,
* as Unique path rows may combine rows from each chunk and may not represent a true
* "ndistinct". Consider a hypertable with 1000 chunks, each chunk has the same 1 distinct
* value, Unique path will add them up and we will get "ndistinct" = 1000 instead of 1. If
* Unique path has "ndistinct=1" we can't go any smaller so will just accept this number.
*/
if (ndistinct > 1)
{
ndistinct =
Max(1, floor(estimate_num_groups(root, skip_scan_path->dvars, ndistinct, NULL, NULL)));
}
skip_scan_path->cpath.path.rows = ndistinct;