1 /*-------------------------------------------------------------------------
4 * hinting on how to execute a query for PostgreSQL
6 * Copyright (c) 2012-2019, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
8 *-------------------------------------------------------------------------
13 #include "access/genam.h"
14 #include "access/heapam.h"
15 #include "access/relation.h"
16 #include "catalog/pg_collation.h"
17 #include "catalog/pg_index.h"
18 #include "commands/prepare.h"
19 #include "mb/pg_wchar.h"
20 #include "miscadmin.h"
21 #include "nodes/nodeFuncs.h"
22 #include "nodes/params.h"
23 #include "optimizer/appendinfo.h"
24 #include "optimizer/clauses.h"
25 #include "optimizer/cost.h"
26 #include "optimizer/geqo.h"
27 #include "optimizer/joininfo.h"
28 #include "optimizer/optimizer.h"
29 #include "optimizer/pathnode.h"
30 #include "optimizer/paths.h"
31 #include "optimizer/plancat.h"
32 #include "optimizer/planner.h"
33 #include "optimizer/prep.h"
34 #include "optimizer/restrictinfo.h"
35 #include "parser/analyze.h"
36 #include "parser/parsetree.h"
37 #include "parser/scansup.h"
38 #include "partitioning/partbounds.h"
39 #include "tcop/utility.h"
40 #include "utils/builtins.h"
41 #include "utils/lsyscache.h"
42 #include "utils/memutils.h"
43 #include "utils/rel.h"
44 #include "utils/snapmgr.h"
45 #include "utils/syscache.h"
46 #include "utils/resowner.h"
48 #include "catalog/pg_class.h"
50 #include "executor/spi.h"
51 #include "catalog/pg_type.h"
55 /* partially copied from pg_stat_statements */
56 #include "normalize_query.h"
59 #include "access/htup_details.h"
61 #ifdef PG_MODULE_MAGIC
65 #define BLOCK_COMMENT_START "/*"
66 #define BLOCK_COMMENT_END "*/"
67 #define HINT_COMMENT_KEYWORD "+"
68 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
69 #define HINT_END BLOCK_COMMENT_END
72 #define HINT_SEQSCAN "SeqScan"
73 #define HINT_INDEXSCAN "IndexScan"
74 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
75 #define HINT_BITMAPSCAN "BitmapScan"
76 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
77 #define HINT_TIDSCAN "TidScan"
78 #define HINT_NOSEQSCAN "NoSeqScan"
79 #define HINT_NOINDEXSCAN "NoIndexScan"
80 #define HINT_NOBITMAPSCAN "NoBitmapScan"
81 #define HINT_NOTIDSCAN "NoTidScan"
82 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
83 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
84 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
85 #define HINT_PARALLEL "Parallel"
87 #define HINT_NESTLOOP "NestLoop"
88 #define HINT_MERGEJOIN "MergeJoin"
89 #define HINT_HASHJOIN "HashJoin"
90 #define HINT_NONESTLOOP "NoNestLoop"
91 #define HINT_NOMERGEJOIN "NoMergeJoin"
92 #define HINT_NOHASHJOIN "NoHashJoin"
93 #define HINT_LEADING "Leading"
94 #define HINT_SET "Set"
95 #define HINT_ROWS "Rows"
97 #define HINT_ARRAY_DEFAULT_INITSIZE 8
99 #define hint_ereport(str, detail) hint_parse_ereport(str, detail)
100 #define hint_parse_ereport(str, detail) \
102 ereport(pg_hint_plan_parse_message_level, \
103 (errmsg("pg_hint_plan: hint syntax error at or near \"%s\"", (str)), \
104 errdetail detail)); \
107 #define skip_space(str) \
108 while (isspace(*str)) \
113 ENABLE_SEQSCAN = 0x01,
114 ENABLE_INDEXSCAN = 0x02,
115 ENABLE_BITMAPSCAN = 0x04,
116 ENABLE_TIDSCAN = 0x08,
117 ENABLE_INDEXONLYSCAN = 0x10
122 ENABLE_NESTLOOP = 0x01,
123 ENABLE_MERGEJOIN = 0x02,
124 ENABLE_HASHJOIN = 0x04
127 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
128 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
129 ENABLE_INDEXONLYSCAN)
130 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
131 #define DISABLE_ALL_SCAN 0
132 #define DISABLE_ALL_JOIN 0
134 /* hint keyword of enum type*/
135 typedef enum HintKeyword
137 HINT_KEYWORD_SEQSCAN,
138 HINT_KEYWORD_INDEXSCAN,
139 HINT_KEYWORD_INDEXSCANREGEXP,
140 HINT_KEYWORD_BITMAPSCAN,
141 HINT_KEYWORD_BITMAPSCANREGEXP,
142 HINT_KEYWORD_TIDSCAN,
143 HINT_KEYWORD_NOSEQSCAN,
144 HINT_KEYWORD_NOINDEXSCAN,
145 HINT_KEYWORD_NOBITMAPSCAN,
146 HINT_KEYWORD_NOTIDSCAN,
147 HINT_KEYWORD_INDEXONLYSCAN,
148 HINT_KEYWORD_INDEXONLYSCANREGEXP,
149 HINT_KEYWORD_NOINDEXONLYSCAN,
151 HINT_KEYWORD_NESTLOOP,
152 HINT_KEYWORD_MERGEJOIN,
153 HINT_KEYWORD_HASHJOIN,
154 HINT_KEYWORD_NONESTLOOP,
155 HINT_KEYWORD_NOMERGEJOIN,
156 HINT_KEYWORD_NOHASHJOIN,
158 HINT_KEYWORD_LEADING,
161 HINT_KEYWORD_PARALLEL,
163 HINT_KEYWORD_UNRECOGNIZED
166 #define SCAN_HINT_ACCEPTS_INDEX_NAMES(kw) \
167 (kw == HINT_KEYWORD_INDEXSCAN || \
168 kw == HINT_KEYWORD_INDEXSCANREGEXP || \
169 kw == HINT_KEYWORD_INDEXONLYSCAN || \
170 kw == HINT_KEYWORD_INDEXONLYSCANREGEXP || \
171 kw == HINT_KEYWORD_BITMAPSCAN || \
172 kw == HINT_KEYWORD_BITMAPSCANREGEXP)
175 typedef struct Hint Hint;
176 typedef struct HintState HintState;
178 typedef Hint *(*HintCreateFunction) (const char *hint_str,
180 HintKeyword hint_keyword);
181 typedef void (*HintDeleteFunction) (Hint *hint);
182 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf, bool nolf);
183 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
184 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
185 Query *parse, const char *str);
188 #define NUM_HINT_TYPE 6
189 typedef enum HintType
191 HINT_TYPE_SCAN_METHOD,
192 HINT_TYPE_JOIN_METHOD,
199 typedef enum HintTypeBitmap
201 HINT_BM_SCAN_METHOD = 1,
205 static const char *HintTypeName[] = {
215 typedef enum HintStatus
217 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
218 HINT_STATE_USED, /* hint is used */
219 HINT_STATE_DUPLICATION, /* specified hint duplication */
220 HINT_STATE_ERROR /* execute error (parse error does not include
224 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
225 (hint)->base.state == HINT_STATE_USED)
227 static unsigned int qno = 0;
228 static unsigned int msgqno = 0;
229 static char qnostr[32];
230 static const char *current_hint_str = NULL;
233 * However we usually take a hint stirng in post_parse_analyze_hook, we still
234 * need to do so in planner_hook when client starts query execution from the
235 * bind message on a prepared query. This variable prevent duplicate and
236 * sometimes harmful hint string retrieval.
238 static bool current_hint_retrieved = false;
240 /* common data for all hints. */
243 const char *hint_str; /* must not do pfree */
244 const char *keyword; /* must not do pfree */
245 HintKeyword hint_keyword;
248 HintDeleteFunction delete_func;
249 HintDescFunction desc_func;
250 HintCmpFunction cmp_func;
251 HintParseFunction parse_func;
254 /* scan method hints */
255 typedef struct ScanMethodHint
261 unsigned char enforce_mask;
264 typedef struct ParentIndexInfo
269 char *expression_str;
276 /* join method hints */
277 typedef struct JoinMethodHint
283 unsigned char enforce_mask;
285 Relids inner_joinrelids;
288 /* join order hints */
289 typedef struct OuterInnerRels
292 List *outer_inner_pair;
295 typedef struct LeadingHint
298 List *relations; /* relation names specified in Leading hint */
299 OuterInnerRels *outer_inner;
302 /* change a run-time parameter hints */
303 typedef struct SetHint
306 char *name; /* name of variable */
312 typedef enum RowsValueType {
313 RVT_ABSOLUTE, /* Rows(... #1000) */
314 RVT_ADD, /* Rows(... +1000) */
315 RVT_SUB, /* Rows(... -1000) */
316 RVT_MULTI, /* Rows(... *1.2) */
318 typedef struct RowsHint
325 Relids inner_joinrelids;
327 RowsValueType value_type;
332 typedef struct ParallelHint
336 char *nworkers_str; /* original string of nworkers */
337 int nworkers; /* num of workers specified by Worker */
338 bool force_parallel; /* force parallel scan */
342 * Describes a context of hint processing.
346 char *hint_str; /* original hint string */
349 int nall_hints; /* # of valid all hints */
350 int max_all_hints; /* # of slots for all hints */
351 Hint **all_hints; /* parsed all hints */
353 /* # of each hints */
354 int num_hints[NUM_HINT_TYPE];
356 /* for scan method hints */
357 ScanMethodHint **scan_hints; /* parsed scan hints */
359 /* Initial values of parameters */
360 int init_scan_mask; /* enable_* mask */
361 int init_nworkers; /* max_parallel_workers_per_gather */
362 /* min_parallel_table_scan_size*/
363 int init_min_para_tablescan_size;
364 /* min_parallel_index_scan_size*/
365 int init_min_para_indexscan_size;
366 int init_paratup_cost; /* parallel_tuple_cost */
367 int init_parasetup_cost;/* parallel_setup_cost */
369 PlannerInfo *current_root; /* PlannerInfo for the followings */
370 Index parent_relid; /* inherit parent of table relid */
371 ScanMethodHint *parent_scan_hint; /* scan hint for the parent */
372 ParallelHint *parent_parallel_hint; /* parallel hint for the parent */
373 List *parent_index_infos; /* list of parent table's index */
375 JoinMethodHint **join_hints; /* parsed join hints */
376 int init_join_mask; /* initial value join parameter */
377 List **join_hint_level;
378 LeadingHint **leading_hint; /* parsed Leading hints */
379 SetHint **set_hints; /* parsed Set hints */
380 GucContext context; /* which GUC parameters can we set? */
381 RowsHint **rows_hints; /* parsed Rows hints */
382 ParallelHint **parallel_hints; /* parsed Parallel hints */
386 * Describes a hint parser module which is bound with particular hint keyword.
388 typedef struct HintParser
391 HintCreateFunction create_func;
392 HintKeyword hint_keyword;
395 /* Module callbacks */
399 static void push_hint(HintState *hstate);
400 static void pop_hint(void);
402 static void pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query);
403 static void pg_hint_plan_ProcessUtility(PlannedStmt *pstmt,
404 const char *queryString,
405 ProcessUtilityContext context,
406 ParamListInfo params, QueryEnvironment *queryEnv,
407 DestReceiver *dest, char *completionTag);
408 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
409 ParamListInfo boundParams);
410 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
414 /* Scan method hint callbacks */
415 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
416 HintKeyword hint_keyword);
417 static void ScanMethodHintDelete(ScanMethodHint *hint);
418 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
419 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
420 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
421 Query *parse, const char *str);
423 /* Join method hint callbacks */
424 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
425 HintKeyword hint_keyword);
426 static void JoinMethodHintDelete(JoinMethodHint *hint);
427 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
428 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
429 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
430 Query *parse, const char *str);
432 /* Leading hint callbacks */
433 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
434 HintKeyword hint_keyword);
435 static void LeadingHintDelete(LeadingHint *hint);
436 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
437 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
438 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
439 Query *parse, const char *str);
441 /* Set hint callbacks */
442 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
443 HintKeyword hint_keyword);
444 static void SetHintDelete(SetHint *hint);
445 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
446 static int SetHintCmp(const SetHint *a, const SetHint *b);
447 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
450 /* Rows hint callbacks */
451 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
452 HintKeyword hint_keyword);
453 static void RowsHintDelete(RowsHint *hint);
454 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
455 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
456 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
457 Query *parse, const char *str);
459 /* Parallel hint callbacks */
460 static Hint *ParallelHintCreate(const char *hint_str, const char *keyword,
461 HintKeyword hint_keyword);
462 static void ParallelHintDelete(ParallelHint *hint);
463 static void ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf);
464 static int ParallelHintCmp(const ParallelHint *a, const ParallelHint *b);
465 static const char *ParallelHintParse(ParallelHint *hint, HintState *hstate,
466 Query *parse, const char *str);
468 static void quote_value(StringInfo buf, const char *value);
470 static const char *parse_quoted_value(const char *str, char **word,
473 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
476 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
477 void pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
478 Index rti, RangeTblEntry *rte);
479 static void create_plain_partial_paths(PlannerInfo *root,
481 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
482 ListCell *other_rels);
483 static void make_rels_by_clauseless_joins(PlannerInfo *root,
485 ListCell *other_rels);
486 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
487 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
489 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
490 Index rti, RangeTblEntry *rte);
491 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
494 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
496 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
498 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
502 static int set_config_option_noerror(const char *name, const char *value,
503 GucContext context, GucSource source,
504 GucAction action, bool changeVal, int elevel);
505 static void setup_scan_method_enforcement(ScanMethodHint *scanhint,
507 static int set_config_int32_option(const char *name, int32 value,
511 static bool pg_hint_plan_enable_hint = true;
512 static int debug_level = 0;
513 static int pg_hint_plan_parse_message_level = INFO;
514 static int pg_hint_plan_debug_message_level = LOG;
515 /* Default is off, to keep backward compatibility. */
516 static bool pg_hint_plan_enable_hint_table = false;
518 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
519 static int recurse_level = 0; /* recursion level incl. direct SPI calls */
520 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
521 /* (This could not be above 1) */
522 static int max_hint_nworkers = -1; /* Maximum nworkers of Workers hints */
524 static const struct config_enum_entry parse_messages_level_options[] = {
525 {"debug", DEBUG2, true},
526 {"debug5", DEBUG5, false},
527 {"debug4", DEBUG4, false},
528 {"debug3", DEBUG3, false},
529 {"debug2", DEBUG2, false},
530 {"debug1", DEBUG1, false},
532 {"info", INFO, false},
533 {"notice", NOTICE, false},
534 {"warning", WARNING, false},
535 {"error", ERROR, false},
537 * {"fatal", FATAL, true},
538 * {"panic", PANIC, true},
543 static const struct config_enum_entry parse_debug_level_options[] = {
546 {"detailed", 2, false},
547 {"verbose", 3, false},
559 /* Saved hook values in case of unload */
560 static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
561 static planner_hook_type prev_planner = NULL;
562 static join_search_hook_type prev_join_search = NULL;
563 static set_rel_pathlist_hook_type prev_set_rel_pathlist = NULL;
564 static ProcessUtility_hook_type prev_ProcessUtility_hook = NULL;
566 /* Hold reference to currently active hint */
567 static HintState *current_hint_state = NULL;
570 * List of hint contexts. We treat the head of the list as the Top of the
571 * context stack, so current_hint_state always points the first element of this
574 static List *HintStateStack = NIL;
576 static const HintParser parsers[] = {
577 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
578 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
579 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
580 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
581 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
582 HINT_KEYWORD_BITMAPSCANREGEXP},
583 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
584 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
585 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
586 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
587 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
588 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
589 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
590 HINT_KEYWORD_INDEXONLYSCANREGEXP},
591 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
593 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
594 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
595 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
596 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
597 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
598 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
600 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
601 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
602 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
603 {HINT_PARALLEL, ParallelHintCreate, HINT_KEYWORD_PARALLEL},
605 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
608 PLpgSQL_plugin plugin_funcs = {
612 pg_hint_plan_plpgsql_stmt_beg,
613 pg_hint_plan_plpgsql_stmt_end,
619 * Module load callbacks
624 PLpgSQL_plugin **var_ptr;
626 /* Define custom GUC variables. */
627 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
628 "Force planner to use plans specified in the hint comment preceding to the query.",
630 &pg_hint_plan_enable_hint,
638 DefineCustomEnumVariable("pg_hint_plan.debug_print",
639 "Logs results of hint parsing.",
643 parse_debug_level_options,
650 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
651 "Message level of parse errors.",
653 &pg_hint_plan_parse_message_level,
655 parse_messages_level_options,
662 DefineCustomEnumVariable("pg_hint_plan.message_level",
663 "Message level of debug messages.",
665 &pg_hint_plan_debug_message_level,
667 parse_messages_level_options,
674 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
675 "Let pg_hint_plan look up the hint table.",
677 &pg_hint_plan_enable_hint_table,
686 prev_post_parse_analyze_hook = post_parse_analyze_hook;
687 post_parse_analyze_hook = pg_hint_plan_post_parse_analyze;
688 prev_planner = planner_hook;
689 planner_hook = pg_hint_plan_planner;
690 prev_join_search = join_search_hook;
691 join_search_hook = pg_hint_plan_join_search;
692 prev_set_rel_pathlist = set_rel_pathlist_hook;
693 set_rel_pathlist_hook = pg_hint_plan_set_rel_pathlist;
694 prev_ProcessUtility_hook = ProcessUtility_hook;
695 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
697 /* setup PL/pgSQL plugin hook */
698 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
699 *var_ptr = &plugin_funcs;
701 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
705 * Module unload callback
711 PLpgSQL_plugin **var_ptr;
713 /* Uninstall hooks. */
714 post_parse_analyze_hook = prev_post_parse_analyze_hook;
715 planner_hook = prev_planner;
716 join_search_hook = prev_join_search;
717 set_rel_pathlist_hook = prev_set_rel_pathlist;
718 ProcessUtility_hook = prev_ProcessUtility_hook;
720 /* uninstall PL/pgSQL plugin hook */
721 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
726 * create and delete functions the hint object
730 ScanMethodHintCreate(const char *hint_str, const char *keyword,
731 HintKeyword hint_keyword)
733 ScanMethodHint *hint;
735 hint = palloc(sizeof(ScanMethodHint));
736 hint->base.hint_str = hint_str;
737 hint->base.keyword = keyword;
738 hint->base.hint_keyword = hint_keyword;
739 hint->base.type = HINT_TYPE_SCAN_METHOD;
740 hint->base.state = HINT_STATE_NOTUSED;
741 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
742 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
743 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
744 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
745 hint->relname = NULL;
746 hint->indexnames = NIL;
747 hint->regexp = false;
748 hint->enforce_mask = 0;
750 return (Hint *) hint;
754 ScanMethodHintDelete(ScanMethodHint *hint)
760 pfree(hint->relname);
761 list_free_deep(hint->indexnames);
766 JoinMethodHintCreate(const char *hint_str, const char *keyword,
767 HintKeyword hint_keyword)
769 JoinMethodHint *hint;
771 hint = palloc(sizeof(JoinMethodHint));
772 hint->base.hint_str = hint_str;
773 hint->base.keyword = keyword;
774 hint->base.hint_keyword = hint_keyword;
775 hint->base.type = HINT_TYPE_JOIN_METHOD;
776 hint->base.state = HINT_STATE_NOTUSED;
777 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
778 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
779 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
780 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
782 hint->inner_nrels = 0;
783 hint->relnames = NULL;
784 hint->enforce_mask = 0;
785 hint->joinrelids = NULL;
786 hint->inner_joinrelids = NULL;
788 return (Hint *) hint;
792 JoinMethodHintDelete(JoinMethodHint *hint)
801 for (i = 0; i < hint->nrels; i++)
802 pfree(hint->relnames[i]);
803 pfree(hint->relnames);
806 bms_free(hint->joinrelids);
807 bms_free(hint->inner_joinrelids);
812 LeadingHintCreate(const char *hint_str, const char *keyword,
813 HintKeyword hint_keyword)
817 hint = palloc(sizeof(LeadingHint));
818 hint->base.hint_str = hint_str;
819 hint->base.keyword = keyword;
820 hint->base.hint_keyword = hint_keyword;
821 hint->base.type = HINT_TYPE_LEADING;
822 hint->base.state = HINT_STATE_NOTUSED;
823 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
824 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
825 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
826 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
827 hint->relations = NIL;
828 hint->outer_inner = NULL;
830 return (Hint *) hint;
834 LeadingHintDelete(LeadingHint *hint)
839 list_free_deep(hint->relations);
840 if (hint->outer_inner)
841 pfree(hint->outer_inner);
846 SetHintCreate(const char *hint_str, const char *keyword,
847 HintKeyword hint_keyword)
851 hint = palloc(sizeof(SetHint));
852 hint->base.hint_str = hint_str;
853 hint->base.keyword = keyword;
854 hint->base.hint_keyword = hint_keyword;
855 hint->base.type = HINT_TYPE_SET;
856 hint->base.state = HINT_STATE_NOTUSED;
857 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
858 hint->base.desc_func = (HintDescFunction) SetHintDesc;
859 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
860 hint->base.parse_func = (HintParseFunction) SetHintParse;
865 return (Hint *) hint;
869 SetHintDelete(SetHint *hint)
879 list_free(hint->words);
884 RowsHintCreate(const char *hint_str, const char *keyword,
885 HintKeyword hint_keyword)
889 hint = palloc(sizeof(RowsHint));
890 hint->base.hint_str = hint_str;
891 hint->base.keyword = keyword;
892 hint->base.hint_keyword = hint_keyword;
893 hint->base.type = HINT_TYPE_ROWS;
894 hint->base.state = HINT_STATE_NOTUSED;
895 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
896 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
897 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
898 hint->base.parse_func = (HintParseFunction) RowsHintParse;
900 hint->inner_nrels = 0;
901 hint->relnames = NULL;
902 hint->joinrelids = NULL;
903 hint->inner_joinrelids = NULL;
904 hint->rows_str = NULL;
905 hint->value_type = RVT_ABSOLUTE;
908 return (Hint *) hint;
912 RowsHintDelete(RowsHint *hint)
921 for (i = 0; i < hint->nrels; i++)
922 pfree(hint->relnames[i]);
923 pfree(hint->relnames);
926 bms_free(hint->joinrelids);
927 bms_free(hint->inner_joinrelids);
932 ParallelHintCreate(const char *hint_str, const char *keyword,
933 HintKeyword hint_keyword)
937 hint = palloc(sizeof(ParallelHint));
938 hint->base.hint_str = hint_str;
939 hint->base.keyword = keyword;
940 hint->base.hint_keyword = hint_keyword;
941 hint->base.type = HINT_TYPE_PARALLEL;
942 hint->base.state = HINT_STATE_NOTUSED;
943 hint->base.delete_func = (HintDeleteFunction) ParallelHintDelete;
944 hint->base.desc_func = (HintDescFunction) ParallelHintDesc;
945 hint->base.cmp_func = (HintCmpFunction) ParallelHintCmp;
946 hint->base.parse_func = (HintParseFunction) ParallelHintParse;
947 hint->relname = NULL;
949 hint->nworkers_str = "0";
951 return (Hint *) hint;
955 ParallelHintDelete(ParallelHint *hint)
961 pfree(hint->relname);
967 HintStateCreate(void)
971 hstate = palloc(sizeof(HintState));
972 hstate->hint_str = NULL;
973 hstate->nall_hints = 0;
974 hstate->max_all_hints = 0;
975 hstate->all_hints = NULL;
976 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
977 hstate->scan_hints = NULL;
978 hstate->init_scan_mask = 0;
979 hstate->init_nworkers = 0;
980 hstate->init_min_para_tablescan_size = 0;
981 hstate->init_min_para_indexscan_size = 0;
982 hstate->init_paratup_cost = 0;
983 hstate->init_parasetup_cost = 0;
984 hstate->current_root = NULL;
985 hstate->parent_relid = 0;
986 hstate->parent_scan_hint = NULL;
987 hstate->parent_parallel_hint = NULL;
988 hstate->parent_index_infos = NIL;
989 hstate->join_hints = NULL;
990 hstate->init_join_mask = 0;
991 hstate->join_hint_level = NULL;
992 hstate->leading_hint = NULL;
993 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
994 hstate->set_hints = NULL;
995 hstate->rows_hints = NULL;
996 hstate->parallel_hints = NULL;
1002 HintStateDelete(HintState *hstate)
1009 if (hstate->hint_str)
1010 pfree(hstate->hint_str);
1012 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1013 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
1014 if (hstate->all_hints)
1015 pfree(hstate->all_hints);
1016 if (hstate->parent_index_infos)
1017 list_free(hstate->parent_index_infos);
1021 * Copy given value into buf, with quoting with '"' if necessary.
1024 quote_value(StringInfo buf, const char *value)
1026 bool need_quote = false;
1029 for (str = value; *str != '\0'; str++)
1031 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
1034 appendStringInfoCharMacro(buf, '"');
1039 for (str = value; *str != '\0'; str++)
1042 appendStringInfoCharMacro(buf, '"');
1044 appendStringInfoCharMacro(buf, *str);
1048 appendStringInfoCharMacro(buf, '"');
1052 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
1056 appendStringInfo(buf, "%s(", hint->base.keyword);
1057 if (hint->relname != NULL)
1059 quote_value(buf, hint->relname);
1060 foreach(l, hint->indexnames)
1062 appendStringInfoCharMacro(buf, ' ');
1063 quote_value(buf, (char *) lfirst(l));
1066 appendStringInfoString(buf, ")");
1068 appendStringInfoChar(buf, '\n');
1072 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
1076 appendStringInfo(buf, "%s(", hint->base.keyword);
1077 if (hint->relnames != NULL)
1079 quote_value(buf, hint->relnames[0]);
1080 for (i = 1; i < hint->nrels; i++)
1082 appendStringInfoCharMacro(buf, ' ');
1083 quote_value(buf, hint->relnames[i]);
1086 appendStringInfoString(buf, ")");
1088 appendStringInfoChar(buf, '\n');
1092 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
1094 if (outer_inner->relation == NULL)
1101 appendStringInfoCharMacro(buf, '(');
1102 foreach(l, outer_inner->outer_inner_pair)
1107 appendStringInfoCharMacro(buf, ' ');
1109 OuterInnerDesc(lfirst(l), buf);
1112 appendStringInfoCharMacro(buf, ')');
1115 quote_value(buf, outer_inner->relation);
1119 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
1121 appendStringInfo(buf, "%s(", HINT_LEADING);
1122 if (hint->outer_inner == NULL)
1129 foreach(l, hint->relations)
1134 appendStringInfoCharMacro(buf, ' ');
1136 quote_value(buf, (char *) lfirst(l));
1140 OuterInnerDesc(hint->outer_inner, buf);
1142 appendStringInfoString(buf, ")");
1144 appendStringInfoChar(buf, '\n');
1148 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1150 bool is_first = true;
1153 appendStringInfo(buf, "%s(", HINT_SET);
1154 foreach(l, hint->words)
1159 appendStringInfoCharMacro(buf, ' ');
1161 quote_value(buf, (char *) lfirst(l));
1163 appendStringInfo(buf, ")");
1165 appendStringInfoChar(buf, '\n');
1169 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1173 appendStringInfo(buf, "%s(", hint->base.keyword);
1174 if (hint->relnames != NULL)
1176 quote_value(buf, hint->relnames[0]);
1177 for (i = 1; i < hint->nrels; i++)
1179 appendStringInfoCharMacro(buf, ' ');
1180 quote_value(buf, hint->relnames[i]);
1183 appendStringInfo(buf, " %s", hint->rows_str);
1184 appendStringInfoString(buf, ")");
1186 appendStringInfoChar(buf, '\n');
1190 ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf)
1192 appendStringInfo(buf, "%s(", hint->base.keyword);
1193 if (hint->relname != NULL)
1195 quote_value(buf, hint->relname);
1197 /* number of workers */
1198 appendStringInfoCharMacro(buf, ' ');
1199 quote_value(buf, hint->nworkers_str);
1200 /* application mode of num of workers */
1201 appendStringInfoCharMacro(buf, ' ');
1202 appendStringInfoString(buf,
1203 (hint->force_parallel ? "hard" : "soft"));
1205 appendStringInfoString(buf, ")");
1207 appendStringInfoChar(buf, '\n');
1211 * Append string which represents all hints in a given state to buf, with
1212 * preceding title with them.
1215 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1216 HintStatus state, bool nolf)
1220 appendStringInfo(buf, "%s:", title);
1222 appendStringInfoChar(buf, '\n');
1225 for (i = 0; i < hstate->nall_hints; i++)
1227 if (hstate->all_hints[i]->state != state)
1230 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1234 if (nolf && nshown == 0)
1235 appendStringInfoString(buf, "(none)");
1239 * Dump contents of given hstate to server log with log level LOG.
1242 HintStateDump(HintState *hstate)
1248 elog(pg_hint_plan_debug_message_level, "pg_hint_plan:\nno hint");
1252 initStringInfo(&buf);
1254 appendStringInfoString(&buf, "pg_hint_plan:\n");
1255 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1256 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1257 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1258 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1260 ereport(pg_hint_plan_debug_message_level,
1261 (errmsg ("%s", buf.data)));
1267 HintStateDump2(HintState *hstate)
1273 elog(pg_hint_plan_debug_message_level,
1274 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1278 initStringInfo(&buf);
1279 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1280 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1281 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1282 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1283 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1284 appendStringInfoChar(&buf, '}');
1286 ereport(pg_hint_plan_debug_message_level,
1287 (errmsg("%s", buf.data),
1289 errhidecontext(true)));
1299 RelnameCmp(const void *a, const void *b)
1301 const char *relnamea = *((const char **) a);
1302 const char *relnameb = *((const char **) b);
1304 return strcmp(relnamea, relnameb);
1308 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1310 return RelnameCmp(&a->relname, &b->relname);
1314 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1318 if (a->nrels != b->nrels)
1319 return a->nrels - b->nrels;
1321 for (i = 0; i < a->nrels; i++)
1324 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1332 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1338 SetHintCmp(const SetHint *a, const SetHint *b)
1340 return strcmp(a->name, b->name);
1344 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1348 if (a->nrels != b->nrels)
1349 return a->nrels - b->nrels;
1351 for (i = 0; i < a->nrels; i++)
1354 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1362 ParallelHintCmp(const ParallelHint *a, const ParallelHint *b)
1364 return RelnameCmp(&a->relname, &b->relname);
1368 HintCmp(const void *a, const void *b)
1370 const Hint *hinta = *((const Hint **) a);
1371 const Hint *hintb = *((const Hint **) b);
1373 if (hinta->type != hintb->type)
1374 return hinta->type - hintb->type;
1375 if (hinta->state == HINT_STATE_ERROR)
1377 if (hintb->state == HINT_STATE_ERROR)
1379 return hinta->cmp_func(hinta, hintb);
1383 * Returns byte offset of hint b from hint a. If hint a was specified before
1384 * b, positive value is returned.
1387 HintCmpWithPos(const void *a, const void *b)
1389 const Hint *hinta = *((const Hint **) a);
1390 const Hint *hintb = *((const Hint **) b);
1393 result = HintCmp(a, b);
1395 result = hinta->hint_str - hintb->hint_str;
1404 parse_keyword(const char *str, StringInfo buf)
1408 while (!isspace(*str) && *str != '(' && *str != '\0')
1409 appendStringInfoCharMacro(buf, *str++);
1415 skip_parenthesis(const char *str, char parenthesis)
1419 if (*str != parenthesis)
1421 if (parenthesis == '(')
1422 hint_ereport(str, ("Opening parenthesis is necessary."));
1423 else if (parenthesis == ')')
1424 hint_ereport(str, ("Closing parenthesis is necessary."));
1435 * Parse a token from str, and store malloc'd copy into word. A token can be
1436 * quoted with '"'. Return value is pointer to unparsed portion of original
1437 * string, or NULL if an error occurred.
1439 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1442 parse_quoted_value(const char *str, char **word, bool truncate)
1447 /* Skip leading spaces. */
1450 initStringInfo(&buf);
1463 /* Double quotation must be closed. */
1467 hint_ereport(str, ("Unterminated quoted string."));
1472 * Skip escaped double quotation.
1474 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1475 * block comments) to be an object name, so users must specify
1476 * alias for such object names.
1478 * Those special names can be allowed if we care escaped slashes
1479 * and asterisks, but we don't.
1488 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1492 appendStringInfoCharMacro(&buf, *str++);
1497 hint_ereport(str, ("Zero-length delimited string."));
1504 /* Truncate name if it's too long */
1506 truncate_identifier(buf.data, strlen(buf.data), true);
1513 static OuterInnerRels *
1514 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1516 OuterInnerRels *outer_inner;
1518 outer_inner = palloc(sizeof(OuterInnerRels));
1519 outer_inner->relation = name;
1520 outer_inner->outer_inner_pair = outer_inner_list;
1526 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1528 List *outer_inner_pair = NIL;
1530 if ((str = skip_parenthesis(str, '(')) == NULL)
1535 /* Store words in parentheses into outer_inner_list. */
1536 while(*str != ')' && *str != '\0')
1538 OuterInnerRels *outer_inner_rels;
1542 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1550 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1553 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1556 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1561 (str = skip_parenthesis(str, ')')) == NULL)
1563 list_free(outer_inner_pair);
1567 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1573 parse_parentheses_Leading(const char *str, List **name_list,
1574 OuterInnerRels **outer_inner)
1577 bool truncate = true;
1579 if ((str = skip_parenthesis(str, '(')) == NULL)
1585 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1590 /* Store words in parentheses into name_list. */
1591 while(*str != ')' && *str != '\0')
1593 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1595 list_free(*name_list);
1599 *name_list = lappend(*name_list, name);
1604 if ((str = skip_parenthesis(str, ')')) == NULL)
1610 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1613 bool truncate = true;
1615 if ((str = skip_parenthesis(str, '(')) == NULL)
1620 /* Store words in parentheses into name_list. */
1621 while(*str != ')' && *str != '\0')
1623 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1625 list_free(*name_list);
1629 *name_list = lappend(*name_list, name);
1632 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1633 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1634 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1635 keyword == HINT_KEYWORD_SET)
1641 if ((str = skip_parenthesis(str, ')')) == NULL)
1647 parse_hints(HintState *hstate, Query *parse, const char *str)
1652 initStringInfo(&buf);
1653 while (*str != '\0')
1655 const HintParser *parser;
1657 /* in error message, we output the comment including the keyword. */
1658 head = (char *) str;
1660 /* parse only the keyword of the hint. */
1661 resetStringInfo(&buf);
1662 str = parse_keyword(str, &buf);
1664 for (parser = parsers; parser->keyword != NULL; parser++)
1666 char *keyword = parser->keyword;
1669 if (pg_strcasecmp(buf.data, keyword) != 0)
1672 hint = parser->create_func(head, keyword, parser->hint_keyword);
1674 /* parser of each hint does parse in a parenthesis. */
1675 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1677 hint->delete_func(hint);
1683 * Add hint information into all_hints array. If we don't have
1684 * enough space, double the array.
1686 if (hstate->nall_hints == 0)
1688 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1689 hstate->all_hints = (Hint **)
1690 palloc(sizeof(Hint *) * hstate->max_all_hints);
1692 else if (hstate->nall_hints == hstate->max_all_hints)
1694 hstate->max_all_hints *= 2;
1695 hstate->all_hints = (Hint **)
1696 repalloc(hstate->all_hints,
1697 sizeof(Hint *) * hstate->max_all_hints);
1700 hstate->all_hints[hstate->nall_hints] = hint;
1701 hstate->nall_hints++;
1708 if (parser->keyword == NULL)
1711 ("Unrecognized hint keyword \"%s\".", buf.data));
1722 * Get hints from table by client-supplied query string and application name.
1725 get_hints_from_table(const char *client_query, const char *client_application)
1727 const char *search_query =
1729 " FROM hint_plan.hints "
1730 " WHERE norm_query_string = $1 "
1731 " AND ( application_name = $2 "
1732 " OR application_name = '' ) "
1733 " ORDER BY application_name DESC";
1734 static SPIPlanPtr plan = NULL;
1736 Oid argtypes[2] = { TEXTOID, TEXTOID };
1738 char nulls[2] = {' ', ' '};
1744 bool snapshot_set = false;
1746 hint_inhibit_level++;
1748 if (!ActiveSnapshotSet())
1750 PushActiveSnapshot(GetTransactionSnapshot());
1751 snapshot_set = true;
1759 p = SPI_prepare(search_query, 2, argtypes);
1760 plan = SPI_saveplan(p);
1764 qry = cstring_to_text(client_query);
1765 app = cstring_to_text(client_application);
1766 values[0] = PointerGetDatum(qry);
1767 values[1] = PointerGetDatum(app);
1769 SPI_execute_plan(plan, values, nulls, true, 1);
1771 if (SPI_processed > 0)
1775 hints = SPI_getvalue(SPI_tuptable->vals[0],
1776 SPI_tuptable->tupdesc, 1);
1778 * Here we use SPI_palloc to ensure that hints string is valid even
1779 * after SPI_finish call. We can't use simple palloc because it
1780 * allocates memory in SPI's context and that context is deleted in
1783 buf = SPI_palloc(strlen(hints) + 1);
1791 PopActiveSnapshot();
1793 hint_inhibit_level--;
1797 hint_inhibit_level--;
1806 * Get client-supplied query string. Addtion to that the jumbled query is
1807 * supplied if the caller requested. From the restriction of JumbleQuery, some
1808 * kind of query needs special amendments. Reutrns NULL if this query doesn't
1809 * change the current hint. This function returns NULL also when something
1810 * wrong has happend and let the caller continue using the current hints.
1813 get_query_string(ParseState *pstate, Query *query, Query **jumblequery)
1815 const char *p = debug_query_string;
1818 * If debug_query_string is set, it is the top level statement. But in some
1819 * cases we reach here with debug_query_string set NULL for example in the
1820 * case of DESCRIBE message handling or EXECUTE command. We may still see a
1821 * candidate top-level query in pstate in the case.
1823 if (pstate && pstate->p_sourcetext)
1824 p = pstate->p_sourcetext;
1826 /* We don't see a query string, return NULL */
1830 if (jumblequery != NULL)
1831 *jumblequery = query;
1833 if (query->commandType == CMD_UTILITY)
1835 Query *target_query = (Query *)query->utilityStmt;
1838 * Some CMD_UTILITY statements have a subquery that we can hint on.
1839 * Since EXPLAIN can be placed before other kind of utility statements
1840 * and EXECUTE can be contained other kind of utility statements, these
1841 * conditions are not mutually exclusive and should be considered in
1844 if (IsA(target_query, ExplainStmt))
1846 ExplainStmt *stmt = (ExplainStmt *)target_query;
1848 Assert(IsA(stmt->query, Query));
1849 target_query = (Query *)stmt->query;
1851 /* strip out the top-level query for further processing */
1852 if (target_query->commandType == CMD_UTILITY &&
1853 target_query->utilityStmt != NULL)
1854 target_query = (Query *)target_query->utilityStmt;
1857 if (IsA(target_query, DeclareCursorStmt))
1859 DeclareCursorStmt *stmt = (DeclareCursorStmt *)target_query;
1860 Query *query = (Query *)stmt->query;
1862 /* the target must be CMD_SELECT in this case */
1863 Assert(IsA(query, Query) && query->commandType == CMD_SELECT);
1864 target_query = query;
1867 if (IsA(target_query, CreateTableAsStmt))
1869 CreateTableAsStmt *stmt = (CreateTableAsStmt *) target_query;
1871 Assert(IsA(stmt->query, Query));
1872 target_query = (Query *) stmt->query;
1874 /* strip out the top-level query for further processing */
1875 if (target_query->commandType == CMD_UTILITY &&
1876 target_query->utilityStmt != NULL)
1877 target_query = (Query *)target_query->utilityStmt;
1880 if (IsA(target_query, ExecuteStmt))
1883 * Use the prepared query for EXECUTE. The Query for jumble
1884 * also replaced with the corresponding one.
1886 ExecuteStmt *stmt = (ExecuteStmt *)target_query;
1887 PreparedStatement *entry;
1889 entry = FetchPreparedStatement(stmt->name, true);
1891 if (entry->plansource->is_valid)
1893 p = entry->plansource->query_string;
1894 target_query = (Query *) linitial (entry->plansource->query_list);
1898 /* igonre the hint for EXECUTE if invalidated */
1900 target_query = NULL;
1904 /* JumbleQuery accespts only a non-utility Query */
1906 (!IsA(target_query, Query) ||
1907 target_query->utilityStmt != NULL))
1908 target_query = NULL;
1911 *jumblequery = target_query;
1914 * Return NULL if pstate is not of top-level query. We don't need this
1915 * when jumble info is not requested or cannot do this when pstate is NULL.
1917 else if (!jumblequery && pstate && pstate->p_sourcetext != p &&
1918 strcmp(pstate->p_sourcetext, p) != 0)
1925 * Get hints from the head block comment in client-supplied query string.
1928 get_hints_from_comment(const char *p)
1930 const char *hint_head;
1938 /* extract query head comment. */
1939 hint_head = strstr(p, HINT_START);
1940 if (hint_head == NULL)
1942 for (;p < hint_head; p++)
1945 * Allow these characters precedes hint comment:
1947 * - alphabets which are in ASCII range
1948 * - space, tabs and new-lines
1949 * - underscores, for identifier
1950 * - commas, for SELECT clause, EXPLAIN and PREPARE
1951 * - parentheses, for EXPLAIN and PREPARE
1953 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1954 * avoid behavior which depends on locale setting.
1956 if (!(*p >= '0' && *p <= '9') &&
1957 !(*p >= 'A' && *p <= 'Z') &&
1958 !(*p >= 'a' && *p <= 'z') &&
1962 *p != '(' && *p != ')')
1966 len = strlen(HINT_START);
1971 /* find hint end keyword. */
1972 if ((tail = strstr(p, HINT_END)) == NULL)
1974 hint_ereport(head, ("Unterminated block comment."));
1978 /* We don't support nested block comments. */
1979 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1981 hint_ereport(head, ("Nested block comments are not supported."));
1985 /* Make a copy of hint. */
1987 head = palloc(len + 1);
1988 memcpy(head, p, len);
1996 * Parse hints that got, create hint struct from parse tree and parse hints.
1999 create_hintstate(Query *parse, const char *hints)
2008 /* -1 means that no Parallel hint is specified. */
2009 max_hint_nworkers = -1;
2012 hstate = HintStateCreate();
2013 hstate->hint_str = (char *) hints;
2015 /* parse each hint. */
2016 parse_hints(hstate, parse, p);
2018 /* When nothing specified a hint, we free HintState and returns NULL. */
2019 if (hstate->nall_hints == 0)
2021 HintStateDelete(hstate);
2025 /* Sort hints in order of original position. */
2026 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
2029 /* Count number of hints per hint-type. */
2030 for (i = 0; i < hstate->nall_hints; i++)
2032 Hint *cur_hint = hstate->all_hints[i];
2033 hstate->num_hints[cur_hint->type]++;
2037 * If an object (or a set of objects) has multiple hints of same hint-type,
2038 * only the last hint is valid and others are ignored in planning.
2039 * Hints except the last are marked as 'duplicated' to remember the order.
2041 for (i = 0; i < hstate->nall_hints - 1; i++)
2043 Hint *cur_hint = hstate->all_hints[i];
2044 Hint *next_hint = hstate->all_hints[i + 1];
2047 * Leading hint is marked as 'duplicated' in transform_join_hints.
2049 if (cur_hint->type == HINT_TYPE_LEADING &&
2050 next_hint->type == HINT_TYPE_LEADING)
2054 * Note that we need to pass addresses of hint pointers, because
2055 * HintCmp is designed to sort array of Hint* by qsort.
2057 if (HintCmp(&cur_hint, &next_hint) == 0)
2059 hint_ereport(cur_hint->hint_str,
2060 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
2061 cur_hint->state = HINT_STATE_DUPLICATION;
2066 * Make sure that per-type array pointers point proper position in the
2067 * array which consists of all hints.
2069 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
2070 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
2071 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
2072 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
2073 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
2074 hstate->set_hints = (SetHint **) (hstate->leading_hint +
2075 hstate->num_hints[HINT_TYPE_LEADING]);
2076 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
2077 hstate->num_hints[HINT_TYPE_SET]);
2078 hstate->parallel_hints = (ParallelHint **) (hstate->set_hints +
2079 hstate->num_hints[HINT_TYPE_ROWS]);
2085 * Parse inside of parentheses of scan-method hints.
2088 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
2091 const char *keyword = hint->base.keyword;
2092 HintKeyword hint_keyword = hint->base.hint_keyword;
2093 List *name_list = NIL;
2096 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2099 /* Parse relation name and index name(s) if given hint accepts. */
2100 length = list_length(name_list);
2102 /* at least twp parameters required */
2106 ("%s hint requires a relation.", hint->base.keyword));
2107 hint->base.state = HINT_STATE_ERROR;
2111 hint->relname = linitial(name_list);
2112 hint->indexnames = list_delete_first(name_list);
2114 /* check whether the hint accepts index name(s) */
2115 if (length > 1 && !SCAN_HINT_ACCEPTS_INDEX_NAMES(hint_keyword))
2118 ("%s hint accepts only one relation.",
2119 hint->base.keyword));
2120 hint->base.state = HINT_STATE_ERROR;
2124 /* Set a bit for specified hint. */
2125 switch (hint_keyword)
2127 case HINT_KEYWORD_SEQSCAN:
2128 hint->enforce_mask = ENABLE_SEQSCAN;
2130 case HINT_KEYWORD_INDEXSCAN:
2131 hint->enforce_mask = ENABLE_INDEXSCAN;
2133 case HINT_KEYWORD_INDEXSCANREGEXP:
2134 hint->enforce_mask = ENABLE_INDEXSCAN;
2135 hint->regexp = true;
2137 case HINT_KEYWORD_BITMAPSCAN:
2138 hint->enforce_mask = ENABLE_BITMAPSCAN;
2140 case HINT_KEYWORD_BITMAPSCANREGEXP:
2141 hint->enforce_mask = ENABLE_BITMAPSCAN;
2142 hint->regexp = true;
2144 case HINT_KEYWORD_TIDSCAN:
2145 hint->enforce_mask = ENABLE_TIDSCAN;
2147 case HINT_KEYWORD_NOSEQSCAN:
2148 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
2150 case HINT_KEYWORD_NOINDEXSCAN:
2151 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
2153 case HINT_KEYWORD_NOBITMAPSCAN:
2154 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
2156 case HINT_KEYWORD_NOTIDSCAN:
2157 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
2159 case HINT_KEYWORD_INDEXONLYSCAN:
2160 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2162 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
2163 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2164 hint->regexp = true;
2166 case HINT_KEYWORD_NOINDEXONLYSCAN:
2167 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
2170 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2179 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2182 const char *keyword = hint->base.keyword;
2183 HintKeyword hint_keyword = hint->base.hint_keyword;
2184 List *name_list = NIL;
2186 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2189 hint->nrels = list_length(name_list);
2191 if (hint->nrels > 0)
2197 * Transform relation names from list to array to sort them with qsort
2200 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2201 foreach (l, name_list)
2203 hint->relnames[i] = lfirst(l);
2208 list_free(name_list);
2210 /* A join hint requires at least two relations */
2211 if (hint->nrels < 2)
2214 ("%s hint requires at least two relations.",
2215 hint->base.keyword));
2216 hint->base.state = HINT_STATE_ERROR;
2220 /* Sort hints in alphabetical order of relation names. */
2221 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2223 switch (hint_keyword)
2225 case HINT_KEYWORD_NESTLOOP:
2226 hint->enforce_mask = ENABLE_NESTLOOP;
2228 case HINT_KEYWORD_MERGEJOIN:
2229 hint->enforce_mask = ENABLE_MERGEJOIN;
2231 case HINT_KEYWORD_HASHJOIN:
2232 hint->enforce_mask = ENABLE_HASHJOIN;
2234 case HINT_KEYWORD_NONESTLOOP:
2235 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2237 case HINT_KEYWORD_NOMERGEJOIN:
2238 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2240 case HINT_KEYWORD_NOHASHJOIN:
2241 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2244 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2253 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2256 if (outer_inner->outer_inner_pair == NIL)
2258 if (outer_inner->relation)
2264 if (list_length(outer_inner->outer_inner_pair) == 2)
2266 foreach(l, outer_inner->outer_inner_pair)
2268 if (!OuterInnerPairCheck(lfirst(l)))
2279 OuterInnerList(OuterInnerRels *outer_inner)
2281 List *outer_inner_list = NIL;
2283 OuterInnerRels *outer_inner_rels;
2285 foreach(l, outer_inner->outer_inner_pair)
2287 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2289 if (outer_inner_rels->relation != NULL)
2290 outer_inner_list = lappend(outer_inner_list,
2291 outer_inner_rels->relation);
2293 outer_inner_list = list_concat(outer_inner_list,
2294 OuterInnerList(outer_inner_rels));
2296 return outer_inner_list;
2300 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2303 List *name_list = NIL;
2304 OuterInnerRels *outer_inner = NULL;
2306 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2310 if (outer_inner != NULL)
2311 name_list = OuterInnerList(outer_inner);
2313 hint->relations = name_list;
2314 hint->outer_inner = outer_inner;
2316 /* A Leading hint requires at least two relations */
2317 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2319 hint_ereport(hint->base.hint_str,
2320 ("%s hint requires at least two relations.",
2322 hint->base.state = HINT_STATE_ERROR;
2324 else if (hint->outer_inner != NULL &&
2325 !OuterInnerPairCheck(hint->outer_inner))
2327 hint_ereport(hint->base.hint_str,
2328 ("%s hint requires two sets of relations when parentheses nests.",
2330 hint->base.state = HINT_STATE_ERROR;
2337 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2339 List *name_list = NIL;
2341 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2345 hint->words = name_list;
2347 /* We need both name and value to set GUC parameter. */
2348 if (list_length(name_list) == 2)
2350 hint->name = linitial(name_list);
2351 hint->value = lsecond(name_list);
2355 hint_ereport(hint->base.hint_str,
2356 ("%s hint requires name and value of GUC parameter.",
2358 hint->base.state = HINT_STATE_ERROR;
2365 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2368 HintKeyword hint_keyword = hint->base.hint_keyword;
2369 List *name_list = NIL;
2373 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2376 /* Last element must be rows specification */
2377 hint->nrels = list_length(name_list) - 1;
2379 if (hint->nrels > 0)
2385 * Transform relation names from list to array to sort them with qsort
2388 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2389 foreach (l, name_list)
2391 if (hint->nrels <= i)
2393 hint->relnames[i] = lfirst(l);
2398 /* Retieve rows estimation */
2399 rows_str = list_nth(name_list, hint->nrels);
2400 hint->rows_str = rows_str; /* store as-is for error logging */
2401 if (rows_str[0] == '#')
2403 hint->value_type = RVT_ABSOLUTE;
2406 else if (rows_str[0] == '+')
2408 hint->value_type = RVT_ADD;
2411 else if (rows_str[0] == '-')
2413 hint->value_type = RVT_SUB;
2416 else if (rows_str[0] == '*')
2418 hint->value_type = RVT_MULTI;
2423 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2424 hint->base.state = HINT_STATE_ERROR;
2427 hint->rows = strtod(rows_str, &end_ptr);
2430 hint_ereport(rows_str,
2431 ("%s hint requires valid number as rows estimation.",
2432 hint->base.keyword));
2433 hint->base.state = HINT_STATE_ERROR;
2437 /* A join hint requires at least two relations */
2438 if (hint->nrels < 2)
2441 ("%s hint requires at least two relations.",
2442 hint->base.keyword));
2443 hint->base.state = HINT_STATE_ERROR;
2447 list_free(name_list);
2449 /* Sort relnames in alphabetical order. */
2450 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2456 ParallelHintParse(ParallelHint *hint, HintState *hstate, Query *parse,
2459 HintKeyword hint_keyword = hint->base.hint_keyword;
2460 List *name_list = NIL;
2464 bool force_parallel = false;
2466 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2469 /* Parse relation name and index name(s) if given hint accepts. */
2470 length = list_length(name_list);
2472 if (length < 2 || length > 3)
2475 ("wrong number of arguments (%d): %s",
2476 length, hint->base.keyword));
2477 hint->base.state = HINT_STATE_ERROR;
2481 hint->relname = linitial(name_list);
2483 /* The second parameter is number of workers */
2484 hint->nworkers_str = list_nth(name_list, 1);
2485 nworkers = strtod(hint->nworkers_str, &end_ptr);
2486 if (*end_ptr || nworkers < 0 || nworkers > max_worker_processes)
2489 hint_ereport(hint->nworkers_str,
2490 ("number of workers must be a number: %s",
2491 hint->base.keyword));
2492 else if (nworkers < 0)
2493 hint_ereport(hint->nworkers_str,
2494 ("number of workers must be positive: %s",
2495 hint->base.keyword));
2496 else if (nworkers > max_worker_processes)
2497 hint_ereport(hint->nworkers_str,
2498 ("number of workers = %d is larger than max_worker_processes(%d): %s",
2499 nworkers, max_worker_processes, hint->base.keyword));
2501 hint->base.state = HINT_STATE_ERROR;
2504 hint->nworkers = nworkers;
2506 /* optional third parameter is specified */
2509 const char *modeparam = (const char *)list_nth(name_list, 2);
2510 if (pg_strcasecmp(modeparam, "hard") == 0)
2511 force_parallel = true;
2512 else if (pg_strcasecmp(modeparam, "soft") != 0)
2514 hint_ereport(modeparam,
2515 ("enforcement must be soft or hard: %s",
2516 hint->base.keyword));
2517 hint->base.state = HINT_STATE_ERROR;
2521 hint->force_parallel = force_parallel;
2523 if (hint->base.state != HINT_STATE_ERROR &&
2524 nworkers > max_hint_nworkers)
2525 max_hint_nworkers = nworkers;
2531 * set GUC parameter functions
2535 get_current_scan_mask()
2540 mask |= ENABLE_SEQSCAN;
2541 if (enable_indexscan)
2542 mask |= ENABLE_INDEXSCAN;
2543 if (enable_bitmapscan)
2544 mask |= ENABLE_BITMAPSCAN;
2546 mask |= ENABLE_TIDSCAN;
2547 if (enable_indexonlyscan)
2548 mask |= ENABLE_INDEXONLYSCAN;
2554 get_current_join_mask()
2558 if (enable_nestloop)
2559 mask |= ENABLE_NESTLOOP;
2560 if (enable_mergejoin)
2561 mask |= ENABLE_MERGEJOIN;
2562 if (enable_hashjoin)
2563 mask |= ENABLE_HASHJOIN;
2569 * Sets GUC prameters without throwing exception. Reutrns false if something
2573 set_config_option_noerror(const char *name, const char *value,
2574 GucContext context, GucSource source,
2575 GucAction action, bool changeVal, int elevel)
2578 MemoryContext ccxt = CurrentMemoryContext;
2582 result = set_config_option(name, value, context, source,
2583 action, changeVal, 0, false);
2589 /* Save error info */
2590 MemoryContextSwitchTo(ccxt);
2591 errdata = CopyErrorData();
2595 (errcode(errdata->sqlerrcode),
2596 errmsg("%s", errdata->message),
2597 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2598 errdata->hint ? errhint("%s", errdata->hint) : 0));
2600 FreeErrorData(errdata);
2608 * Sets GUC parameter of int32 type without throwing exceptions. Returns false
2609 * if something wrong.
2612 set_config_int32_option(const char *name, int32 value, GucContext context)
2614 char buf[16]; /* enough for int32 */
2616 if (snprintf(buf, 16, "%d", value) < 0)
2618 ereport(pg_hint_plan_parse_message_level,
2619 (errmsg ("Failed to convert integer to string: %d", value)));
2624 set_config_option_noerror(name, buf, context,
2625 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2626 pg_hint_plan_parse_message_level);
2629 /* setup scan method enforcement according to given options */
2631 setup_guc_enforcement(SetHint **options, int noptions, GucContext context)
2635 for (i = 0; i < noptions; i++)
2637 SetHint *hint = options[i];
2640 if (!hint_state_enabled(hint))
2643 result = set_config_option_noerror(hint->name, hint->value, context,
2644 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2645 pg_hint_plan_parse_message_level);
2647 hint->base.state = HINT_STATE_USED;
2649 hint->base.state = HINT_STATE_ERROR;
2656 * Setup parallel execution environment.
2658 * If hint is not NULL, set up using it, elsewise reset to initial environment.
2661 setup_parallel_plan_enforcement(ParallelHint *hint, HintState *state)
2665 hint->base.state = HINT_STATE_USED;
2666 set_config_int32_option("max_parallel_workers_per_gather",
2667 hint->nworkers, state->context);
2670 set_config_int32_option("max_parallel_workers_per_gather",
2671 state->init_nworkers, state->context);
2673 /* force means that enforce parallel as far as possible */
2674 if (hint && hint->force_parallel && hint->nworkers > 0)
2676 set_config_int32_option("parallel_tuple_cost", 0, state->context);
2677 set_config_int32_option("parallel_setup_cost", 0, state->context);
2678 set_config_int32_option("min_parallel_table_scan_size", 0,
2680 set_config_int32_option("min_parallel_index_scan_size", 0,
2685 set_config_int32_option("parallel_tuple_cost",
2686 state->init_paratup_cost, state->context);
2687 set_config_int32_option("parallel_setup_cost",
2688 state->init_parasetup_cost, state->context);
2689 set_config_int32_option("min_parallel_table_scan_size",
2690 state->init_min_para_tablescan_size,
2692 set_config_int32_option("min_parallel_index_scan_size",
2693 state->init_min_para_indexscan_size,
2698 #define SET_CONFIG_OPTION(name, type_bits) \
2699 set_config_option_noerror((name), \
2700 (mask & (type_bits)) ? "true" : "false", \
2701 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2705 * Setup GUC environment to enforce scan methods. If scanhint is NULL, reset
2706 * GUCs to the saved state in state.
2709 setup_scan_method_enforcement(ScanMethodHint *scanhint, HintState *state)
2711 unsigned char enforce_mask = state->init_scan_mask;
2712 GucContext context = state->context;
2717 enforce_mask = scanhint->enforce_mask;
2718 scanhint->base.state = HINT_STATE_USED;
2721 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2722 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2723 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2725 mask = enforce_mask;
2727 mask = enforce_mask & current_hint_state->init_scan_mask;
2729 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2730 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2731 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2732 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2733 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2737 set_join_config_options(unsigned char enforce_mask, GucContext context)
2741 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2742 enforce_mask == ENABLE_HASHJOIN)
2743 mask = enforce_mask;
2745 mask = enforce_mask & current_hint_state->init_join_mask;
2747 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2748 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2749 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2753 * Push a hint into hint stack which is implemented with List struct. Head of
2754 * list is top of stack.
2757 push_hint(HintState *hstate)
2759 /* Prepend new hint to the list means pushing to stack. */
2760 HintStateStack = lcons(hstate, HintStateStack);
2762 /* Pushed hint is the one which should be used hereafter. */
2763 current_hint_state = hstate;
2766 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2770 /* Hint stack must not be empty. */
2771 if(HintStateStack == NIL)
2772 elog(ERROR, "hint stack is empty");
2775 * Take a hint at the head from the list, and free it. Switch
2776 * current_hint_state to point new head (NULL if the list is empty).
2778 HintStateStack = list_delete_first(HintStateStack);
2779 HintStateDelete(current_hint_state);
2780 if(HintStateStack == NIL)
2781 current_hint_state = NULL;
2783 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
2787 * Retrieve and store hint string from given query or from the hint table.
2790 get_current_hint_string(ParseState *pstate, Query *query)
2792 const char *query_str;
2793 MemoryContext oldcontext;
2795 /* do nothing under hint table search */
2796 if (hint_inhibit_level > 0)
2799 /* We alredy have one, don't parse it again. */
2800 if (current_hint_retrieved)
2803 /* Don't parse the current query hereafter */
2804 current_hint_retrieved = true;
2806 if (!pg_hint_plan_enable_hint)
2808 if (current_hint_str)
2810 pfree((void *)current_hint_str);
2811 current_hint_str = NULL;
2816 /* increment the query number */
2818 if (debug_level > 1)
2819 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2822 /* search the hint table for a hint if requested */
2823 if (pg_hint_plan_enable_hint_table)
2826 pgssJumbleState jstate;
2828 char *normalized_query = NULL;
2830 query_str = get_query_string(pstate, query, &jumblequery);
2832 /* If this query is not for hint, just return */
2836 /* clear the previous hint string */
2837 if (current_hint_str)
2839 pfree((void *)current_hint_str);
2840 current_hint_str = NULL;
2846 * XXX: normalization code is copied from pg_stat_statements.c.
2847 * Make sure to keep up-to-date with it.
2849 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2850 jstate.jumble_len = 0;
2851 jstate.clocations_buf_size = 32;
2852 jstate.clocations = (pgssLocationLen *)
2853 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2854 jstate.clocations_count = 0;
2856 JumbleQuery(&jstate, jumblequery);
2859 * Normalize the query string by replacing constants with '?'
2862 * Search hint string which is stored keyed by query string
2863 * and application name. The query string is normalized to allow
2866 * Adding 1 byte to query_len ensures that the returned string has
2867 * a terminating NULL.
2869 query_len = strlen(query_str) + 1;
2871 generate_normalized_query(&jstate, query_str,
2872 query->stmt_location,
2874 GetDatabaseEncoding());
2877 * find a hint for the normalized query. the result should be in
2880 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2882 get_hints_from_table(normalized_query, application_name);
2883 MemoryContextSwitchTo(oldcontext);
2885 if (debug_level > 1)
2887 if (current_hint_str)
2888 ereport(pg_hint_plan_debug_message_level,
2889 (errmsg("pg_hint_plan[qno=0x%x]: "
2890 "post_parse_analyze_hook: "
2891 "hints from table: \"%s\": "
2892 "normalized_query=\"%s\", "
2893 "application name =\"%s\"",
2894 qno, current_hint_str,
2895 normalized_query, application_name),
2896 errhidestmt(msgqno != qno),
2897 errhidecontext(msgqno != qno)));
2899 ereport(pg_hint_plan_debug_message_level,
2900 (errmsg("pg_hint_plan[qno=0x%x]: "
2901 "no match found in table: "
2902 "application name = \"%s\", "
2903 "normalized_query=\"%s\"",
2904 qno, application_name,
2906 errhidestmt(msgqno != qno),
2907 errhidecontext(msgqno != qno)));
2913 /* retrun if we have hint here */
2914 if (current_hint_str)
2918 query_str = get_query_string(pstate, query, NULL);
2923 * get hints from the comment. However we may have the same query
2924 * string with the previous call, but the extra comparison seems no
2927 if (current_hint_str)
2928 pfree((void *)current_hint_str);
2930 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2931 current_hint_str = get_hints_from_comment(query_str);
2932 MemoryContextSwitchTo(oldcontext);
2937 * Failed to get query. We would be in fetching invalidated
2938 * plancache. Try the next chance.
2940 current_hint_retrieved = false;
2943 if (debug_level > 1)
2945 if (debug_level == 1 && query_str && debug_query_string &&
2946 strcmp(query_str, debug_query_string))
2947 ereport(pg_hint_plan_debug_message_level,
2948 (errmsg("hints in comment=\"%s\"",
2949 current_hint_str ? current_hint_str : "(none)"),
2950 errhidestmt(msgqno != qno),
2951 errhidecontext(msgqno != qno)));
2953 ereport(pg_hint_plan_debug_message_level,
2954 (errmsg("hints in comment=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2955 current_hint_str ? current_hint_str : "(none)",
2956 query_str ? query_str : "(none)",
2957 debug_query_string ? debug_query_string : "(none)"),
2958 errhidestmt(msgqno != qno),
2959 errhidecontext(msgqno != qno)));
2965 * Retrieve hint string from the current query.
2968 pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query)
2970 if (prev_post_parse_analyze_hook)
2971 prev_post_parse_analyze_hook(pstate, query);
2973 /* always retrieve hint from the top-level query string */
2974 if (plpgsql_recurse_level == 0)
2975 current_hint_retrieved = false;
2977 get_current_hint_string(pstate, query);
2981 * We need to reset current_hint_retrieved flag always when a command execution
2982 * is finished. This is true even for a pure utility command that doesn't
2983 * involve planning phase.
2986 pg_hint_plan_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
2987 ProcessUtilityContext context,
2988 ParamListInfo params, QueryEnvironment *queryEnv,
2989 DestReceiver *dest, char *completionTag)
2991 if (prev_ProcessUtility_hook)
2992 prev_ProcessUtility_hook(pstmt, queryString, context, params, queryEnv,
2993 dest, completionTag);
2995 standard_ProcessUtility(pstmt, queryString, context, params, queryEnv,
2996 dest, completionTag);
2998 if (plpgsql_recurse_level == 0)
2999 current_hint_retrieved = false;
3003 * Read and set up hint information
3005 static PlannedStmt *
3006 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
3009 PlannedStmt *result;
3011 const char *prev_hint_str = NULL;
3014 * Use standard planner if pg_hint_plan is disabled or current nesting
3015 * depth is nesting depth of SPI calls. Other hook functions try to change
3016 * plan with current_hint_state if any, so set it to NULL.
3018 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
3020 if (debug_level > 1)
3021 ereport(pg_hint_plan_debug_message_level,
3022 (errmsg ("pg_hint_plan%s: planner: enable_hint=%d,"
3023 " hint_inhibit_level=%d",
3024 qnostr, pg_hint_plan_enable_hint,
3025 hint_inhibit_level),
3026 errhidestmt(msgqno != qno)));
3029 goto standard_planner_proc;
3033 * Support for nested plpgsql functions. This is quite ugly but this is the
3034 * only point I could find where I can get the query string.
3036 if (plpgsql_recurse_level > 0 &&
3037 error_context_stack && error_context_stack->arg)
3039 MemoryContext oldcontext;
3041 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
3043 get_hints_from_comment((char *)error_context_stack->arg);
3044 MemoryContextSwitchTo(oldcontext);
3048 * Query execution in extended protocol can be started without the analyze
3049 * phase. In the case retrieve hint string here.
3051 if (!current_hint_str)
3052 get_current_hint_string(NULL, parse);
3054 /* No hint, go the normal way */
3055 if (!current_hint_str)
3056 goto standard_planner_proc;
3058 /* parse the hint into hint state struct */
3059 hstate = create_hintstate(parse, pstrdup(current_hint_str));
3061 /* run standard planner if the statement has not valid hint */
3063 goto standard_planner_proc;
3066 * Push new hint struct to the hint stack to disable previous hint context.
3070 /* Set scan enforcement here. */
3071 save_nestlevel = NewGUCNestLevel();
3073 /* Apply Set hints, then save it as the initial state */
3074 setup_guc_enforcement(current_hint_state->set_hints,
3075 current_hint_state->num_hints[HINT_TYPE_SET],
3076 current_hint_state->context);
3078 current_hint_state->init_scan_mask = get_current_scan_mask();
3079 current_hint_state->init_join_mask = get_current_join_mask();
3080 current_hint_state->init_min_para_tablescan_size =
3081 min_parallel_table_scan_size;
3082 current_hint_state->init_min_para_indexscan_size =
3083 min_parallel_index_scan_size;
3084 current_hint_state->init_paratup_cost = parallel_tuple_cost;
3085 current_hint_state->init_parasetup_cost = parallel_setup_cost;
3088 * max_parallel_workers_per_gather should be non-zero here if Workers hint
3091 if (max_hint_nworkers > 0 && max_parallel_workers_per_gather < 1)
3092 set_config_int32_option("max_parallel_workers_per_gather",
3093 1, current_hint_state->context);
3094 current_hint_state->init_nworkers = max_parallel_workers_per_gather;
3096 if (debug_level > 1)
3098 ereport(pg_hint_plan_debug_message_level,
3099 (errhidestmt(msgqno != qno),
3100 errmsg("pg_hint_plan%s: planner", qnostr)));
3105 * The planner call below may replace current_hint_str. Store and restore
3106 * it so that the subsequent planning in the upper level doesn't get
3110 prev_hint_str = current_hint_str;
3111 current_hint_str = NULL;
3114 * Use PG_TRY mechanism to recover GUC parameters and current_hint_state to
3115 * the state when this planner started when error occurred in planner.
3120 result = (*prev_planner) (parse, cursorOptions, boundParams);
3122 result = standard_planner(parse, cursorOptions, boundParams);
3124 current_hint_str = prev_hint_str;
3130 * Rollback changes of GUC parameters, and pop current hint context
3131 * from hint stack to rewind the state.
3133 current_hint_str = prev_hint_str;
3135 AtEOXact_GUC(true, save_nestlevel);
3143 * current_hint_str is useless after planning of the top-level query.
3145 if (recurse_level < 1 && current_hint_str)
3147 pfree((void *)current_hint_str);
3148 current_hint_str = NULL;
3149 current_hint_retrieved = false;
3152 /* Print hint in debug mode. */
3153 if (debug_level == 1)
3154 HintStateDump(current_hint_state);
3155 else if (debug_level > 1)
3156 HintStateDump2(current_hint_state);
3159 * Rollback changes of GUC parameters, and pop current hint context from
3160 * hint stack to rewind the state.
3162 AtEOXact_GUC(true, save_nestlevel);
3167 standard_planner_proc:
3168 if (debug_level > 1)
3170 ereport(pg_hint_plan_debug_message_level,
3171 (errhidestmt(msgqno != qno),
3172 errmsg("pg_hint_plan%s: planner: no valid hint",
3176 current_hint_state = NULL;
3178 return (*prev_planner) (parse, cursorOptions, boundParams);
3180 return standard_planner(parse, cursorOptions, boundParams);
3184 * Find scan method hint to be applied to the given relation
3187 static ScanMethodHint *
3188 find_scan_hint(PlannerInfo *root, Index relid)
3192 ScanMethodHint *real_name_hint = NULL;
3193 ScanMethodHint *alias_hint = NULL;
3196 /* This should not be a join rel */
3198 rel = root->simple_rel_array[relid];
3201 * This function is called for any RelOptInfo or its inheritance parent if
3202 * any. If we are called from inheritance planner, the RelOptInfo for the
3203 * parent of target child relation is not set in the planner info.
3205 * Otherwise we should check that the reloptinfo is base relation or
3206 * inheritance children.
3209 rel->reloptkind != RELOPT_BASEREL &&
3210 rel->reloptkind != RELOPT_OTHER_MEMBER_REL)
3214 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3216 rte = root->simple_rte_array[relid];
3219 /* We don't hint on other than relation and foreign tables */
3220 if (rte->rtekind != RTE_RELATION ||
3221 rte->relkind == RELKIND_FOREIGN_TABLE)
3224 /* Find scan method hint, which matches given names, from the list. */
3225 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
3227 ScanMethodHint *hint = current_hint_state->scan_hints[i];
3229 /* We ignore disabled hints. */
3230 if (!hint_state_enabled(hint))
3234 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3237 /* check the real name for appendrel children */
3238 if (!real_name_hint &&
3239 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3241 char *realname = get_rel_name(rte->relid);
3243 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3244 real_name_hint = hint;
3247 /* No more match expected, break */
3248 if(alias_hint && real_name_hint)
3252 /* real name match precedes alias match */
3254 return real_name_hint;
3259 static ParallelHint *
3260 find_parallel_hint(PlannerInfo *root, Index relid)
3264 ParallelHint *real_name_hint = NULL;
3265 ParallelHint *alias_hint = NULL;
3268 /* This should not be a join rel */
3270 rel = root->simple_rel_array[relid];
3273 * Parallel planning is appliable only on base relation, which has
3280 * We have set root->glob->parallelModeOK if needed. What we should do here
3281 * is just following the decision of planner.
3283 if (!rel->consider_parallel)
3287 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3289 rte = root->simple_rte_array[relid];
3292 /* Find parallel method hint, which matches given names, from the list. */
3293 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_PARALLEL]; i++)
3295 ParallelHint *hint = current_hint_state->parallel_hints[i];
3297 /* We ignore disabled hints. */
3298 if (!hint_state_enabled(hint))
3302 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3305 /* check the real name for appendrel children */
3306 if (!real_name_hint &&
3307 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3309 char *realname = get_rel_name(rte->relid);
3311 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3312 real_name_hint = hint;
3315 /* No more match expected, break */
3316 if(alias_hint && real_name_hint)
3320 /* real name match precedes alias match */
3322 return real_name_hint;
3330 * Returns TRUE on match, FALSE on no match.
3332 * s1 --- the data to match against
3333 * s2 --- the pattern
3335 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
3338 regexpeq(const char *s1, const char *s2)
3344 strcpy(name.data, s1);
3345 regexp = cstring_to_text(s2);
3347 result = DirectFunctionCall2Coll(nameregexeq,
3348 DEFAULT_COLLATION_OID,
3349 NameGetDatum(&name),
3350 PointerGetDatum(regexp));
3351 return DatumGetBool(result);
3355 /* Remove indexes instructed not to use by hint. */
3357 restrict_indexes(PlannerInfo *root, ScanMethodHint *hint, RelOptInfo *rel,
3358 bool using_parent_hint)
3364 RangeTblEntry *rte = root->simple_rte_array[rel->relid];
3365 Oid relationObjectId = rte->relid;
3368 * We delete all the IndexOptInfo list and prevent you from being usable by
3371 if (hint->enforce_mask == ENABLE_SEQSCAN ||
3372 hint->enforce_mask == ENABLE_TIDSCAN)
3374 list_free_deep(rel->indexlist);
3375 rel->indexlist = NIL;
3376 hint->base.state = HINT_STATE_USED;
3382 * When a list of indexes is not specified, we just use all indexes.
3384 if (hint->indexnames == NIL)
3388 * Leaving only an specified index, we delete it from a IndexOptInfo list
3392 if (debug_level > 0)
3393 initStringInfo(&buf);
3395 for (cell = list_head(rel->indexlist); cell; cell = next)
3397 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
3398 char *indexname = get_rel_name(info->indexoid);
3400 bool use_index = false;
3404 foreach(l, hint->indexnames)
3406 char *hintname = (char *) lfirst(l);
3410 result = regexpeq(indexname, hintname);
3412 result = RelnameCmp(&indexname, &hintname) == 0;
3417 if (debug_level > 0)
3419 appendStringInfoCharMacro(&buf, ' ');
3420 quote_value(&buf, indexname);
3428 * Apply index restriction of parent hint to children. Since index
3429 * inheritance is not explicitly described we should search for an
3430 * children's index with the same definition to that of the parent.
3432 if (using_parent_hint && !use_index)
3434 foreach(l, current_hint_state->parent_index_infos)
3438 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
3441 * we check the 'same' index by comparing uniqueness, access
3442 * method and index key columns.
3444 if (p_info->indisunique != info->unique ||
3445 p_info->method != info->relam ||
3446 list_length(p_info->column_names) != info->ncolumns)
3449 /* Check if index key columns match */
3450 for (i = 0; i < info->ncolumns; i++)
3452 char *c_attname = NULL;
3453 char *p_attname = NULL;
3455 p_attname = list_nth(p_info->column_names, i);
3458 * if both of the key of the same position are expressions,
3459 * ignore them for now and check later.
3461 if (info->indexkeys[i] == 0 && !p_attname)
3464 /* deny if one is expression while another is not */
3465 if (info->indexkeys[i] == 0 || !p_attname)
3468 c_attname = get_attname(relationObjectId,
3469 info->indexkeys[i], false);
3471 /* deny if any of column attributes don't match */
3472 if (strcmp(p_attname, c_attname) != 0 ||
3473 p_info->indcollation[i] != info->indexcollations[i] ||
3474 p_info->opclass[i] != info->opcintype[i]||
3475 ((p_info->indoption[i] & INDOPTION_DESC) != 0)
3476 != info->reverse_sort[i] ||
3477 ((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0)
3478 != info->nulls_first[i])
3482 /* deny this if any difference found */
3483 if (i != info->ncolumns)
3486 /* check on key expressions */
3487 if ((p_info->expression_str && (info->indexprs != NIL)) ||
3488 (p_info->indpred_str && (info->indpred != NIL)))
3490 /* fetch the index of this child */
3491 ht_idx = SearchSysCache1(INDEXRELID,
3492 ObjectIdGetDatum(info->indexoid));
3494 /* check expressions if both expressions are available */
3495 if (p_info->expression_str &&
3496 !heap_attisnull(ht_idx, Anum_pg_index_indexprs, NULL))
3503 * to change the expression's parameter of child's
3506 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3507 Anum_pg_index_indexprs,
3510 result = DirectFunctionCall2(pg_get_expr,
3515 /* deny if expressions don't match */
3516 if (strcmp(p_info->expression_str,
3517 text_to_cstring(DatumGetTextP(result))) != 0)
3520 ReleaseSysCache(ht_idx);
3525 /* compare index predicates */
3526 if (p_info->indpred_str &&
3527 !heap_attisnull(ht_idx, Anum_pg_index_indpred, NULL))
3533 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3534 Anum_pg_index_indpred,
3537 result = DirectFunctionCall2(pg_get_expr,
3542 if (strcmp(p_info->indpred_str,
3543 text_to_cstring(DatumGetTextP(result))) != 0)
3546 ReleaseSysCache(ht_idx);
3552 ReleaseSysCache(ht_idx);
3554 else if (p_info->expression_str || (info->indexprs != NIL))
3556 else if (p_info->indpred_str || (info->indpred != NIL))
3561 /* to log the candidate of index */
3562 if (debug_level > 0)
3564 appendStringInfoCharMacro(&buf, ' ');
3565 quote_value(&buf, indexname);
3573 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
3580 if (debug_level == 1)
3582 StringInfoData rel_buf;
3583 char *disprelname = "";
3586 * If this hint targetted the parent, use the real name of this
3587 * child. Otherwise use hint specification.
3589 if (using_parent_hint)
3590 disprelname = get_rel_name(rte->relid);
3592 disprelname = hint->relname;
3595 initStringInfo(&rel_buf);
3596 quote_value(&rel_buf, disprelname);
3598 ereport(pg_hint_plan_debug_message_level,
3599 (errmsg("available indexes for %s(%s):%s",
3604 pfree(rel_buf.data);
3609 * Return information of index definition.
3611 static ParentIndexInfo *
3612 get_parent_index_info(Oid indexoid, Oid relid)
3614 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3615 Relation indexRelation;
3616 Form_pg_index index;
3620 indexRelation = index_open(indexoid, RowExclusiveLock);
3622 index = indexRelation->rd_index;
3624 p_info->indisunique = index->indisunique;
3625 p_info->method = indexRelation->rd_rel->relam;
3627 p_info->column_names = NIL;
3628 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3629 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3630 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3633 * Collect relation attribute names of index columns for index
3634 * identification, not index attribute names. NULL means expression index
3637 for (i = 0; i < index->indnatts; i++)
3639 attname = get_attname(relid, index->indkey.values[i], true);
3640 p_info->column_names = lappend(p_info->column_names, attname);
3642 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3643 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3644 p_info->indoption[i] = indexRelation->rd_indoption[i];
3648 * to check to match the expression's parameter of index with child indexes
3650 p_info->expression_str = NULL;
3651 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs,
3658 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3659 Anum_pg_index_indexprs, &isnull);
3661 result = DirectFunctionCall2(pg_get_expr,
3663 ObjectIdGetDatum(relid));
3665 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3669 * to check to match the predicate's parameter of index with child indexes
3671 p_info->indpred_str = NULL;
3672 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred,
3679 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3680 Anum_pg_index_indpred, &isnull);
3682 result = DirectFunctionCall2(pg_get_expr,
3684 ObjectIdGetDatum(relid));
3686 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3689 index_close(indexRelation, NoLock);
3695 * cancel hint enforcement
3698 reset_hint_enforcement()
3700 setup_scan_method_enforcement(NULL, current_hint_state);
3701 setup_parallel_plan_enforcement(NULL, current_hint_state);
3705 * Set planner guc parameters according to corresponding scan hints. Returns
3706 * bitmap of HintTypeBitmap. If shint or phint is not NULL, set used hint
3707 * there respectively.
3710 setup_hint_enforcement(PlannerInfo *root, RelOptInfo *rel,
3711 ScanMethodHint **rshint, ParallelHint **rphint)
3713 Index new_parent_relid = 0;
3715 ScanMethodHint *shint = NULL;
3716 ParallelHint *phint = NULL;
3717 bool inhparent = root->simple_rte_array[rel->relid]->inh;
3718 Oid relationObjectId = root->simple_rte_array[rel->relid]->relid;
3721 /* reset returns if requested */
3722 if (rshint != NULL) *rshint = NULL;
3723 if (rphint != NULL) *rphint = NULL;
3726 * We could register the parent relation of the following children here
3727 * when inhparent == true but inheritnce planner doesn't call this function
3728 * for parents. Since we cannot distinguish who called this function we
3729 * cannot do other than always seeking the parent regardless of who called
3734 /* set up only parallel hints for parent relation */
3735 phint = find_parallel_hint(root, rel->relid);
3738 setup_parallel_plan_enforcement(phint, current_hint_state);
3739 if (rphint) *rphint = phint;
3740 ret |= HINT_BM_PARALLEL;
3744 if (debug_level > 1)
3745 ereport(pg_hint_plan_debug_message_level,
3747 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3748 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3749 " current_hint_state=%p, hint_inhibit_level=%d",
3750 qnostr, relationObjectId,
3751 get_rel_name(relationObjectId),
3752 inhparent, current_hint_state, hint_inhibit_level)));
3757 * Forget about the parent of another subquery, but don't forget if the
3758 * inhTargetkind of the root is not INHKIND_NONE, which signals the root
3759 * contains only appendrel members. See inheritance_planner for details.
3761 * (PG12.0) 428b260f87 added one more planning cycle for updates on
3762 * partitioned tables and hints set up in the cycle are overriden by the
3763 * second cycle. Since I didn't find no apparent distinction between the
3764 * PlannerRoot of the cycle and that of ordinary CMD_SELECT, pg_hint_plan
3765 * accepts both cycles and the later one wins. In the second cycle root
3766 * doesn't have inheritance information at all so use the parent_relid set
3767 * in the first cycle.
3769 if (root->inhTargetKind == INHKIND_NONE)
3771 if (root != current_hint_state->current_root)
3772 current_hint_state->parent_relid = 0;
3774 /* Find the parent for this relation other than the registered parent */
3775 foreach (l, root->append_rel_list)
3777 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3779 if (appinfo->child_relid == rel->relid)
3781 if (current_hint_state->parent_relid != appinfo->parent_relid)
3783 new_parent_relid = appinfo->parent_relid;
3784 current_hint_state->current_root = root;
3793 * This relation doesn't have a parent. Cancel
3794 * current_hint_state.
3796 current_hint_state->parent_relid = 0;
3797 current_hint_state->parent_scan_hint = NULL;
3798 current_hint_state->parent_parallel_hint = NULL;
3802 if (new_parent_relid > 0)
3805 * Here we found a new parent for the current relation. Scan continues
3806 * hint to other childrens of this parent so remember it to avoid
3807 * redundant setup cost.
3809 current_hint_state->parent_relid = new_parent_relid;
3811 /* Find hints for the parent */
3812 current_hint_state->parent_scan_hint =
3813 find_scan_hint(root, current_hint_state->parent_relid);
3815 current_hint_state->parent_parallel_hint =
3816 find_parallel_hint(root, current_hint_state->parent_relid);
3819 * If hint is found for the parent, apply it for this child instead
3822 if (current_hint_state->parent_scan_hint)
3824 ScanMethodHint * pshint = current_hint_state->parent_scan_hint;
3826 pshint->base.state = HINT_STATE_USED;
3828 /* Apply index mask in the same manner to the parent. */
3829 if (pshint->indexnames)
3832 Relation parent_rel;
3835 root->simple_rte_array[current_hint_state->parent_relid]->relid;
3836 parent_rel = heap_open(parentrel_oid, NoLock);
3838 /* Search the parent relation for indexes match the hint spec */
3839 foreach(l, RelationGetIndexList(parent_rel))
3841 Oid indexoid = lfirst_oid(l);
3842 char *indexname = get_rel_name(indexoid);
3844 ParentIndexInfo *parent_index_info;
3846 foreach(lc, pshint->indexnames)
3848 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3855 get_parent_index_info(indexoid, parentrel_oid);
3856 current_hint_state->parent_index_infos =
3857 lappend(current_hint_state->parent_index_infos,
3860 heap_close(parent_rel, NoLock);
3865 shint = find_scan_hint(root, rel->relid);
3867 shint = current_hint_state->parent_scan_hint;
3871 bool using_parent_hint =
3872 (shint == current_hint_state->parent_scan_hint);
3874 ret |= HINT_BM_SCAN_METHOD;
3876 /* Setup scan enforcement environment */
3877 setup_scan_method_enforcement(shint, current_hint_state);
3879 /* restrict unwanted inexes */
3880 restrict_indexes(root, shint, rel, using_parent_hint);
3882 if (debug_level > 1)
3884 char *additional_message = "";
3886 if (shint == current_hint_state->parent_scan_hint)
3887 additional_message = " by parent hint";
3889 ereport(pg_hint_plan_debug_message_level,
3891 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3892 " index deletion%s:"
3893 " relation=%u(%s), inhparent=%d, "
3894 "current_hint_state=%p,"
3895 " hint_inhibit_level=%d, scanmask=0x%x",
3896 qnostr, additional_message,
3898 get_rel_name(relationObjectId),
3899 inhparent, current_hint_state,
3901 shint->enforce_mask)));
3905 /* Do the same for parallel plan enforcement */
3906 phint = find_parallel_hint(root, rel->relid);
3908 phint = current_hint_state->parent_parallel_hint;
3910 setup_parallel_plan_enforcement(phint, current_hint_state);
3913 ret |= HINT_BM_PARALLEL;
3915 /* Nothing to apply. Reset the scan mask to intial state */
3916 if (!shint && ! phint)
3918 if (debug_level > 1)
3919 ereport(pg_hint_plan_debug_message_level,
3920 (errhidestmt (true),
3921 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3923 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3924 " hint_inhibit_level=%d, scanmask=0x%x",
3925 qnostr, relationObjectId,
3926 get_rel_name(relationObjectId),
3927 inhparent, current_hint_state, hint_inhibit_level,
3928 current_hint_state->init_scan_mask)));
3930 setup_scan_method_enforcement(NULL, current_hint_state);
3935 if (rshint != NULL) *rshint = shint;
3936 if (rphint != NULL) *rphint = phint;
3942 * Return index of relation which matches given aliasname, or 0 if not found.
3943 * If same aliasname was used multiple times in a query, return -1.
3946 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3952 for (i = 1; i < root->simple_rel_array_size; i++)
3956 if (root->simple_rel_array[i] == NULL)
3959 Assert(i == root->simple_rel_array[i]->relid);
3961 if (RelnameCmp(&aliasname,
3962 &root->simple_rte_array[i]->eref->aliasname) != 0)
3965 foreach(l, initial_rels)
3967 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3969 if (rel->reloptkind == RELOPT_BASEREL)
3971 if (rel->relid != i)
3976 Assert(rel->reloptkind == RELOPT_JOINREL);
3978 if (!bms_is_member(i, rel->relids))
3985 ("Relation name \"%s\" is ambiguous.",
4000 * Return join hint which matches given joinrelids.
4002 static JoinMethodHint *
4003 find_join_hint(Relids joinrelids)
4008 join_hint = current_hint_state->join_hint_level[bms_num_members(joinrelids)];
4010 foreach(l, join_hint)
4012 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
4014 if (bms_equal(joinrelids, hint->joinrelids))
4022 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
4023 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
4025 OuterInnerRels *outer_rels;
4026 OuterInnerRels *inner_rels;
4027 Relids outer_relids;
4028 Relids inner_relids;
4030 JoinMethodHint *hint;
4032 if (outer_inner->relation != NULL)
4034 return bms_make_singleton(
4035 find_relid_aliasname(root, outer_inner->relation,
4037 leading_hint->base.hint_str));
4040 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
4041 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
4043 outer_relids = OuterInnerJoinCreate(outer_rels,
4049 inner_relids = OuterInnerJoinCreate(inner_rels,
4056 join_relids = bms_add_members(outer_relids, inner_relids);
4058 if (bms_num_members(join_relids) > nbaserel)
4062 * If we don't have join method hint, create new one for the
4063 * join combination with all join methods are enabled.
4065 hint = find_join_hint(join_relids);
4069 * Here relnames is not set, since Relids bitmap is sufficient to
4070 * control paths of this query afterward.
4072 hint = (JoinMethodHint *) JoinMethodHintCreate(
4073 leading_hint->base.hint_str,
4075 HINT_KEYWORD_LEADING);
4076 hint->base.state = HINT_STATE_USED;
4077 hint->nrels = bms_num_members(join_relids);
4078 hint->enforce_mask = ENABLE_ALL_JOIN;
4079 hint->joinrelids = bms_copy(join_relids);
4080 hint->inner_nrels = bms_num_members(inner_relids);
4081 hint->inner_joinrelids = bms_copy(inner_relids);
4083 hstate->join_hint_level[hint->nrels] =
4084 lappend(hstate->join_hint_level[hint->nrels], hint);
4088 hint->inner_nrels = bms_num_members(inner_relids);
4089 hint->inner_joinrelids = bms_copy(inner_relids);
4096 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
4097 int nrels, char **relnames)
4100 Relids relids = NULL;
4104 for (j = 0; j < nrels; j++)
4106 relname = relnames[j];
4108 relid = find_relid_aliasname(root, relname, initial_rels,
4112 base->state = HINT_STATE_ERROR;
4115 * the aliasname is not found(relid == 0) or same aliasname was used
4116 * multiple times in a query(relid == -1)
4123 if (bms_is_member(relid, relids))
4125 hint_ereport(base->hint_str,
4126 ("Relation name \"%s\" is duplicated.", relname));
4127 base->state = HINT_STATE_ERROR;
4131 relids = bms_add_member(relids, relid);
4136 * Transform join method hint into handy form.
4138 * - create bitmap of relids from alias names, to make it easier to check
4139 * whether a join path matches a join method hint.
4140 * - add join method hints which are necessary to enforce join order
4141 * specified by Leading hint
4144 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
4145 List *initial_rels, JoinMethodHint **join_method_hints)
4153 LeadingHint *lhint = NULL;
4156 * Create bitmap of relids from alias names for each join method hint.
4157 * Bitmaps are more handy than strings in join searching.
4159 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
4161 JoinMethodHint *hint = hstate->join_hints[i];
4163 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4166 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4167 initial_rels, hint->nrels, hint->relnames);
4169 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
4172 hstate->join_hint_level[hint->nrels] =
4173 lappend(hstate->join_hint_level[hint->nrels], hint);
4177 * Create bitmap of relids from alias names for each rows hint.
4178 * Bitmaps are more handy than strings in join searching.
4180 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
4182 RowsHint *hint = hstate->rows_hints[i];
4184 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4187 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4188 initial_rels, hint->nrels, hint->relnames);
4191 /* Do nothing if no Leading hint was supplied. */
4192 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
4196 * Decide whether to use Leading hint
4198 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
4200 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
4203 if (leading_hint->base.state == HINT_STATE_ERROR)
4209 foreach(l, leading_hint->relations)
4211 relname = (char *)lfirst(l);;
4213 relid = find_relid_aliasname(root, relname, initial_rels,
4214 leading_hint->base.hint_str);
4216 leading_hint->base.state = HINT_STATE_ERROR;
4221 if (bms_is_member(relid, relids))
4223 hint_ereport(leading_hint->base.hint_str,
4224 ("Relation name \"%s\" is duplicated.", relname));
4225 leading_hint->base.state = HINT_STATE_ERROR;
4229 relids = bms_add_member(relids, relid);
4232 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
4237 hint_ereport(lhint->base.hint_str,
4238 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
4239 lhint->base.state = HINT_STATE_DUPLICATION;
4241 leading_hint->base.state = HINT_STATE_USED;
4242 lhint = leading_hint;
4245 /* check to exist Leading hint marked with 'used'. */
4250 * We need join method hints which fit specified join order in every join
4251 * level. For example, Leading(A B C) virtually requires following join
4252 * method hints, if no join method hint supplied:
4254 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
4255 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
4257 * If we already have join method hint which fits specified join order in
4258 * that join level, we leave it as-is and don't add new hints.
4262 if (lhint->outer_inner == NULL)
4264 foreach(l, lhint->relations)
4266 JoinMethodHint *hint;
4268 relname = (char *)lfirst(l);
4271 * Find relid of the relation which has given name. If we have the
4272 * name given in Leading hint multiple times in the join, nothing to
4275 relid = find_relid_aliasname(root, relname, initial_rels,
4278 /* Create bitmap of relids for current join level. */
4279 joinrelids = bms_add_member(joinrelids, relid);
4282 /* We never have join method hint for single relation. */
4287 * If we don't have join method hint, create new one for the
4288 * join combination with all join methods are enabled.
4290 hint = find_join_hint(joinrelids);
4294 * Here relnames is not set, since Relids bitmap is sufficient
4295 * to control paths of this query afterward.
4297 hint = (JoinMethodHint *) JoinMethodHintCreate(
4298 lhint->base.hint_str,
4300 HINT_KEYWORD_LEADING);
4301 hint->base.state = HINT_STATE_USED;
4302 hint->nrels = njoinrels;
4303 hint->enforce_mask = ENABLE_ALL_JOIN;
4304 hint->joinrelids = bms_copy(joinrelids);
4307 join_method_hints[njoinrels] = hint;
4309 if (njoinrels >= nbaserel)
4312 bms_free(joinrelids);
4318 * Delete all join hints which have different combination from Leading
4321 for (i = 2; i <= njoinrels; i++)
4323 list_free(hstate->join_hint_level[i]);
4325 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
4330 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
4337 njoinrels = bms_num_members(joinrelids);
4338 Assert(njoinrels >= 2);
4341 * Delete all join hints which have different combination from Leading
4344 for (i = 2;i <= njoinrels; i++)
4346 if (hstate->join_hint_level[i] != NIL)
4348 ListCell *prev = NULL;
4349 ListCell *next = NULL;
4350 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
4353 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
4357 if (hint->inner_nrels == 0 &&
4358 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
4359 bms_equal(bms_union(hint->joinrelids, joinrelids),
4362 hstate->join_hint_level[i] =
4363 list_delete_cell(hstate->join_hint_level[i], l,
4372 bms_free(joinrelids);
4375 if (hint_state_enabled(lhint))
4377 set_join_config_options(DISABLE_ALL_JOIN, current_hint_state->context);
4384 * wrapper of make_join_rel()
4386 * call make_join_rel() after changing enable_* parameters according to given
4390 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
4393 JoinMethodHint *hint;
4397 joinrelids = bms_union(rel1->relids, rel2->relids);
4398 hint = find_join_hint(joinrelids);
4399 bms_free(joinrelids);
4402 return pg_hint_plan_make_join_rel(root, rel1, rel2);
4404 if (hint->inner_nrels == 0)
4406 save_nestlevel = NewGUCNestLevel();
4408 set_join_config_options(hint->enforce_mask,
4409 current_hint_state->context);
4411 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4412 hint->base.state = HINT_STATE_USED;
4415 * Restore the GUC variables we set above.
4417 AtEOXact_GUC(true, save_nestlevel);
4420 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4429 add_paths_to_joinrel_wrapper(PlannerInfo *root,
4430 RelOptInfo *joinrel,
4431 RelOptInfo *outerrel,
4432 RelOptInfo *innerrel,
4434 SpecialJoinInfo *sjinfo,
4438 JoinMethodHint *join_hint;
4441 joinrelids = bms_union(outerrel->relids, innerrel->relids);
4442 join_hint = find_join_hint(joinrelids);
4443 bms_free(joinrelids);
4445 if (join_hint && join_hint->inner_nrels != 0)
4447 save_nestlevel = NewGUCNestLevel();
4449 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
4452 set_join_config_options(join_hint->enforce_mask,
4453 current_hint_state->context);
4455 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4456 sjinfo, restrictlist);
4457 join_hint->base.state = HINT_STATE_USED;
4461 set_join_config_options(DISABLE_ALL_JOIN,
4462 current_hint_state->context);
4463 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4464 sjinfo, restrictlist);
4468 * Restore the GUC variables we set above.
4470 AtEOXact_GUC(true, save_nestlevel);
4473 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4474 sjinfo, restrictlist);
4478 get_num_baserels(List *initial_rels)
4483 foreach(l, initial_rels)
4485 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
4487 if (rel->reloptkind == RELOPT_BASEREL)
4489 else if (rel->reloptkind ==RELOPT_JOINREL)
4490 nbaserel+= bms_num_members(rel->relids);
4493 /* other values not expected here */
4494 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
4502 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
4505 JoinMethodHint **join_method_hints;
4509 bool leading_hint_enable;
4512 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
4513 * valid hint is supplied or current nesting depth is nesting depth of SPI
4516 if (!current_hint_state || hint_inhibit_level > 0)
4518 if (prev_join_search)
4519 return (*prev_join_search) (root, levels_needed, initial_rels);
4520 else if (enable_geqo && levels_needed >= geqo_threshold)
4521 return geqo(root, levels_needed, initial_rels);
4523 return standard_join_search(root, levels_needed, initial_rels);
4527 * In the case using GEQO, only scan method hints and Set hints have
4528 * effect. Join method and join order is not controllable by hints.
4530 if (enable_geqo && levels_needed >= geqo_threshold)
4531 return geqo(root, levels_needed, initial_rels);
4533 nbaserel = get_num_baserels(initial_rels);
4534 current_hint_state->join_hint_level =
4535 palloc0(sizeof(List *) * (nbaserel + 1));
4536 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4538 leading_hint_enable = transform_join_hints(current_hint_state,
4540 initial_rels, join_method_hints);
4542 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4545 * Adjust number of parallel workers of the result rel to the largest
4546 * number of the component paths.
4548 if (current_hint_state->num_hints[HINT_TYPE_PARALLEL] > 0)
4553 foreach (lc, initial_rels)
4556 RelOptInfo *rel = (RelOptInfo *) lfirst(lc);
4558 foreach (lcp, rel->partial_pathlist)
4560 Path *path = (Path *) lfirst(lcp);
4562 if (nworkers < path-> parallel_workers)
4563 nworkers = path-> parallel_workers;
4567 foreach (lc, rel->partial_pathlist)
4569 Path *path = (Path *) lfirst(lc);
4571 if (path->parallel_safe && path->parallel_workers < nworkers)
4572 path->parallel_workers = nworkers;
4576 for (i = 2; i <= nbaserel; i++)
4578 list_free(current_hint_state->join_hint_level[i]);
4580 /* free Leading hint only */
4581 if (join_method_hints[i] != NULL &&
4582 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4583 JoinMethodHintDelete(join_method_hints[i]);
4585 pfree(current_hint_state->join_hint_level);
4586 pfree(join_method_hints);
4588 if (leading_hint_enable)
4589 set_join_config_options(current_hint_state->init_join_mask,
4590 current_hint_state->context);
4596 * Force number of wokers if instructed by hint
4599 pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
4600 Index rti, RangeTblEntry *rte)
4602 ParallelHint *phint;
4606 /* call the previous hook */
4607 if (prev_set_rel_pathlist)
4608 prev_set_rel_pathlist(root, rel, rti, rte);
4610 /* Nothing to do if no hint available */
4611 if (current_hint_state == NULL)
4614 /* Don't touch dummy rels. */
4615 if (IS_DUMMY_REL(rel))
4619 * We can accept only plain relations, foreign tables and table saples are
4620 * also unacceptable. See set_rel_pathlist.
4622 if ((rel->rtekind != RTE_RELATION &&
4623 rel->rtekind != RTE_SUBQUERY)||
4624 rte->relkind == RELKIND_FOREIGN_TABLE ||
4625 rte->tablesample != NULL)
4629 * Even though UNION ALL node doesn't have particular name so usually it is
4630 * unhintable, turn on parallel when it contains parallel nodes.
4632 if (rel->rtekind == RTE_SUBQUERY)
4635 bool inhibit_nonparallel = false;
4637 if (rel->partial_pathlist == NIL)
4640 foreach(lc, rel->partial_pathlist)
4643 AppendPath *apath = (AppendPath *) lfirst(lc);
4644 int parallel_workers = 0;
4646 if (!IsA(apath, AppendPath))
4649 foreach (lcp, apath->subpaths)
4651 Path *spath = (Path *) lfirst(lcp);
4653 if (spath->parallel_aware &&
4654 parallel_workers < spath->parallel_workers)
4655 parallel_workers = spath->parallel_workers;
4658 apath->path.parallel_workers = parallel_workers;
4659 inhibit_nonparallel = true;
4662 if (inhibit_nonparallel)
4666 foreach(lc, rel->pathlist)
4668 Path *path = (Path *) lfirst(lc);
4670 if (path->startup_cost < disable_cost)
4672 path->startup_cost += disable_cost;
4673 path->total_cost += disable_cost;
4681 /* We cannot handle if this requires an outer */
4682 if (rel->lateral_relids)
4685 /* Return if this relation gets no enfocement */
4686 if ((found_hints = setup_hint_enforcement(root, rel, NULL, &phint)) == 0)
4689 /* Here, we regenerate paths with the current hint restriction */
4690 if (found_hints & HINT_BM_SCAN_METHOD || found_hints & HINT_BM_PARALLEL)
4693 * When hint is specified on non-parent relations, discard existing
4694 * paths and regenerate based on the hint considered. Otherwise we
4695 * already have hinted childx paths then just adjust the number of
4696 * planned number of workers.
4698 if (root->simple_rte_array[rel->relid]->inh)
4700 /* enforce number of workers if requested */
4701 if (phint && phint->force_parallel)
4703 if (phint->nworkers == 0)
4705 list_free_deep(rel->partial_pathlist);
4706 rel->partial_pathlist = NIL;
4710 /* prioritize partial paths */
4711 foreach (l, rel->partial_pathlist)
4713 Path *ppath = (Path *) lfirst(l);
4715 if (ppath->parallel_safe)
4717 ppath->parallel_workers = phint->nworkers;
4718 ppath->startup_cost = 0;
4719 ppath->total_cost = 0;
4723 /* disable non-partial paths */
4724 foreach (l, rel->pathlist)
4726 Path *ppath = (Path *) lfirst(l);
4728 if (ppath->startup_cost < disable_cost)
4730 ppath->startup_cost += disable_cost;
4731 ppath->total_cost += disable_cost;
4739 /* Just discard all the paths considered so far */
4740 list_free_deep(rel->pathlist);
4741 rel->pathlist = NIL;
4742 list_free_deep(rel->partial_pathlist);
4743 rel->partial_pathlist = NIL;
4745 /* Regenerate paths with the current enforcement */
4746 set_plain_rel_pathlist(root, rel, rte);
4748 /* Additional work to enforce parallel query execution */
4749 if (phint && phint->nworkers > 0)
4752 * For Parallel Append to be planned properly, we shouldn't set
4753 * the costs of non-partial paths to disable-value. Lower the
4754 * priority of non-parallel paths by setting partial path costs
4757 foreach (l, rel->partial_pathlist)
4759 Path *path = (Path *) lfirst(l);
4761 path->startup_cost = 0;
4762 path->total_cost = 0;
4765 /* enforce number of workers if requested */
4766 if (phint->force_parallel)
4768 foreach (l, rel->partial_pathlist)
4770 Path *ppath = (Path *) lfirst(l);
4772 if (ppath->parallel_safe)
4773 ppath->parallel_workers = phint->nworkers;
4777 /* Generate gather paths */
4778 if (rel->reloptkind == RELOPT_BASEREL &&
4779 bms_membership(root->all_baserels) != BMS_SINGLETON)
4780 generate_gather_paths(root, rel, false);
4785 reset_hint_enforcement();
4790 * Build access paths for a base relation
4792 * This function was copied and edited from set_rel_pathlist() in
4793 * src/backend/optimizer/path/allpaths.c in order not to copy other static
4794 * functions not required here.
4797 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4798 Index rti, RangeTblEntry *rte)
4800 if (IS_DUMMY_REL(rel))
4802 /* We already proved the relation empty, so nothing more to do */
4806 /* It's an "append relation", process accordingly */
4807 set_append_rel_pathlist(root, rel, rti, rte);
4811 if (rel->rtekind == RTE_RELATION)
4813 if (rte->relkind == RELKIND_RELATION)
4815 if(rte->tablesample != NULL)
4816 elog(ERROR, "sampled relation is not supported");
4818 /* Plain relation */
4819 set_plain_rel_pathlist(root, rel, rte);
4822 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4825 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4829 * Allow a plugin to editorialize on the set of Paths for this base
4830 * relation. It could add new paths (such as CustomPaths) by calling
4831 * add_path(), or delete or modify paths added by the core code.
4833 if (set_rel_pathlist_hook)
4834 (*set_rel_pathlist_hook) (root, rel, rti, rte);
4836 /* Now find the cheapest of the paths for this rel */
4841 * stmt_beg callback is called when each query in PL/pgSQL function is about
4842 * to be executed. At that timing, we save query string in the global variable
4843 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4844 * variable for the purpose, because its content is only necessary until
4845 * planner hook is called for the query, so recursive PL/pgSQL function calls
4846 * don't harm this mechanism.
4849 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4851 plpgsql_recurse_level++;
4855 * stmt_end callback is called then each query in PL/pgSQL function has
4856 * finished. At that timing, we clear plpgsql_query_string to tell planner
4857 * hook that next call is not for a query written in PL/pgSQL block.
4860 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4862 plpgsql_recurse_level--;
4865 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4870 if (!isTopLevel || phase != RESOURCE_RELEASE_AFTER_LOCKS)
4872 /* Cancel plpgsql nest level*/
4873 plpgsql_recurse_level = 0;
4876 #define standard_join_search pg_hint_plan_standard_join_search
4877 #define join_search_one_level pg_hint_plan_join_search_one_level
4878 #define make_join_rel make_join_rel_wrapper
4881 #undef make_join_rel
4882 #define make_join_rel pg_hint_plan_make_join_rel
4883 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4884 #include "make_join_rel.c"
4886 #include "pg_stat_statements.c"