1 /*-------------------------------------------------------------------------
4 * hinting on how to execute a query for PostgreSQL
6 * Copyright (c) 2012-2020, 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/float.h"
42 #include "utils/lsyscache.h"
43 #include "utils/memutils.h"
44 #include "utils/rel.h"
45 #include "utils/snapmgr.h"
46 #include "utils/syscache.h"
47 #include "utils/resowner.h"
49 #include "catalog/pg_class.h"
51 #include "executor/spi.h"
52 #include "catalog/pg_type.h"
56 /* partially copied from pg_stat_statements */
57 #include "normalize_query.h"
60 #include "access/htup_details.h"
62 #ifdef PG_MODULE_MAGIC
66 #define BLOCK_COMMENT_START "/*"
67 #define BLOCK_COMMENT_END "*/"
68 #define HINT_COMMENT_KEYWORD "+"
69 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
70 #define HINT_END BLOCK_COMMENT_END
73 #define HINT_SEQSCAN "SeqScan"
74 #define HINT_INDEXSCAN "IndexScan"
75 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
76 #define HINT_BITMAPSCAN "BitmapScan"
77 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
78 #define HINT_TIDSCAN "TidScan"
79 #define HINT_NOSEQSCAN "NoSeqScan"
80 #define HINT_NOINDEXSCAN "NoIndexScan"
81 #define HINT_NOBITMAPSCAN "NoBitmapScan"
82 #define HINT_NOTIDSCAN "NoTidScan"
83 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
84 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
85 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
86 #define HINT_PARALLEL "Parallel"
88 #define HINT_NESTLOOP "NestLoop"
89 #define HINT_MERGEJOIN "MergeJoin"
90 #define HINT_HASHJOIN "HashJoin"
91 #define HINT_NONESTLOOP "NoNestLoop"
92 #define HINT_NOMERGEJOIN "NoMergeJoin"
93 #define HINT_NOHASHJOIN "NoHashJoin"
94 #define HINT_LEADING "Leading"
95 #define HINT_SET "Set"
96 #define HINT_ROWS "Rows"
98 #define HINT_ARRAY_DEFAULT_INITSIZE 8
100 #define hint_ereport(str, detail) hint_parse_ereport(str, detail)
101 #define hint_parse_ereport(str, detail) \
103 ereport(pg_hint_plan_parse_message_level, \
104 (errmsg("pg_hint_plan: hint syntax error at or near \"%s\"", (str)), \
105 errdetail detail)); \
108 #define skip_space(str) \
109 while (isspace(*str)) \
114 ENABLE_SEQSCAN = 0x01,
115 ENABLE_INDEXSCAN = 0x02,
116 ENABLE_BITMAPSCAN = 0x04,
117 ENABLE_TIDSCAN = 0x08,
118 ENABLE_INDEXONLYSCAN = 0x10
123 ENABLE_NESTLOOP = 0x01,
124 ENABLE_MERGEJOIN = 0x02,
125 ENABLE_HASHJOIN = 0x04
128 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
129 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
130 ENABLE_INDEXONLYSCAN)
131 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
132 #define DISABLE_ALL_SCAN 0
133 #define DISABLE_ALL_JOIN 0
135 /* hint keyword of enum type*/
136 typedef enum HintKeyword
138 HINT_KEYWORD_SEQSCAN,
139 HINT_KEYWORD_INDEXSCAN,
140 HINT_KEYWORD_INDEXSCANREGEXP,
141 HINT_KEYWORD_BITMAPSCAN,
142 HINT_KEYWORD_BITMAPSCANREGEXP,
143 HINT_KEYWORD_TIDSCAN,
144 HINT_KEYWORD_NOSEQSCAN,
145 HINT_KEYWORD_NOINDEXSCAN,
146 HINT_KEYWORD_NOBITMAPSCAN,
147 HINT_KEYWORD_NOTIDSCAN,
148 HINT_KEYWORD_INDEXONLYSCAN,
149 HINT_KEYWORD_INDEXONLYSCANREGEXP,
150 HINT_KEYWORD_NOINDEXONLYSCAN,
152 HINT_KEYWORD_NESTLOOP,
153 HINT_KEYWORD_MERGEJOIN,
154 HINT_KEYWORD_HASHJOIN,
155 HINT_KEYWORD_NONESTLOOP,
156 HINT_KEYWORD_NOMERGEJOIN,
157 HINT_KEYWORD_NOHASHJOIN,
159 HINT_KEYWORD_LEADING,
162 HINT_KEYWORD_PARALLEL,
164 HINT_KEYWORD_UNRECOGNIZED
167 #define SCAN_HINT_ACCEPTS_INDEX_NAMES(kw) \
168 (kw == HINT_KEYWORD_INDEXSCAN || \
169 kw == HINT_KEYWORD_INDEXSCANREGEXP || \
170 kw == HINT_KEYWORD_INDEXONLYSCAN || \
171 kw == HINT_KEYWORD_INDEXONLYSCANREGEXP || \
172 kw == HINT_KEYWORD_BITMAPSCAN || \
173 kw == HINT_KEYWORD_BITMAPSCANREGEXP)
176 typedef struct Hint Hint;
177 typedef struct HintState HintState;
179 typedef Hint *(*HintCreateFunction) (const char *hint_str,
181 HintKeyword hint_keyword);
182 typedef void (*HintDeleteFunction) (Hint *hint);
183 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf, bool nolf);
184 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
185 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
186 Query *parse, const char *str);
189 #define NUM_HINT_TYPE 6
190 typedef enum HintType
192 HINT_TYPE_SCAN_METHOD,
193 HINT_TYPE_JOIN_METHOD,
200 typedef enum HintTypeBitmap
202 HINT_BM_SCAN_METHOD = 1,
206 static const char *HintTypeName[] = {
216 typedef enum HintStatus
218 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
219 HINT_STATE_USED, /* hint is used */
220 HINT_STATE_DUPLICATION, /* specified hint duplication */
221 HINT_STATE_ERROR /* execute error (parse error does not include
225 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
226 (hint)->base.state == HINT_STATE_USED)
228 static unsigned int qno = 0;
229 static unsigned int msgqno = 0;
230 static char qnostr[32];
231 static const char *current_hint_str = NULL;
234 * However we usually take a hint stirng in post_parse_analyze_hook, we still
235 * need to do so in planner_hook when client starts query execution from the
236 * bind message on a prepared query. This variable prevent duplicate and
237 * sometimes harmful hint string retrieval.
239 static bool current_hint_retrieved = false;
241 /* common data for all hints. */
244 const char *hint_str; /* must not do pfree */
245 const char *keyword; /* must not do pfree */
246 HintKeyword hint_keyword;
249 HintDeleteFunction delete_func;
250 HintDescFunction desc_func;
251 HintCmpFunction cmp_func;
252 HintParseFunction parse_func;
255 /* scan method hints */
256 typedef struct ScanMethodHint
262 unsigned char enforce_mask;
265 typedef struct ParentIndexInfo
270 char *expression_str;
277 /* join method hints */
278 typedef struct JoinMethodHint
284 unsigned char enforce_mask;
286 Relids inner_joinrelids;
289 /* join order hints */
290 typedef struct OuterInnerRels
293 List *outer_inner_pair;
296 typedef struct LeadingHint
299 List *relations; /* relation names specified in Leading hint */
300 OuterInnerRels *outer_inner;
303 /* change a run-time parameter hints */
304 typedef struct SetHint
307 char *name; /* name of variable */
313 typedef enum RowsValueType {
314 RVT_ABSOLUTE, /* Rows(... #1000) */
315 RVT_ADD, /* Rows(... +1000) */
316 RVT_SUB, /* Rows(... -1000) */
317 RVT_MULTI, /* Rows(... *1.2) */
319 typedef struct RowsHint
326 Relids inner_joinrelids;
328 RowsValueType value_type;
333 typedef struct ParallelHint
337 char *nworkers_str; /* original string of nworkers */
338 int nworkers; /* num of workers specified by Worker */
339 bool force_parallel; /* force parallel scan */
343 * Describes a context of hint processing.
347 char *hint_str; /* original hint string */
350 int nall_hints; /* # of valid all hints */
351 int max_all_hints; /* # of slots for all hints */
352 Hint **all_hints; /* parsed all hints */
354 /* # of each hints */
355 int num_hints[NUM_HINT_TYPE];
357 /* for scan method hints */
358 ScanMethodHint **scan_hints; /* parsed scan hints */
360 /* Initial values of parameters */
361 int init_scan_mask; /* enable_* mask */
362 int init_nworkers; /* max_parallel_workers_per_gather */
363 /* min_parallel_table_scan_size*/
364 int init_min_para_tablescan_size;
365 /* min_parallel_index_scan_size*/
366 int init_min_para_indexscan_size;
367 double init_paratup_cost; /* parallel_tuple_cost */
368 double init_parasetup_cost;/* parallel_setup_cost */
370 PlannerInfo *current_root; /* PlannerInfo for the followings */
371 Index parent_relid; /* inherit parent of table relid */
372 ScanMethodHint *parent_scan_hint; /* scan hint for the parent */
373 ParallelHint *parent_parallel_hint; /* parallel hint for the parent */
374 List *parent_index_infos; /* list of parent table's index */
376 JoinMethodHint **join_hints; /* parsed join hints */
377 int init_join_mask; /* initial value join parameter */
378 List **join_hint_level;
379 LeadingHint **leading_hint; /* parsed Leading hints */
380 SetHint **set_hints; /* parsed Set hints */
381 GucContext context; /* which GUC parameters can we set? */
382 RowsHint **rows_hints; /* parsed Rows hints */
383 ParallelHint **parallel_hints; /* parsed Parallel hints */
387 * Describes a hint parser module which is bound with particular hint keyword.
389 typedef struct HintParser
392 HintCreateFunction create_func;
393 HintKeyword hint_keyword;
396 /* Module callbacks */
400 static void push_hint(HintState *hstate);
401 static void pop_hint(void);
403 static void pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query);
404 static void pg_hint_plan_ProcessUtility(PlannedStmt *pstmt,
405 const char *queryString,
406 ProcessUtilityContext context,
407 ParamListInfo params, QueryEnvironment *queryEnv,
408 DestReceiver *dest, char *completionTag);
409 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
410 ParamListInfo boundParams);
411 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
415 /* Scan method hint callbacks */
416 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
417 HintKeyword hint_keyword);
418 static void ScanMethodHintDelete(ScanMethodHint *hint);
419 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
420 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
421 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
422 Query *parse, const char *str);
424 /* Join method hint callbacks */
425 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
426 HintKeyword hint_keyword);
427 static void JoinMethodHintDelete(JoinMethodHint *hint);
428 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
429 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
430 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
431 Query *parse, const char *str);
433 /* Leading hint callbacks */
434 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
435 HintKeyword hint_keyword);
436 static void LeadingHintDelete(LeadingHint *hint);
437 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
438 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
439 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
440 Query *parse, const char *str);
442 /* Set hint callbacks */
443 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
444 HintKeyword hint_keyword);
445 static void SetHintDelete(SetHint *hint);
446 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
447 static int SetHintCmp(const SetHint *a, const SetHint *b);
448 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
451 /* Rows hint callbacks */
452 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
453 HintKeyword hint_keyword);
454 static void RowsHintDelete(RowsHint *hint);
455 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
456 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
457 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
458 Query *parse, const char *str);
460 /* Parallel hint callbacks */
461 static Hint *ParallelHintCreate(const char *hint_str, const char *keyword,
462 HintKeyword hint_keyword);
463 static void ParallelHintDelete(ParallelHint *hint);
464 static void ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf);
465 static int ParallelHintCmp(const ParallelHint *a, const ParallelHint *b);
466 static const char *ParallelHintParse(ParallelHint *hint, HintState *hstate,
467 Query *parse, const char *str);
469 static void quote_value(StringInfo buf, const char *value);
471 static const char *parse_quoted_value(const char *str, char **word,
474 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
477 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
478 void pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
479 Index rti, RangeTblEntry *rte);
480 static void create_plain_partial_paths(PlannerInfo *root,
482 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
483 ListCell *other_rels);
484 static void make_rels_by_clauseless_joins(PlannerInfo *root,
486 ListCell *other_rels);
487 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
488 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
490 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
491 Index rti, RangeTblEntry *rte);
492 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
495 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
497 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
499 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
503 static int set_config_option_noerror(const char *name, const char *value,
504 GucContext context, GucSource source,
505 GucAction action, bool changeVal, int elevel);
506 static void setup_scan_method_enforcement(ScanMethodHint *scanhint,
508 static int set_config_int32_option(const char *name, int32 value,
510 static int set_config_double_option(const char *name, double value,
514 static bool pg_hint_plan_enable_hint = true;
515 static int debug_level = 0;
516 static int pg_hint_plan_parse_message_level = INFO;
517 static int pg_hint_plan_debug_message_level = LOG;
518 /* Default is off, to keep backward compatibility. */
519 static bool pg_hint_plan_enable_hint_table = false;
521 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
522 static int recurse_level = 0; /* recursion level incl. direct SPI calls */
523 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
524 /* (This could not be above 1) */
525 static int max_hint_nworkers = -1; /* Maximum nworkers of Workers hints */
527 static const struct config_enum_entry parse_messages_level_options[] = {
528 {"debug", DEBUG2, true},
529 {"debug5", DEBUG5, false},
530 {"debug4", DEBUG4, false},
531 {"debug3", DEBUG3, false},
532 {"debug2", DEBUG2, false},
533 {"debug1", DEBUG1, false},
535 {"info", INFO, false},
536 {"notice", NOTICE, false},
537 {"warning", WARNING, false},
538 {"error", ERROR, false},
540 * {"fatal", FATAL, true},
541 * {"panic", PANIC, true},
546 static const struct config_enum_entry parse_debug_level_options[] = {
549 {"detailed", 2, false},
550 {"verbose", 3, false},
562 /* Saved hook values in case of unload */
563 static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
564 static planner_hook_type prev_planner = NULL;
565 static join_search_hook_type prev_join_search = NULL;
566 static set_rel_pathlist_hook_type prev_set_rel_pathlist = NULL;
567 static ProcessUtility_hook_type prev_ProcessUtility_hook = NULL;
569 /* Hold reference to currently active hint */
570 static HintState *current_hint_state = NULL;
573 * List of hint contexts. We treat the head of the list as the Top of the
574 * context stack, so current_hint_state always points the first element of this
577 static List *HintStateStack = NIL;
579 static const HintParser parsers[] = {
580 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
581 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
582 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
583 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
584 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
585 HINT_KEYWORD_BITMAPSCANREGEXP},
586 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
587 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
588 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
589 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
590 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
591 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
592 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
593 HINT_KEYWORD_INDEXONLYSCANREGEXP},
594 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
596 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
597 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
598 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
599 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
600 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
601 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
603 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
604 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
605 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
606 {HINT_PARALLEL, ParallelHintCreate, HINT_KEYWORD_PARALLEL},
608 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
611 PLpgSQL_plugin plugin_funcs = {
615 pg_hint_plan_plpgsql_stmt_beg,
616 pg_hint_plan_plpgsql_stmt_end,
622 * Module load callbacks
627 PLpgSQL_plugin **var_ptr;
629 /* Define custom GUC variables. */
630 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
631 "Force planner to use plans specified in the hint comment preceding to the query.",
633 &pg_hint_plan_enable_hint,
641 DefineCustomEnumVariable("pg_hint_plan.debug_print",
642 "Logs results of hint parsing.",
646 parse_debug_level_options,
653 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
654 "Message level of parse errors.",
656 &pg_hint_plan_parse_message_level,
658 parse_messages_level_options,
665 DefineCustomEnumVariable("pg_hint_plan.message_level",
666 "Message level of debug messages.",
668 &pg_hint_plan_debug_message_level,
670 parse_messages_level_options,
677 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
678 "Let pg_hint_plan look up the hint table.",
680 &pg_hint_plan_enable_hint_table,
689 prev_post_parse_analyze_hook = post_parse_analyze_hook;
690 post_parse_analyze_hook = pg_hint_plan_post_parse_analyze;
691 prev_planner = planner_hook;
692 planner_hook = pg_hint_plan_planner;
693 prev_join_search = join_search_hook;
694 join_search_hook = pg_hint_plan_join_search;
695 prev_set_rel_pathlist = set_rel_pathlist_hook;
696 set_rel_pathlist_hook = pg_hint_plan_set_rel_pathlist;
697 prev_ProcessUtility_hook = ProcessUtility_hook;
698 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
700 /* setup PL/pgSQL plugin hook */
701 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
702 *var_ptr = &plugin_funcs;
704 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
708 * Module unload callback
714 PLpgSQL_plugin **var_ptr;
716 /* Uninstall hooks. */
717 post_parse_analyze_hook = prev_post_parse_analyze_hook;
718 planner_hook = prev_planner;
719 join_search_hook = prev_join_search;
720 set_rel_pathlist_hook = prev_set_rel_pathlist;
721 ProcessUtility_hook = prev_ProcessUtility_hook;
723 /* uninstall PL/pgSQL plugin hook */
724 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
729 * create and delete functions the hint object
733 ScanMethodHintCreate(const char *hint_str, const char *keyword,
734 HintKeyword hint_keyword)
736 ScanMethodHint *hint;
738 hint = palloc(sizeof(ScanMethodHint));
739 hint->base.hint_str = hint_str;
740 hint->base.keyword = keyword;
741 hint->base.hint_keyword = hint_keyword;
742 hint->base.type = HINT_TYPE_SCAN_METHOD;
743 hint->base.state = HINT_STATE_NOTUSED;
744 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
745 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
746 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
747 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
748 hint->relname = NULL;
749 hint->indexnames = NIL;
750 hint->regexp = false;
751 hint->enforce_mask = 0;
753 return (Hint *) hint;
757 ScanMethodHintDelete(ScanMethodHint *hint)
763 pfree(hint->relname);
764 list_free_deep(hint->indexnames);
769 JoinMethodHintCreate(const char *hint_str, const char *keyword,
770 HintKeyword hint_keyword)
772 JoinMethodHint *hint;
774 hint = palloc(sizeof(JoinMethodHint));
775 hint->base.hint_str = hint_str;
776 hint->base.keyword = keyword;
777 hint->base.hint_keyword = hint_keyword;
778 hint->base.type = HINT_TYPE_JOIN_METHOD;
779 hint->base.state = HINT_STATE_NOTUSED;
780 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
781 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
782 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
783 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
785 hint->inner_nrels = 0;
786 hint->relnames = NULL;
787 hint->enforce_mask = 0;
788 hint->joinrelids = NULL;
789 hint->inner_joinrelids = NULL;
791 return (Hint *) hint;
795 JoinMethodHintDelete(JoinMethodHint *hint)
804 for (i = 0; i < hint->nrels; i++)
805 pfree(hint->relnames[i]);
806 pfree(hint->relnames);
809 bms_free(hint->joinrelids);
810 bms_free(hint->inner_joinrelids);
815 LeadingHintCreate(const char *hint_str, const char *keyword,
816 HintKeyword hint_keyword)
820 hint = palloc(sizeof(LeadingHint));
821 hint->base.hint_str = hint_str;
822 hint->base.keyword = keyword;
823 hint->base.hint_keyword = hint_keyword;
824 hint->base.type = HINT_TYPE_LEADING;
825 hint->base.state = HINT_STATE_NOTUSED;
826 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
827 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
828 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
829 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
830 hint->relations = NIL;
831 hint->outer_inner = NULL;
833 return (Hint *) hint;
837 LeadingHintDelete(LeadingHint *hint)
842 list_free_deep(hint->relations);
843 if (hint->outer_inner)
844 pfree(hint->outer_inner);
849 SetHintCreate(const char *hint_str, const char *keyword,
850 HintKeyword hint_keyword)
854 hint = palloc(sizeof(SetHint));
855 hint->base.hint_str = hint_str;
856 hint->base.keyword = keyword;
857 hint->base.hint_keyword = hint_keyword;
858 hint->base.type = HINT_TYPE_SET;
859 hint->base.state = HINT_STATE_NOTUSED;
860 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
861 hint->base.desc_func = (HintDescFunction) SetHintDesc;
862 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
863 hint->base.parse_func = (HintParseFunction) SetHintParse;
868 return (Hint *) hint;
872 SetHintDelete(SetHint *hint)
882 list_free(hint->words);
887 RowsHintCreate(const char *hint_str, const char *keyword,
888 HintKeyword hint_keyword)
892 hint = palloc(sizeof(RowsHint));
893 hint->base.hint_str = hint_str;
894 hint->base.keyword = keyword;
895 hint->base.hint_keyword = hint_keyword;
896 hint->base.type = HINT_TYPE_ROWS;
897 hint->base.state = HINT_STATE_NOTUSED;
898 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
899 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
900 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
901 hint->base.parse_func = (HintParseFunction) RowsHintParse;
903 hint->inner_nrels = 0;
904 hint->relnames = NULL;
905 hint->joinrelids = NULL;
906 hint->inner_joinrelids = NULL;
907 hint->rows_str = NULL;
908 hint->value_type = RVT_ABSOLUTE;
911 return (Hint *) hint;
915 RowsHintDelete(RowsHint *hint)
924 for (i = 0; i < hint->nrels; i++)
925 pfree(hint->relnames[i]);
926 pfree(hint->relnames);
929 bms_free(hint->joinrelids);
930 bms_free(hint->inner_joinrelids);
935 ParallelHintCreate(const char *hint_str, const char *keyword,
936 HintKeyword hint_keyword)
940 hint = palloc(sizeof(ParallelHint));
941 hint->base.hint_str = hint_str;
942 hint->base.keyword = keyword;
943 hint->base.hint_keyword = hint_keyword;
944 hint->base.type = HINT_TYPE_PARALLEL;
945 hint->base.state = HINT_STATE_NOTUSED;
946 hint->base.delete_func = (HintDeleteFunction) ParallelHintDelete;
947 hint->base.desc_func = (HintDescFunction) ParallelHintDesc;
948 hint->base.cmp_func = (HintCmpFunction) ParallelHintCmp;
949 hint->base.parse_func = (HintParseFunction) ParallelHintParse;
950 hint->relname = NULL;
952 hint->nworkers_str = "0";
954 return (Hint *) hint;
958 ParallelHintDelete(ParallelHint *hint)
964 pfree(hint->relname);
970 HintStateCreate(void)
974 hstate = palloc(sizeof(HintState));
975 hstate->hint_str = NULL;
976 hstate->nall_hints = 0;
977 hstate->max_all_hints = 0;
978 hstate->all_hints = NULL;
979 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
980 hstate->scan_hints = NULL;
981 hstate->init_scan_mask = 0;
982 hstate->init_nworkers = 0;
983 hstate->init_min_para_tablescan_size = 0;
984 hstate->init_min_para_indexscan_size = 0;
985 hstate->init_paratup_cost = 0;
986 hstate->init_parasetup_cost = 0;
987 hstate->current_root = NULL;
988 hstate->parent_relid = 0;
989 hstate->parent_scan_hint = NULL;
990 hstate->parent_parallel_hint = NULL;
991 hstate->parent_index_infos = NIL;
992 hstate->join_hints = NULL;
993 hstate->init_join_mask = 0;
994 hstate->join_hint_level = NULL;
995 hstate->leading_hint = NULL;
996 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
997 hstate->set_hints = NULL;
998 hstate->rows_hints = NULL;
999 hstate->parallel_hints = NULL;
1005 HintStateDelete(HintState *hstate)
1012 if (hstate->hint_str)
1013 pfree(hstate->hint_str);
1015 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1016 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
1017 if (hstate->all_hints)
1018 pfree(hstate->all_hints);
1019 if (hstate->parent_index_infos)
1020 list_free(hstate->parent_index_infos);
1024 * Copy given value into buf, with quoting with '"' if necessary.
1027 quote_value(StringInfo buf, const char *value)
1029 bool need_quote = false;
1032 for (str = value; *str != '\0'; str++)
1034 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
1037 appendStringInfoCharMacro(buf, '"');
1042 for (str = value; *str != '\0'; str++)
1045 appendStringInfoCharMacro(buf, '"');
1047 appendStringInfoCharMacro(buf, *str);
1051 appendStringInfoCharMacro(buf, '"');
1055 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
1059 appendStringInfo(buf, "%s(", hint->base.keyword);
1060 if (hint->relname != NULL)
1062 quote_value(buf, hint->relname);
1063 foreach(l, hint->indexnames)
1065 appendStringInfoCharMacro(buf, ' ');
1066 quote_value(buf, (char *) lfirst(l));
1069 appendStringInfoString(buf, ")");
1071 appendStringInfoChar(buf, '\n');
1075 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
1079 appendStringInfo(buf, "%s(", hint->base.keyword);
1080 if (hint->relnames != NULL)
1082 quote_value(buf, hint->relnames[0]);
1083 for (i = 1; i < hint->nrels; i++)
1085 appendStringInfoCharMacro(buf, ' ');
1086 quote_value(buf, hint->relnames[i]);
1089 appendStringInfoString(buf, ")");
1091 appendStringInfoChar(buf, '\n');
1095 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
1097 if (outer_inner->relation == NULL)
1104 appendStringInfoCharMacro(buf, '(');
1105 foreach(l, outer_inner->outer_inner_pair)
1110 appendStringInfoCharMacro(buf, ' ');
1112 OuterInnerDesc(lfirst(l), buf);
1115 appendStringInfoCharMacro(buf, ')');
1118 quote_value(buf, outer_inner->relation);
1122 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
1124 appendStringInfo(buf, "%s(", HINT_LEADING);
1125 if (hint->outer_inner == NULL)
1132 foreach(l, hint->relations)
1137 appendStringInfoCharMacro(buf, ' ');
1139 quote_value(buf, (char *) lfirst(l));
1143 OuterInnerDesc(hint->outer_inner, buf);
1145 appendStringInfoString(buf, ")");
1147 appendStringInfoChar(buf, '\n');
1151 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1153 bool is_first = true;
1156 appendStringInfo(buf, "%s(", HINT_SET);
1157 foreach(l, hint->words)
1162 appendStringInfoCharMacro(buf, ' ');
1164 quote_value(buf, (char *) lfirst(l));
1166 appendStringInfo(buf, ")");
1168 appendStringInfoChar(buf, '\n');
1172 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1176 appendStringInfo(buf, "%s(", hint->base.keyword);
1177 if (hint->relnames != NULL)
1179 quote_value(buf, hint->relnames[0]);
1180 for (i = 1; i < hint->nrels; i++)
1182 appendStringInfoCharMacro(buf, ' ');
1183 quote_value(buf, hint->relnames[i]);
1186 if (hint->rows_str != NULL)
1187 appendStringInfo(buf, " %s", hint->rows_str);
1188 appendStringInfoString(buf, ")");
1190 appendStringInfoChar(buf, '\n');
1194 ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf)
1196 appendStringInfo(buf, "%s(", hint->base.keyword);
1197 if (hint->relname != NULL)
1199 quote_value(buf, hint->relname);
1201 /* number of workers */
1202 appendStringInfoCharMacro(buf, ' ');
1203 quote_value(buf, hint->nworkers_str);
1204 /* application mode of num of workers */
1205 appendStringInfoCharMacro(buf, ' ');
1206 appendStringInfoString(buf,
1207 (hint->force_parallel ? "hard" : "soft"));
1209 appendStringInfoString(buf, ")");
1211 appendStringInfoChar(buf, '\n');
1215 * Append string which represents all hints in a given state to buf, with
1216 * preceding title with them.
1219 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1220 HintStatus state, bool nolf)
1224 appendStringInfo(buf, "%s:", title);
1226 appendStringInfoChar(buf, '\n');
1229 for (i = 0; i < hstate->nall_hints; i++)
1231 if (hstate->all_hints[i]->state != state)
1234 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1238 if (nolf && nshown == 0)
1239 appendStringInfoString(buf, "(none)");
1243 * Dump contents of given hstate to server log with log level LOG.
1246 HintStateDump(HintState *hstate)
1252 elog(pg_hint_plan_debug_message_level, "pg_hint_plan:\nno hint");
1256 initStringInfo(&buf);
1258 appendStringInfoString(&buf, "pg_hint_plan:\n");
1259 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1260 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1261 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1262 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1264 ereport(pg_hint_plan_debug_message_level,
1265 (errmsg ("%s", buf.data)));
1271 HintStateDump2(HintState *hstate)
1277 elog(pg_hint_plan_debug_message_level,
1278 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1282 initStringInfo(&buf);
1283 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1284 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1285 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1286 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1287 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1288 appendStringInfoChar(&buf, '}');
1290 ereport(pg_hint_plan_debug_message_level,
1291 (errmsg("%s", buf.data),
1293 errhidecontext(true)));
1303 RelnameCmp(const void *a, const void *b)
1305 const char *relnamea = *((const char **) a);
1306 const char *relnameb = *((const char **) b);
1308 return strcmp(relnamea, relnameb);
1312 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1314 return RelnameCmp(&a->relname, &b->relname);
1318 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1322 if (a->nrels != b->nrels)
1323 return a->nrels - b->nrels;
1325 for (i = 0; i < a->nrels; i++)
1328 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1336 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1342 SetHintCmp(const SetHint *a, const SetHint *b)
1344 return strcmp(a->name, b->name);
1348 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1352 if (a->nrels != b->nrels)
1353 return a->nrels - b->nrels;
1355 for (i = 0; i < a->nrels; i++)
1358 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1366 ParallelHintCmp(const ParallelHint *a, const ParallelHint *b)
1368 return RelnameCmp(&a->relname, &b->relname);
1372 HintCmp(const void *a, const void *b)
1374 const Hint *hinta = *((const Hint **) a);
1375 const Hint *hintb = *((const Hint **) b);
1377 if (hinta->type != hintb->type)
1378 return hinta->type - hintb->type;
1379 if (hinta->state == HINT_STATE_ERROR)
1381 if (hintb->state == HINT_STATE_ERROR)
1383 return hinta->cmp_func(hinta, hintb);
1387 * Returns byte offset of hint b from hint a. If hint a was specified before
1388 * b, positive value is returned.
1391 HintCmpWithPos(const void *a, const void *b)
1393 const Hint *hinta = *((const Hint **) a);
1394 const Hint *hintb = *((const Hint **) b);
1397 result = HintCmp(a, b);
1399 result = hinta->hint_str - hintb->hint_str;
1408 parse_keyword(const char *str, StringInfo buf)
1412 while (!isspace(*str) && *str != '(' && *str != '\0')
1413 appendStringInfoCharMacro(buf, *str++);
1419 skip_parenthesis(const char *str, char parenthesis)
1423 if (*str != parenthesis)
1425 if (parenthesis == '(')
1426 hint_ereport(str, ("Opening parenthesis is necessary."));
1427 else if (parenthesis == ')')
1428 hint_ereport(str, ("Closing parenthesis is necessary."));
1439 * Parse a token from str, and store malloc'd copy into word. A token can be
1440 * quoted with '"'. Return value is pointer to unparsed portion of original
1441 * string, or NULL if an error occurred.
1443 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1446 parse_quoted_value(const char *str, char **word, bool truncate)
1451 /* Skip leading spaces. */
1454 initStringInfo(&buf);
1467 /* Double quotation must be closed. */
1471 hint_ereport(str, ("Unterminated quoted string."));
1476 * Skip escaped double quotation.
1478 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1479 * block comments) to be an object name, so users must specify
1480 * alias for such object names.
1482 * Those special names can be allowed if we care escaped slashes
1483 * and asterisks, but we don't.
1492 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1496 appendStringInfoCharMacro(&buf, *str++);
1501 hint_ereport(str, ("Zero-length delimited string."));
1508 /* Truncate name if it's too long */
1510 truncate_identifier(buf.data, strlen(buf.data), true);
1517 static OuterInnerRels *
1518 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1520 OuterInnerRels *outer_inner;
1522 outer_inner = palloc(sizeof(OuterInnerRels));
1523 outer_inner->relation = name;
1524 outer_inner->outer_inner_pair = outer_inner_list;
1530 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1532 List *outer_inner_pair = NIL;
1534 if ((str = skip_parenthesis(str, '(')) == NULL)
1539 /* Store words in parentheses into outer_inner_list. */
1540 while(*str != ')' && *str != '\0')
1542 OuterInnerRels *outer_inner_rels;
1546 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1554 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1557 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1560 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1565 (str = skip_parenthesis(str, ')')) == NULL)
1567 list_free(outer_inner_pair);
1571 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1577 parse_parentheses_Leading(const char *str, List **name_list,
1578 OuterInnerRels **outer_inner)
1581 bool truncate = true;
1583 if ((str = skip_parenthesis(str, '(')) == NULL)
1589 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1594 /* Store words in parentheses into name_list. */
1595 while(*str != ')' && *str != '\0')
1597 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1599 list_free(*name_list);
1603 *name_list = lappend(*name_list, name);
1608 if ((str = skip_parenthesis(str, ')')) == NULL)
1614 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1617 bool truncate = true;
1619 if ((str = skip_parenthesis(str, '(')) == NULL)
1624 /* Store words in parentheses into name_list. */
1625 while(*str != ')' && *str != '\0')
1627 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1629 list_free(*name_list);
1633 *name_list = lappend(*name_list, name);
1636 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1637 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1638 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1639 keyword == HINT_KEYWORD_SET)
1645 if ((str = skip_parenthesis(str, ')')) == NULL)
1651 parse_hints(HintState *hstate, Query *parse, const char *str)
1656 initStringInfo(&buf);
1657 while (*str != '\0')
1659 const HintParser *parser;
1661 /* in error message, we output the comment including the keyword. */
1662 head = (char *) str;
1664 /* parse only the keyword of the hint. */
1665 resetStringInfo(&buf);
1666 str = parse_keyword(str, &buf);
1668 for (parser = parsers; parser->keyword != NULL; parser++)
1670 char *keyword = parser->keyword;
1673 if (pg_strcasecmp(buf.data, keyword) != 0)
1676 hint = parser->create_func(head, keyword, parser->hint_keyword);
1678 /* parser of each hint does parse in a parenthesis. */
1679 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1681 hint->delete_func(hint);
1687 * Add hint information into all_hints array. If we don't have
1688 * enough space, double the array.
1690 if (hstate->nall_hints == 0)
1692 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1693 hstate->all_hints = (Hint **)
1694 palloc(sizeof(Hint *) * hstate->max_all_hints);
1696 else if (hstate->nall_hints == hstate->max_all_hints)
1698 hstate->max_all_hints *= 2;
1699 hstate->all_hints = (Hint **)
1700 repalloc(hstate->all_hints,
1701 sizeof(Hint *) * hstate->max_all_hints);
1704 hstate->all_hints[hstate->nall_hints] = hint;
1705 hstate->nall_hints++;
1712 if (parser->keyword == NULL)
1715 ("Unrecognized hint keyword \"%s\".", buf.data));
1726 * Get hints from table by client-supplied query string and application name.
1729 get_hints_from_table(const char *client_query, const char *client_application)
1731 const char *search_query =
1733 " FROM hint_plan.hints "
1734 " WHERE norm_query_string = $1 "
1735 " AND ( application_name = $2 "
1736 " OR application_name = '' ) "
1737 " ORDER BY application_name DESC";
1738 static SPIPlanPtr plan = NULL;
1740 Oid argtypes[2] = { TEXTOID, TEXTOID };
1742 char nulls[2] = {' ', ' '};
1748 bool snapshot_set = false;
1750 hint_inhibit_level++;
1752 if (!ActiveSnapshotSet())
1754 PushActiveSnapshot(GetTransactionSnapshot());
1755 snapshot_set = true;
1763 p = SPI_prepare(search_query, 2, argtypes);
1764 plan = SPI_saveplan(p);
1768 qry = cstring_to_text(client_query);
1769 app = cstring_to_text(client_application);
1770 values[0] = PointerGetDatum(qry);
1771 values[1] = PointerGetDatum(app);
1773 SPI_execute_plan(plan, values, nulls, true, 1);
1775 if (SPI_processed > 0)
1779 hints = SPI_getvalue(SPI_tuptable->vals[0],
1780 SPI_tuptable->tupdesc, 1);
1782 * Here we use SPI_palloc to ensure that hints string is valid even
1783 * after SPI_finish call. We can't use simple palloc because it
1784 * allocates memory in SPI's context and that context is deleted in
1787 buf = SPI_palloc(strlen(hints) + 1);
1795 PopActiveSnapshot();
1797 hint_inhibit_level--;
1801 hint_inhibit_level--;
1810 * Get client-supplied query string. Addtion to that the jumbled query is
1811 * supplied if the caller requested. From the restriction of JumbleQuery, some
1812 * kind of query needs special amendments. Reutrns NULL if this query doesn't
1813 * change the current hint. This function returns NULL also when something
1814 * wrong has happend and let the caller continue using the current hints.
1817 get_query_string(ParseState *pstate, Query *query, Query **jumblequery)
1819 const char *p = debug_query_string;
1822 * If debug_query_string is set, it is the top level statement. But in some
1823 * cases we reach here with debug_query_string set NULL for example in the
1824 * case of DESCRIBE message handling or EXECUTE command. We may still see a
1825 * candidate top-level query in pstate in the case.
1827 if (pstate && pstate->p_sourcetext)
1828 p = pstate->p_sourcetext;
1830 /* We don't see a query string, return NULL */
1834 if (jumblequery != NULL)
1835 *jumblequery = query;
1837 if (query->commandType == CMD_UTILITY)
1839 Query *target_query = (Query *)query->utilityStmt;
1842 * Some CMD_UTILITY statements have a subquery that we can hint on.
1843 * Since EXPLAIN can be placed before other kind of utility statements
1844 * and EXECUTE can be contained other kind of utility statements, these
1845 * conditions are not mutually exclusive and should be considered in
1848 if (IsA(target_query, ExplainStmt))
1850 ExplainStmt *stmt = (ExplainStmt *)target_query;
1852 Assert(IsA(stmt->query, Query));
1853 target_query = (Query *)stmt->query;
1855 /* strip out the top-level query for further processing */
1856 if (target_query->commandType == CMD_UTILITY &&
1857 target_query->utilityStmt != NULL)
1858 target_query = (Query *)target_query->utilityStmt;
1861 if (IsA(target_query, DeclareCursorStmt))
1863 DeclareCursorStmt *stmt = (DeclareCursorStmt *)target_query;
1864 Query *query = (Query *)stmt->query;
1866 /* the target must be CMD_SELECT in this case */
1867 Assert(IsA(query, Query) && query->commandType == CMD_SELECT);
1868 target_query = query;
1871 if (IsA(target_query, CreateTableAsStmt))
1873 CreateTableAsStmt *stmt = (CreateTableAsStmt *) target_query;
1875 Assert(IsA(stmt->query, Query));
1876 target_query = (Query *) stmt->query;
1878 /* strip out the top-level query for further processing */
1879 if (target_query->commandType == CMD_UTILITY &&
1880 target_query->utilityStmt != NULL)
1881 target_query = (Query *)target_query->utilityStmt;
1884 if (IsA(target_query, ExecuteStmt))
1887 * Use the prepared query for EXECUTE. The Query for jumble
1888 * also replaced with the corresponding one.
1890 ExecuteStmt *stmt = (ExecuteStmt *)target_query;
1891 PreparedStatement *entry;
1893 entry = FetchPreparedStatement(stmt->name, true);
1895 if (entry->plansource->is_valid)
1897 p = entry->plansource->query_string;
1898 target_query = (Query *) linitial (entry->plansource->query_list);
1902 /* igonre the hint for EXECUTE if invalidated */
1904 target_query = NULL;
1908 /* JumbleQuery accespts only a non-utility Query */
1910 (!IsA(target_query, Query) ||
1911 target_query->utilityStmt != NULL))
1912 target_query = NULL;
1915 *jumblequery = target_query;
1918 * Return NULL if pstate is not of top-level query. We don't need this
1919 * when jumble info is not requested or cannot do this when pstate is NULL.
1921 else if (!jumblequery && pstate && pstate->p_sourcetext != p &&
1922 strcmp(pstate->p_sourcetext, p) != 0)
1929 * Get hints from the head block comment in client-supplied query string.
1932 get_hints_from_comment(const char *p)
1934 const char *hint_head;
1942 /* extract query head comment. */
1943 hint_head = strstr(p, HINT_START);
1944 if (hint_head == NULL)
1946 for (;p < hint_head; p++)
1949 * Allow these characters precedes hint comment:
1951 * - alphabets which are in ASCII range
1952 * - space, tabs and new-lines
1953 * - underscores, for identifier
1954 * - commas, for SELECT clause, EXPLAIN and PREPARE
1955 * - parentheses, for EXPLAIN and PREPARE
1957 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1958 * avoid behavior which depends on locale setting.
1960 if (!(*p >= '0' && *p <= '9') &&
1961 !(*p >= 'A' && *p <= 'Z') &&
1962 !(*p >= 'a' && *p <= 'z') &&
1966 *p != '(' && *p != ')')
1970 len = strlen(HINT_START);
1975 /* find hint end keyword. */
1976 if ((tail = strstr(p, HINT_END)) == NULL)
1978 hint_ereport(head, ("Unterminated block comment."));
1982 /* We don't support nested block comments. */
1983 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1985 hint_ereport(head, ("Nested block comments are not supported."));
1989 /* Make a copy of hint. */
1991 head = palloc(len + 1);
1992 memcpy(head, p, len);
2000 * Parse hints that got, create hint struct from parse tree and parse hints.
2003 create_hintstate(Query *parse, const char *hints)
2012 /* -1 means that no Parallel hint is specified. */
2013 max_hint_nworkers = -1;
2016 hstate = HintStateCreate();
2017 hstate->hint_str = (char *) hints;
2019 /* parse each hint. */
2020 parse_hints(hstate, parse, p);
2022 /* When nothing specified a hint, we free HintState and returns NULL. */
2023 if (hstate->nall_hints == 0)
2025 HintStateDelete(hstate);
2029 /* Sort hints in order of original position. */
2030 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
2033 /* Count number of hints per hint-type. */
2034 for (i = 0; i < hstate->nall_hints; i++)
2036 Hint *cur_hint = hstate->all_hints[i];
2037 hstate->num_hints[cur_hint->type]++;
2041 * If an object (or a set of objects) has multiple hints of same hint-type,
2042 * only the last hint is valid and others are ignored in planning.
2043 * Hints except the last are marked as 'duplicated' to remember the order.
2045 for (i = 0; i < hstate->nall_hints - 1; i++)
2047 Hint *cur_hint = hstate->all_hints[i];
2048 Hint *next_hint = hstate->all_hints[i + 1];
2051 * Leading hint is marked as 'duplicated' in transform_join_hints.
2053 if (cur_hint->type == HINT_TYPE_LEADING &&
2054 next_hint->type == HINT_TYPE_LEADING)
2058 * Note that we need to pass addresses of hint pointers, because
2059 * HintCmp is designed to sort array of Hint* by qsort.
2061 if (HintCmp(&cur_hint, &next_hint) == 0)
2063 hint_ereport(cur_hint->hint_str,
2064 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
2065 cur_hint->state = HINT_STATE_DUPLICATION;
2070 * Make sure that per-type array pointers point proper position in the
2071 * array which consists of all hints.
2073 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
2074 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
2075 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
2076 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
2077 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
2078 hstate->set_hints = (SetHint **) (hstate->leading_hint +
2079 hstate->num_hints[HINT_TYPE_LEADING]);
2080 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
2081 hstate->num_hints[HINT_TYPE_SET]);
2082 hstate->parallel_hints = (ParallelHint **) (hstate->rows_hints +
2083 hstate->num_hints[HINT_TYPE_ROWS]);
2089 * Parse inside of parentheses of scan-method hints.
2092 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
2095 const char *keyword = hint->base.keyword;
2096 HintKeyword hint_keyword = hint->base.hint_keyword;
2097 List *name_list = NIL;
2100 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2103 /* Parse relation name and index name(s) if given hint accepts. */
2104 length = list_length(name_list);
2106 /* at least twp parameters required */
2110 ("%s hint requires a relation.", hint->base.keyword));
2111 hint->base.state = HINT_STATE_ERROR;
2115 hint->relname = linitial(name_list);
2116 hint->indexnames = list_delete_first(name_list);
2118 /* check whether the hint accepts index name(s) */
2119 if (length > 1 && !SCAN_HINT_ACCEPTS_INDEX_NAMES(hint_keyword))
2122 ("%s hint accepts only one relation.",
2123 hint->base.keyword));
2124 hint->base.state = HINT_STATE_ERROR;
2128 /* Set a bit for specified hint. */
2129 switch (hint_keyword)
2131 case HINT_KEYWORD_SEQSCAN:
2132 hint->enforce_mask = ENABLE_SEQSCAN;
2134 case HINT_KEYWORD_INDEXSCAN:
2135 hint->enforce_mask = ENABLE_INDEXSCAN;
2137 case HINT_KEYWORD_INDEXSCANREGEXP:
2138 hint->enforce_mask = ENABLE_INDEXSCAN;
2139 hint->regexp = true;
2141 case HINT_KEYWORD_BITMAPSCAN:
2142 hint->enforce_mask = ENABLE_BITMAPSCAN;
2144 case HINT_KEYWORD_BITMAPSCANREGEXP:
2145 hint->enforce_mask = ENABLE_BITMAPSCAN;
2146 hint->regexp = true;
2148 case HINT_KEYWORD_TIDSCAN:
2149 hint->enforce_mask = ENABLE_TIDSCAN;
2151 case HINT_KEYWORD_NOSEQSCAN:
2152 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
2154 case HINT_KEYWORD_NOINDEXSCAN:
2155 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
2157 case HINT_KEYWORD_NOBITMAPSCAN:
2158 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
2160 case HINT_KEYWORD_NOTIDSCAN:
2161 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
2163 case HINT_KEYWORD_INDEXONLYSCAN:
2164 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2166 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
2167 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2168 hint->regexp = true;
2170 case HINT_KEYWORD_NOINDEXONLYSCAN:
2171 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
2174 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2183 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2186 const char *keyword = hint->base.keyword;
2187 HintKeyword hint_keyword = hint->base.hint_keyword;
2188 List *name_list = NIL;
2190 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2193 hint->nrels = list_length(name_list);
2195 if (hint->nrels > 0)
2201 * Transform relation names from list to array to sort them with qsort
2204 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2205 foreach (l, name_list)
2207 hint->relnames[i] = lfirst(l);
2212 list_free(name_list);
2214 /* A join hint requires at least two relations */
2215 if (hint->nrels < 2)
2218 ("%s hint requires at least two relations.",
2219 hint->base.keyword));
2220 hint->base.state = HINT_STATE_ERROR;
2224 /* Sort hints in alphabetical order of relation names. */
2225 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2227 switch (hint_keyword)
2229 case HINT_KEYWORD_NESTLOOP:
2230 hint->enforce_mask = ENABLE_NESTLOOP;
2232 case HINT_KEYWORD_MERGEJOIN:
2233 hint->enforce_mask = ENABLE_MERGEJOIN;
2235 case HINT_KEYWORD_HASHJOIN:
2236 hint->enforce_mask = ENABLE_HASHJOIN;
2238 case HINT_KEYWORD_NONESTLOOP:
2239 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2241 case HINT_KEYWORD_NOMERGEJOIN:
2242 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2244 case HINT_KEYWORD_NOHASHJOIN:
2245 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2248 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2257 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2260 if (outer_inner->outer_inner_pair == NIL)
2262 if (outer_inner->relation)
2268 if (list_length(outer_inner->outer_inner_pair) == 2)
2270 foreach(l, outer_inner->outer_inner_pair)
2272 if (!OuterInnerPairCheck(lfirst(l)))
2283 OuterInnerList(OuterInnerRels *outer_inner)
2285 List *outer_inner_list = NIL;
2287 OuterInnerRels *outer_inner_rels;
2289 foreach(l, outer_inner->outer_inner_pair)
2291 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2293 if (outer_inner_rels->relation != NULL)
2294 outer_inner_list = lappend(outer_inner_list,
2295 outer_inner_rels->relation);
2297 outer_inner_list = list_concat(outer_inner_list,
2298 OuterInnerList(outer_inner_rels));
2300 return outer_inner_list;
2304 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2307 List *name_list = NIL;
2308 OuterInnerRels *outer_inner = NULL;
2310 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2314 if (outer_inner != NULL)
2315 name_list = OuterInnerList(outer_inner);
2317 hint->relations = name_list;
2318 hint->outer_inner = outer_inner;
2320 /* A Leading hint requires at least two relations */
2321 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2323 hint_ereport(hint->base.hint_str,
2324 ("%s hint requires at least two relations.",
2326 hint->base.state = HINT_STATE_ERROR;
2328 else if (hint->outer_inner != NULL &&
2329 !OuterInnerPairCheck(hint->outer_inner))
2331 hint_ereport(hint->base.hint_str,
2332 ("%s hint requires two sets of relations when parentheses nests.",
2334 hint->base.state = HINT_STATE_ERROR;
2341 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2343 List *name_list = NIL;
2345 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2349 hint->words = name_list;
2351 /* We need both name and value to set GUC parameter. */
2352 if (list_length(name_list) == 2)
2354 hint->name = linitial(name_list);
2355 hint->value = lsecond(name_list);
2359 hint_ereport(hint->base.hint_str,
2360 ("%s hint requires name and value of GUC parameter.",
2362 hint->base.state = HINT_STATE_ERROR;
2369 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2372 HintKeyword hint_keyword = hint->base.hint_keyword;
2373 List *name_list = NIL;
2379 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2382 /* Last element must be rows specification */
2383 hint->nrels = list_length(name_list) - 1;
2385 if (hint->nrels < 1)
2388 ("%s hint needs at least one relation followed by one correction term.",
2389 hint->base.keyword));
2390 hint->base.state = HINT_STATE_ERROR;
2397 * Transform relation names from list to array to sort them with qsort
2400 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2401 foreach (l, name_list)
2403 if (hint->nrels <= i)
2405 hint->relnames[i] = lfirst(l);
2409 /* Retieve rows estimation */
2410 rows_str = list_nth(name_list, hint->nrels);
2411 hint->rows_str = rows_str; /* store as-is for error logging */
2412 if (rows_str[0] == '#')
2414 hint->value_type = RVT_ABSOLUTE;
2417 else if (rows_str[0] == '+')
2419 hint->value_type = RVT_ADD;
2422 else if (rows_str[0] == '-')
2424 hint->value_type = RVT_SUB;
2427 else if (rows_str[0] == '*')
2429 hint->value_type = RVT_MULTI;
2434 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2435 hint->base.state = HINT_STATE_ERROR;
2438 hint->rows = strtod(rows_str, &end_ptr);
2441 hint_ereport(rows_str,
2442 ("%s hint requires valid number as rows estimation.",
2443 hint->base.keyword));
2444 hint->base.state = HINT_STATE_ERROR;
2448 /* A join hint requires at least two relations */
2449 if (hint->nrels < 2)
2452 ("%s hint requires at least two relations.",
2453 hint->base.keyword));
2454 hint->base.state = HINT_STATE_ERROR;
2458 list_free(name_list);
2460 /* Sort relnames in alphabetical order. */
2461 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2467 ParallelHintParse(ParallelHint *hint, HintState *hstate, Query *parse,
2470 HintKeyword hint_keyword = hint->base.hint_keyword;
2471 List *name_list = NIL;
2475 bool force_parallel = false;
2477 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2480 /* Parse relation name and index name(s) if given hint accepts. */
2481 length = list_length(name_list);
2483 if (length < 2 || length > 3)
2486 ("wrong number of arguments (%d): %s",
2487 length, hint->base.keyword));
2488 hint->base.state = HINT_STATE_ERROR;
2492 hint->relname = linitial(name_list);
2494 /* The second parameter is number of workers */
2495 hint->nworkers_str = list_nth(name_list, 1);
2496 nworkers = strtod(hint->nworkers_str, &end_ptr);
2497 if (*end_ptr || nworkers < 0 || nworkers > max_worker_processes)
2500 hint_ereport(hint->nworkers_str,
2501 ("number of workers must be a number: %s",
2502 hint->base.keyword));
2503 else if (nworkers < 0)
2504 hint_ereport(hint->nworkers_str,
2505 ("number of workers must be positive: %s",
2506 hint->base.keyword));
2507 else if (nworkers > max_worker_processes)
2508 hint_ereport(hint->nworkers_str,
2509 ("number of workers = %d is larger than max_worker_processes(%d): %s",
2510 nworkers, max_worker_processes, hint->base.keyword));
2512 hint->base.state = HINT_STATE_ERROR;
2515 hint->nworkers = nworkers;
2517 /* optional third parameter is specified */
2520 const char *modeparam = (const char *)list_nth(name_list, 2);
2521 if (pg_strcasecmp(modeparam, "hard") == 0)
2522 force_parallel = true;
2523 else if (pg_strcasecmp(modeparam, "soft") != 0)
2525 hint_ereport(modeparam,
2526 ("enforcement must be soft or hard: %s",
2527 hint->base.keyword));
2528 hint->base.state = HINT_STATE_ERROR;
2532 hint->force_parallel = force_parallel;
2534 if (hint->base.state != HINT_STATE_ERROR &&
2535 nworkers > max_hint_nworkers)
2536 max_hint_nworkers = nworkers;
2542 * set GUC parameter functions
2546 get_current_scan_mask()
2551 mask |= ENABLE_SEQSCAN;
2552 if (enable_indexscan)
2553 mask |= ENABLE_INDEXSCAN;
2554 if (enable_bitmapscan)
2555 mask |= ENABLE_BITMAPSCAN;
2557 mask |= ENABLE_TIDSCAN;
2558 if (enable_indexonlyscan)
2559 mask |= ENABLE_INDEXONLYSCAN;
2565 get_current_join_mask()
2569 if (enable_nestloop)
2570 mask |= ENABLE_NESTLOOP;
2571 if (enable_mergejoin)
2572 mask |= ENABLE_MERGEJOIN;
2573 if (enable_hashjoin)
2574 mask |= ENABLE_HASHJOIN;
2580 * Sets GUC prameters without throwing exception. Reutrns false if something
2584 set_config_option_noerror(const char *name, const char *value,
2585 GucContext context, GucSource source,
2586 GucAction action, bool changeVal, int elevel)
2589 MemoryContext ccxt = CurrentMemoryContext;
2593 result = set_config_option(name, value, context, source,
2594 action, changeVal, 0, false);
2600 /* Save error info */
2601 MemoryContextSwitchTo(ccxt);
2602 errdata = CopyErrorData();
2606 (errcode(errdata->sqlerrcode),
2607 errmsg("%s", errdata->message),
2608 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2609 errdata->hint ? errhint("%s", errdata->hint) : 0));
2611 FreeErrorData(errdata);
2619 * Sets GUC parameter of int32 type without throwing exceptions. Returns false
2620 * if something wrong.
2623 set_config_int32_option(const char *name, int32 value, GucContext context)
2625 char buf[16]; /* enough for int32 */
2627 if (snprintf(buf, 16, "%d", value) < 0)
2629 ereport(pg_hint_plan_parse_message_level,
2630 (errmsg ("Failed to convert integer to string: %d", value)));
2635 set_config_option_noerror(name, buf, context,
2636 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2637 pg_hint_plan_parse_message_level);
2641 * Sets GUC parameter of double type without throwing exceptions. Returns false
2642 * if something wrong.
2645 set_config_double_option(const char *name, double value, GucContext context)
2647 char *buf = float8out_internal(value);
2650 result = set_config_option_noerror(name, buf, context,
2651 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2652 pg_hint_plan_parse_message_level);
2657 /* setup scan method enforcement according to given options */
2659 setup_guc_enforcement(SetHint **options, int noptions, GucContext context)
2663 for (i = 0; i < noptions; i++)
2665 SetHint *hint = options[i];
2668 if (!hint_state_enabled(hint))
2671 result = set_config_option_noerror(hint->name, hint->value, context,
2672 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2673 pg_hint_plan_parse_message_level);
2675 hint->base.state = HINT_STATE_USED;
2677 hint->base.state = HINT_STATE_ERROR;
2684 * Setup parallel execution environment.
2686 * If hint is not NULL, set up using it, elsewise reset to initial environment.
2689 setup_parallel_plan_enforcement(ParallelHint *hint, HintState *state)
2693 hint->base.state = HINT_STATE_USED;
2694 set_config_int32_option("max_parallel_workers_per_gather",
2695 hint->nworkers, state->context);
2698 set_config_int32_option("max_parallel_workers_per_gather",
2699 state->init_nworkers, state->context);
2701 /* force means that enforce parallel as far as possible */
2702 if (hint && hint->force_parallel && hint->nworkers > 0)
2704 set_config_double_option("parallel_tuple_cost", 0.0, state->context);
2705 set_config_double_option("parallel_setup_cost", 0.0, state->context);
2706 set_config_int32_option("min_parallel_table_scan_size", 0,
2708 set_config_int32_option("min_parallel_index_scan_size", 0,
2713 set_config_double_option("parallel_tuple_cost",
2714 state->init_paratup_cost, state->context);
2715 set_config_double_option("parallel_setup_cost",
2716 state->init_parasetup_cost, state->context);
2717 set_config_int32_option("min_parallel_table_scan_size",
2718 state->init_min_para_tablescan_size,
2720 set_config_int32_option("min_parallel_index_scan_size",
2721 state->init_min_para_indexscan_size,
2726 #define SET_CONFIG_OPTION(name, type_bits) \
2727 set_config_option_noerror((name), \
2728 (mask & (type_bits)) ? "true" : "false", \
2729 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2733 * Setup GUC environment to enforce scan methods. If scanhint is NULL, reset
2734 * GUCs to the saved state in state.
2737 setup_scan_method_enforcement(ScanMethodHint *scanhint, HintState *state)
2739 unsigned char enforce_mask = state->init_scan_mask;
2740 GucContext context = state->context;
2745 enforce_mask = scanhint->enforce_mask;
2746 scanhint->base.state = HINT_STATE_USED;
2749 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2750 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2751 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2753 mask = enforce_mask;
2755 mask = enforce_mask & current_hint_state->init_scan_mask;
2757 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2758 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2759 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2760 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2761 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2765 set_join_config_options(unsigned char enforce_mask, GucContext context)
2769 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2770 enforce_mask == ENABLE_HASHJOIN)
2771 mask = enforce_mask;
2773 mask = enforce_mask & current_hint_state->init_join_mask;
2775 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2776 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2777 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2780 * Hash join may be rejected for the reason of estimated memory usage. Try
2781 * getting rid of that limitation. This change on work_mem is reverted just
2782 * after searching join path so no suginificant side-effects are expected.
2784 if (enforce_mask == ENABLE_HASHJOIN)
2788 /* See final_cost_hashjoin(). */
2789 if (work_mem < MAX_KILOBYTES)
2791 snprintf(buf, sizeof(buf), UINT64_FORMAT, (uint64)MAX_KILOBYTES);
2792 set_config_option_noerror("work_mem", buf,
2793 context, PGC_S_SESSION, GUC_ACTION_SAVE,
2800 * Push a hint into hint stack which is implemented with List struct. Head of
2801 * list is top of stack.
2804 push_hint(HintState *hstate)
2806 /* Prepend new hint to the list means pushing to stack. */
2807 HintStateStack = lcons(hstate, HintStateStack);
2809 /* Pushed hint is the one which should be used hereafter. */
2810 current_hint_state = hstate;
2813 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2817 /* Hint stack must not be empty. */
2818 if(HintStateStack == NIL)
2819 elog(ERROR, "hint stack is empty");
2822 * Take a hint at the head from the list, and free it. Switch
2823 * current_hint_state to point new head (NULL if the list is empty).
2825 HintStateStack = list_delete_first(HintStateStack);
2826 HintStateDelete(current_hint_state);
2827 if(HintStateStack == NIL)
2828 current_hint_state = NULL;
2830 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
2834 * Retrieve and store hint string from given query or from the hint table.
2837 get_current_hint_string(ParseState *pstate, Query *query)
2839 const char *query_str;
2840 MemoryContext oldcontext;
2842 /* do nothing under hint table search */
2843 if (hint_inhibit_level > 0)
2846 /* We alredy have one, don't parse it again. */
2847 if (current_hint_retrieved)
2850 /* Don't parse the current query hereafter */
2851 current_hint_retrieved = true;
2853 if (!pg_hint_plan_enable_hint)
2855 if (current_hint_str)
2857 pfree((void *)current_hint_str);
2858 current_hint_str = NULL;
2863 /* increment the query number */
2865 if (debug_level > 1)
2866 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2869 /* search the hint table for a hint if requested */
2870 if (pg_hint_plan_enable_hint_table)
2873 pgssJumbleState jstate;
2875 char *normalized_query = NULL;
2877 query_str = get_query_string(pstate, query, &jumblequery);
2879 /* If this query is not for hint, just return */
2883 /* clear the previous hint string */
2884 if (current_hint_str)
2886 pfree((void *)current_hint_str);
2887 current_hint_str = NULL;
2893 * XXX: normalization code is copied from pg_stat_statements.c.
2894 * Make sure to keep up-to-date with it.
2896 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2897 jstate.jumble_len = 0;
2898 jstate.clocations_buf_size = 32;
2899 jstate.clocations = (pgssLocationLen *)
2900 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2901 jstate.clocations_count = 0;
2903 JumbleQuery(&jstate, jumblequery);
2906 * Normalize the query string by replacing constants with '?'
2909 * Search hint string which is stored keyed by query string
2910 * and application name. The query string is normalized to allow
2913 * Adding 1 byte to query_len ensures that the returned string has
2914 * a terminating NULL.
2916 query_len = strlen(query_str) + 1;
2918 generate_normalized_query(&jstate, query_str, 0, &query_len,
2919 GetDatabaseEncoding());
2922 * find a hint for the normalized query. the result should be in
2925 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2927 get_hints_from_table(normalized_query, application_name);
2928 MemoryContextSwitchTo(oldcontext);
2930 if (debug_level > 1)
2932 if (current_hint_str)
2933 ereport(pg_hint_plan_debug_message_level,
2934 (errmsg("pg_hint_plan[qno=0x%x]: "
2935 "post_parse_analyze_hook: "
2936 "hints from table: \"%s\": "
2937 "normalized_query=\"%s\", "
2938 "application name =\"%s\"",
2939 qno, current_hint_str,
2940 normalized_query, application_name),
2941 errhidestmt(msgqno != qno),
2942 errhidecontext(msgqno != qno)));
2944 ereport(pg_hint_plan_debug_message_level,
2945 (errmsg("pg_hint_plan[qno=0x%x]: "
2946 "no match found in table: "
2947 "application name = \"%s\", "
2948 "normalized_query=\"%s\"",
2949 qno, application_name,
2951 errhidestmt(msgqno != qno),
2952 errhidecontext(msgqno != qno)));
2958 /* retrun if we have hint here */
2959 if (current_hint_str)
2963 query_str = get_query_string(pstate, query, NULL);
2968 * get hints from the comment. However we may have the same query
2969 * string with the previous call, but the extra comparison seems no
2972 if (current_hint_str)
2973 pfree((void *)current_hint_str);
2975 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2976 current_hint_str = get_hints_from_comment(query_str);
2977 MemoryContextSwitchTo(oldcontext);
2982 * Failed to get query. We would be in fetching invalidated
2983 * plancache. Try the next chance.
2985 current_hint_retrieved = false;
2988 if (debug_level > 1)
2990 if (debug_level == 1 && query_str && debug_query_string &&
2991 strcmp(query_str, debug_query_string))
2992 ereport(pg_hint_plan_debug_message_level,
2993 (errmsg("hints in comment=\"%s\"",
2994 current_hint_str ? current_hint_str : "(none)"),
2995 errhidestmt(msgqno != qno),
2996 errhidecontext(msgqno != qno)));
2998 ereport(pg_hint_plan_debug_message_level,
2999 (errmsg("hints in comment=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
3000 current_hint_str ? current_hint_str : "(none)",
3001 query_str ? query_str : "(none)",
3002 debug_query_string ? debug_query_string : "(none)"),
3003 errhidestmt(msgqno != qno),
3004 errhidecontext(msgqno != qno)));
3010 * Retrieve hint string from the current query.
3013 pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query)
3015 if (prev_post_parse_analyze_hook)
3016 prev_post_parse_analyze_hook(pstate, query);
3018 /* always retrieve hint from the top-level query string */
3019 if (plpgsql_recurse_level == 0)
3020 current_hint_retrieved = false;
3022 get_current_hint_string(pstate, query);
3026 * We need to reset current_hint_retrieved flag always when a command execution
3027 * is finished. This is true even for a pure utility command that doesn't
3028 * involve planning phase.
3031 pg_hint_plan_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
3032 ProcessUtilityContext context,
3033 ParamListInfo params, QueryEnvironment *queryEnv,
3034 DestReceiver *dest, char *completionTag)
3036 if (prev_ProcessUtility_hook)
3037 prev_ProcessUtility_hook(pstmt, queryString, context, params, queryEnv,
3038 dest, completionTag);
3040 standard_ProcessUtility(pstmt, queryString, context, params, queryEnv,
3041 dest, completionTag);
3043 if (plpgsql_recurse_level == 0)
3044 current_hint_retrieved = false;
3048 * Read and set up hint information
3050 static PlannedStmt *
3051 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
3054 PlannedStmt *result;
3056 const char *prev_hint_str = NULL;
3059 * Use standard planner if pg_hint_plan is disabled or current nesting
3060 * depth is nesting depth of SPI calls. Other hook functions try to change
3061 * plan with current_hint_state if any, so set it to NULL.
3063 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
3065 if (debug_level > 1)
3066 ereport(pg_hint_plan_debug_message_level,
3067 (errmsg ("pg_hint_plan%s: planner: enable_hint=%d,"
3068 " hint_inhibit_level=%d",
3069 qnostr, pg_hint_plan_enable_hint,
3070 hint_inhibit_level),
3071 errhidestmt(msgqno != qno)));
3074 goto standard_planner_proc;
3078 * Support for nested plpgsql functions. This is quite ugly but this is the
3079 * only point I could find where I can get the query string.
3081 if (plpgsql_recurse_level > 0 &&
3082 error_context_stack && error_context_stack->arg)
3084 MemoryContext oldcontext;
3086 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
3088 get_hints_from_comment((char *)error_context_stack->arg);
3089 MemoryContextSwitchTo(oldcontext);
3093 * Query execution in extended protocol can be started without the analyze
3094 * phase. In the case retrieve hint string here.
3096 if (!current_hint_str)
3097 get_current_hint_string(NULL, parse);
3099 /* No hint, go the normal way */
3100 if (!current_hint_str)
3101 goto standard_planner_proc;
3103 /* parse the hint into hint state struct */
3104 hstate = create_hintstate(parse, pstrdup(current_hint_str));
3106 /* run standard planner if the statement has not valid hint */
3108 goto standard_planner_proc;
3111 * Push new hint struct to the hint stack to disable previous hint context.
3115 /* Set scan enforcement here. */
3116 save_nestlevel = NewGUCNestLevel();
3118 /* Apply Set hints, then save it as the initial state */
3119 setup_guc_enforcement(current_hint_state->set_hints,
3120 current_hint_state->num_hints[HINT_TYPE_SET],
3121 current_hint_state->context);
3123 current_hint_state->init_scan_mask = get_current_scan_mask();
3124 current_hint_state->init_join_mask = get_current_join_mask();
3125 current_hint_state->init_min_para_tablescan_size =
3126 min_parallel_table_scan_size;
3127 current_hint_state->init_min_para_indexscan_size =
3128 min_parallel_index_scan_size;
3129 current_hint_state->init_paratup_cost = parallel_tuple_cost;
3130 current_hint_state->init_parasetup_cost = parallel_setup_cost;
3133 * max_parallel_workers_per_gather should be non-zero here if Workers hint
3136 if (max_hint_nworkers > 0 && max_parallel_workers_per_gather < 1)
3137 set_config_int32_option("max_parallel_workers_per_gather",
3138 1, current_hint_state->context);
3139 current_hint_state->init_nworkers = max_parallel_workers_per_gather;
3141 if (debug_level > 1)
3143 ereport(pg_hint_plan_debug_message_level,
3144 (errhidestmt(msgqno != qno),
3145 errmsg("pg_hint_plan%s: planner", qnostr)));
3150 * The planner call below may replace current_hint_str. Store and restore
3151 * it so that the subsequent planning in the upper level doesn't get
3155 prev_hint_str = current_hint_str;
3156 current_hint_str = NULL;
3159 * Use PG_TRY mechanism to recover GUC parameters and current_hint_state to
3160 * the state when this planner started when error occurred in planner.
3165 result = (*prev_planner) (parse, cursorOptions, boundParams);
3167 result = standard_planner(parse, cursorOptions, boundParams);
3169 current_hint_str = prev_hint_str;
3175 * Rollback changes of GUC parameters, and pop current hint context
3176 * from hint stack to rewind the state.
3178 current_hint_str = prev_hint_str;
3180 AtEOXact_GUC(true, save_nestlevel);
3188 * current_hint_str is useless after planning of the top-level query.
3190 if (recurse_level < 1 && current_hint_str)
3192 pfree((void *)current_hint_str);
3193 current_hint_str = NULL;
3194 current_hint_retrieved = false;
3197 /* Print hint in debug mode. */
3198 if (debug_level == 1)
3199 HintStateDump(current_hint_state);
3200 else if (debug_level > 1)
3201 HintStateDump2(current_hint_state);
3204 * Rollback changes of GUC parameters, and pop current hint context from
3205 * hint stack to rewind the state.
3207 AtEOXact_GUC(true, save_nestlevel);
3212 standard_planner_proc:
3213 if (debug_level > 1)
3215 ereport(pg_hint_plan_debug_message_level,
3216 (errhidestmt(msgqno != qno),
3217 errmsg("pg_hint_plan%s: planner: no valid hint",
3221 current_hint_state = NULL;
3223 result = (*prev_planner) (parse, cursorOptions, boundParams);
3225 result = standard_planner(parse, cursorOptions, boundParams);
3227 /* The upper-level planner still needs the current hint state */
3228 if (HintStateStack != NIL)
3229 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
3235 * Find scan method hint to be applied to the given relation
3238 static ScanMethodHint *
3239 find_scan_hint(PlannerInfo *root, Index relid)
3243 ScanMethodHint *real_name_hint = NULL;
3244 ScanMethodHint *alias_hint = NULL;
3247 /* This should not be a join rel */
3249 rel = root->simple_rel_array[relid];
3252 * This function is called for any RelOptInfo or its inheritance parent if
3253 * any. If we are called from inheritance planner, the RelOptInfo for the
3254 * parent of target child relation is not set in the planner info.
3256 * Otherwise we should check that the reloptinfo is base relation or
3257 * inheritance children.
3260 rel->reloptkind != RELOPT_BASEREL &&
3261 rel->reloptkind != RELOPT_OTHER_MEMBER_REL)
3265 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3267 rte = root->simple_rte_array[relid];
3270 /* We don't hint on other than relation and foreign tables */
3271 if (rte->rtekind != RTE_RELATION ||
3272 rte->relkind == RELKIND_FOREIGN_TABLE)
3275 /* Find scan method hint, which matches given names, from the list. */
3276 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
3278 ScanMethodHint *hint = current_hint_state->scan_hints[i];
3280 /* We ignore disabled hints. */
3281 if (!hint_state_enabled(hint))
3285 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3288 /* check the real name for appendrel children */
3289 if (!real_name_hint &&
3290 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3292 char *realname = get_rel_name(rte->relid);
3294 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3295 real_name_hint = hint;
3298 /* No more match expected, break */
3299 if(alias_hint && real_name_hint)
3303 /* real name match precedes alias match */
3305 return real_name_hint;
3310 static ParallelHint *
3311 find_parallel_hint(PlannerInfo *root, Index relid)
3315 ParallelHint *real_name_hint = NULL;
3316 ParallelHint *alias_hint = NULL;
3319 /* This should not be a join rel */
3321 rel = root->simple_rel_array[relid];
3324 * Parallel planning is appliable only on base relation, which has
3331 * We have set root->glob->parallelModeOK if needed. What we should do here
3332 * is just following the decision of planner.
3334 if (!rel->consider_parallel)
3338 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3340 rte = root->simple_rte_array[relid];
3343 /* Find parallel method hint, which matches given names, from the list. */
3344 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_PARALLEL]; i++)
3346 ParallelHint *hint = current_hint_state->parallel_hints[i];
3348 /* We ignore disabled hints. */
3349 if (!hint_state_enabled(hint))
3353 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3356 /* check the real name for appendrel children */
3357 if (!real_name_hint &&
3358 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3360 char *realname = get_rel_name(rte->relid);
3362 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3363 real_name_hint = hint;
3366 /* No more match expected, break */
3367 if(alias_hint && real_name_hint)
3371 /* real name match precedes alias match */
3373 return real_name_hint;
3381 * Returns TRUE on match, FALSE on no match.
3383 * s1 --- the data to match against
3384 * s2 --- the pattern
3386 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
3389 regexpeq(const char *s1, const char *s2)
3395 strcpy(name.data, s1);
3396 regexp = cstring_to_text(s2);
3398 result = DirectFunctionCall2Coll(nameregexeq,
3399 DEFAULT_COLLATION_OID,
3400 NameGetDatum(&name),
3401 PointerGetDatum(regexp));
3402 return DatumGetBool(result);
3406 /* Remove indexes instructed not to use by hint. */
3408 restrict_indexes(PlannerInfo *root, ScanMethodHint *hint, RelOptInfo *rel,
3409 bool using_parent_hint)
3415 RangeTblEntry *rte = root->simple_rte_array[rel->relid];
3416 Oid relationObjectId = rte->relid;
3419 * We delete all the IndexOptInfo list and prevent you from being usable by
3422 if (hint->enforce_mask == ENABLE_SEQSCAN ||
3423 hint->enforce_mask == ENABLE_TIDSCAN)
3425 list_free_deep(rel->indexlist);
3426 rel->indexlist = NIL;
3427 hint->base.state = HINT_STATE_USED;
3433 * When a list of indexes is not specified, we just use all indexes.
3435 if (hint->indexnames == NIL)
3439 * Leaving only an specified index, we delete it from a IndexOptInfo list
3443 if (debug_level > 0)
3444 initStringInfo(&buf);
3446 for (cell = list_head(rel->indexlist); cell; cell = next)
3448 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
3449 char *indexname = get_rel_name(info->indexoid);
3451 bool use_index = false;
3455 foreach(l, hint->indexnames)
3457 char *hintname = (char *) lfirst(l);
3461 result = regexpeq(indexname, hintname);
3463 result = RelnameCmp(&indexname, &hintname) == 0;
3468 if (debug_level > 0)
3470 appendStringInfoCharMacro(&buf, ' ');
3471 quote_value(&buf, indexname);
3479 * Apply index restriction of parent hint to children. Since index
3480 * inheritance is not explicitly described we should search for an
3481 * children's index with the same definition to that of the parent.
3483 if (using_parent_hint && !use_index)
3485 foreach(l, current_hint_state->parent_index_infos)
3489 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
3492 * we check the 'same' index by comparing uniqueness, access
3493 * method and index key columns.
3495 if (p_info->indisunique != info->unique ||
3496 p_info->method != info->relam ||
3497 list_length(p_info->column_names) != info->ncolumns)
3500 /* Check if index key columns match */
3501 for (i = 0; i < info->ncolumns; i++)
3503 char *c_attname = NULL;
3504 char *p_attname = NULL;
3506 p_attname = list_nth(p_info->column_names, i);
3509 * if both of the key of the same position are expressions,
3510 * ignore them for now and check later.
3512 if (info->indexkeys[i] == 0 && !p_attname)
3515 /* deny if one is expression while another is not */
3516 if (info->indexkeys[i] == 0 || !p_attname)
3519 c_attname = get_attname(relationObjectId,
3520 info->indexkeys[i], false);
3522 /* deny if any of column attributes don't match */
3523 if (strcmp(p_attname, c_attname) != 0 ||
3524 p_info->indcollation[i] != info->indexcollations[i] ||
3525 p_info->opclass[i] != info->opcintype[i]||
3526 ((p_info->indoption[i] & INDOPTION_DESC) != 0)
3527 != info->reverse_sort[i] ||
3528 ((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0)
3529 != info->nulls_first[i])
3533 /* deny this if any difference found */
3534 if (i != info->ncolumns)
3537 /* check on key expressions */
3538 if ((p_info->expression_str && (info->indexprs != NIL)) ||
3539 (p_info->indpred_str && (info->indpred != NIL)))
3541 /* fetch the index of this child */
3542 ht_idx = SearchSysCache1(INDEXRELID,
3543 ObjectIdGetDatum(info->indexoid));
3545 /* check expressions if both expressions are available */
3546 if (p_info->expression_str &&
3547 !heap_attisnull(ht_idx, Anum_pg_index_indexprs, NULL))
3554 * to change the expression's parameter of child's
3557 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3558 Anum_pg_index_indexprs,
3561 result = DirectFunctionCall2(pg_get_expr,
3566 /* deny if expressions don't match */
3567 if (strcmp(p_info->expression_str,
3568 text_to_cstring(DatumGetTextP(result))) != 0)
3571 ReleaseSysCache(ht_idx);
3576 /* compare index predicates */
3577 if (p_info->indpred_str &&
3578 !heap_attisnull(ht_idx, Anum_pg_index_indpred, NULL))
3584 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3585 Anum_pg_index_indpred,
3588 result = DirectFunctionCall2(pg_get_expr,
3593 if (strcmp(p_info->indpred_str,
3594 text_to_cstring(DatumGetTextP(result))) != 0)
3597 ReleaseSysCache(ht_idx);
3603 ReleaseSysCache(ht_idx);
3605 else if (p_info->expression_str || (info->indexprs != NIL))
3607 else if (p_info->indpred_str || (info->indpred != NIL))
3612 /* to log the candidate of index */
3613 if (debug_level > 0)
3615 appendStringInfoCharMacro(&buf, ' ');
3616 quote_value(&buf, indexname);
3624 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
3631 if (debug_level == 1)
3633 StringInfoData rel_buf;
3634 char *disprelname = "";
3637 * If this hint targetted the parent, use the real name of this
3638 * child. Otherwise use hint specification.
3640 if (using_parent_hint)
3641 disprelname = get_rel_name(rte->relid);
3643 disprelname = hint->relname;
3646 initStringInfo(&rel_buf);
3647 quote_value(&rel_buf, disprelname);
3649 ereport(pg_hint_plan_debug_message_level,
3650 (errmsg("available indexes for %s(%s):%s",
3655 pfree(rel_buf.data);
3660 * Return information of index definition.
3662 static ParentIndexInfo *
3663 get_parent_index_info(Oid indexoid, Oid relid)
3665 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3666 Relation indexRelation;
3667 Form_pg_index index;
3671 indexRelation = index_open(indexoid, RowExclusiveLock);
3673 index = indexRelation->rd_index;
3675 p_info->indisunique = index->indisunique;
3676 p_info->method = indexRelation->rd_rel->relam;
3678 p_info->column_names = NIL;
3679 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3680 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3681 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3684 * Collect relation attribute names of index columns for index
3685 * identification, not index attribute names. NULL means expression index
3688 for (i = 0; i < index->indnatts; i++)
3690 attname = get_attname(relid, index->indkey.values[i], true);
3691 p_info->column_names = lappend(p_info->column_names, attname);
3693 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3694 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3695 p_info->indoption[i] = indexRelation->rd_indoption[i];
3699 * to check to match the expression's parameter of index with child indexes
3701 p_info->expression_str = NULL;
3702 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs,
3709 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3710 Anum_pg_index_indexprs, &isnull);
3712 result = DirectFunctionCall2(pg_get_expr,
3714 ObjectIdGetDatum(relid));
3716 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3720 * to check to match the predicate's parameter of index with child indexes
3722 p_info->indpred_str = NULL;
3723 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred,
3730 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3731 Anum_pg_index_indpred, &isnull);
3733 result = DirectFunctionCall2(pg_get_expr,
3735 ObjectIdGetDatum(relid));
3737 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3740 index_close(indexRelation, NoLock);
3746 * cancel hint enforcement
3749 reset_hint_enforcement()
3751 setup_scan_method_enforcement(NULL, current_hint_state);
3752 setup_parallel_plan_enforcement(NULL, current_hint_state);
3756 * Set planner guc parameters according to corresponding scan hints. Returns
3757 * bitmap of HintTypeBitmap. If shint or phint is not NULL, set used hint
3758 * there respectively.
3761 setup_hint_enforcement(PlannerInfo *root, RelOptInfo *rel,
3762 ScanMethodHint **rshint, ParallelHint **rphint)
3764 Index new_parent_relid = 0;
3766 ScanMethodHint *shint = NULL;
3767 ParallelHint *phint = NULL;
3768 bool inhparent = root->simple_rte_array[rel->relid]->inh;
3769 Oid relationObjectId = root->simple_rte_array[rel->relid]->relid;
3772 /* reset returns if requested */
3773 if (rshint != NULL) *rshint = NULL;
3774 if (rphint != NULL) *rphint = NULL;
3777 * We could register the parent relation of the following children here
3778 * when inhparent == true but inheritnce planner doesn't call this function
3779 * for parents. Since we cannot distinguish who called this function we
3780 * cannot do other than always seeking the parent regardless of who called
3785 /* set up only parallel hints for parent relation */
3786 phint = find_parallel_hint(root, rel->relid);
3789 setup_parallel_plan_enforcement(phint, current_hint_state);
3790 if (rphint) *rphint = phint;
3791 ret |= HINT_BM_PARALLEL;
3795 if (debug_level > 1)
3796 ereport(pg_hint_plan_debug_message_level,
3798 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3799 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3800 " current_hint_state=%p, hint_inhibit_level=%d",
3801 qnostr, relationObjectId,
3802 get_rel_name(relationObjectId),
3803 inhparent, current_hint_state, hint_inhibit_level)));
3808 * Forget about the parent of another subquery, but don't forget if the
3809 * inhTargetkind of the root is not INHKIND_NONE, which signals the root
3810 * contains only appendrel members. See inheritance_planner for details.
3812 * (PG12.0) 428b260f87 added one more planning cycle for updates on
3813 * partitioned tables and hints set up in the cycle are overriden by the
3814 * second cycle. Since I didn't find no apparent distinction between the
3815 * PlannerRoot of the cycle and that of ordinary CMD_SELECT, pg_hint_plan
3816 * accepts both cycles and the later one wins. In the second cycle root
3817 * doesn't have inheritance information at all so use the parent_relid set
3818 * in the first cycle.
3820 if (root->inhTargetKind == INHKIND_NONE)
3822 if (root != current_hint_state->current_root)
3823 current_hint_state->parent_relid = 0;
3825 /* Find the parent for this relation other than the registered parent */
3826 foreach (l, root->append_rel_list)
3828 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3830 if (appinfo->child_relid == rel->relid)
3832 if (current_hint_state->parent_relid != appinfo->parent_relid)
3834 new_parent_relid = appinfo->parent_relid;
3835 current_hint_state->current_root = root;
3844 * This relation doesn't have a parent. Cancel
3845 * current_hint_state.
3847 current_hint_state->parent_relid = 0;
3848 current_hint_state->parent_scan_hint = NULL;
3849 current_hint_state->parent_parallel_hint = NULL;
3853 if (new_parent_relid > 0)
3856 * Here we found a new parent for the current relation. Scan continues
3857 * hint to other childrens of this parent so remember it to avoid
3858 * redundant setup cost.
3860 current_hint_state->parent_relid = new_parent_relid;
3862 /* Find hints for the parent */
3863 current_hint_state->parent_scan_hint =
3864 find_scan_hint(root, current_hint_state->parent_relid);
3866 current_hint_state->parent_parallel_hint =
3867 find_parallel_hint(root, current_hint_state->parent_relid);
3870 * If hint is found for the parent, apply it for this child instead
3873 if (current_hint_state->parent_scan_hint)
3875 ScanMethodHint * pshint = current_hint_state->parent_scan_hint;
3877 pshint->base.state = HINT_STATE_USED;
3879 /* Apply index mask in the same manner to the parent. */
3880 if (pshint->indexnames)
3883 Relation parent_rel;
3886 root->simple_rte_array[current_hint_state->parent_relid]->relid;
3887 parent_rel = heap_open(parentrel_oid, NoLock);
3889 /* Search the parent relation for indexes match the hint spec */
3890 foreach(l, RelationGetIndexList(parent_rel))
3892 Oid indexoid = lfirst_oid(l);
3893 char *indexname = get_rel_name(indexoid);
3895 ParentIndexInfo *parent_index_info;
3897 foreach(lc, pshint->indexnames)
3899 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3906 get_parent_index_info(indexoid, parentrel_oid);
3907 current_hint_state->parent_index_infos =
3908 lappend(current_hint_state->parent_index_infos,
3911 heap_close(parent_rel, NoLock);
3916 shint = find_scan_hint(root, rel->relid);
3918 shint = current_hint_state->parent_scan_hint;
3922 bool using_parent_hint =
3923 (shint == current_hint_state->parent_scan_hint);
3925 ret |= HINT_BM_SCAN_METHOD;
3927 /* Setup scan enforcement environment */
3928 setup_scan_method_enforcement(shint, current_hint_state);
3930 /* restrict unwanted inexes */
3931 restrict_indexes(root, shint, rel, using_parent_hint);
3933 if (debug_level > 1)
3935 char *additional_message = "";
3937 if (shint == current_hint_state->parent_scan_hint)
3938 additional_message = " by parent hint";
3940 ereport(pg_hint_plan_debug_message_level,
3942 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3943 " index deletion%s:"
3944 " relation=%u(%s), inhparent=%d, "
3945 "current_hint_state=%p,"
3946 " hint_inhibit_level=%d, scanmask=0x%x",
3947 qnostr, additional_message,
3949 get_rel_name(relationObjectId),
3950 inhparent, current_hint_state,
3952 shint->enforce_mask)));
3956 /* Do the same for parallel plan enforcement */
3957 phint = find_parallel_hint(root, rel->relid);
3959 phint = current_hint_state->parent_parallel_hint;
3961 setup_parallel_plan_enforcement(phint, current_hint_state);
3964 ret |= HINT_BM_PARALLEL;
3966 /* Nothing to apply. Reset the scan mask to intial state */
3967 if (!shint && ! phint)
3969 if (debug_level > 1)
3970 ereport(pg_hint_plan_debug_message_level,
3971 (errhidestmt (true),
3972 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3974 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3975 " hint_inhibit_level=%d, scanmask=0x%x",
3976 qnostr, relationObjectId,
3977 get_rel_name(relationObjectId),
3978 inhparent, current_hint_state, hint_inhibit_level,
3979 current_hint_state->init_scan_mask)));
3981 setup_scan_method_enforcement(NULL, current_hint_state);
3986 if (rshint != NULL) *rshint = shint;
3987 if (rphint != NULL) *rphint = phint;
3993 * Return index of relation which matches given aliasname, or 0 if not found.
3994 * If same aliasname was used multiple times in a query, return -1.
3997 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
4003 for (i = 1; i < root->simple_rel_array_size; i++)
4007 if (root->simple_rel_array[i] == NULL)
4010 Assert(i == root->simple_rel_array[i]->relid);
4012 if (RelnameCmp(&aliasname,
4013 &root->simple_rte_array[i]->eref->aliasname) != 0)
4016 foreach(l, initial_rels)
4018 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
4020 if (rel->reloptkind == RELOPT_BASEREL)
4022 if (rel->relid != i)
4027 Assert(rel->reloptkind == RELOPT_JOINREL);
4029 if (!bms_is_member(i, rel->relids))
4036 ("Relation name \"%s\" is ambiguous.",
4051 * Return join hint which matches given joinrelids.
4053 static JoinMethodHint *
4054 find_join_hint(Relids joinrelids)
4059 join_hint = current_hint_state->join_hint_level[bms_num_members(joinrelids)];
4061 foreach(l, join_hint)
4063 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
4065 if (bms_equal(joinrelids, hint->joinrelids))
4073 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
4074 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
4076 OuterInnerRels *outer_rels;
4077 OuterInnerRels *inner_rels;
4078 Relids outer_relids;
4079 Relids inner_relids;
4081 JoinMethodHint *hint;
4083 if (outer_inner->relation != NULL)
4085 return bms_make_singleton(
4086 find_relid_aliasname(root, outer_inner->relation,
4088 leading_hint->base.hint_str));
4091 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
4092 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
4094 outer_relids = OuterInnerJoinCreate(outer_rels,
4100 inner_relids = OuterInnerJoinCreate(inner_rels,
4107 join_relids = bms_add_members(outer_relids, inner_relids);
4109 if (bms_num_members(join_relids) > nbaserel)
4113 * If we don't have join method hint, create new one for the
4114 * join combination with all join methods are enabled.
4116 hint = find_join_hint(join_relids);
4120 * Here relnames is not set, since Relids bitmap is sufficient to
4121 * control paths of this query afterward.
4123 hint = (JoinMethodHint *) JoinMethodHintCreate(
4124 leading_hint->base.hint_str,
4126 HINT_KEYWORD_LEADING);
4127 hint->base.state = HINT_STATE_USED;
4128 hint->nrels = bms_num_members(join_relids);
4129 hint->enforce_mask = ENABLE_ALL_JOIN;
4130 hint->joinrelids = bms_copy(join_relids);
4131 hint->inner_nrels = bms_num_members(inner_relids);
4132 hint->inner_joinrelids = bms_copy(inner_relids);
4134 hstate->join_hint_level[hint->nrels] =
4135 lappend(hstate->join_hint_level[hint->nrels], hint);
4139 hint->inner_nrels = bms_num_members(inner_relids);
4140 hint->inner_joinrelids = bms_copy(inner_relids);
4147 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
4148 int nrels, char **relnames)
4151 Relids relids = NULL;
4155 for (j = 0; j < nrels; j++)
4157 relname = relnames[j];
4159 relid = find_relid_aliasname(root, relname, initial_rels,
4163 base->state = HINT_STATE_ERROR;
4166 * the aliasname is not found(relid == 0) or same aliasname was used
4167 * multiple times in a query(relid == -1)
4174 if (bms_is_member(relid, relids))
4176 hint_ereport(base->hint_str,
4177 ("Relation name \"%s\" is duplicated.", relname));
4178 base->state = HINT_STATE_ERROR;
4182 relids = bms_add_member(relids, relid);
4187 * Transform join method hint into handy form.
4189 * - create bitmap of relids from alias names, to make it easier to check
4190 * whether a join path matches a join method hint.
4191 * - add join method hints which are necessary to enforce join order
4192 * specified by Leading hint
4195 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
4196 List *initial_rels, JoinMethodHint **join_method_hints)
4204 LeadingHint *lhint = NULL;
4207 * Create bitmap of relids from alias names for each join method hint.
4208 * Bitmaps are more handy than strings in join searching.
4210 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
4212 JoinMethodHint *hint = hstate->join_hints[i];
4214 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4217 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4218 initial_rels, hint->nrels, hint->relnames);
4220 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
4223 hstate->join_hint_level[hint->nrels] =
4224 lappend(hstate->join_hint_level[hint->nrels], hint);
4228 * Create bitmap of relids from alias names for each rows hint.
4229 * Bitmaps are more handy than strings in join searching.
4231 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
4233 RowsHint *hint = hstate->rows_hints[i];
4235 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4238 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4239 initial_rels, hint->nrels, hint->relnames);
4242 /* Do nothing if no Leading hint was supplied. */
4243 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
4247 * Decide whether to use Leading hint
4249 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
4251 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
4254 if (leading_hint->base.state == HINT_STATE_ERROR)
4260 foreach(l, leading_hint->relations)
4262 relname = (char *)lfirst(l);;
4264 relid = find_relid_aliasname(root, relname, initial_rels,
4265 leading_hint->base.hint_str);
4267 leading_hint->base.state = HINT_STATE_ERROR;
4272 if (bms_is_member(relid, relids))
4274 hint_ereport(leading_hint->base.hint_str,
4275 ("Relation name \"%s\" is duplicated.", relname));
4276 leading_hint->base.state = HINT_STATE_ERROR;
4280 relids = bms_add_member(relids, relid);
4283 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
4288 hint_ereport(lhint->base.hint_str,
4289 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
4290 lhint->base.state = HINT_STATE_DUPLICATION;
4292 leading_hint->base.state = HINT_STATE_USED;
4293 lhint = leading_hint;
4296 /* check to exist Leading hint marked with 'used'. */
4301 * We need join method hints which fit specified join order in every join
4302 * level. For example, Leading(A B C) virtually requires following join
4303 * method hints, if no join method hint supplied:
4305 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
4306 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
4308 * If we already have join method hint which fits specified join order in
4309 * that join level, we leave it as-is and don't add new hints.
4313 if (lhint->outer_inner == NULL)
4315 foreach(l, lhint->relations)
4317 JoinMethodHint *hint;
4319 relname = (char *)lfirst(l);
4322 * Find relid of the relation which has given name. If we have the
4323 * name given in Leading hint multiple times in the join, nothing to
4326 relid = find_relid_aliasname(root, relname, initial_rels,
4329 /* Create bitmap of relids for current join level. */
4330 joinrelids = bms_add_member(joinrelids, relid);
4333 /* We never have join method hint for single relation. */
4338 * If we don't have join method hint, create new one for the
4339 * join combination with all join methods are enabled.
4341 hint = find_join_hint(joinrelids);
4345 * Here relnames is not set, since Relids bitmap is sufficient
4346 * to control paths of this query afterward.
4348 hint = (JoinMethodHint *) JoinMethodHintCreate(
4349 lhint->base.hint_str,
4351 HINT_KEYWORD_LEADING);
4352 hint->base.state = HINT_STATE_USED;
4353 hint->nrels = njoinrels;
4354 hint->enforce_mask = ENABLE_ALL_JOIN;
4355 hint->joinrelids = bms_copy(joinrelids);
4358 join_method_hints[njoinrels] = hint;
4360 if (njoinrels >= nbaserel)
4363 bms_free(joinrelids);
4369 * Delete all join hints which have different combination from Leading
4372 for (i = 2; i <= njoinrels; i++)
4374 list_free(hstate->join_hint_level[i]);
4376 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
4381 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
4388 njoinrels = bms_num_members(joinrelids);
4389 Assert(njoinrels >= 2);
4392 * Delete all join hints which have different combination from Leading
4395 for (i = 2;i <= njoinrels; i++)
4397 if (hstate->join_hint_level[i] != NIL)
4399 ListCell *prev = NULL;
4400 ListCell *next = NULL;
4401 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
4404 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
4408 if (hint->inner_nrels == 0 &&
4409 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
4410 bms_equal(bms_union(hint->joinrelids, joinrelids),
4413 hstate->join_hint_level[i] =
4414 list_delete_cell(hstate->join_hint_level[i], l,
4423 bms_free(joinrelids);
4426 if (hint_state_enabled(lhint))
4428 set_join_config_options(DISABLE_ALL_JOIN, current_hint_state->context);
4435 * wrapper of make_join_rel()
4437 * call make_join_rel() after changing enable_* parameters according to given
4441 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
4444 JoinMethodHint *hint;
4448 joinrelids = bms_union(rel1->relids, rel2->relids);
4449 hint = find_join_hint(joinrelids);
4450 bms_free(joinrelids);
4453 return pg_hint_plan_make_join_rel(root, rel1, rel2);
4455 if (hint->inner_nrels == 0)
4457 save_nestlevel = NewGUCNestLevel();
4459 set_join_config_options(hint->enforce_mask,
4460 current_hint_state->context);
4462 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4463 hint->base.state = HINT_STATE_USED;
4466 * Restore the GUC variables we set above.
4468 AtEOXact_GUC(true, save_nestlevel);
4471 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4480 add_paths_to_joinrel_wrapper(PlannerInfo *root,
4481 RelOptInfo *joinrel,
4482 RelOptInfo *outerrel,
4483 RelOptInfo *innerrel,
4485 SpecialJoinInfo *sjinfo,
4489 JoinMethodHint *join_hint;
4492 joinrelids = bms_union(outerrel->relids, innerrel->relids);
4493 join_hint = find_join_hint(joinrelids);
4494 bms_free(joinrelids);
4496 if (join_hint && join_hint->inner_nrels != 0)
4498 save_nestlevel = NewGUCNestLevel();
4500 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
4503 set_join_config_options(join_hint->enforce_mask,
4504 current_hint_state->context);
4506 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4507 sjinfo, restrictlist);
4508 join_hint->base.state = HINT_STATE_USED;
4512 set_join_config_options(DISABLE_ALL_JOIN,
4513 current_hint_state->context);
4514 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4515 sjinfo, restrictlist);
4519 * Restore the GUC variables we set above.
4521 AtEOXact_GUC(true, save_nestlevel);
4524 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4525 sjinfo, restrictlist);
4529 get_num_baserels(List *initial_rels)
4534 foreach(l, initial_rels)
4536 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
4538 if (rel->reloptkind == RELOPT_BASEREL)
4540 else if (rel->reloptkind ==RELOPT_JOINREL)
4541 nbaserel+= bms_num_members(rel->relids);
4544 /* other values not expected here */
4545 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
4553 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
4556 JoinMethodHint **join_method_hints;
4560 bool leading_hint_enable;
4563 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
4564 * valid hint is supplied or current nesting depth is nesting depth of SPI
4567 if (!current_hint_state || hint_inhibit_level > 0)
4569 if (prev_join_search)
4570 return (*prev_join_search) (root, levels_needed, initial_rels);
4571 else if (enable_geqo && levels_needed >= geqo_threshold)
4572 return geqo(root, levels_needed, initial_rels);
4574 return standard_join_search(root, levels_needed, initial_rels);
4578 * In the case using GEQO, only scan method hints and Set hints have
4579 * effect. Join method and join order is not controllable by hints.
4581 if (enable_geqo && levels_needed >= geqo_threshold)
4582 return geqo(root, levels_needed, initial_rels);
4584 nbaserel = get_num_baserels(initial_rels);
4585 current_hint_state->join_hint_level =
4586 palloc0(sizeof(List *) * (nbaserel + 1));
4587 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4589 leading_hint_enable = transform_join_hints(current_hint_state,
4591 initial_rels, join_method_hints);
4593 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4596 * Adjust number of parallel workers of the result rel to the largest
4597 * number of the component paths.
4599 if (current_hint_state->num_hints[HINT_TYPE_PARALLEL] > 0)
4604 foreach (lc, initial_rels)
4607 RelOptInfo *rel = (RelOptInfo *) lfirst(lc);
4609 foreach (lcp, rel->partial_pathlist)
4611 Path *path = (Path *) lfirst(lcp);
4613 if (nworkers < path-> parallel_workers)
4614 nworkers = path-> parallel_workers;
4618 foreach (lc, rel->partial_pathlist)
4620 Path *path = (Path *) lfirst(lc);
4622 if (path->parallel_safe && path->parallel_workers < nworkers)
4623 path->parallel_workers = nworkers;
4627 for (i = 2; i <= nbaserel; i++)
4629 list_free(current_hint_state->join_hint_level[i]);
4631 /* free Leading hint only */
4632 if (join_method_hints[i] != NULL &&
4633 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4634 JoinMethodHintDelete(join_method_hints[i]);
4636 pfree(current_hint_state->join_hint_level);
4637 pfree(join_method_hints);
4639 if (leading_hint_enable)
4640 set_join_config_options(current_hint_state->init_join_mask,
4641 current_hint_state->context);
4647 * Force number of wokers if instructed by hint
4650 pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
4651 Index rti, RangeTblEntry *rte)
4653 ParallelHint *phint;
4657 /* call the previous hook */
4658 if (prev_set_rel_pathlist)
4659 prev_set_rel_pathlist(root, rel, rti, rte);
4661 /* Nothing to do if no hint available */
4662 if (current_hint_state == NULL)
4665 /* Don't touch dummy rels. */
4666 if (IS_DUMMY_REL(rel))
4670 * We can accept only plain relations, foreign tables and table saples are
4671 * also unacceptable. See set_rel_pathlist.
4673 if ((rel->rtekind != RTE_RELATION &&
4674 rel->rtekind != RTE_SUBQUERY)||
4675 rte->relkind == RELKIND_FOREIGN_TABLE ||
4676 rte->tablesample != NULL)
4680 * Even though UNION ALL node doesn't have particular name so usually it is
4681 * unhintable, turn on parallel when it contains parallel nodes.
4683 if (rel->rtekind == RTE_SUBQUERY)
4686 bool inhibit_nonparallel = false;
4688 if (rel->partial_pathlist == NIL)
4691 foreach(lc, rel->partial_pathlist)
4694 AppendPath *apath = (AppendPath *) lfirst(lc);
4695 int parallel_workers = 0;
4697 if (!IsA(apath, AppendPath))
4700 foreach (lcp, apath->subpaths)
4702 Path *spath = (Path *) lfirst(lcp);
4704 if (spath->parallel_aware &&
4705 parallel_workers < spath->parallel_workers)
4706 parallel_workers = spath->parallel_workers;
4709 apath->path.parallel_workers = parallel_workers;
4710 inhibit_nonparallel = true;
4713 if (inhibit_nonparallel)
4717 foreach(lc, rel->pathlist)
4719 Path *path = (Path *) lfirst(lc);
4721 if (path->startup_cost < disable_cost)
4723 path->startup_cost += disable_cost;
4724 path->total_cost += disable_cost;
4732 /* We cannot handle if this requires an outer */
4733 if (rel->lateral_relids)
4736 /* Return if this relation gets no enfocement */
4737 if ((found_hints = setup_hint_enforcement(root, rel, NULL, &phint)) == 0)
4740 /* Here, we regenerate paths with the current hint restriction */
4741 if (found_hints & HINT_BM_SCAN_METHOD || found_hints & HINT_BM_PARALLEL)
4744 * When hint is specified on non-parent relations, discard existing
4745 * paths and regenerate based on the hint considered. Otherwise we
4746 * already have hinted childx paths then just adjust the number of
4747 * planned number of workers.
4749 if (root->simple_rte_array[rel->relid]->inh)
4751 /* enforce number of workers if requested */
4752 if (phint && phint->force_parallel)
4754 if (phint->nworkers == 0)
4756 list_free_deep(rel->partial_pathlist);
4757 rel->partial_pathlist = NIL;
4761 /* prioritize partial paths */
4762 foreach (l, rel->partial_pathlist)
4764 Path *ppath = (Path *) lfirst(l);
4766 if (ppath->parallel_safe)
4768 ppath->parallel_workers = phint->nworkers;
4769 ppath->startup_cost = 0;
4770 ppath->total_cost = 0;
4774 /* disable non-partial paths */
4775 foreach (l, rel->pathlist)
4777 Path *ppath = (Path *) lfirst(l);
4779 if (ppath->startup_cost < disable_cost)
4781 ppath->startup_cost += disable_cost;
4782 ppath->total_cost += disable_cost;
4790 /* Just discard all the paths considered so far */
4791 list_free_deep(rel->pathlist);
4792 rel->pathlist = NIL;
4793 list_free_deep(rel->partial_pathlist);
4794 rel->partial_pathlist = NIL;
4796 /* Regenerate paths with the current enforcement */
4797 set_plain_rel_pathlist(root, rel, rte);
4799 /* Additional work to enforce parallel query execution */
4800 if (phint && phint->nworkers > 0)
4803 * For Parallel Append to be planned properly, we shouldn't set
4804 * the costs of non-partial paths to disable-value. Lower the
4805 * priority of non-parallel paths by setting partial path costs
4808 foreach (l, rel->partial_pathlist)
4810 Path *path = (Path *) lfirst(l);
4812 path->startup_cost = 0;
4813 path->total_cost = 0;
4816 /* enforce number of workers if requested */
4817 if (phint->force_parallel)
4819 foreach (l, rel->partial_pathlist)
4821 Path *ppath = (Path *) lfirst(l);
4823 if (ppath->parallel_safe)
4824 ppath->parallel_workers = phint->nworkers;
4828 /* Generate gather paths */
4829 if (rel->reloptkind == RELOPT_BASEREL &&
4830 bms_membership(root->all_baserels) != BMS_SINGLETON)
4831 generate_gather_paths(root, rel, false);
4836 reset_hint_enforcement();
4841 * Build access paths for a base relation
4843 * This function was copied and edited from set_rel_pathlist() in
4844 * src/backend/optimizer/path/allpaths.c in order not to copy other static
4845 * functions not required here.
4848 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4849 Index rti, RangeTblEntry *rte)
4851 if (IS_DUMMY_REL(rel))
4853 /* We already proved the relation empty, so nothing more to do */
4857 /* It's an "append relation", process accordingly */
4858 set_append_rel_pathlist(root, rel, rti, rte);
4862 if (rel->rtekind == RTE_RELATION)
4864 if (rte->relkind == RELKIND_RELATION)
4866 if(rte->tablesample != NULL)
4867 elog(ERROR, "sampled relation is not supported");
4869 /* Plain relation */
4870 set_plain_rel_pathlist(root, rel, rte);
4873 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4876 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4880 * Allow a plugin to editorialize on the set of Paths for this base
4881 * relation. It could add new paths (such as CustomPaths) by calling
4882 * add_path(), or delete or modify paths added by the core code.
4884 if (set_rel_pathlist_hook)
4885 (*set_rel_pathlist_hook) (root, rel, rti, rte);
4887 /* Now find the cheapest of the paths for this rel */
4892 * stmt_beg callback is called when each query in PL/pgSQL function is about
4893 * to be executed. At that timing, we save query string in the global variable
4894 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4895 * variable for the purpose, because its content is only necessary until
4896 * planner hook is called for the query, so recursive PL/pgSQL function calls
4897 * don't harm this mechanism.
4900 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4902 plpgsql_recurse_level++;
4906 * stmt_end callback is called then each query in PL/pgSQL function has
4907 * finished. At that timing, we clear plpgsql_query_string to tell planner
4908 * hook that next call is not for a query written in PL/pgSQL block.
4911 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4913 plpgsql_recurse_level--;
4916 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4921 if (!isTopLevel || phase != RESOURCE_RELEASE_AFTER_LOCKS)
4923 /* Cancel plpgsql nest level*/
4924 plpgsql_recurse_level = 0;
4927 #define standard_join_search pg_hint_plan_standard_join_search
4928 #define join_search_one_level pg_hint_plan_join_search_one_level
4929 #define make_join_rel make_join_rel_wrapper
4932 #undef make_join_rel
4933 #define make_join_rel pg_hint_plan_make_join_rel
4934 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4935 #include "make_join_rel.c"
4937 #include "pg_stat_statements.c"