1 /*-------------------------------------------------------------------------
4 * hinting on how to execute a query for PostgreSQL
6 * Copyright (c) 2012-2019, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
8 *-------------------------------------------------------------------------
13 #include "access/genam.h"
14 #include "access/heapam.h"
15 #include "catalog/pg_collation.h"
16 #include "catalog/pg_index.h"
17 #include "commands/prepare.h"
18 #include "mb/pg_wchar.h"
19 #include "miscadmin.h"
20 #include "nodes/nodeFuncs.h"
21 #include "nodes/params.h"
22 #include "nodes/relation.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/pathnode.h"
29 #include "optimizer/paths.h"
30 #include "optimizer/plancat.h"
31 #include "optimizer/planner.h"
32 #include "optimizer/prep.h"
33 #include "optimizer/restrictinfo.h"
34 #include "parser/analyze.h"
35 #include "parser/parsetree.h"
36 #include "parser/scansup.h"
37 #include "partitioning/partbounds.h"
38 #include "tcop/utility.h"
39 #include "utils/builtins.h"
40 #include "utils/lsyscache.h"
41 #include "utils/memutils.h"
42 #include "utils/rel.h"
43 #include "utils/snapmgr.h"
44 #include "utils/syscache.h"
45 #include "utils/resowner.h"
47 #include "catalog/pg_class.h"
49 #include "executor/spi.h"
50 #include "catalog/pg_type.h"
54 /* partially copied from pg_stat_statements */
55 #include "normalize_query.h"
58 #include "access/htup_details.h"
60 #ifdef PG_MODULE_MAGIC
64 #define BLOCK_COMMENT_START "/*"
65 #define BLOCK_COMMENT_END "*/"
66 #define HINT_COMMENT_KEYWORD "+"
67 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
68 #define HINT_END BLOCK_COMMENT_END
71 #define HINT_SEQSCAN "SeqScan"
72 #define HINT_INDEXSCAN "IndexScan"
73 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
74 #define HINT_BITMAPSCAN "BitmapScan"
75 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
76 #define HINT_TIDSCAN "TidScan"
77 #define HINT_NOSEQSCAN "NoSeqScan"
78 #define HINT_NOINDEXSCAN "NoIndexScan"
79 #define HINT_NOBITMAPSCAN "NoBitmapScan"
80 #define HINT_NOTIDSCAN "NoTidScan"
81 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
82 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
83 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
84 #define HINT_PARALLEL "Parallel"
86 #define HINT_NESTLOOP "NestLoop"
87 #define HINT_MERGEJOIN "MergeJoin"
88 #define HINT_HASHJOIN "HashJoin"
89 #define HINT_NONESTLOOP "NoNestLoop"
90 #define HINT_NOMERGEJOIN "NoMergeJoin"
91 #define HINT_NOHASHJOIN "NoHashJoin"
92 #define HINT_LEADING "Leading"
93 #define HINT_SET "Set"
94 #define HINT_ROWS "Rows"
96 #define HINT_ARRAY_DEFAULT_INITSIZE 8
98 #define hint_ereport(str, detail) hint_parse_ereport(str, detail)
99 #define hint_parse_ereport(str, detail) \
101 ereport(pg_hint_plan_parse_message_level, \
102 (errmsg("pg_hint_plan: hint syntax error at or near \"%s\"", (str)), \
103 errdetail detail)); \
106 #define skip_space(str) \
107 while (isspace(*str)) \
112 ENABLE_SEQSCAN = 0x01,
113 ENABLE_INDEXSCAN = 0x02,
114 ENABLE_BITMAPSCAN = 0x04,
115 ENABLE_TIDSCAN = 0x08,
116 ENABLE_INDEXONLYSCAN = 0x10
121 ENABLE_NESTLOOP = 0x01,
122 ENABLE_MERGEJOIN = 0x02,
123 ENABLE_HASHJOIN = 0x04
126 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
127 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
128 ENABLE_INDEXONLYSCAN)
129 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
130 #define DISABLE_ALL_SCAN 0
131 #define DISABLE_ALL_JOIN 0
133 /* hint keyword of enum type*/
134 typedef enum HintKeyword
136 HINT_KEYWORD_SEQSCAN,
137 HINT_KEYWORD_INDEXSCAN,
138 HINT_KEYWORD_INDEXSCANREGEXP,
139 HINT_KEYWORD_BITMAPSCAN,
140 HINT_KEYWORD_BITMAPSCANREGEXP,
141 HINT_KEYWORD_TIDSCAN,
142 HINT_KEYWORD_NOSEQSCAN,
143 HINT_KEYWORD_NOINDEXSCAN,
144 HINT_KEYWORD_NOBITMAPSCAN,
145 HINT_KEYWORD_NOTIDSCAN,
146 HINT_KEYWORD_INDEXONLYSCAN,
147 HINT_KEYWORD_INDEXONLYSCANREGEXP,
148 HINT_KEYWORD_NOINDEXONLYSCAN,
150 HINT_KEYWORD_NESTLOOP,
151 HINT_KEYWORD_MERGEJOIN,
152 HINT_KEYWORD_HASHJOIN,
153 HINT_KEYWORD_NONESTLOOP,
154 HINT_KEYWORD_NOMERGEJOIN,
155 HINT_KEYWORD_NOHASHJOIN,
157 HINT_KEYWORD_LEADING,
160 HINT_KEYWORD_PARALLEL,
162 HINT_KEYWORD_UNRECOGNIZED
165 #define SCAN_HINT_ACCEPTS_INDEX_NAMES(kw) \
166 (kw == HINT_KEYWORD_INDEXSCAN || \
167 kw == HINT_KEYWORD_INDEXSCANREGEXP || \
168 kw == HINT_KEYWORD_INDEXONLYSCAN || \
169 kw == HINT_KEYWORD_INDEXONLYSCANREGEXP || \
170 kw == HINT_KEYWORD_BITMAPSCAN || \
171 kw == HINT_KEYWORD_BITMAPSCANREGEXP)
174 typedef struct Hint Hint;
175 typedef struct HintState HintState;
177 typedef Hint *(*HintCreateFunction) (const char *hint_str,
179 HintKeyword hint_keyword);
180 typedef void (*HintDeleteFunction) (Hint *hint);
181 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf, bool nolf);
182 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
183 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
184 Query *parse, const char *str);
187 #define NUM_HINT_TYPE 6
188 typedef enum HintType
190 HINT_TYPE_SCAN_METHOD,
191 HINT_TYPE_JOIN_METHOD,
198 typedef enum HintTypeBitmap
200 HINT_BM_SCAN_METHOD = 1,
204 static const char *HintTypeName[] = {
214 typedef enum HintStatus
216 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
217 HINT_STATE_USED, /* hint is used */
218 HINT_STATE_DUPLICATION, /* specified hint duplication */
219 HINT_STATE_ERROR /* execute error (parse error does not include
223 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
224 (hint)->base.state == HINT_STATE_USED)
226 static unsigned int qno = 0;
227 static unsigned int msgqno = 0;
228 static char qnostr[32];
229 static const char *current_hint_str = NULL;
232 * However we usually take a hint stirng in post_parse_analyze_hook, we still
233 * need to do so in planner_hook when client starts query execution from the
234 * bind message on a prepared query. This variable prevent duplicate and
235 * sometimes harmful hint string retrieval.
237 static bool current_hint_retrieved = false;
239 /* common data for all hints. */
242 const char *hint_str; /* must not do pfree */
243 const char *keyword; /* must not do pfree */
244 HintKeyword hint_keyword;
247 HintDeleteFunction delete_func;
248 HintDescFunction desc_func;
249 HintCmpFunction cmp_func;
250 HintParseFunction parse_func;
253 /* scan method hints */
254 typedef struct ScanMethodHint
260 unsigned char enforce_mask;
263 typedef struct ParentIndexInfo
268 char *expression_str;
275 /* join method hints */
276 typedef struct JoinMethodHint
282 unsigned char enforce_mask;
284 Relids inner_joinrelids;
287 /* join order hints */
288 typedef struct OuterInnerRels
291 List *outer_inner_pair;
294 typedef struct LeadingHint
297 List *relations; /* relation names specified in Leading hint */
298 OuterInnerRels *outer_inner;
301 /* change a run-time parameter hints */
302 typedef struct SetHint
305 char *name; /* name of variable */
311 typedef enum RowsValueType {
312 RVT_ABSOLUTE, /* Rows(... #1000) */
313 RVT_ADD, /* Rows(... +1000) */
314 RVT_SUB, /* Rows(... -1000) */
315 RVT_MULTI, /* Rows(... *1.2) */
317 typedef struct RowsHint
324 Relids inner_joinrelids;
326 RowsValueType value_type;
331 typedef struct ParallelHint
335 char *nworkers_str; /* original string of nworkers */
336 int nworkers; /* num of workers specified by Worker */
337 bool force_parallel; /* force parallel scan */
341 * Describes a context of hint processing.
345 char *hint_str; /* original hint string */
348 int nall_hints; /* # of valid all hints */
349 int max_all_hints; /* # of slots for all hints */
350 Hint **all_hints; /* parsed all hints */
352 /* # of each hints */
353 int num_hints[NUM_HINT_TYPE];
355 /* for scan method hints */
356 ScanMethodHint **scan_hints; /* parsed scan hints */
358 /* Initial values of parameters */
359 int init_scan_mask; /* enable_* mask */
360 int init_nworkers; /* max_parallel_workers_per_gather */
361 /* min_parallel_table_scan_size*/
362 int init_min_para_tablescan_size;
363 /* min_parallel_index_scan_size*/
364 int init_min_para_indexscan_size;
365 int init_paratup_cost; /* parallel_tuple_cost */
366 int init_parasetup_cost;/* parallel_setup_cost */
368 PlannerInfo *current_root; /* PlannerInfo for the followings */
369 Index parent_relid; /* inherit parent of table relid */
370 ScanMethodHint *parent_scan_hint; /* scan hint for the parent */
371 ParallelHint *parent_parallel_hint; /* parallel hint for the parent */
372 List *parent_index_infos; /* list of parent table's index */
374 JoinMethodHint **join_hints; /* parsed join hints */
375 int init_join_mask; /* initial value join parameter */
376 List **join_hint_level;
377 LeadingHint **leading_hint; /* parsed Leading hints */
378 SetHint **set_hints; /* parsed Set hints */
379 GucContext context; /* which GUC parameters can we set? */
380 RowsHint **rows_hints; /* parsed Rows hints */
381 ParallelHint **parallel_hints; /* parsed Parallel hints */
385 * Describes a hint parser module which is bound with particular hint keyword.
387 typedef struct HintParser
390 HintCreateFunction create_func;
391 HintKeyword hint_keyword;
394 /* Module callbacks */
398 static void push_hint(HintState *hstate);
399 static void pop_hint(void);
401 static void pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query);
402 static void pg_hint_plan_ProcessUtility(PlannedStmt *pstmt,
403 const char *queryString,
404 ProcessUtilityContext context,
405 ParamListInfo params, QueryEnvironment *queryEnv,
406 DestReceiver *dest, char *completionTag);
407 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
408 ParamListInfo boundParams);
409 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
413 /* Scan method hint callbacks */
414 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
415 HintKeyword hint_keyword);
416 static void ScanMethodHintDelete(ScanMethodHint *hint);
417 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
418 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
419 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
420 Query *parse, const char *str);
422 /* Join method hint callbacks */
423 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
424 HintKeyword hint_keyword);
425 static void JoinMethodHintDelete(JoinMethodHint *hint);
426 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
427 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
428 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
429 Query *parse, const char *str);
431 /* Leading hint callbacks */
432 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
433 HintKeyword hint_keyword);
434 static void LeadingHintDelete(LeadingHint *hint);
435 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
436 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
437 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
438 Query *parse, const char *str);
440 /* Set hint callbacks */
441 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
442 HintKeyword hint_keyword);
443 static void SetHintDelete(SetHint *hint);
444 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
445 static int SetHintCmp(const SetHint *a, const SetHint *b);
446 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
449 /* Rows hint callbacks */
450 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
451 HintKeyword hint_keyword);
452 static void RowsHintDelete(RowsHint *hint);
453 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
454 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
455 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
456 Query *parse, const char *str);
458 /* Parallel hint callbacks */
459 static Hint *ParallelHintCreate(const char *hint_str, const char *keyword,
460 HintKeyword hint_keyword);
461 static void ParallelHintDelete(ParallelHint *hint);
462 static void ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf);
463 static int ParallelHintCmp(const ParallelHint *a, const ParallelHint *b);
464 static const char *ParallelHintParse(ParallelHint *hint, HintState *hstate,
465 Query *parse, const char *str);
467 static void quote_value(StringInfo buf, const char *value);
469 static const char *parse_quoted_value(const char *str, char **word,
472 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
475 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
476 void pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
477 Index rti, RangeTblEntry *rte);
478 static void create_plain_partial_paths(PlannerInfo *root,
480 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
481 ListCell *other_rels);
482 static void make_rels_by_clauseless_joins(PlannerInfo *root,
484 ListCell *other_rels);
485 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
486 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
488 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
489 Index rti, RangeTblEntry *rte);
490 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
493 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
495 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
497 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
501 static int set_config_option_noerror(const char *name, const char *value,
502 GucContext context, GucSource source,
503 GucAction action, bool changeVal, int elevel);
504 static void setup_scan_method_enforcement(ScanMethodHint *scanhint,
506 static int set_config_int32_option(const char *name, int32 value,
510 static bool pg_hint_plan_enable_hint = true;
511 static int debug_level = 0;
512 static int pg_hint_plan_parse_message_level = INFO;
513 static int pg_hint_plan_debug_message_level = LOG;
514 /* Default is off, to keep backward compatibility. */
515 static bool pg_hint_plan_enable_hint_table = false;
517 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
518 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
519 /* (This could not be above 1) */
520 static int max_hint_nworkers = -1; /* Maximum nworkers of Workers hints */
522 static const struct config_enum_entry parse_messages_level_options[] = {
523 {"debug", DEBUG2, true},
524 {"debug5", DEBUG5, false},
525 {"debug4", DEBUG4, false},
526 {"debug3", DEBUG3, false},
527 {"debug2", DEBUG2, false},
528 {"debug1", DEBUG1, false},
530 {"info", INFO, false},
531 {"notice", NOTICE, false},
532 {"warning", WARNING, false},
533 {"error", ERROR, false},
535 * {"fatal", FATAL, true},
536 * {"panic", PANIC, true},
541 static const struct config_enum_entry parse_debug_level_options[] = {
544 {"detailed", 2, false},
545 {"verbose", 3, false},
557 /* Saved hook values in case of unload */
558 static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
559 static planner_hook_type prev_planner = NULL;
560 static join_search_hook_type prev_join_search = NULL;
561 static set_rel_pathlist_hook_type prev_set_rel_pathlist = NULL;
562 static ProcessUtility_hook_type prev_ProcessUtility_hook = NULL;
564 /* Hold reference to currently active hint */
565 static HintState *current_hint_state = NULL;
568 * List of hint contexts. We treat the head of the list as the Top of the
569 * context stack, so current_hint_state always points the first element of this
572 static List *HintStateStack = NIL;
574 static const HintParser parsers[] = {
575 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
576 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
577 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
578 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
579 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
580 HINT_KEYWORD_BITMAPSCANREGEXP},
581 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
582 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
583 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
584 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
585 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
586 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
587 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
588 HINT_KEYWORD_INDEXONLYSCANREGEXP},
589 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
591 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
592 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
593 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
594 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
595 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
596 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
598 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
599 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
600 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
601 {HINT_PARALLEL, ParallelHintCreate, HINT_KEYWORD_PARALLEL},
603 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
606 PLpgSQL_plugin plugin_funcs = {
610 pg_hint_plan_plpgsql_stmt_beg,
611 pg_hint_plan_plpgsql_stmt_end,
617 * Module load callbacks
622 PLpgSQL_plugin **var_ptr;
624 /* Define custom GUC variables. */
625 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
626 "Force planner to use plans specified in the hint comment preceding to the query.",
628 &pg_hint_plan_enable_hint,
636 DefineCustomEnumVariable("pg_hint_plan.debug_print",
637 "Logs results of hint parsing.",
641 parse_debug_level_options,
648 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
649 "Message level of parse errors.",
651 &pg_hint_plan_parse_message_level,
653 parse_messages_level_options,
660 DefineCustomEnumVariable("pg_hint_plan.message_level",
661 "Message level of debug messages.",
663 &pg_hint_plan_debug_message_level,
665 parse_messages_level_options,
672 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
673 "Let pg_hint_plan look up the hint table.",
675 &pg_hint_plan_enable_hint_table,
684 prev_post_parse_analyze_hook = post_parse_analyze_hook;
685 post_parse_analyze_hook = pg_hint_plan_post_parse_analyze;
686 prev_planner = planner_hook;
687 planner_hook = pg_hint_plan_planner;
688 prev_join_search = join_search_hook;
689 join_search_hook = pg_hint_plan_join_search;
690 prev_set_rel_pathlist = set_rel_pathlist_hook;
691 set_rel_pathlist_hook = pg_hint_plan_set_rel_pathlist;
692 prev_ProcessUtility_hook = ProcessUtility_hook;
693 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
695 /* setup PL/pgSQL plugin hook */
696 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
697 *var_ptr = &plugin_funcs;
699 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
703 * Module unload callback
709 PLpgSQL_plugin **var_ptr;
711 /* Uninstall hooks. */
712 post_parse_analyze_hook = prev_post_parse_analyze_hook;
713 planner_hook = prev_planner;
714 join_search_hook = prev_join_search;
715 set_rel_pathlist_hook = prev_set_rel_pathlist;
716 ProcessUtility_hook = prev_ProcessUtility_hook;
718 /* uninstall PL/pgSQL plugin hook */
719 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
724 * create and delete functions the hint object
728 ScanMethodHintCreate(const char *hint_str, const char *keyword,
729 HintKeyword hint_keyword)
731 ScanMethodHint *hint;
733 hint = palloc(sizeof(ScanMethodHint));
734 hint->base.hint_str = hint_str;
735 hint->base.keyword = keyword;
736 hint->base.hint_keyword = hint_keyword;
737 hint->base.type = HINT_TYPE_SCAN_METHOD;
738 hint->base.state = HINT_STATE_NOTUSED;
739 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
740 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
741 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
742 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
743 hint->relname = NULL;
744 hint->indexnames = NIL;
745 hint->regexp = false;
746 hint->enforce_mask = 0;
748 return (Hint *) hint;
752 ScanMethodHintDelete(ScanMethodHint *hint)
758 pfree(hint->relname);
759 list_free_deep(hint->indexnames);
764 JoinMethodHintCreate(const char *hint_str, const char *keyword,
765 HintKeyword hint_keyword)
767 JoinMethodHint *hint;
769 hint = palloc(sizeof(JoinMethodHint));
770 hint->base.hint_str = hint_str;
771 hint->base.keyword = keyword;
772 hint->base.hint_keyword = hint_keyword;
773 hint->base.type = HINT_TYPE_JOIN_METHOD;
774 hint->base.state = HINT_STATE_NOTUSED;
775 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
776 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
777 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
778 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
780 hint->inner_nrels = 0;
781 hint->relnames = NULL;
782 hint->enforce_mask = 0;
783 hint->joinrelids = NULL;
784 hint->inner_joinrelids = NULL;
786 return (Hint *) hint;
790 JoinMethodHintDelete(JoinMethodHint *hint)
799 for (i = 0; i < hint->nrels; i++)
800 pfree(hint->relnames[i]);
801 pfree(hint->relnames);
804 bms_free(hint->joinrelids);
805 bms_free(hint->inner_joinrelids);
810 LeadingHintCreate(const char *hint_str, const char *keyword,
811 HintKeyword hint_keyword)
815 hint = palloc(sizeof(LeadingHint));
816 hint->base.hint_str = hint_str;
817 hint->base.keyword = keyword;
818 hint->base.hint_keyword = hint_keyword;
819 hint->base.type = HINT_TYPE_LEADING;
820 hint->base.state = HINT_STATE_NOTUSED;
821 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
822 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
823 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
824 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
825 hint->relations = NIL;
826 hint->outer_inner = NULL;
828 return (Hint *) hint;
832 LeadingHintDelete(LeadingHint *hint)
837 list_free_deep(hint->relations);
838 if (hint->outer_inner)
839 pfree(hint->outer_inner);
844 SetHintCreate(const char *hint_str, const char *keyword,
845 HintKeyword hint_keyword)
849 hint = palloc(sizeof(SetHint));
850 hint->base.hint_str = hint_str;
851 hint->base.keyword = keyword;
852 hint->base.hint_keyword = hint_keyword;
853 hint->base.type = HINT_TYPE_SET;
854 hint->base.state = HINT_STATE_NOTUSED;
855 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
856 hint->base.desc_func = (HintDescFunction) SetHintDesc;
857 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
858 hint->base.parse_func = (HintParseFunction) SetHintParse;
863 return (Hint *) hint;
867 SetHintDelete(SetHint *hint)
877 list_free(hint->words);
882 RowsHintCreate(const char *hint_str, const char *keyword,
883 HintKeyword hint_keyword)
887 hint = palloc(sizeof(RowsHint));
888 hint->base.hint_str = hint_str;
889 hint->base.keyword = keyword;
890 hint->base.hint_keyword = hint_keyword;
891 hint->base.type = HINT_TYPE_ROWS;
892 hint->base.state = HINT_STATE_NOTUSED;
893 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
894 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
895 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
896 hint->base.parse_func = (HintParseFunction) RowsHintParse;
898 hint->inner_nrels = 0;
899 hint->relnames = NULL;
900 hint->joinrelids = NULL;
901 hint->inner_joinrelids = NULL;
902 hint->rows_str = NULL;
903 hint->value_type = RVT_ABSOLUTE;
906 return (Hint *) hint;
910 RowsHintDelete(RowsHint *hint)
919 for (i = 0; i < hint->nrels; i++)
920 pfree(hint->relnames[i]);
921 pfree(hint->relnames);
924 bms_free(hint->joinrelids);
925 bms_free(hint->inner_joinrelids);
930 ParallelHintCreate(const char *hint_str, const char *keyword,
931 HintKeyword hint_keyword)
935 hint = palloc(sizeof(ScanMethodHint));
936 hint->base.hint_str = hint_str;
937 hint->base.keyword = keyword;
938 hint->base.hint_keyword = hint_keyword;
939 hint->base.type = HINT_TYPE_PARALLEL;
940 hint->base.state = HINT_STATE_NOTUSED;
941 hint->base.delete_func = (HintDeleteFunction) ParallelHintDelete;
942 hint->base.desc_func = (HintDescFunction) ParallelHintDesc;
943 hint->base.cmp_func = (HintCmpFunction) ParallelHintCmp;
944 hint->base.parse_func = (HintParseFunction) ParallelHintParse;
945 hint->relname = NULL;
947 hint->nworkers_str = "0";
949 return (Hint *) hint;
953 ParallelHintDelete(ParallelHint *hint)
959 pfree(hint->relname);
965 HintStateCreate(void)
969 hstate = palloc(sizeof(HintState));
970 hstate->hint_str = NULL;
971 hstate->nall_hints = 0;
972 hstate->max_all_hints = 0;
973 hstate->all_hints = NULL;
974 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
975 hstate->scan_hints = NULL;
976 hstate->init_scan_mask = 0;
977 hstate->init_nworkers = 0;
978 hstate->init_min_para_tablescan_size = 0;
979 hstate->init_min_para_indexscan_size = 0;
980 hstate->init_paratup_cost = 0;
981 hstate->init_parasetup_cost = 0;
982 hstate->current_root = NULL;
983 hstate->parent_relid = 0;
984 hstate->parent_scan_hint = NULL;
985 hstate->parent_parallel_hint = NULL;
986 hstate->parent_index_infos = NIL;
987 hstate->join_hints = NULL;
988 hstate->init_join_mask = 0;
989 hstate->join_hint_level = NULL;
990 hstate->leading_hint = NULL;
991 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
992 hstate->set_hints = NULL;
993 hstate->rows_hints = NULL;
994 hstate->parallel_hints = NULL;
1000 HintStateDelete(HintState *hstate)
1007 if (hstate->hint_str)
1008 pfree(hstate->hint_str);
1010 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1011 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
1012 if (hstate->all_hints)
1013 pfree(hstate->all_hints);
1014 if (hstate->parent_index_infos)
1015 list_free(hstate->parent_index_infos);
1019 * Copy given value into buf, with quoting with '"' if necessary.
1022 quote_value(StringInfo buf, const char *value)
1024 bool need_quote = false;
1027 for (str = value; *str != '\0'; str++)
1029 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
1032 appendStringInfoCharMacro(buf, '"');
1037 for (str = value; *str != '\0'; str++)
1040 appendStringInfoCharMacro(buf, '"');
1042 appendStringInfoCharMacro(buf, *str);
1046 appendStringInfoCharMacro(buf, '"');
1050 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
1054 appendStringInfo(buf, "%s(", hint->base.keyword);
1055 if (hint->relname != NULL)
1057 quote_value(buf, hint->relname);
1058 foreach(l, hint->indexnames)
1060 appendStringInfoCharMacro(buf, ' ');
1061 quote_value(buf, (char *) lfirst(l));
1064 appendStringInfoString(buf, ")");
1066 appendStringInfoChar(buf, '\n');
1070 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
1074 appendStringInfo(buf, "%s(", hint->base.keyword);
1075 if (hint->relnames != NULL)
1077 quote_value(buf, hint->relnames[0]);
1078 for (i = 1; i < hint->nrels; i++)
1080 appendStringInfoCharMacro(buf, ' ');
1081 quote_value(buf, hint->relnames[i]);
1084 appendStringInfoString(buf, ")");
1086 appendStringInfoChar(buf, '\n');
1090 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
1092 if (outer_inner->relation == NULL)
1099 appendStringInfoCharMacro(buf, '(');
1100 foreach(l, outer_inner->outer_inner_pair)
1105 appendStringInfoCharMacro(buf, ' ');
1107 OuterInnerDesc(lfirst(l), buf);
1110 appendStringInfoCharMacro(buf, ')');
1113 quote_value(buf, outer_inner->relation);
1117 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
1119 appendStringInfo(buf, "%s(", HINT_LEADING);
1120 if (hint->outer_inner == NULL)
1127 foreach(l, hint->relations)
1132 appendStringInfoCharMacro(buf, ' ');
1134 quote_value(buf, (char *) lfirst(l));
1138 OuterInnerDesc(hint->outer_inner, buf);
1140 appendStringInfoString(buf, ")");
1142 appendStringInfoChar(buf, '\n');
1146 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1148 bool is_first = true;
1151 appendStringInfo(buf, "%s(", HINT_SET);
1152 foreach(l, hint->words)
1157 appendStringInfoCharMacro(buf, ' ');
1159 quote_value(buf, (char *) lfirst(l));
1161 appendStringInfo(buf, ")");
1163 appendStringInfoChar(buf, '\n');
1167 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1171 appendStringInfo(buf, "%s(", hint->base.keyword);
1172 if (hint->relnames != NULL)
1174 quote_value(buf, hint->relnames[0]);
1175 for (i = 1; i < hint->nrels; i++)
1177 appendStringInfoCharMacro(buf, ' ');
1178 quote_value(buf, hint->relnames[i]);
1181 appendStringInfo(buf, " %s", hint->rows_str);
1182 appendStringInfoString(buf, ")");
1184 appendStringInfoChar(buf, '\n');
1188 ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf)
1190 appendStringInfo(buf, "%s(", hint->base.keyword);
1191 if (hint->relname != NULL)
1193 quote_value(buf, hint->relname);
1195 /* number of workers */
1196 appendStringInfoCharMacro(buf, ' ');
1197 quote_value(buf, hint->nworkers_str);
1198 /* application mode of num of workers */
1199 appendStringInfoCharMacro(buf, ' ');
1200 appendStringInfoString(buf,
1201 (hint->force_parallel ? "hard" : "soft"));
1203 appendStringInfoString(buf, ")");
1205 appendStringInfoChar(buf, '\n');
1209 * Append string which represents all hints in a given state to buf, with
1210 * preceding title with them.
1213 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1214 HintStatus state, bool nolf)
1218 appendStringInfo(buf, "%s:", title);
1220 appendStringInfoChar(buf, '\n');
1223 for (i = 0; i < hstate->nall_hints; i++)
1225 if (hstate->all_hints[i]->state != state)
1228 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1232 if (nolf && nshown == 0)
1233 appendStringInfoString(buf, "(none)");
1237 * Dump contents of given hstate to server log with log level LOG.
1240 HintStateDump(HintState *hstate)
1246 elog(pg_hint_plan_debug_message_level, "pg_hint_plan:\nno hint");
1250 initStringInfo(&buf);
1252 appendStringInfoString(&buf, "pg_hint_plan:\n");
1253 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1254 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1255 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1256 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1258 ereport(pg_hint_plan_debug_message_level,
1259 (errmsg ("%s", buf.data)));
1265 HintStateDump2(HintState *hstate)
1271 elog(pg_hint_plan_debug_message_level,
1272 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1276 initStringInfo(&buf);
1277 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1278 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1279 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1280 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1281 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1282 appendStringInfoChar(&buf, '}');
1284 ereport(pg_hint_plan_debug_message_level,
1285 (errmsg("%s", buf.data),
1287 errhidecontext(true)));
1297 RelnameCmp(const void *a, const void *b)
1299 const char *relnamea = *((const char **) a);
1300 const char *relnameb = *((const char **) b);
1302 return strcmp(relnamea, relnameb);
1306 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1308 return RelnameCmp(&a->relname, &b->relname);
1312 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1316 if (a->nrels != b->nrels)
1317 return a->nrels - b->nrels;
1319 for (i = 0; i < a->nrels; i++)
1322 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1330 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1336 SetHintCmp(const SetHint *a, const SetHint *b)
1338 return strcmp(a->name, b->name);
1342 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1346 if (a->nrels != b->nrels)
1347 return a->nrels - b->nrels;
1349 for (i = 0; i < a->nrels; i++)
1352 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1360 ParallelHintCmp(const ParallelHint *a, const ParallelHint *b)
1362 return RelnameCmp(&a->relname, &b->relname);
1366 HintCmp(const void *a, const void *b)
1368 const Hint *hinta = *((const Hint **) a);
1369 const Hint *hintb = *((const Hint **) b);
1371 if (hinta->type != hintb->type)
1372 return hinta->type - hintb->type;
1373 if (hinta->state == HINT_STATE_ERROR)
1375 if (hintb->state == HINT_STATE_ERROR)
1377 return hinta->cmp_func(hinta, hintb);
1381 * Returns byte offset of hint b from hint a. If hint a was specified before
1382 * b, positive value is returned.
1385 HintCmpWithPos(const void *a, const void *b)
1387 const Hint *hinta = *((const Hint **) a);
1388 const Hint *hintb = *((const Hint **) b);
1391 result = HintCmp(a, b);
1393 result = hinta->hint_str - hintb->hint_str;
1402 parse_keyword(const char *str, StringInfo buf)
1406 while (!isspace(*str) && *str != '(' && *str != '\0')
1407 appendStringInfoCharMacro(buf, *str++);
1413 skip_parenthesis(const char *str, char parenthesis)
1417 if (*str != parenthesis)
1419 if (parenthesis == '(')
1420 hint_ereport(str, ("Opening parenthesis is necessary."));
1421 else if (parenthesis == ')')
1422 hint_ereport(str, ("Closing parenthesis is necessary."));
1433 * Parse a token from str, and store malloc'd copy into word. A token can be
1434 * quoted with '"'. Return value is pointer to unparsed portion of original
1435 * string, or NULL if an error occurred.
1437 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1440 parse_quoted_value(const char *str, char **word, bool truncate)
1445 /* Skip leading spaces. */
1448 initStringInfo(&buf);
1461 /* Double quotation must be closed. */
1465 hint_ereport(str, ("Unterminated quoted string."));
1470 * Skip escaped double quotation.
1472 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1473 * block comments) to be an object name, so users must specify
1474 * alias for such object names.
1476 * Those special names can be allowed if we care escaped slashes
1477 * and asterisks, but we don't.
1486 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1490 appendStringInfoCharMacro(&buf, *str++);
1495 hint_ereport(str, ("Zero-length delimited string."));
1502 /* Truncate name if it's too long */
1504 truncate_identifier(buf.data, strlen(buf.data), true);
1511 static OuterInnerRels *
1512 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1514 OuterInnerRels *outer_inner;
1516 outer_inner = palloc(sizeof(OuterInnerRels));
1517 outer_inner->relation = name;
1518 outer_inner->outer_inner_pair = outer_inner_list;
1524 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1526 List *outer_inner_pair = NIL;
1528 if ((str = skip_parenthesis(str, '(')) == NULL)
1533 /* Store words in parentheses into outer_inner_list. */
1534 while(*str != ')' && *str != '\0')
1536 OuterInnerRels *outer_inner_rels;
1540 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1548 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1551 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1554 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1559 (str = skip_parenthesis(str, ')')) == NULL)
1561 list_free(outer_inner_pair);
1565 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1571 parse_parentheses_Leading(const char *str, List **name_list,
1572 OuterInnerRels **outer_inner)
1575 bool truncate = true;
1577 if ((str = skip_parenthesis(str, '(')) == NULL)
1583 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1588 /* Store words in parentheses into name_list. */
1589 while(*str != ')' && *str != '\0')
1591 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1593 list_free(*name_list);
1597 *name_list = lappend(*name_list, name);
1602 if ((str = skip_parenthesis(str, ')')) == NULL)
1608 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1611 bool truncate = true;
1613 if ((str = skip_parenthesis(str, '(')) == NULL)
1618 /* Store words in parentheses into name_list. */
1619 while(*str != ')' && *str != '\0')
1621 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1623 list_free(*name_list);
1627 *name_list = lappend(*name_list, name);
1630 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1631 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1632 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1633 keyword == HINT_KEYWORD_SET)
1639 if ((str = skip_parenthesis(str, ')')) == NULL)
1645 parse_hints(HintState *hstate, Query *parse, const char *str)
1650 initStringInfo(&buf);
1651 while (*str != '\0')
1653 const HintParser *parser;
1655 /* in error message, we output the comment including the keyword. */
1656 head = (char *) str;
1658 /* parse only the keyword of the hint. */
1659 resetStringInfo(&buf);
1660 str = parse_keyword(str, &buf);
1662 for (parser = parsers; parser->keyword != NULL; parser++)
1664 char *keyword = parser->keyword;
1667 if (pg_strcasecmp(buf.data, keyword) != 0)
1670 hint = parser->create_func(head, keyword, parser->hint_keyword);
1672 /* parser of each hint does parse in a parenthesis. */
1673 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1675 hint->delete_func(hint);
1681 * Add hint information into all_hints array. If we don't have
1682 * enough space, double the array.
1684 if (hstate->nall_hints == 0)
1686 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1687 hstate->all_hints = (Hint **)
1688 palloc(sizeof(Hint *) * hstate->max_all_hints);
1690 else if (hstate->nall_hints == hstate->max_all_hints)
1692 hstate->max_all_hints *= 2;
1693 hstate->all_hints = (Hint **)
1694 repalloc(hstate->all_hints,
1695 sizeof(Hint *) * hstate->max_all_hints);
1698 hstate->all_hints[hstate->nall_hints] = hint;
1699 hstate->nall_hints++;
1706 if (parser->keyword == NULL)
1709 ("Unrecognized hint keyword \"%s\".", buf.data));
1720 * Get hints from table by client-supplied query string and application name.
1723 get_hints_from_table(const char *client_query, const char *client_application)
1725 const char *search_query =
1727 " FROM hint_plan.hints "
1728 " WHERE norm_query_string = $1 "
1729 " AND ( application_name = $2 "
1730 " OR application_name = '' ) "
1731 " ORDER BY application_name DESC";
1732 static SPIPlanPtr plan = NULL;
1734 Oid argtypes[2] = { TEXTOID, TEXTOID };
1736 char nulls[2] = {' ', ' '};
1742 bool snapshot_set = false;
1744 hint_inhibit_level++;
1746 if (!ActiveSnapshotSet())
1748 PushActiveSnapshot(GetTransactionSnapshot());
1749 snapshot_set = true;
1757 p = SPI_prepare(search_query, 2, argtypes);
1758 plan = SPI_saveplan(p);
1762 qry = cstring_to_text(client_query);
1763 app = cstring_to_text(client_application);
1764 values[0] = PointerGetDatum(qry);
1765 values[1] = PointerGetDatum(app);
1767 SPI_execute_plan(plan, values, nulls, true, 1);
1769 if (SPI_processed > 0)
1773 hints = SPI_getvalue(SPI_tuptable->vals[0],
1774 SPI_tuptable->tupdesc, 1);
1776 * Here we use SPI_palloc to ensure that hints string is valid even
1777 * after SPI_finish call. We can't use simple palloc because it
1778 * allocates memory in SPI's context and that context is deleted in
1781 buf = SPI_palloc(strlen(hints) + 1);
1789 PopActiveSnapshot();
1791 hint_inhibit_level--;
1795 hint_inhibit_level--;
1804 * Get client-supplied query string. Addtion to that the jumbled query is
1805 * supplied if the caller requested. From the restriction of JumbleQuery, some
1806 * kind of query needs special amendments. Reutrns NULL if this query doesn't
1807 * change the current hint. This function returns NULL also when something
1808 * wrong has happend and let the caller continue using the current hints.
1811 get_query_string(ParseState *pstate, Query *query, Query **jumblequery)
1813 const char *p = debug_query_string;
1816 * If debug_query_string is set, it is the top level statement. But in some
1817 * cases we reach here with debug_query_string set NULL for example in the
1818 * case of DESCRIBE message handling or EXECUTE command. We may still see a
1819 * candidate top-level query in pstate in the case.
1822 p = pstate->p_sourcetext;
1824 /* We don't see a query string, return NULL */
1828 if (jumblequery != NULL)
1829 *jumblequery = query;
1831 if (query->commandType == CMD_UTILITY)
1833 Query *target_query = (Query *)query->utilityStmt;
1836 * Some CMD_UTILITY statements have a subquery that we can hint on.
1837 * Since EXPLAIN can be placed before other kind of utility statements
1838 * and EXECUTE can be contained other kind of utility statements, these
1839 * conditions are not mutually exclusive and should be considered in
1842 if (IsA(target_query, ExplainStmt))
1844 ExplainStmt *stmt = (ExplainStmt *)target_query;
1846 Assert(IsA(stmt->query, Query));
1847 target_query = (Query *)stmt->query;
1849 /* strip out the top-level query for further processing */
1850 if (target_query->commandType == CMD_UTILITY &&
1851 target_query->utilityStmt != NULL)
1852 target_query = (Query *)target_query->utilityStmt;
1855 if (IsA(target_query, DeclareCursorStmt))
1857 DeclareCursorStmt *stmt = (DeclareCursorStmt *)target_query;
1858 Query *query = (Query *)stmt->query;
1860 /* the target must be CMD_SELECT in this case */
1861 Assert(IsA(query, Query) && query->commandType == CMD_SELECT);
1862 target_query = query;
1865 if (IsA(target_query, CreateTableAsStmt))
1867 CreateTableAsStmt *stmt = (CreateTableAsStmt *) target_query;
1869 Assert(IsA(stmt->query, Query));
1870 target_query = (Query *) stmt->query;
1872 /* strip out the top-level query for further processing */
1873 if (target_query->commandType == CMD_UTILITY &&
1874 target_query->utilityStmt != NULL)
1875 target_query = (Query *)target_query->utilityStmt;
1878 if (IsA(target_query, ExecuteStmt))
1881 * Use the prepared query for EXECUTE. The Query for jumble
1882 * also replaced with the corresponding one.
1884 ExecuteStmt *stmt = (ExecuteStmt *)target_query;
1885 PreparedStatement *entry;
1887 entry = FetchPreparedStatement(stmt->name, true);
1888 p = entry->plansource->query_string;
1889 target_query = (Query *) linitial (entry->plansource->query_list);
1892 /* JumbleQuery accespts only a non-utility Query */
1893 if (!IsA(target_query, Query) ||
1894 target_query->utilityStmt != NULL)
1895 target_query = NULL;
1898 *jumblequery = target_query;
1901 * Return NULL if pstate is not of top-level query. We don't need this
1902 * when jumble info is not requested or cannot do this when pstate is NULL.
1904 else if (!jumblequery && pstate && pstate->p_sourcetext != p &&
1905 strcmp(pstate->p_sourcetext, p) != 0)
1912 * Get hints from the head block comment in client-supplied query string.
1915 get_hints_from_comment(const char *p)
1917 const char *hint_head;
1925 /* extract query head comment. */
1926 hint_head = strstr(p, HINT_START);
1927 if (hint_head == NULL)
1929 for (;p < hint_head; p++)
1932 * Allow these characters precedes hint comment:
1934 * - alphabets which are in ASCII range
1935 * - space, tabs and new-lines
1936 * - underscores, for identifier
1937 * - commas, for SELECT clause, EXPLAIN and PREPARE
1938 * - parentheses, for EXPLAIN and PREPARE
1940 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1941 * avoid behavior which depends on locale setting.
1943 if (!(*p >= '0' && *p <= '9') &&
1944 !(*p >= 'A' && *p <= 'Z') &&
1945 !(*p >= 'a' && *p <= 'z') &&
1949 *p != '(' && *p != ')')
1953 len = strlen(HINT_START);
1958 /* find hint end keyword. */
1959 if ((tail = strstr(p, HINT_END)) == NULL)
1961 hint_ereport(head, ("Unterminated block comment."));
1965 /* We don't support nested block comments. */
1966 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1968 hint_ereport(head, ("Nested block comments are not supported."));
1972 /* Make a copy of hint. */
1974 head = palloc(len + 1);
1975 memcpy(head, p, len);
1983 * Parse hints that got, create hint struct from parse tree and parse hints.
1986 create_hintstate(Query *parse, const char *hints)
1995 /* -1 means that no Parallel hint is specified. */
1996 max_hint_nworkers = -1;
1999 hstate = HintStateCreate();
2000 hstate->hint_str = (char *) hints;
2002 /* parse each hint. */
2003 parse_hints(hstate, parse, p);
2005 /* When nothing specified a hint, we free HintState and returns NULL. */
2006 if (hstate->nall_hints == 0)
2008 HintStateDelete(hstate);
2012 /* Sort hints in order of original position. */
2013 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
2016 /* Count number of hints per hint-type. */
2017 for (i = 0; i < hstate->nall_hints; i++)
2019 Hint *cur_hint = hstate->all_hints[i];
2020 hstate->num_hints[cur_hint->type]++;
2024 * If an object (or a set of objects) has multiple hints of same hint-type,
2025 * only the last hint is valid and others are ignored in planning.
2026 * Hints except the last are marked as 'duplicated' to remember the order.
2028 for (i = 0; i < hstate->nall_hints - 1; i++)
2030 Hint *cur_hint = hstate->all_hints[i];
2031 Hint *next_hint = hstate->all_hints[i + 1];
2034 * Leading hint is marked as 'duplicated' in transform_join_hints.
2036 if (cur_hint->type == HINT_TYPE_LEADING &&
2037 next_hint->type == HINT_TYPE_LEADING)
2041 * Note that we need to pass addresses of hint pointers, because
2042 * HintCmp is designed to sort array of Hint* by qsort.
2044 if (HintCmp(&cur_hint, &next_hint) == 0)
2046 hint_ereport(cur_hint->hint_str,
2047 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
2048 cur_hint->state = HINT_STATE_DUPLICATION;
2053 * Make sure that per-type array pointers point proper position in the
2054 * array which consists of all hints.
2056 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
2057 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
2058 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
2059 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
2060 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
2061 hstate->set_hints = (SetHint **) (hstate->leading_hint +
2062 hstate->num_hints[HINT_TYPE_LEADING]);
2063 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
2064 hstate->num_hints[HINT_TYPE_SET]);
2065 hstate->parallel_hints = (ParallelHint **) (hstate->set_hints +
2066 hstate->num_hints[HINT_TYPE_ROWS]);
2072 * Parse inside of parentheses of scan-method hints.
2075 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
2078 const char *keyword = hint->base.keyword;
2079 HintKeyword hint_keyword = hint->base.hint_keyword;
2080 List *name_list = NIL;
2083 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2086 /* Parse relation name and index name(s) if given hint accepts. */
2087 length = list_length(name_list);
2089 /* at least twp parameters required */
2093 ("%s hint requires a relation.", hint->base.keyword));
2094 hint->base.state = HINT_STATE_ERROR;
2098 hint->relname = linitial(name_list);
2099 hint->indexnames = list_delete_first(name_list);
2101 /* check whether the hint accepts index name(s) */
2102 if (length > 1 && !SCAN_HINT_ACCEPTS_INDEX_NAMES(hint_keyword))
2105 ("%s hint accepts only one relation.",
2106 hint->base.keyword));
2107 hint->base.state = HINT_STATE_ERROR;
2111 /* Set a bit for specified hint. */
2112 switch (hint_keyword)
2114 case HINT_KEYWORD_SEQSCAN:
2115 hint->enforce_mask = ENABLE_SEQSCAN;
2117 case HINT_KEYWORD_INDEXSCAN:
2118 hint->enforce_mask = ENABLE_INDEXSCAN;
2120 case HINT_KEYWORD_INDEXSCANREGEXP:
2121 hint->enforce_mask = ENABLE_INDEXSCAN;
2122 hint->regexp = true;
2124 case HINT_KEYWORD_BITMAPSCAN:
2125 hint->enforce_mask = ENABLE_BITMAPSCAN;
2127 case HINT_KEYWORD_BITMAPSCANREGEXP:
2128 hint->enforce_mask = ENABLE_BITMAPSCAN;
2129 hint->regexp = true;
2131 case HINT_KEYWORD_TIDSCAN:
2132 hint->enforce_mask = ENABLE_TIDSCAN;
2134 case HINT_KEYWORD_NOSEQSCAN:
2135 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
2137 case HINT_KEYWORD_NOINDEXSCAN:
2138 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
2140 case HINT_KEYWORD_NOBITMAPSCAN:
2141 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
2143 case HINT_KEYWORD_NOTIDSCAN:
2144 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
2146 case HINT_KEYWORD_INDEXONLYSCAN:
2147 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2149 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
2150 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2151 hint->regexp = true;
2153 case HINT_KEYWORD_NOINDEXONLYSCAN:
2154 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
2157 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2166 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2169 const char *keyword = hint->base.keyword;
2170 HintKeyword hint_keyword = hint->base.hint_keyword;
2171 List *name_list = NIL;
2173 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2176 hint->nrels = list_length(name_list);
2178 if (hint->nrels > 0)
2184 * Transform relation names from list to array to sort them with qsort
2187 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2188 foreach (l, name_list)
2190 hint->relnames[i] = lfirst(l);
2195 list_free(name_list);
2197 /* A join hint requires at least two relations */
2198 if (hint->nrels < 2)
2201 ("%s hint requires at least two relations.",
2202 hint->base.keyword));
2203 hint->base.state = HINT_STATE_ERROR;
2207 /* Sort hints in alphabetical order of relation names. */
2208 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2210 switch (hint_keyword)
2212 case HINT_KEYWORD_NESTLOOP:
2213 hint->enforce_mask = ENABLE_NESTLOOP;
2215 case HINT_KEYWORD_MERGEJOIN:
2216 hint->enforce_mask = ENABLE_MERGEJOIN;
2218 case HINT_KEYWORD_HASHJOIN:
2219 hint->enforce_mask = ENABLE_HASHJOIN;
2221 case HINT_KEYWORD_NONESTLOOP:
2222 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2224 case HINT_KEYWORD_NOMERGEJOIN:
2225 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2227 case HINT_KEYWORD_NOHASHJOIN:
2228 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2231 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2240 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2243 if (outer_inner->outer_inner_pair == NIL)
2245 if (outer_inner->relation)
2251 if (list_length(outer_inner->outer_inner_pair) == 2)
2253 foreach(l, outer_inner->outer_inner_pair)
2255 if (!OuterInnerPairCheck(lfirst(l)))
2266 OuterInnerList(OuterInnerRels *outer_inner)
2268 List *outer_inner_list = NIL;
2270 OuterInnerRels *outer_inner_rels;
2272 foreach(l, outer_inner->outer_inner_pair)
2274 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2276 if (outer_inner_rels->relation != NULL)
2277 outer_inner_list = lappend(outer_inner_list,
2278 outer_inner_rels->relation);
2280 outer_inner_list = list_concat(outer_inner_list,
2281 OuterInnerList(outer_inner_rels));
2283 return outer_inner_list;
2287 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2290 List *name_list = NIL;
2291 OuterInnerRels *outer_inner = NULL;
2293 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2297 if (outer_inner != NULL)
2298 name_list = OuterInnerList(outer_inner);
2300 hint->relations = name_list;
2301 hint->outer_inner = outer_inner;
2303 /* A Leading hint requires at least two relations */
2304 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2306 hint_ereport(hint->base.hint_str,
2307 ("%s hint requires at least two relations.",
2309 hint->base.state = HINT_STATE_ERROR;
2311 else if (hint->outer_inner != NULL &&
2312 !OuterInnerPairCheck(hint->outer_inner))
2314 hint_ereport(hint->base.hint_str,
2315 ("%s hint requires two sets of relations when parentheses nests.",
2317 hint->base.state = HINT_STATE_ERROR;
2324 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2326 List *name_list = NIL;
2328 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2332 hint->words = name_list;
2334 /* We need both name and value to set GUC parameter. */
2335 if (list_length(name_list) == 2)
2337 hint->name = linitial(name_list);
2338 hint->value = lsecond(name_list);
2342 hint_ereport(hint->base.hint_str,
2343 ("%s hint requires name and value of GUC parameter.",
2345 hint->base.state = HINT_STATE_ERROR;
2352 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2355 HintKeyword hint_keyword = hint->base.hint_keyword;
2356 List *name_list = NIL;
2360 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2363 /* Last element must be rows specification */
2364 hint->nrels = list_length(name_list) - 1;
2366 if (hint->nrels > 0)
2372 * Transform relation names from list to array to sort them with qsort
2375 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2376 foreach (l, name_list)
2378 if (hint->nrels <= i)
2380 hint->relnames[i] = lfirst(l);
2385 /* Retieve rows estimation */
2386 rows_str = list_nth(name_list, hint->nrels);
2387 hint->rows_str = rows_str; /* store as-is for error logging */
2388 if (rows_str[0] == '#')
2390 hint->value_type = RVT_ABSOLUTE;
2393 else if (rows_str[0] == '+')
2395 hint->value_type = RVT_ADD;
2398 else if (rows_str[0] == '-')
2400 hint->value_type = RVT_SUB;
2403 else if (rows_str[0] == '*')
2405 hint->value_type = RVT_MULTI;
2410 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2411 hint->base.state = HINT_STATE_ERROR;
2414 hint->rows = strtod(rows_str, &end_ptr);
2417 hint_ereport(rows_str,
2418 ("%s hint requires valid number as rows estimation.",
2419 hint->base.keyword));
2420 hint->base.state = HINT_STATE_ERROR;
2424 /* A join hint requires at least two relations */
2425 if (hint->nrels < 2)
2428 ("%s hint requires at least two relations.",
2429 hint->base.keyword));
2430 hint->base.state = HINT_STATE_ERROR;
2434 list_free(name_list);
2436 /* Sort relnames in alphabetical order. */
2437 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2443 ParallelHintParse(ParallelHint *hint, HintState *hstate, Query *parse,
2446 HintKeyword hint_keyword = hint->base.hint_keyword;
2447 List *name_list = NIL;
2451 bool force_parallel = false;
2453 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2456 /* Parse relation name and index name(s) if given hint accepts. */
2457 length = list_length(name_list);
2459 if (length < 2 || length > 3)
2462 ("wrong number of arguments (%d): %s",
2463 length, hint->base.keyword));
2464 hint->base.state = HINT_STATE_ERROR;
2468 hint->relname = linitial(name_list);
2470 /* The second parameter is number of workers */
2471 hint->nworkers_str = list_nth(name_list, 1);
2472 nworkers = strtod(hint->nworkers_str, &end_ptr);
2473 if (*end_ptr || nworkers < 0 || nworkers > max_worker_processes)
2476 hint_ereport(hint->nworkers_str,
2477 ("number of workers must be a number: %s",
2478 hint->base.keyword));
2479 else if (nworkers < 0)
2480 hint_ereport(hint->nworkers_str,
2481 ("number of workers must be positive: %s",
2482 hint->base.keyword));
2483 else if (nworkers > max_worker_processes)
2484 hint_ereport(hint->nworkers_str,
2485 ("number of workers = %d is larger than max_worker_processes(%d): %s",
2486 nworkers, max_worker_processes, hint->base.keyword));
2488 hint->base.state = HINT_STATE_ERROR;
2491 hint->nworkers = nworkers;
2493 /* optional third parameter is specified */
2496 const char *modeparam = (const char *)list_nth(name_list, 2);
2497 if (pg_strcasecmp(modeparam, "hard") == 0)
2498 force_parallel = true;
2499 else if (pg_strcasecmp(modeparam, "soft") != 0)
2501 hint_ereport(modeparam,
2502 ("enforcement must be soft or hard: %s",
2503 hint->base.keyword));
2504 hint->base.state = HINT_STATE_ERROR;
2508 hint->force_parallel = force_parallel;
2510 if (hint->base.state != HINT_STATE_ERROR &&
2511 nworkers > max_hint_nworkers)
2512 max_hint_nworkers = nworkers;
2518 * set GUC parameter functions
2522 get_current_scan_mask()
2527 mask |= ENABLE_SEQSCAN;
2528 if (enable_indexscan)
2529 mask |= ENABLE_INDEXSCAN;
2530 if (enable_bitmapscan)
2531 mask |= ENABLE_BITMAPSCAN;
2533 mask |= ENABLE_TIDSCAN;
2534 if (enable_indexonlyscan)
2535 mask |= ENABLE_INDEXONLYSCAN;
2541 get_current_join_mask()
2545 if (enable_nestloop)
2546 mask |= ENABLE_NESTLOOP;
2547 if (enable_mergejoin)
2548 mask |= ENABLE_MERGEJOIN;
2549 if (enable_hashjoin)
2550 mask |= ENABLE_HASHJOIN;
2556 * Sets GUC prameters without throwing exception. Reutrns false if something
2560 set_config_option_noerror(const char *name, const char *value,
2561 GucContext context, GucSource source,
2562 GucAction action, bool changeVal, int elevel)
2565 MemoryContext ccxt = CurrentMemoryContext;
2569 result = set_config_option(name, value, context, source,
2570 action, changeVal, 0, false);
2576 /* Save error info */
2577 MemoryContextSwitchTo(ccxt);
2578 errdata = CopyErrorData();
2582 (errcode(errdata->sqlerrcode),
2583 errmsg("%s", errdata->message),
2584 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2585 errdata->hint ? errhint("%s", errdata->hint) : 0));
2587 FreeErrorData(errdata);
2595 * Sets GUC parameter of int32 type without throwing exceptions. Returns false
2596 * if something wrong.
2599 set_config_int32_option(const char *name, int32 value, GucContext context)
2601 char buf[16]; /* enough for int32 */
2603 if (snprintf(buf, 16, "%d", value) < 0)
2605 ereport(pg_hint_plan_parse_message_level,
2606 (errmsg ("Failed to convert integer to string: %d", value)));
2611 set_config_option_noerror(name, buf, context,
2612 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2613 pg_hint_plan_parse_message_level);
2616 /* setup scan method enforcement according to given options */
2618 setup_guc_enforcement(SetHint **options, int noptions, GucContext context)
2622 for (i = 0; i < noptions; i++)
2624 SetHint *hint = options[i];
2627 if (!hint_state_enabled(hint))
2630 result = set_config_option_noerror(hint->name, hint->value, context,
2631 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2632 pg_hint_plan_parse_message_level);
2634 hint->base.state = HINT_STATE_USED;
2636 hint->base.state = HINT_STATE_ERROR;
2643 * Setup parallel execution environment.
2645 * If hint is not NULL, set up using it, elsewise reset to initial environment.
2648 setup_parallel_plan_enforcement(ParallelHint *hint, HintState *state)
2652 hint->base.state = HINT_STATE_USED;
2653 set_config_int32_option("max_parallel_workers_per_gather",
2654 hint->nworkers, state->context);
2657 set_config_int32_option("max_parallel_workers_per_gather",
2658 state->init_nworkers, state->context);
2660 /* force means that enforce parallel as far as possible */
2661 if (hint && hint->force_parallel && hint->nworkers > 0)
2663 set_config_int32_option("parallel_tuple_cost", 0, state->context);
2664 set_config_int32_option("parallel_setup_cost", 0, state->context);
2665 set_config_int32_option("min_parallel_table_scan_size", 0,
2667 set_config_int32_option("min_parallel_index_scan_size", 0,
2672 set_config_int32_option("parallel_tuple_cost",
2673 state->init_paratup_cost, state->context);
2674 set_config_int32_option("parallel_setup_cost",
2675 state->init_parasetup_cost, state->context);
2676 set_config_int32_option("min_parallel_table_scan_size",
2677 state->init_min_para_tablescan_size,
2679 set_config_int32_option("min_parallel_index_scan_size",
2680 state->init_min_para_indexscan_size,
2685 #define SET_CONFIG_OPTION(name, type_bits) \
2686 set_config_option_noerror((name), \
2687 (mask & (type_bits)) ? "true" : "false", \
2688 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2692 * Setup GUC environment to enforce scan methods. If scanhint is NULL, reset
2693 * GUCs to the saved state in state.
2696 setup_scan_method_enforcement(ScanMethodHint *scanhint, HintState *state)
2698 unsigned char enforce_mask = state->init_scan_mask;
2699 GucContext context = state->context;
2704 enforce_mask = scanhint->enforce_mask;
2705 scanhint->base.state = HINT_STATE_USED;
2708 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2709 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2710 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2712 mask = enforce_mask;
2714 mask = enforce_mask & current_hint_state->init_scan_mask;
2716 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2717 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2718 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2719 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2720 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2724 set_join_config_options(unsigned char enforce_mask, GucContext context)
2728 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2729 enforce_mask == ENABLE_HASHJOIN)
2730 mask = enforce_mask;
2732 mask = enforce_mask & current_hint_state->init_join_mask;
2734 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2735 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2736 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2740 * Push a hint into hint stack which is implemented with List struct. Head of
2741 * list is top of stack.
2744 push_hint(HintState *hstate)
2746 /* Prepend new hint to the list means pushing to stack. */
2747 HintStateStack = lcons(hstate, HintStateStack);
2749 /* Pushed hint is the one which should be used hereafter. */
2750 current_hint_state = hstate;
2753 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2757 /* Hint stack must not be empty. */
2758 if(HintStateStack == NIL)
2759 elog(ERROR, "hint stack is empty");
2762 * Take a hint at the head from the list, and free it. Switch
2763 * current_hint_state to point new head (NULL if the list is empty).
2765 HintStateStack = list_delete_first(HintStateStack);
2766 HintStateDelete(current_hint_state);
2767 if(HintStateStack == NIL)
2768 current_hint_state = NULL;
2770 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
2774 * Retrieve and store hint string from given query or from the hint table.
2777 get_current_hint_string(ParseState *pstate, Query *query)
2779 const char *query_str;
2780 MemoryContext oldcontext;
2782 /* do nothing under hint table search */
2783 if (hint_inhibit_level > 0)
2786 /* We alredy have one, don't parse it again. */
2787 if (current_hint_retrieved)
2790 /* Don't parse the current query hereafter */
2791 current_hint_retrieved = true;
2793 if (!pg_hint_plan_enable_hint)
2795 if (current_hint_str)
2797 pfree((void *)current_hint_str);
2798 current_hint_str = NULL;
2803 /* increment the query number */
2805 if (debug_level > 1)
2806 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2809 /* search the hint table for a hint if requested */
2810 if (pg_hint_plan_enable_hint_table)
2813 pgssJumbleState jstate;
2815 char *normalized_query = NULL;
2817 query_str = get_query_string(pstate, query, &jumblequery);
2819 /* If this query is not for hint, just return */
2823 /* clear the previous hint string */
2824 if (current_hint_str)
2826 pfree((void *)current_hint_str);
2827 current_hint_str = NULL;
2833 * XXX: normalization code is copied from pg_stat_statements.c.
2834 * Make sure to keep up-to-date with it.
2836 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2837 jstate.jumble_len = 0;
2838 jstate.clocations_buf_size = 32;
2839 jstate.clocations = (pgssLocationLen *)
2840 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2841 jstate.clocations_count = 0;
2843 JumbleQuery(&jstate, jumblequery);
2846 * Normalize the query string by replacing constants with '?'
2849 * Search hint string which is stored keyed by query string
2850 * and application name. The query string is normalized to allow
2853 * Adding 1 byte to query_len ensures that the returned string has
2854 * a terminating NULL.
2856 query_len = strlen(query_str) + 1;
2858 generate_normalized_query(&jstate, query_str,
2859 query->stmt_location,
2861 GetDatabaseEncoding());
2864 * find a hint for the normalized query. the result should be in
2867 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2869 get_hints_from_table(normalized_query, application_name);
2870 MemoryContextSwitchTo(oldcontext);
2872 if (debug_level > 1)
2874 if (current_hint_str)
2875 ereport(pg_hint_plan_debug_message_level,
2876 (errmsg("pg_hint_plan[qno=0x%x]: "
2877 "post_parse_analyze_hook: "
2878 "hints from table: \"%s\": "
2879 "normalized_query=\"%s\", "
2880 "application name =\"%s\"",
2881 qno, current_hint_str,
2882 normalized_query, application_name),
2883 errhidestmt(msgqno != qno),
2884 errhidecontext(msgqno != qno)));
2886 ereport(pg_hint_plan_debug_message_level,
2887 (errmsg("pg_hint_plan[qno=0x%x]: "
2888 "no match found in table: "
2889 "application name = \"%s\", "
2890 "normalized_query=\"%s\"",
2891 qno, application_name,
2893 errhidestmt(msgqno != qno),
2894 errhidecontext(msgqno != qno)));
2900 /* retrun if we have hint here */
2901 if (current_hint_str)
2905 query_str = get_query_string(pstate, query, NULL);
2910 * get hints from the comment. However we may have the same query
2911 * string with the previous call, but the extra comparison seems no
2914 if (current_hint_str)
2915 pfree((void *)current_hint_str);
2917 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2918 current_hint_str = get_hints_from_comment(query_str);
2919 MemoryContextSwitchTo(oldcontext);
2922 if (debug_level > 1)
2924 if (debug_level == 1 && query_str && debug_query_string &&
2925 strcmp(query_str, debug_query_string))
2926 ereport(pg_hint_plan_debug_message_level,
2927 (errmsg("hints in comment=\"%s\"",
2928 current_hint_str ? current_hint_str : "(none)"),
2929 errhidestmt(msgqno != qno),
2930 errhidecontext(msgqno != qno)));
2932 ereport(pg_hint_plan_debug_message_level,
2933 (errmsg("hints in comment=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2934 current_hint_str ? current_hint_str : "(none)",
2935 query_str ? query_str : "(none)",
2936 debug_query_string ? debug_query_string : "(none)"),
2937 errhidestmt(msgqno != qno),
2938 errhidecontext(msgqno != qno)));
2944 * Retrieve hint string from the current query.
2947 pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query)
2949 if (prev_post_parse_analyze_hook)
2950 prev_post_parse_analyze_hook(pstate, query);
2952 /* always retrieve hint from the top-level query string */
2953 if (plpgsql_recurse_level == 0)
2954 current_hint_retrieved = false;
2956 get_current_hint_string(pstate, query);
2960 * We need to reset current_hint_retrieved flag always when a command execution
2961 * is finished. This is true even for a pure utility command that doesn't
2962 * involve planning phase.
2965 pg_hint_plan_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
2966 ProcessUtilityContext context,
2967 ParamListInfo params, QueryEnvironment *queryEnv,
2968 DestReceiver *dest, char *completionTag)
2970 if (prev_ProcessUtility_hook)
2971 prev_ProcessUtility_hook(pstmt, queryString, context, params, queryEnv,
2972 dest, completionTag);
2974 standard_ProcessUtility(pstmt, queryString, context, params, queryEnv,
2975 dest, completionTag);
2977 if (plpgsql_recurse_level == 0)
2978 current_hint_retrieved = false;
2982 * Read and set up hint information
2984 static PlannedStmt *
2985 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2988 PlannedStmt *result;
2992 * Use standard planner if pg_hint_plan is disabled or current nesting
2993 * depth is nesting depth of SPI calls. Other hook functions try to change
2994 * plan with current_hint_state if any, so set it to NULL.
2996 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2998 if (debug_level > 1)
2999 ereport(pg_hint_plan_debug_message_level,
3000 (errmsg ("pg_hint_plan%s: planner: enable_hint=%d,"
3001 " hint_inhibit_level=%d",
3002 qnostr, pg_hint_plan_enable_hint,
3003 hint_inhibit_level),
3004 errhidestmt(msgqno != qno)));
3007 goto standard_planner_proc;
3011 * Support for nested plpgsql functions. This is quite ugly but this is the
3012 * only point I could find where I can get the query string.
3014 if (plpgsql_recurse_level > 0)
3016 MemoryContext oldcontext;
3018 if (current_hint_str)
3019 pfree((void *)current_hint_str);
3021 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
3023 get_hints_from_comment((char *)error_context_stack->arg);
3024 MemoryContextSwitchTo(oldcontext);
3028 * Query execution in extended protocol can be started without the analyze
3029 * phase. In the case retrieve hint string here.
3031 if (!current_hint_str)
3032 get_current_hint_string(NULL, parse);
3034 /* No hint, go the normal way */
3035 if (!current_hint_str)
3036 goto standard_planner_proc;
3038 /* parse the hint into hint state struct */
3039 hstate = create_hintstate(parse, pstrdup(current_hint_str));
3041 /* run standard planner if the statement has not valid hint */
3043 goto standard_planner_proc;
3046 * Push new hint struct to the hint stack to disable previous hint context.
3050 /* Set scan enforcement here. */
3051 save_nestlevel = NewGUCNestLevel();
3053 /* Apply Set hints, then save it as the initial state */
3054 setup_guc_enforcement(current_hint_state->set_hints,
3055 current_hint_state->num_hints[HINT_TYPE_SET],
3056 current_hint_state->context);
3058 current_hint_state->init_scan_mask = get_current_scan_mask();
3059 current_hint_state->init_join_mask = get_current_join_mask();
3060 current_hint_state->init_min_para_tablescan_size =
3061 min_parallel_table_scan_size;
3062 current_hint_state->init_min_para_indexscan_size =
3063 min_parallel_index_scan_size;
3064 current_hint_state->init_paratup_cost = parallel_tuple_cost;
3065 current_hint_state->init_parasetup_cost = parallel_setup_cost;
3068 * max_parallel_workers_per_gather should be non-zero here if Workers hint
3071 if (max_hint_nworkers > 0 && max_parallel_workers_per_gather < 1)
3072 set_config_int32_option("max_parallel_workers_per_gather",
3073 1, current_hint_state->context);
3074 current_hint_state->init_nworkers = max_parallel_workers_per_gather;
3076 if (debug_level > 1)
3078 ereport(pg_hint_plan_debug_message_level,
3079 (errhidestmt(msgqno != qno),
3080 errmsg("pg_hint_plan%s: planner", qnostr)));
3085 * Use PG_TRY mechanism to recover GUC parameters and current_hint_state to
3086 * the state when this planner started when error occurred in planner.
3091 result = (*prev_planner) (parse, cursorOptions, boundParams);
3093 result = standard_planner(parse, cursorOptions, boundParams);
3098 * Rollback changes of GUC parameters, and pop current hint context
3099 * from hint stack to rewind the state.
3101 AtEOXact_GUC(true, save_nestlevel);
3109 * current_hint_str is useless after planning of the top-level query.
3111 if (plpgsql_recurse_level < 1 && current_hint_str)
3113 pfree((void *)current_hint_str);
3114 current_hint_str = NULL;
3115 current_hint_retrieved = false;
3118 /* Print hint in debug mode. */
3119 if (debug_level == 1)
3120 HintStateDump(current_hint_state);
3121 else if (debug_level > 1)
3122 HintStateDump2(current_hint_state);
3125 * Rollback changes of GUC parameters, and pop current hint context from
3126 * hint stack to rewind the state.
3128 AtEOXact_GUC(true, save_nestlevel);
3133 standard_planner_proc:
3134 if (debug_level > 1)
3136 ereport(pg_hint_plan_debug_message_level,
3137 (errhidestmt(msgqno != qno),
3138 errmsg("pg_hint_plan%s: planner: no valid hint",
3142 current_hint_state = NULL;
3144 return (*prev_planner) (parse, cursorOptions, boundParams);
3146 return standard_planner(parse, cursorOptions, boundParams);
3150 * Find scan method hint to be applied to the given relation
3153 static ScanMethodHint *
3154 find_scan_hint(PlannerInfo *root, Index relid)
3158 ScanMethodHint *real_name_hint = NULL;
3159 ScanMethodHint *alias_hint = NULL;
3162 /* This should not be a join rel */
3164 rel = root->simple_rel_array[relid];
3167 * This function is called for any RelOptInfo or its inheritance parent if
3168 * any. If we are called from inheritance planner, the RelOptInfo for the
3169 * parent of target child relation is not set in the planner info.
3171 * Otherwise we should check that the reloptinfo is base relation or
3172 * inheritance children.
3175 rel->reloptkind != RELOPT_BASEREL &&
3176 rel->reloptkind != RELOPT_OTHER_MEMBER_REL)
3180 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3182 rte = root->simple_rte_array[relid];
3185 /* We don't hint on other than relation and foreign tables */
3186 if (rte->rtekind != RTE_RELATION ||
3187 rte->relkind == RELKIND_FOREIGN_TABLE)
3190 /* Find scan method hint, which matches given names, from the list. */
3191 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
3193 ScanMethodHint *hint = current_hint_state->scan_hints[i];
3195 /* We ignore disabled hints. */
3196 if (!hint_state_enabled(hint))
3200 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3203 /* check the real name for appendrel children */
3204 if (!real_name_hint &&
3205 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3207 char *realname = get_rel_name(rte->relid);
3209 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3210 real_name_hint = hint;
3213 /* No more match expected, break */
3214 if(alias_hint && real_name_hint)
3218 /* real name match precedes alias match */
3220 return real_name_hint;
3225 static ParallelHint *
3226 find_parallel_hint(PlannerInfo *root, Index relid)
3230 ParallelHint *real_name_hint = NULL;
3231 ParallelHint *alias_hint = NULL;
3234 /* This should not be a join rel */
3236 rel = root->simple_rel_array[relid];
3239 * Parallel planning is appliable only on base relation, which has
3246 * We have set root->glob->parallelModeOK if needed. What we should do here
3247 * is just following the decision of planner.
3249 if (!rel->consider_parallel)
3253 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3255 rte = root->simple_rte_array[relid];
3258 /* Find parallel method hint, which matches given names, from the list. */
3259 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_PARALLEL]; i++)
3261 ParallelHint *hint = current_hint_state->parallel_hints[i];
3263 /* We ignore disabled hints. */
3264 if (!hint_state_enabled(hint))
3268 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3271 /* check the real name for appendrel children */
3272 if (!real_name_hint &&
3273 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3275 char *realname = get_rel_name(rte->relid);
3277 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3278 real_name_hint = hint;
3281 /* No more match expected, break */
3282 if(alias_hint && real_name_hint)
3286 /* real name match precedes alias match */
3288 return real_name_hint;
3296 * Returns TRUE on match, FALSE on no match.
3298 * s1 --- the data to match against
3299 * s2 --- the pattern
3301 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
3304 regexpeq(const char *s1, const char *s2)
3310 strcpy(name.data, s1);
3311 regexp = cstring_to_text(s2);
3313 result = DirectFunctionCall2Coll(nameregexeq,
3314 DEFAULT_COLLATION_OID,
3315 NameGetDatum(&name),
3316 PointerGetDatum(regexp));
3317 return DatumGetBool(result);
3321 /* Remove indexes instructed not to use by hint. */
3323 restrict_indexes(PlannerInfo *root, ScanMethodHint *hint, RelOptInfo *rel,
3324 bool using_parent_hint)
3330 RangeTblEntry *rte = root->simple_rte_array[rel->relid];
3331 Oid relationObjectId = rte->relid;
3334 * We delete all the IndexOptInfo list and prevent you from being usable by
3337 if (hint->enforce_mask == ENABLE_SEQSCAN ||
3338 hint->enforce_mask == ENABLE_TIDSCAN)
3340 list_free_deep(rel->indexlist);
3341 rel->indexlist = NIL;
3342 hint->base.state = HINT_STATE_USED;
3348 * When a list of indexes is not specified, we just use all indexes.
3350 if (hint->indexnames == NIL)
3354 * Leaving only an specified index, we delete it from a IndexOptInfo list
3358 if (debug_level > 0)
3359 initStringInfo(&buf);
3361 for (cell = list_head(rel->indexlist); cell; cell = next)
3363 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
3364 char *indexname = get_rel_name(info->indexoid);
3366 bool use_index = false;
3370 foreach(l, hint->indexnames)
3372 char *hintname = (char *) lfirst(l);
3376 result = regexpeq(indexname, hintname);
3378 result = RelnameCmp(&indexname, &hintname) == 0;
3383 if (debug_level > 0)
3385 appendStringInfoCharMacro(&buf, ' ');
3386 quote_value(&buf, indexname);
3394 * Apply index restriction of parent hint to children. Since index
3395 * inheritance is not explicitly described we should search for an
3396 * children's index with the same definition to that of the parent.
3398 if (using_parent_hint && !use_index)
3400 foreach(l, current_hint_state->parent_index_infos)
3404 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
3407 * we check the 'same' index by comparing uniqueness, access
3408 * method and index key columns.
3410 if (p_info->indisunique != info->unique ||
3411 p_info->method != info->relam ||
3412 list_length(p_info->column_names) != info->ncolumns)
3415 /* Check if index key columns match */
3416 for (i = 0; i < info->ncolumns; i++)
3418 char *c_attname = NULL;
3419 char *p_attname = NULL;
3421 p_attname = list_nth(p_info->column_names, i);
3424 * if both of the key of the same position are expressions,
3425 * ignore them for now and check later.
3427 if (info->indexkeys[i] == 0 && !p_attname)
3430 /* deny if one is expression while another is not */
3431 if (info->indexkeys[i] == 0 || !p_attname)
3434 c_attname = get_attname(relationObjectId,
3435 info->indexkeys[i], false);
3437 /* deny if any of column attributes don't match */
3438 if (strcmp(p_attname, c_attname) != 0 ||
3439 p_info->indcollation[i] != info->indexcollations[i] ||
3440 p_info->opclass[i] != info->opcintype[i]||
3441 ((p_info->indoption[i] & INDOPTION_DESC) != 0)
3442 != info->reverse_sort[i] ||
3443 ((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0)
3444 != info->nulls_first[i])
3448 /* deny this if any difference found */
3449 if (i != info->ncolumns)
3452 /* check on key expressions */
3453 if ((p_info->expression_str && (info->indexprs != NIL)) ||
3454 (p_info->indpred_str && (info->indpred != NIL)))
3456 /* fetch the index of this child */
3457 ht_idx = SearchSysCache1(INDEXRELID,
3458 ObjectIdGetDatum(info->indexoid));
3460 /* check expressions if both expressions are available */
3461 if (p_info->expression_str &&
3462 !heap_attisnull(ht_idx, Anum_pg_index_indexprs, NULL))
3469 * to change the expression's parameter of child's
3472 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3473 Anum_pg_index_indexprs,
3476 result = DirectFunctionCall2(pg_get_expr,
3481 /* deny if expressions don't match */
3482 if (strcmp(p_info->expression_str,
3483 text_to_cstring(DatumGetTextP(result))) != 0)
3486 ReleaseSysCache(ht_idx);
3491 /* compare index predicates */
3492 if (p_info->indpred_str &&
3493 !heap_attisnull(ht_idx, Anum_pg_index_indpred, NULL))
3499 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3500 Anum_pg_index_indpred,
3503 result = DirectFunctionCall2(pg_get_expr,
3508 if (strcmp(p_info->indpred_str,
3509 text_to_cstring(DatumGetTextP(result))) != 0)
3512 ReleaseSysCache(ht_idx);
3518 ReleaseSysCache(ht_idx);
3520 else if (p_info->expression_str || (info->indexprs != NIL))
3522 else if (p_info->indpred_str || (info->indpred != NIL))
3527 /* to log the candidate of index */
3528 if (debug_level > 0)
3530 appendStringInfoCharMacro(&buf, ' ');
3531 quote_value(&buf, indexname);
3539 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
3546 if (debug_level == 1)
3548 StringInfoData rel_buf;
3549 char *disprelname = "";
3552 * If this hint targetted the parent, use the real name of this
3553 * child. Otherwise use hint specification.
3555 if (using_parent_hint)
3556 disprelname = get_rel_name(rte->relid);
3558 disprelname = hint->relname;
3561 initStringInfo(&rel_buf);
3562 quote_value(&rel_buf, disprelname);
3564 ereport(pg_hint_plan_debug_message_level,
3565 (errmsg("available indexes for %s(%s):%s",
3570 pfree(rel_buf.data);
3575 * Return information of index definition.
3577 static ParentIndexInfo *
3578 get_parent_index_info(Oid indexoid, Oid relid)
3580 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3581 Relation indexRelation;
3582 Form_pg_index index;
3586 indexRelation = index_open(indexoid, RowExclusiveLock);
3588 index = indexRelation->rd_index;
3590 p_info->indisunique = index->indisunique;
3591 p_info->method = indexRelation->rd_rel->relam;
3593 p_info->column_names = NIL;
3594 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3595 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3596 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3599 * Collect relation attribute names of index columns for index
3600 * identification, not index attribute names. NULL means expression index
3603 for (i = 0; i < index->indnatts; i++)
3605 attname = get_attname(relid, index->indkey.values[i], true);
3606 p_info->column_names = lappend(p_info->column_names, attname);
3608 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3609 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3610 p_info->indoption[i] = indexRelation->rd_indoption[i];
3614 * to check to match the expression's parameter of index with child indexes
3616 p_info->expression_str = NULL;
3617 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs,
3624 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3625 Anum_pg_index_indexprs, &isnull);
3627 result = DirectFunctionCall2(pg_get_expr,
3629 ObjectIdGetDatum(relid));
3631 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3635 * to check to match the predicate's parameter of index with child indexes
3637 p_info->indpred_str = NULL;
3638 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred,
3645 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3646 Anum_pg_index_indpred, &isnull);
3648 result = DirectFunctionCall2(pg_get_expr,
3650 ObjectIdGetDatum(relid));
3652 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3655 index_close(indexRelation, NoLock);
3661 * cancel hint enforcement
3664 reset_hint_enforcement()
3666 setup_scan_method_enforcement(NULL, current_hint_state);
3667 setup_parallel_plan_enforcement(NULL, current_hint_state);
3671 * Set planner guc parameters according to corresponding scan hints. Returns
3672 * bitmap of HintTypeBitmap. If shint or phint is not NULL, set used hint
3673 * there respectively.
3676 setup_hint_enforcement(PlannerInfo *root, RelOptInfo *rel,
3677 ScanMethodHint **rshint, ParallelHint **rphint)
3679 Index new_parent_relid = 0;
3681 ScanMethodHint *shint = NULL;
3682 ParallelHint *phint = NULL;
3683 bool inhparent = root->simple_rte_array[rel->relid]->inh;
3684 Oid relationObjectId = root->simple_rte_array[rel->relid]->relid;
3687 /* reset returns if requested */
3688 if (rshint != NULL) *rshint = NULL;
3689 if (rphint != NULL) *rphint = NULL;
3692 * We could register the parent relation of the following children here
3693 * when inhparent == true but inheritnce planner doesn't call this function
3694 * for parents. Since we cannot distinguish who called this function we
3695 * cannot do other than always seeking the parent regardless of who called
3700 /* set up only parallel hints for parent relation */
3701 phint = find_parallel_hint(root, rel->relid);
3704 setup_parallel_plan_enforcement(phint, current_hint_state);
3705 if (rphint) *rphint = phint;
3706 ret |= HINT_BM_PARALLEL;
3710 if (debug_level > 1)
3711 ereport(pg_hint_plan_debug_message_level,
3713 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3714 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3715 " current_hint_state=%p, hint_inhibit_level=%d",
3716 qnostr, relationObjectId,
3717 get_rel_name(relationObjectId),
3718 inhparent, current_hint_state, hint_inhibit_level)));
3722 /* Forget about the parent of another subquery */
3723 if (root != current_hint_state->current_root)
3724 current_hint_state->parent_relid = 0;
3726 /* Find the parent for this relation other than the registered parent */
3727 foreach (l, root->append_rel_list)
3729 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3731 if (appinfo->child_relid == rel->relid)
3733 if (current_hint_state->parent_relid != appinfo->parent_relid)
3735 new_parent_relid = appinfo->parent_relid;
3736 current_hint_state->current_root = root;
3744 /* This relation doesn't have a parent. Cancel current_hint_state. */
3745 current_hint_state->parent_relid = 0;
3746 current_hint_state->parent_scan_hint = NULL;
3747 current_hint_state->parent_parallel_hint = NULL;
3750 if (new_parent_relid > 0)
3753 * Here we found a new parent for the current relation. Scan continues
3754 * hint to other childrens of this parent so remember it to avoid
3755 * redundant setup cost.
3757 current_hint_state->parent_relid = new_parent_relid;
3759 /* Find hints for the parent */
3760 current_hint_state->parent_scan_hint =
3761 find_scan_hint(root, current_hint_state->parent_relid);
3763 current_hint_state->parent_parallel_hint =
3764 find_parallel_hint(root, current_hint_state->parent_relid);
3767 * If hint is found for the parent, apply it for this child instead
3770 if (current_hint_state->parent_scan_hint)
3772 ScanMethodHint * pshint = current_hint_state->parent_scan_hint;
3774 pshint->base.state = HINT_STATE_USED;
3776 /* Apply index mask in the same manner to the parent. */
3777 if (pshint->indexnames)
3780 Relation parent_rel;
3783 root->simple_rte_array[current_hint_state->parent_relid]->relid;
3784 parent_rel = heap_open(parentrel_oid, NoLock);
3786 /* Search the parent relation for indexes match the hint spec */
3787 foreach(l, RelationGetIndexList(parent_rel))
3789 Oid indexoid = lfirst_oid(l);
3790 char *indexname = get_rel_name(indexoid);
3792 ParentIndexInfo *parent_index_info;
3794 foreach(lc, pshint->indexnames)
3796 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3803 get_parent_index_info(indexoid, parentrel_oid);
3804 current_hint_state->parent_index_infos =
3805 lappend(current_hint_state->parent_index_infos,
3808 heap_close(parent_rel, NoLock);
3813 shint = find_scan_hint(root, rel->relid);
3815 shint = current_hint_state->parent_scan_hint;
3819 bool using_parent_hint =
3820 (shint == current_hint_state->parent_scan_hint);
3822 ret |= HINT_BM_SCAN_METHOD;
3824 /* Setup scan enforcement environment */
3825 setup_scan_method_enforcement(shint, current_hint_state);
3827 /* restrict unwanted inexes */
3828 restrict_indexes(root, shint, rel, using_parent_hint);
3830 if (debug_level > 1)
3832 char *additional_message = "";
3834 if (shint == current_hint_state->parent_scan_hint)
3835 additional_message = " by parent hint";
3837 ereport(pg_hint_plan_debug_message_level,
3839 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3840 " index deletion%s:"
3841 " relation=%u(%s), inhparent=%d, "
3842 "current_hint_state=%p,"
3843 " hint_inhibit_level=%d, scanmask=0x%x",
3844 qnostr, additional_message,
3846 get_rel_name(relationObjectId),
3847 inhparent, current_hint_state,
3849 shint->enforce_mask)));
3853 /* Do the same for parallel plan enforcement */
3854 phint = find_parallel_hint(root, rel->relid);
3856 phint = current_hint_state->parent_parallel_hint;
3858 setup_parallel_plan_enforcement(phint, current_hint_state);
3861 ret |= HINT_BM_PARALLEL;
3863 /* Nothing to apply. Reset the scan mask to intial state */
3864 if (!shint && ! phint)
3866 if (debug_level > 1)
3867 ereport(pg_hint_plan_debug_message_level,
3868 (errhidestmt (true),
3869 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3871 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3872 " hint_inhibit_level=%d, scanmask=0x%x",
3873 qnostr, relationObjectId,
3874 get_rel_name(relationObjectId),
3875 inhparent, current_hint_state, hint_inhibit_level,
3876 current_hint_state->init_scan_mask)));
3878 setup_scan_method_enforcement(NULL, current_hint_state);
3883 if (rshint != NULL) *rshint = shint;
3884 if (rphint != NULL) *rphint = phint;
3890 * Return index of relation which matches given aliasname, or 0 if not found.
3891 * If same aliasname was used multiple times in a query, return -1.
3894 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3900 for (i = 1; i < root->simple_rel_array_size; i++)
3904 if (root->simple_rel_array[i] == NULL)
3907 Assert(i == root->simple_rel_array[i]->relid);
3909 if (RelnameCmp(&aliasname,
3910 &root->simple_rte_array[i]->eref->aliasname) != 0)
3913 foreach(l, initial_rels)
3915 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3917 if (rel->reloptkind == RELOPT_BASEREL)
3919 if (rel->relid != i)
3924 Assert(rel->reloptkind == RELOPT_JOINREL);
3926 if (!bms_is_member(i, rel->relids))
3933 ("Relation name \"%s\" is ambiguous.",
3948 * Return join hint which matches given joinrelids.
3950 static JoinMethodHint *
3951 find_join_hint(Relids joinrelids)
3956 join_hint = current_hint_state->join_hint_level[bms_num_members(joinrelids)];
3958 foreach(l, join_hint)
3960 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3962 if (bms_equal(joinrelids, hint->joinrelids))
3970 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3971 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3973 OuterInnerRels *outer_rels;
3974 OuterInnerRels *inner_rels;
3975 Relids outer_relids;
3976 Relids inner_relids;
3978 JoinMethodHint *hint;
3980 if (outer_inner->relation != NULL)
3982 return bms_make_singleton(
3983 find_relid_aliasname(root, outer_inner->relation,
3985 leading_hint->base.hint_str));
3988 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3989 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3991 outer_relids = OuterInnerJoinCreate(outer_rels,
3997 inner_relids = OuterInnerJoinCreate(inner_rels,
4004 join_relids = bms_add_members(outer_relids, inner_relids);
4006 if (bms_num_members(join_relids) > nbaserel)
4010 * If we don't have join method hint, create new one for the
4011 * join combination with all join methods are enabled.
4013 hint = find_join_hint(join_relids);
4017 * Here relnames is not set, since Relids bitmap is sufficient to
4018 * control paths of this query afterward.
4020 hint = (JoinMethodHint *) JoinMethodHintCreate(
4021 leading_hint->base.hint_str,
4023 HINT_KEYWORD_LEADING);
4024 hint->base.state = HINT_STATE_USED;
4025 hint->nrels = bms_num_members(join_relids);
4026 hint->enforce_mask = ENABLE_ALL_JOIN;
4027 hint->joinrelids = bms_copy(join_relids);
4028 hint->inner_nrels = bms_num_members(inner_relids);
4029 hint->inner_joinrelids = bms_copy(inner_relids);
4031 hstate->join_hint_level[hint->nrels] =
4032 lappend(hstate->join_hint_level[hint->nrels], hint);
4036 hint->inner_nrels = bms_num_members(inner_relids);
4037 hint->inner_joinrelids = bms_copy(inner_relids);
4044 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
4045 int nrels, char **relnames)
4048 Relids relids = NULL;
4052 for (j = 0; j < nrels; j++)
4054 relname = relnames[j];
4056 relid = find_relid_aliasname(root, relname, initial_rels,
4060 base->state = HINT_STATE_ERROR;
4063 * the aliasname is not found(relid == 0) or same aliasname was used
4064 * multiple times in a query(relid == -1)
4071 if (bms_is_member(relid, relids))
4073 hint_ereport(base->hint_str,
4074 ("Relation name \"%s\" is duplicated.", relname));
4075 base->state = HINT_STATE_ERROR;
4079 relids = bms_add_member(relids, relid);
4084 * Transform join method hint into handy form.
4086 * - create bitmap of relids from alias names, to make it easier to check
4087 * whether a join path matches a join method hint.
4088 * - add join method hints which are necessary to enforce join order
4089 * specified by Leading hint
4092 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
4093 List *initial_rels, JoinMethodHint **join_method_hints)
4101 LeadingHint *lhint = NULL;
4104 * Create bitmap of relids from alias names for each join method hint.
4105 * Bitmaps are more handy than strings in join searching.
4107 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
4109 JoinMethodHint *hint = hstate->join_hints[i];
4111 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4114 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4115 initial_rels, hint->nrels, hint->relnames);
4117 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
4120 hstate->join_hint_level[hint->nrels] =
4121 lappend(hstate->join_hint_level[hint->nrels], hint);
4125 * Create bitmap of relids from alias names for each rows hint.
4126 * Bitmaps are more handy than strings in join searching.
4128 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
4130 RowsHint *hint = hstate->rows_hints[i];
4132 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4135 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4136 initial_rels, hint->nrels, hint->relnames);
4139 /* Do nothing if no Leading hint was supplied. */
4140 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
4144 * Decide whether to use Leading hint
4146 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
4148 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
4151 if (leading_hint->base.state == HINT_STATE_ERROR)
4157 foreach(l, leading_hint->relations)
4159 relname = (char *)lfirst(l);;
4161 relid = find_relid_aliasname(root, relname, initial_rels,
4162 leading_hint->base.hint_str);
4164 leading_hint->base.state = HINT_STATE_ERROR;
4169 if (bms_is_member(relid, relids))
4171 hint_ereport(leading_hint->base.hint_str,
4172 ("Relation name \"%s\" is duplicated.", relname));
4173 leading_hint->base.state = HINT_STATE_ERROR;
4177 relids = bms_add_member(relids, relid);
4180 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
4185 hint_ereport(lhint->base.hint_str,
4186 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
4187 lhint->base.state = HINT_STATE_DUPLICATION;
4189 leading_hint->base.state = HINT_STATE_USED;
4190 lhint = leading_hint;
4193 /* check to exist Leading hint marked with 'used'. */
4198 * We need join method hints which fit specified join order in every join
4199 * level. For example, Leading(A B C) virtually requires following join
4200 * method hints, if no join method hint supplied:
4202 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
4203 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
4205 * If we already have join method hint which fits specified join order in
4206 * that join level, we leave it as-is and don't add new hints.
4210 if (lhint->outer_inner == NULL)
4212 foreach(l, lhint->relations)
4214 JoinMethodHint *hint;
4216 relname = (char *)lfirst(l);
4219 * Find relid of the relation which has given name. If we have the
4220 * name given in Leading hint multiple times in the join, nothing to
4223 relid = find_relid_aliasname(root, relname, initial_rels,
4226 /* Create bitmap of relids for current join level. */
4227 joinrelids = bms_add_member(joinrelids, relid);
4230 /* We never have join method hint for single relation. */
4235 * If we don't have join method hint, create new one for the
4236 * join combination with all join methods are enabled.
4238 hint = find_join_hint(joinrelids);
4242 * Here relnames is not set, since Relids bitmap is sufficient
4243 * to control paths of this query afterward.
4245 hint = (JoinMethodHint *) JoinMethodHintCreate(
4246 lhint->base.hint_str,
4248 HINT_KEYWORD_LEADING);
4249 hint->base.state = HINT_STATE_USED;
4250 hint->nrels = njoinrels;
4251 hint->enforce_mask = ENABLE_ALL_JOIN;
4252 hint->joinrelids = bms_copy(joinrelids);
4255 join_method_hints[njoinrels] = hint;
4257 if (njoinrels >= nbaserel)
4260 bms_free(joinrelids);
4266 * Delete all join hints which have different combination from Leading
4269 for (i = 2; i <= njoinrels; i++)
4271 list_free(hstate->join_hint_level[i]);
4273 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
4278 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
4285 njoinrels = bms_num_members(joinrelids);
4286 Assert(njoinrels >= 2);
4289 * Delete all join hints which have different combination from Leading
4292 for (i = 2;i <= njoinrels; i++)
4294 if (hstate->join_hint_level[i] != NIL)
4296 ListCell *prev = NULL;
4297 ListCell *next = NULL;
4298 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
4301 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
4305 if (hint->inner_nrels == 0 &&
4306 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
4307 bms_equal(bms_union(hint->joinrelids, joinrelids),
4310 hstate->join_hint_level[i] =
4311 list_delete_cell(hstate->join_hint_level[i], l,
4320 bms_free(joinrelids);
4323 if (hint_state_enabled(lhint))
4325 set_join_config_options(DISABLE_ALL_JOIN, current_hint_state->context);
4332 * wrapper of make_join_rel()
4334 * call make_join_rel() after changing enable_* parameters according to given
4338 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
4341 JoinMethodHint *hint;
4345 joinrelids = bms_union(rel1->relids, rel2->relids);
4346 hint = find_join_hint(joinrelids);
4347 bms_free(joinrelids);
4350 return pg_hint_plan_make_join_rel(root, rel1, rel2);
4352 if (hint->inner_nrels == 0)
4354 save_nestlevel = NewGUCNestLevel();
4356 set_join_config_options(hint->enforce_mask,
4357 current_hint_state->context);
4359 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4360 hint->base.state = HINT_STATE_USED;
4363 * Restore the GUC variables we set above.
4365 AtEOXact_GUC(true, save_nestlevel);
4368 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4377 add_paths_to_joinrel_wrapper(PlannerInfo *root,
4378 RelOptInfo *joinrel,
4379 RelOptInfo *outerrel,
4380 RelOptInfo *innerrel,
4382 SpecialJoinInfo *sjinfo,
4386 JoinMethodHint *join_hint;
4389 joinrelids = bms_union(outerrel->relids, innerrel->relids);
4390 join_hint = find_join_hint(joinrelids);
4391 bms_free(joinrelids);
4393 if (join_hint && join_hint->inner_nrels != 0)
4395 save_nestlevel = NewGUCNestLevel();
4397 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
4400 set_join_config_options(join_hint->enforce_mask,
4401 current_hint_state->context);
4403 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4404 sjinfo, restrictlist);
4405 join_hint->base.state = HINT_STATE_USED;
4409 set_join_config_options(DISABLE_ALL_JOIN,
4410 current_hint_state->context);
4411 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4412 sjinfo, restrictlist);
4416 * Restore the GUC variables we set above.
4418 AtEOXact_GUC(true, save_nestlevel);
4421 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4422 sjinfo, restrictlist);
4426 get_num_baserels(List *initial_rels)
4431 foreach(l, initial_rels)
4433 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
4435 if (rel->reloptkind == RELOPT_BASEREL)
4437 else if (rel->reloptkind ==RELOPT_JOINREL)
4438 nbaserel+= bms_num_members(rel->relids);
4441 /* other values not expected here */
4442 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
4450 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
4453 JoinMethodHint **join_method_hints;
4457 bool leading_hint_enable;
4460 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
4461 * valid hint is supplied or current nesting depth is nesting depth of SPI
4464 if (!current_hint_state || hint_inhibit_level > 0)
4466 if (prev_join_search)
4467 return (*prev_join_search) (root, levels_needed, initial_rels);
4468 else if (enable_geqo && levels_needed >= geqo_threshold)
4469 return geqo(root, levels_needed, initial_rels);
4471 return standard_join_search(root, levels_needed, initial_rels);
4475 * In the case using GEQO, only scan method hints and Set hints have
4476 * effect. Join method and join order is not controllable by hints.
4478 if (enable_geqo && levels_needed >= geqo_threshold)
4479 return geqo(root, levels_needed, initial_rels);
4481 nbaserel = get_num_baserels(initial_rels);
4482 current_hint_state->join_hint_level =
4483 palloc0(sizeof(List *) * (nbaserel + 1));
4484 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4486 leading_hint_enable = transform_join_hints(current_hint_state,
4488 initial_rels, join_method_hints);
4490 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4493 * Adjust number of parallel workers of the result rel to the largest
4494 * number of the component paths.
4496 if (current_hint_state->num_hints[HINT_TYPE_PARALLEL] > 0)
4501 foreach (lc, initial_rels)
4504 RelOptInfo *rel = (RelOptInfo *) lfirst(lc);
4506 foreach (lcp, rel->partial_pathlist)
4508 Path *path = (Path *) lfirst(lcp);
4510 if (nworkers < path-> parallel_workers)
4511 nworkers = path-> parallel_workers;
4515 foreach (lc, rel->partial_pathlist)
4517 Path *path = (Path *) lfirst(lc);
4519 if (path->parallel_safe && path->parallel_workers < nworkers)
4520 path->parallel_workers = nworkers;
4524 for (i = 2; i <= nbaserel; i++)
4526 list_free(current_hint_state->join_hint_level[i]);
4528 /* free Leading hint only */
4529 if (join_method_hints[i] != NULL &&
4530 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4531 JoinMethodHintDelete(join_method_hints[i]);
4533 pfree(current_hint_state->join_hint_level);
4534 pfree(join_method_hints);
4536 if (leading_hint_enable)
4537 set_join_config_options(current_hint_state->init_join_mask,
4538 current_hint_state->context);
4544 * Force number of wokers if instructed by hint
4547 pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
4548 Index rti, RangeTblEntry *rte)
4550 ParallelHint *phint;
4554 /* call the previous hook */
4555 if (prev_set_rel_pathlist)
4556 prev_set_rel_pathlist(root, rel, rti, rte);
4558 /* Nothing to do if no hint available */
4559 if (current_hint_state == NULL)
4562 /* Don't touch dummy rels. */
4563 if (IS_DUMMY_REL(rel))
4567 * We can accept only plain relations, foreign tables and table saples are
4568 * also unacceptable. See set_rel_pathlist.
4570 if ((rel->rtekind != RTE_RELATION &&
4571 rel->rtekind != RTE_SUBQUERY)||
4572 rte->relkind == RELKIND_FOREIGN_TABLE ||
4573 rte->tablesample != NULL)
4577 * Even though UNION ALL node doesn't have particular name so usually it is
4578 * unhintable, turn on parallel when it contains parallel nodes.
4580 if (rel->rtekind == RTE_SUBQUERY)
4583 bool inhibit_nonparallel = false;
4585 if (rel->partial_pathlist == NIL)
4588 foreach(lc, rel->partial_pathlist)
4591 AppendPath *apath = (AppendPath *) lfirst(lc);
4592 int parallel_workers = 0;
4594 if (!IsA(apath, AppendPath))
4597 foreach (lcp, apath->subpaths)
4599 Path *spath = (Path *) lfirst(lcp);
4601 if (spath->parallel_aware &&
4602 parallel_workers < spath->parallel_workers)
4603 parallel_workers = spath->parallel_workers;
4606 apath->path.parallel_workers = parallel_workers;
4607 inhibit_nonparallel = true;
4610 if (inhibit_nonparallel)
4614 foreach(lc, rel->pathlist)
4616 Path *path = (Path *) lfirst(lc);
4618 if (path->startup_cost < disable_cost)
4620 path->startup_cost += disable_cost;
4621 path->total_cost += disable_cost;
4629 /* We cannot handle if this requires an outer */
4630 if (rel->lateral_relids)
4633 /* Return if this relation gets no enfocement */
4634 if ((found_hints = setup_hint_enforcement(root, rel, NULL, &phint)) == 0)
4637 /* Here, we regenerate paths with the current hint restriction */
4638 if (found_hints & HINT_BM_SCAN_METHOD || found_hints & HINT_BM_PARALLEL)
4641 * When hint is specified on non-parent relations, discard existing
4642 * paths and regenerate based on the hint considered. Otherwise we
4643 * already have hinted childx paths then just adjust the number of
4644 * planned number of workers.
4646 if (root->simple_rte_array[rel->relid]->inh)
4648 /* enforce number of workers if requested */
4649 if (phint && phint->force_parallel)
4651 if (phint->nworkers == 0)
4653 list_free_deep(rel->partial_pathlist);
4654 rel->partial_pathlist = NIL;
4658 /* prioritize partial paths */
4659 foreach (l, rel->partial_pathlist)
4661 Path *ppath = (Path *) lfirst(l);
4663 if (ppath->parallel_safe)
4665 ppath->parallel_workers = phint->nworkers;
4666 ppath->startup_cost = 0;
4667 ppath->total_cost = 0;
4671 /* disable non-partial paths */
4672 foreach (l, rel->pathlist)
4674 Path *ppath = (Path *) lfirst(l);
4676 if (ppath->startup_cost < disable_cost)
4678 ppath->startup_cost += disable_cost;
4679 ppath->total_cost += disable_cost;
4687 /* Just discard all the paths considered so far */
4688 list_free_deep(rel->pathlist);
4689 rel->pathlist = NIL;
4690 list_free_deep(rel->partial_pathlist);
4691 rel->partial_pathlist = NIL;
4693 /* Regenerate paths with the current enforcement */
4694 set_plain_rel_pathlist(root, rel, rte);
4696 /* Additional work to enforce parallel query execution */
4697 if (phint && phint->nworkers > 0)
4700 * For Parallel Append to be planned properly, we shouldn't set
4701 * the costs of non-partial paths to disable-value. Lower the
4702 * priority of non-parallel paths by setting partial path costs
4705 foreach (l, rel->partial_pathlist)
4707 Path *path = (Path *) lfirst(l);
4709 path->startup_cost = 0;
4710 path->total_cost = 0;
4713 /* enforce number of workers if requested */
4714 if (phint->force_parallel)
4716 foreach (l, rel->partial_pathlist)
4718 Path *ppath = (Path *) lfirst(l);
4720 if (ppath->parallel_safe)
4721 ppath->parallel_workers = phint->nworkers;
4725 /* Generate gather paths */
4726 if (rel->reloptkind == RELOPT_BASEREL)
4727 generate_gather_paths(root, rel, false);
4732 reset_hint_enforcement();
4737 * Build access paths for a base relation
4739 * This function was copied and edited from set_rel_pathlist() in
4740 * src/backend/optimizer/path/allpaths.c in order not to copy other static
4741 * functions not required here.
4744 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4745 Index rti, RangeTblEntry *rte)
4747 if (IS_DUMMY_REL(rel))
4749 /* We already proved the relation empty, so nothing more to do */
4753 /* It's an "append relation", process accordingly */
4754 set_append_rel_pathlist(root, rel, rti, rte);
4758 if (rel->rtekind == RTE_RELATION)
4760 if (rte->relkind == RELKIND_RELATION)
4762 if(rte->tablesample != NULL)
4763 elog(ERROR, "sampled relation is not supported");
4765 /* Plain relation */
4766 set_plain_rel_pathlist(root, rel, rte);
4769 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4772 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4776 * Allow a plugin to editorialize on the set of Paths for this base
4777 * relation. It could add new paths (such as CustomPaths) by calling
4778 * add_path(), or delete or modify paths added by the core code.
4780 if (set_rel_pathlist_hook)
4781 (*set_rel_pathlist_hook) (root, rel, rti, rte);
4783 /* Now find the cheapest of the paths for this rel */
4788 * stmt_beg callback is called when each query in PL/pgSQL function is about
4789 * to be executed. At that timing, we save query string in the global variable
4790 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4791 * variable for the purpose, because its content is only necessary until
4792 * planner hook is called for the query, so recursive PL/pgSQL function calls
4793 * don't harm this mechanism.
4796 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4798 plpgsql_recurse_level++;
4802 * stmt_end callback is called then each query in PL/pgSQL function has
4803 * finished. At that timing, we clear plpgsql_query_string to tell planner
4804 * hook that next call is not for a query written in PL/pgSQL block.
4807 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4809 plpgsql_recurse_level--;
4812 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4817 if (!isTopLevel || phase != RESOURCE_RELEASE_AFTER_LOCKS)
4819 /* Cancel plpgsql nest level*/
4820 plpgsql_recurse_level = 0;
4823 #define standard_join_search pg_hint_plan_standard_join_search
4824 #define join_search_one_level pg_hint_plan_join_search_one_level
4825 #define make_join_rel make_join_rel_wrapper
4828 #undef make_join_rel
4829 #define make_join_rel pg_hint_plan_make_join_rel
4830 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4831 #include "make_join_rel.c"
4833 #include "pg_stat_statements.c"