-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathpg_pathman.c
2513 lines (2140 loc) · 67.3 KB
/
pg_pathman.c
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
/* ------------------------------------------------------------------------
*
* pg_pathman.c
* This module sets planner hooks, handles SELECT queries and produces
* paths for partitioned tables
*
* Copyright (c) 2015-2021, Postgres Professional
*
* ------------------------------------------------------------------------
*/
#include "compat/pg_compat.h"
#include "compat/rowmarks_fix.h"
#include "init.h"
#include "hooks.h"
#include "pathman.h"
#include "partition_filter.h"
#include "partition_router.h"
#include "partition_overseer.h"
#include "planner_tree_modification.h"
#include "runtime_append.h"
#include "runtime_merge_append.h"
#include "postgres.h"
#include "access/genam.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#if PG_VERSION_NUM >= 120000
#include "access/table.h"
#endif
#include "access/xact.h"
#include "catalog/pg_collation.h"
#include "catalog/indexing.h"
#include "catalog/pg_type.h"
#include "catalog/pg_extension.h"
#include "commands/extension.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#if PG_VERSION_NUM >= 120000
#include "optimizer/optimizer.h"
#endif
#include "optimizer/clauses.h"
#include "optimizer/plancat.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/cost.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/rel.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/selfuncs.h"
#include "utils/typcache.h"
PG_MODULE_MAGIC;
Oid pathman_config_relid = InvalidOid,
pathman_config_params_relid = InvalidOid;
/* pg module functions */
void _PG_init(void);
/* Expression tree handlers */
static Node *wrapper_make_expression(WrapperNode *wrap, int index, bool *alwaysTrue);
static void handle_const(const Const *c,
const Oid collid,
const int strategy,
const WalkerContext *context,
WrapperNode *result);
static void handle_array(ArrayType *array,
const Oid collid,
const int strategy,
const bool use_or,
const WalkerContext *context,
WrapperNode *result);
static void handle_boolexpr(const BoolExpr *expr,
const WalkerContext *context,
WrapperNode *result);
static void handle_arrexpr(const ScalarArrayOpExpr *expr,
const WalkerContext *context,
WrapperNode *result);
static void handle_opexpr(const OpExpr *expr,
const WalkerContext *context,
WrapperNode *result);
static Datum array_find_min_max(Datum *values,
bool *isnull,
int length,
Oid value_type,
Oid collid,
bool take_min,
bool *result_null);
/* Copied from PostgreSQL (allpaths.c) */
static void set_plain_rel_size(PlannerInfo *root,
RelOptInfo *rel,
RangeTblEntry *rte);
static void set_plain_rel_pathlist(PlannerInfo *root,
RelOptInfo *rel,
RangeTblEntry *rte);
static List *accumulate_append_subpath(List *subpaths, Path *path);
static void generate_mergeappend_paths(PlannerInfo *root,
RelOptInfo *rel,
List *live_childrels,
List *all_child_pathkeys,
PathKey *pathkeyAsc,
PathKey *pathkeyDesc);
/* Can we transform this node into a Const? */
static bool
IsConstValue(Node *node, const WalkerContext *context)
{
switch (nodeTag(node))
{
case T_Const:
return true;
case T_Param:
return WcxtHasExprContext(context);
case T_RowExpr:
{
RowExpr *row = (RowExpr *) node;
ListCell *lc;
/* Can't do anything about RECORD of wrong type */
if (row->row_typeid != context->prel->ev_type)
return false;
/* Check that args are const values */
foreach (lc, row->args)
if (!IsConstValue((Node *) lfirst(lc), context))
return false;
}
return true;
default:
return false;
}
}
/* Extract a Const from node that has been checked by IsConstValue() */
static Const *
ExtractConst(Node *node, const WalkerContext *context)
{
ExprState *estate;
ExprContext *econtext = context->econtext;
Datum value;
bool isnull;
Oid typid,
collid;
int typmod;
/* Fast path for Consts */
if (IsA(node, Const))
return (Const *) node;
/* Just a paranoid check */
Assert(IsConstValue(node, context));
switch (nodeTag(node))
{
case T_Param:
{
Param *param = (Param *) node;
typid = param->paramtype;
typmod = param->paramtypmod;
collid = param->paramcollid;
/* It must be provided */
Assert(WcxtHasExprContext(context));
}
break;
case T_RowExpr:
{
RowExpr *row = (RowExpr *) node;
typid = row->row_typeid;
typmod = -1;
collid = InvalidOid;
#if PG_VERSION_NUM >= 100000
/* If there's no context - create it! */
if (!WcxtHasExprContext(context))
econtext = CreateStandaloneExprContext();
#endif
}
break;
default:
elog(ERROR, "error in function " CppAsString(ExtractConst));
}
/* Evaluate expression */
estate = ExecInitExpr((Expr *) node, NULL);
value = ExecEvalExprCompat(estate, econtext, &isnull);
#if PG_VERSION_NUM >= 100000
/* Free temp econtext if needed */
if (econtext && !WcxtHasExprContext(context))
FreeExprContext(econtext, true);
#endif
/* Finally return Const */
return makeConst(typid, typmod, collid, get_typlen(typid),
value, isnull, get_typbyval(typid));
}
/*
* Checks if expression is a KEY OP PARAM or PARAM OP KEY,
* where KEY is partitioning expression and PARAM is whatever.
*
* Returns:
* operator's Oid if KEY is a partitioning expr,
* otherwise InvalidOid.
*/
static Oid
IsKeyOpParam(const OpExpr *expr,
const WalkerContext *context,
Node **param_ptr) /* ret value #1 */
{
Node *left = linitial(expr->args),
*right = lsecond(expr->args);
/* Check number of arguments */
if (list_length(expr->args) != 2)
return InvalidOid;
/* KEY OP PARAM */
if (match_expr_to_operand(context->prel_expr, left))
{
*param_ptr = right;
/* return the same operator */
return expr->opno;
}
/* PARAM OP KEY */
if (match_expr_to_operand(context->prel_expr, right))
{
*param_ptr = left;
/* commute to (KEY OP PARAM) */
return get_commutator(expr->opno);
}
return InvalidOid;
}
/* Selectivity estimator for common 'paramsel' */
static inline double
estimate_paramsel_using_prel(const PartRelationInfo *prel, int strategy)
{
/* If it's "=", divide by partitions number */
if (strategy == BTEqualStrategyNumber)
return 1.0 / (double) PrelChildrenCount(prel);
/* Default selectivity estimate for inequalities */
else if (prel->parttype == PT_RANGE && strategy > 0)
return DEFAULT_INEQ_SEL;
/* Else there's not much to do */
else return 1.0;
}
#if defined(PGPRO_EE) && PG_VERSION_NUM >= 100000
/*
* Reset cache at start and at finish ATX transaction
*/
static void
pathman_xact_cb(XactEvent event, void *arg)
{
if (getNestLevelATX() > 0)
{
/*
* For each ATX transaction start/finish: need to reset pg_pathman
* cache because we shouldn't see uncommitted data in autonomous
* transaction and data of autonomous transaction in main transaction
*/
if ((event == XACT_EVENT_START /* start */) ||
(event == XACT_EVENT_ABORT ||
event == XACT_EVENT_PARALLEL_ABORT ||
event == XACT_EVENT_COMMIT ||
event == XACT_EVENT_PARALLEL_COMMIT ||
event == XACT_EVENT_PREPARE /* finish */))
{
pathman_relcache_hook(PointerGetDatum(NULL), InvalidOid);
}
}
}
#endif
/*
* -------------------
* General functions
* -------------------
*/
#if PG_VERSION_NUM >= 150000 /* for commit 4f2400cb3f10 */
static shmem_request_hook_type prev_shmem_request_hook = NULL;
static void pg_pathman_shmem_request(void);
#endif
/* Set initial values for all Postmaster's forks */
void
_PG_init(void)
{
if (!process_shared_preload_libraries_in_progress)
{
elog(ERROR, "pg_pathman module must be initialized by Postmaster. "
"Put the following line to configuration file: "
"shared_preload_libraries='pg_pathman'");
}
/* Request additional shared resources */
#if PG_VERSION_NUM >= 150000 /* for commit 4f2400cb3f10 */
prev_shmem_request_hook = shmem_request_hook;
shmem_request_hook = pg_pathman_shmem_request;
#else
RequestAddinShmemSpace(estimate_pathman_shmem_size());
#endif
/* Assign pg_pathman's initial state */
pathman_init_state.pg_pathman_enable = DEFAULT_PATHMAN_ENABLE;
pathman_init_state.auto_partition = DEFAULT_PATHMAN_AUTO;
pathman_init_state.override_copy = DEFAULT_PATHMAN_OVERRIDE_COPY;
pathman_init_state.initialization_needed = true; /* ofc it's needed! */
/* Set basic hooks */
pathman_set_rel_pathlist_hook_next = set_rel_pathlist_hook;
set_rel_pathlist_hook = pathman_rel_pathlist_hook;
pathman_set_join_pathlist_next = set_join_pathlist_hook;
set_join_pathlist_hook = pathman_join_pathlist_hook;
pathman_shmem_startup_hook_next = shmem_startup_hook;
shmem_startup_hook = pathman_shmem_startup_hook;
pathman_post_parse_analyze_hook_next = post_parse_analyze_hook;
post_parse_analyze_hook = pathman_post_parse_analyze_hook;
pathman_planner_hook_next = planner_hook;
planner_hook = pathman_planner_hook;
pathman_process_utility_hook_next = ProcessUtility_hook;
ProcessUtility_hook = pathman_process_utility_hook;
pathman_executor_start_hook_prev = ExecutorStart_hook;
ExecutorStart_hook = pathman_executor_start_hook;
/* Initialize static data for all subsystems */
init_main_pathman_toggles();
init_relation_info_static_data();
init_runtime_append_static_data();
init_runtime_merge_append_static_data();
init_partition_filter_static_data();
init_partition_router_static_data();
init_partition_overseer_static_data();
#ifdef PGPRO_EE
/* Callbacks for reload relcache for ATX transactions */
PgproRegisterXactCallback(pathman_xact_cb, NULL, XACT_EVENT_KIND_VANILLA | XACT_EVENT_KIND_ATX);
#endif
}
#if PG_VERSION_NUM >= 150000 /* for commit 4f2400cb3f10 */
static void
pg_pathman_shmem_request(void)
{
if (prev_shmem_request_hook)
prev_shmem_request_hook();
RequestAddinShmemSpace(estimate_pathman_shmem_size());
}
#endif
/* Get cached PATHMAN_CONFIG relation Oid */
Oid
get_pathman_config_relid(bool invalid_is_ok)
{
if (!IsPathmanInitialized())
{
if (invalid_is_ok)
return InvalidOid;
elog(ERROR, "pg_pathman is not initialized yet");
}
/* Raise ERROR if Oid is invalid */
if (!OidIsValid(pathman_config_relid) && !invalid_is_ok)
elog(ERROR, "unexpected error in function "
CppAsString(get_pathman_config_relid));
return pathman_config_relid;
}
/* Get cached PATHMAN_CONFIG_PARAMS relation Oid */
Oid
get_pathman_config_params_relid(bool invalid_is_ok)
{
if (!IsPathmanInitialized())
{
if (invalid_is_ok)
return InvalidOid;
elog(ERROR, "pg_pathman is not initialized yet");
}
/* Raise ERROR if Oid is invalid */
if (!OidIsValid(pathman_config_relid) && !invalid_is_ok)
elog(ERROR, "unexpected error in function "
CppAsString(get_pathman_config_params_relid));
return pathman_config_params_relid;
}
/*
* Return pg_pathman schema's Oid or InvalidOid if that's not possible.
*/
Oid
get_pathman_schema(void)
{
Oid result;
Relation rel;
SysScanDesc scandesc;
HeapTuple tuple;
ScanKeyData entry[1];
Oid ext_oid;
/* It's impossible to fetch pg_pathman's schema now */
if (!IsTransactionState())
return InvalidOid;
ext_oid = get_extension_oid("pg_pathman", true);
if (ext_oid == InvalidOid)
return InvalidOid; /* exit if pg_pathman does not exist */
ScanKeyInit(&entry[0],
#if PG_VERSION_NUM >= 120000
Anum_pg_extension_oid,
#else
ObjectIdAttributeNumber,
#endif
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(ext_oid));
rel = heap_open_compat(ExtensionRelationId, AccessShareLock);
scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
NULL, 1, entry);
tuple = systable_getnext(scandesc);
/* We assume that there can be at most one matching tuple */
if (HeapTupleIsValid(tuple))
result = ((Form_pg_extension) GETSTRUCT(tuple))->extnamespace;
else
result = InvalidOid;
systable_endscan(scandesc);
heap_close_compat(rel, AccessShareLock);
return result;
}
/*
* ----------------------------------------
* RTE expansion (add RTE for partitions)
* ----------------------------------------
*/
/*
* Creates child relation and adds it to root.
* Returns child index in simple_rel_array.
*
* NOTE: partially based on the expand_inherited_rtentry() function.
*/
Index
append_child_relation(PlannerInfo *root,
Relation parent_relation,
PlanRowMark *parent_rowmark,
Index parent_rti,
int ir_index,
Oid child_oid,
List *wrappers)
{
RangeTblEntry *parent_rte,
*child_rte;
RelOptInfo *parent_rel,
*child_rel;
Relation child_relation;
AppendRelInfo *appinfo;
Index child_rti;
PlanRowMark *child_rowmark = NULL;
Node *childqual;
List *childquals;
ListCell *lc1,
*lc2;
LOCKMODE lockmode;
#if PG_VERSION_NUM >= 130000 /* see commit 55a1954d */
TupleDesc child_tupdesc;
List *parent_colnames;
List *child_colnames;
#endif
/* Choose a correct lock mode */
if (parent_rti == root->parse->resultRelation)
lockmode = RowExclusiveLock;
else if (parent_rowmark && RowMarkRequiresRowShareLock(parent_rowmark->markType))
lockmode = RowShareLock;
else
lockmode = AccessShareLock;
/* Acquire a suitable lock on partition */
LockRelationOid(child_oid, lockmode);
/* Check that partition exists */
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(child_oid)))
{
UnlockRelationOid(child_oid, lockmode);
return 0;
}
parent_rel = root->simple_rel_array[parent_rti];
/* make clang analyzer quiet */
if (!parent_rel)
elog(ERROR, "parent relation is NULL");
parent_rte = root->simple_rte_array[parent_rti];
/* Open child relation (we've just locked it) */
child_relation = heap_open_compat(child_oid, NoLock);
/* Create RangeTblEntry for child relation */
#if PG_VERSION_NUM >= 130000 /* see commit 55a1954d */
child_rte = makeNode(RangeTblEntry);
memcpy(child_rte, parent_rte, sizeof(RangeTblEntry));
#else
child_rte = copyObject(parent_rte);
#endif
child_rte->relid = child_oid;
child_rte->relkind = child_relation->rd_rel->relkind;
#if PG_VERSION_NUM >= 160000 /* for commit a61b1f74823c */
/* No permission checking for the child RTE */
child_rte->perminfoindex = 0;
#else
child_rte->requiredPerms = 0; /* perform all checks on parent */
#endif
child_rte->inh = false;
/* Add 'child_rte' to rtable and 'root->simple_rte_array' */
root->parse->rtable = lappend(root->parse->rtable, child_rte);
child_rti = list_length(root->parse->rtable);
root->simple_rte_array[child_rti] = child_rte;
/* Build an AppendRelInfo for this child */
appinfo = makeNode(AppendRelInfo);
appinfo->parent_relid = parent_rti;
appinfo->child_relid = child_rti;
appinfo->parent_reloid = parent_rte->relid;
/* Store table row types for wholerow references */
appinfo->parent_reltype = RelationGetDescr(parent_relation)->tdtypeid;
appinfo->child_reltype = RelationGetDescr(child_relation)->tdtypeid;
make_inh_translation_list(parent_relation, child_relation, child_rti,
&appinfo->translated_vars, appinfo);
#if PG_VERSION_NUM >= 130000 /* see commit 55a1954d */
/* tablesample is probably null, but copy it */
child_rte->tablesample = copyObject(parent_rte->tablesample);
/*
* Construct an alias clause for the child, which we can also use as eref.
* This is important so that EXPLAIN will print the right column aliases
* for child-table columns. (Since ruleutils.c doesn't have any easy way
* to reassociate parent and child columns, we must get the child column
* aliases right to start with. Note that setting childrte->alias forces
* ruleutils.c to use these column names, which it otherwise would not.)
*/
child_tupdesc = RelationGetDescr(child_relation);
parent_colnames = parent_rte->eref->colnames;
child_colnames = NIL;
for (int cattno = 0; cattno < child_tupdesc->natts; cattno++)
{
Form_pg_attribute att = TupleDescAttr(child_tupdesc, cattno);
const char *attname;
if (att->attisdropped)
{
/* Always insert an empty string for a dropped column */
attname = "";
}
else if (appinfo->parent_colnos[cattno] > 0 &&
appinfo->parent_colnos[cattno] <= list_length(parent_colnames))
{
/* Duplicate the query-assigned name for the parent column */
attname = strVal(list_nth(parent_colnames,
appinfo->parent_colnos[cattno] - 1));
}
else
{
/* New column, just use its real name */
attname = NameStr(att->attname);
}
child_colnames = lappend(child_colnames, makeString(pstrdup(attname)));
}
/*
* We just duplicate the parent's table alias name for each child. If the
* plan gets printed, ruleutils.c has to sort out unique table aliases to
* use, which it can handle.
*/
child_rte->alias = child_rte->eref = makeAlias(parent_rte->eref->aliasname,
child_colnames);
#endif
/* Now append 'appinfo' to 'root->append_rel_list' */
root->append_rel_list = lappend(root->append_rel_list, appinfo);
/* And to array in >= 11, it must be big enough */
#if PG_VERSION_NUM >= 110000
root->append_rel_array[child_rti] = appinfo;
#endif
/* Create RelOptInfo for this child (and make some estimates as well) */
child_rel = build_simple_rel_compat(root, child_rti, parent_rel);
/* Increase total_table_pages using the 'child_rel' */
root->total_table_pages += (double) child_rel->pages;
/* Create rowmarks required for child rels */
/*
* XXX: vanilla recurses down with *top* rowmark, not immediate parent one.
* Not sure about example where this matters though.
*/
if (parent_rowmark)
{
child_rowmark = makeNode(PlanRowMark);
child_rowmark->rti = child_rti;
child_rowmark->prti = parent_rti;
child_rowmark->rowmarkId = parent_rowmark->rowmarkId;
/* Reselect rowmark type, because relkind might not match parent */
child_rowmark->markType = select_rowmark_type(child_rte,
parent_rowmark->strength);
child_rowmark->allMarkTypes = (1 << child_rowmark->markType);
child_rowmark->strength = parent_rowmark->strength;
child_rowmark->waitPolicy = parent_rowmark->waitPolicy;
child_rowmark->isParent = false;
root->rowMarks = lappend(root->rowMarks, child_rowmark);
/* Adjust tlist for RowMarks (see planner.c) */
/*
* XXX Saner approach seems to
* 1) Add tle to top parent and processed_tlist once in rel_pathlist_hook.
* 2) Mark isParent = true
* *parent* knows it is parent, after all; why should child bother?
* 3) Recursion (code executed in childs) starts at 2)
*/
if (!parent_rowmark->isParent && !root->parse->setOperations)
{
append_tle_for_rowmark(root, parent_rowmark);
}
/* Include child's rowmark type in parent's allMarkTypes */
parent_rowmark->allMarkTypes |= child_rowmark->allMarkTypes;
parent_rowmark->isParent = true;
}
#if PG_VERSION_NUM < 160000 /* for commit a61b1f74823c */
/* Translate column privileges for this child */
if (parent_rte->relid != child_oid)
{
child_rte->selectedCols = translate_col_privs(parent_rte->selectedCols,
appinfo->translated_vars);
child_rte->insertedCols = translate_col_privs(parent_rte->insertedCols,
appinfo->translated_vars);
child_rte->updatedCols = translate_col_privs(parent_rte->updatedCols,
appinfo->translated_vars);
}
#if PG_VERSION_NUM >= 130000 /* see commit 55a1954d */
else
{
child_rte->selectedCols = bms_copy(parent_rte->selectedCols);
child_rte->insertedCols = bms_copy(parent_rte->insertedCols);
child_rte->updatedCols = bms_copy(parent_rte->updatedCols);
}
#endif
#endif /* PG_VERSION_NUM < 160000 */
/* Here and below we assume that parent RelOptInfo exists */
Assert(parent_rel);
/* Adjust join quals for this child */
child_rel->joininfo = (List *) adjust_appendrel_attrs_compat(root,
(Node *) parent_rel->joininfo,
appinfo);
/* Adjust target list for this child */
adjust_rel_targetlist_compat(root, child_rel, parent_rel, appinfo);
/*
* Copy restrictions. If it's not the parent table, copy only
* those restrictions that are related to this partition.
*/
if (parent_rte->relid != child_oid)
{
childquals = NIL;
forboth (lc1, wrappers, lc2, parent_rel->baserestrictinfo)
{
WrapperNode *wrap = (WrapperNode *) lfirst(lc1);
Node *new_clause;
bool always_true;
/* Generate a set of clauses for this child using WrapperNode */
new_clause = wrapper_make_expression(wrap, ir_index, &always_true);
/* Don't add this clause if it's always true */
if (always_true)
continue;
/* Clause should not be NULL */
Assert(new_clause);
childquals = lappend(childquals, new_clause);
}
}
/* If it's the parent table, copy all restrictions */
else childquals = get_all_actual_clauses(parent_rel->baserestrictinfo);
/* Now it's time to change varnos and rebuld quals */
childquals = (List *) adjust_appendrel_attrs_compat(root,
(Node *) childquals,
appinfo);
childqual = eval_const_expressions(root, (Node *)
make_ands_explicit(childquals));
if (childqual && IsA(childqual, Const) &&
(((Const *) childqual)->constisnull ||
!DatumGetBool(((Const *) childqual)->constvalue)))
{
/*
* Restriction reduces to constant FALSE or constant NULL after
* substitution, so this child need not be scanned.
*/
#if PG_VERSION_NUM >= 120000
mark_dummy_rel(child_rel);
#else
set_dummy_rel_pathlist(child_rel);
#endif
}
childquals = make_ands_implicit((Expr *) childqual);
childquals = make_restrictinfos_from_actual_clauses(root, childquals);
/* Set new shiny childquals */
child_rel->baserestrictinfo = childquals;
if (relation_excluded_by_constraints(root, child_rel, child_rte))
{
/*
* This child need not be scanned, so we can omit it from the
* appendrel.
*/
#if PG_VERSION_NUM >= 120000
mark_dummy_rel(child_rel);
#else
set_dummy_rel_pathlist(child_rel);
#endif
}
/*
* We have to make child entries in the EquivalenceClass data
* structures as well.
*/
if (parent_rel->has_eclass_joins || has_useful_pathkeys(root, parent_rel))
add_child_rel_equivalences(root, appinfo, parent_rel, child_rel);
child_rel->has_eclass_joins = parent_rel->has_eclass_joins;
/* Expand child partition if it might have subpartitions */
if (parent_rte->relid != child_oid &&
child_relation->rd_rel->relhassubclass)
{
/* See XXX above */
if (child_rowmark)
child_rowmark->isParent = true;
pathman_rel_pathlist_hook(root,
child_rel,
child_rti,
child_rte);
}
/* Close child relations, but keep locks */
heap_close_compat(child_relation, NoLock);
return child_rti;
}
/*
* -------------------------
* RANGE partition pruning
* -------------------------
*/
/* Given 'value' and 'ranges', return selected partitions list */
void
select_range_partitions(const Datum value,
const Oid collid,
FmgrInfo *cmp_func,
const RangeEntry *ranges,
const int nranges,
const int strategy,
WrapperNode *result) /* returned partitions */
{
bool lossy = false,
miss_left, /* 'value' is less than left bound */
miss_right; /* 'value' is greater that right bound */
int startidx = 0,
endidx = nranges - 1,
cmp_min,
cmp_max,
i = 0;
Bound value_bound = MakeBound(value); /* convert value to Bound */
#ifdef USE_ASSERT_CHECKING
int counter = 0;
#endif
/* Initial value (no missing partitions found) */
result->found_gap = false;
/* Check 'ranges' array */
if (nranges == 0)
{
result->rangeset = NIL;
return;
}
/* Check corner cases */
else
{
Assert(ranges);
Assert(cmp_func);
/* Compare 'value' to absolute MIN and MAX bounds */
cmp_min = cmp_bounds(cmp_func, collid, &value_bound, &ranges[startidx].min);
cmp_max = cmp_bounds(cmp_func, collid, &value_bound, &ranges[endidx].max);
if ((cmp_min <= 0 && strategy == BTLessStrategyNumber) ||
(cmp_min < 0 && (strategy == BTLessEqualStrategyNumber ||
strategy == BTEqualStrategyNumber)))
{
result->rangeset = NIL;
return;
}
if (cmp_max >= 0 && (strategy == BTGreaterEqualStrategyNumber ||
strategy == BTGreaterStrategyNumber ||
strategy == BTEqualStrategyNumber))
{
result->rangeset = NIL;
return;
}
if ((cmp_min < 0 && strategy == BTGreaterStrategyNumber) ||
(cmp_min <= 0 && strategy == BTGreaterEqualStrategyNumber))
{
result->rangeset = list_make1_irange(make_irange(startidx,
endidx,
IR_COMPLETE));
return;
}
if (cmp_max >= 0 && (strategy == BTLessEqualStrategyNumber ||
strategy == BTLessStrategyNumber))
{
result->rangeset = list_make1_irange(make_irange(startidx,
endidx,
IR_COMPLETE));
return;
}
}
/* Binary search */
while (true)
{
Assert(ranges);
Assert(cmp_func);
/* Calculate new pivot */
i = startidx + (endidx - startidx) / 2;
Assert(i >= 0 && i < nranges);
/* Compare 'value' to current MIN and MAX bounds */
cmp_min = cmp_bounds(cmp_func, collid, &value_bound, &ranges[i].min);
cmp_max = cmp_bounds(cmp_func, collid, &value_bound, &ranges[i].max);
/* How is 'value' located with respect to left & right bounds? */
miss_left = (cmp_min < 0 || (cmp_min == 0 && strategy == BTLessStrategyNumber));
miss_right = (cmp_max > 0 || (cmp_max == 0 && strategy != BTLessStrategyNumber));
/* Searched value is inside of partition */
if (!miss_left && !miss_right)
{
/* 'value' == 'min' and we want everything on the right */
if (cmp_min == 0 && strategy == BTGreaterEqualStrategyNumber)
lossy = false;
/* 'value' == 'max' and we want everything on the left */
else if (cmp_max == 0 && strategy == BTLessStrategyNumber)
lossy = false;
/* We're somewhere in the middle */
else lossy = true;
break; /* just exit loop */
}
/* Indices have met, looks like there's no partition */
if (startidx >= endidx)
{
result->rangeset = NIL;
result->found_gap = true;
/* Return if it's "key = value" */
if (strategy == BTEqualStrategyNumber)
return;
/*
* Use current partition 'i' as a pivot that will be
* excluded by relation_excluded_by_constraints() if
* (lossy == true) & its WHERE clauses are trivial.
*/
if ((miss_left && (strategy == BTLessStrategyNumber ||
strategy == BTLessEqualStrategyNumber)) ||
(miss_right && (strategy == BTGreaterStrategyNumber ||
strategy == BTGreaterEqualStrategyNumber)))
lossy = true;
else
lossy = false;
break; /* just exit loop */
}
if (miss_left)
endidx = i - 1;
else if (miss_right)
startidx = i + 1;
/* For debug's sake */
Assert(++counter < 100);
}
/* Filter partitions */
switch(strategy)
{
case BTLessStrategyNumber:
case BTLessEqualStrategyNumber:
if (lossy)
{
result->rangeset = list_make1_irange(make_irange(i, i, IR_LOSSY));
if (i > 0)
result->rangeset = lcons_irange(make_irange(0, i - 1, IR_COMPLETE),
result->rangeset);
}
else
{
result->rangeset = list_make1_irange(make_irange(0, i, IR_COMPLETE));
}
break;
case BTEqualStrategyNumber:
result->rangeset = list_make1_irange(make_irange(i, i, IR_LOSSY));
break;
case BTGreaterEqualStrategyNumber:
case BTGreaterStrategyNumber:
if (lossy)
{
result->rangeset = list_make1_irange(make_irange(i, i, IR_LOSSY));
if (i < nranges - 1)
result->rangeset = lappend_irange(result->rangeset,
make_irange(i + 1,