1 /*-------------------------------------------------------------------------
4 * hinting on how to execute a query for PostgreSQL
6 * Copyright (c) 2012-2018, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
8 *-------------------------------------------------------------------------
13 #include "catalog/pg_collation.h"
14 #include "catalog/pg_index.h"
15 #include "commands/prepare.h"
16 #include "mb/pg_wchar.h"
17 #include "miscadmin.h"
18 #include "nodes/nodeFuncs.h"
19 #include "nodes/params.h"
20 #include "nodes/relation.h"
21 #include "optimizer/clauses.h"
22 #include "optimizer/cost.h"
23 #include "optimizer/geqo.h"
24 #include "optimizer/joininfo.h"
25 #include "optimizer/pathnode.h"
26 #include "optimizer/paths.h"
27 #include "optimizer/plancat.h"
28 #include "optimizer/planner.h"
29 #include "optimizer/prep.h"
30 #include "optimizer/restrictinfo.h"
31 #include "parser/analyze.h"
32 #include "parser/parsetree.h"
33 #include "parser/scansup.h"
34 #include "partitioning/partbounds.h"
35 #include "tcop/utility.h"
36 #include "utils/builtins.h"
37 #include "utils/lsyscache.h"
38 #include "utils/memutils.h"
39 #include "utils/rel.h"
40 #include "utils/snapmgr.h"
41 #include "utils/syscache.h"
42 #include "utils/resowner.h"
44 #include "catalog/pg_class.h"
46 #include "executor/spi.h"
47 #include "catalog/pg_type.h"
51 /* partially copied from pg_stat_statements */
52 #include "normalize_query.h"
55 #include "access/htup_details.h"
57 #ifdef PG_MODULE_MAGIC
61 #define BLOCK_COMMENT_START "/*"
62 #define BLOCK_COMMENT_END "*/"
63 #define HINT_COMMENT_KEYWORD "+"
64 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
65 #define HINT_END BLOCK_COMMENT_END
68 #define HINT_SEQSCAN "SeqScan"
69 #define HINT_INDEXSCAN "IndexScan"
70 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
71 #define HINT_BITMAPSCAN "BitmapScan"
72 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
73 #define HINT_TIDSCAN "TidScan"
74 #define HINT_NOSEQSCAN "NoSeqScan"
75 #define HINT_NOINDEXSCAN "NoIndexScan"
76 #define HINT_NOBITMAPSCAN "NoBitmapScan"
77 #define HINT_NOTIDSCAN "NoTidScan"
78 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
79 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
80 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
81 #define HINT_PARALLEL "Parallel"
83 #define HINT_NESTLOOP "NestLoop"
84 #define HINT_MERGEJOIN "MergeJoin"
85 #define HINT_HASHJOIN "HashJoin"
86 #define HINT_NONESTLOOP "NoNestLoop"
87 #define HINT_NOMERGEJOIN "NoMergeJoin"
88 #define HINT_NOHASHJOIN "NoHashJoin"
89 #define HINT_LEADING "Leading"
90 #define HINT_SET "Set"
91 #define HINT_ROWS "Rows"
93 #define HINT_ARRAY_DEFAULT_INITSIZE 8
95 #define hint_ereport(str, detail) hint_parse_ereport(str, detail)
96 #define hint_parse_ereport(str, detail) \
98 ereport(pg_hint_plan_parse_message_level, \
99 (errmsg("pg_hint_plan: hint syntax error at or near \"%s\"", (str)), \
100 errdetail detail)); \
103 #define skip_space(str) \
104 while (isspace(*str)) \
109 ENABLE_SEQSCAN = 0x01,
110 ENABLE_INDEXSCAN = 0x02,
111 ENABLE_BITMAPSCAN = 0x04,
112 ENABLE_TIDSCAN = 0x08,
113 ENABLE_INDEXONLYSCAN = 0x10
118 ENABLE_NESTLOOP = 0x01,
119 ENABLE_MERGEJOIN = 0x02,
120 ENABLE_HASHJOIN = 0x04
123 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
124 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
125 ENABLE_INDEXONLYSCAN)
126 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
127 #define DISABLE_ALL_SCAN 0
128 #define DISABLE_ALL_JOIN 0
130 /* hint keyword of enum type*/
131 typedef enum HintKeyword
133 HINT_KEYWORD_SEQSCAN,
134 HINT_KEYWORD_INDEXSCAN,
135 HINT_KEYWORD_INDEXSCANREGEXP,
136 HINT_KEYWORD_BITMAPSCAN,
137 HINT_KEYWORD_BITMAPSCANREGEXP,
138 HINT_KEYWORD_TIDSCAN,
139 HINT_KEYWORD_NOSEQSCAN,
140 HINT_KEYWORD_NOINDEXSCAN,
141 HINT_KEYWORD_NOBITMAPSCAN,
142 HINT_KEYWORD_NOTIDSCAN,
143 HINT_KEYWORD_INDEXONLYSCAN,
144 HINT_KEYWORD_INDEXONLYSCANREGEXP,
145 HINT_KEYWORD_NOINDEXONLYSCAN,
147 HINT_KEYWORD_NESTLOOP,
148 HINT_KEYWORD_MERGEJOIN,
149 HINT_KEYWORD_HASHJOIN,
150 HINT_KEYWORD_NONESTLOOP,
151 HINT_KEYWORD_NOMERGEJOIN,
152 HINT_KEYWORD_NOHASHJOIN,
154 HINT_KEYWORD_LEADING,
157 HINT_KEYWORD_PARALLEL,
159 HINT_KEYWORD_UNRECOGNIZED
162 #define SCAN_HINT_ACCEPTS_INDEX_NAMES(kw) \
163 (kw == HINT_KEYWORD_INDEXSCAN || \
164 kw == HINT_KEYWORD_INDEXSCANREGEXP || \
165 kw == HINT_KEYWORD_INDEXONLYSCAN || \
166 kw == HINT_KEYWORD_INDEXONLYSCANREGEXP || \
167 kw == HINT_KEYWORD_BITMAPSCAN || \
168 kw == HINT_KEYWORD_BITMAPSCANREGEXP)
171 typedef struct Hint Hint;
172 typedef struct HintState HintState;
174 typedef Hint *(*HintCreateFunction) (const char *hint_str,
176 HintKeyword hint_keyword);
177 typedef void (*HintDeleteFunction) (Hint *hint);
178 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf, bool nolf);
179 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
180 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
181 Query *parse, const char *str);
184 #define NUM_HINT_TYPE 6
185 typedef enum HintType
187 HINT_TYPE_SCAN_METHOD,
188 HINT_TYPE_JOIN_METHOD,
195 typedef enum HintTypeBitmap
197 HINT_BM_SCAN_METHOD = 1,
201 static const char *HintTypeName[] = {
211 typedef enum HintStatus
213 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
214 HINT_STATE_USED, /* hint is used */
215 HINT_STATE_DUPLICATION, /* specified hint duplication */
216 HINT_STATE_ERROR /* execute error (parse error does not include
220 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
221 (hint)->base.state == HINT_STATE_USED)
223 static unsigned int qno = 0;
224 static unsigned int msgqno = 0;
225 static char qnostr[32];
226 static const char *current_hint_str = NULL;
229 * However we usually take a hint stirng in post_parse_analyze_hook, we still
230 * need to do so in planner_hook when client starts query execution from the
231 * bind message on a prepared query. This variable prevent duplicate and
232 * sometimes harmful hint string retrieval.
234 static bool current_hint_retrieved = false;
236 /* common data for all hints. */
239 const char *hint_str; /* must not do pfree */
240 const char *keyword; /* must not do pfree */
241 HintKeyword hint_keyword;
244 HintDeleteFunction delete_func;
245 HintDescFunction desc_func;
246 HintCmpFunction cmp_func;
247 HintParseFunction parse_func;
250 /* scan method hints */
251 typedef struct ScanMethodHint
257 unsigned char enforce_mask;
260 typedef struct ParentIndexInfo
265 char *expression_str;
272 /* join method hints */
273 typedef struct JoinMethodHint
279 unsigned char enforce_mask;
281 Relids inner_joinrelids;
284 /* join order hints */
285 typedef struct OuterInnerRels
288 List *outer_inner_pair;
291 typedef struct LeadingHint
294 List *relations; /* relation names specified in Leading hint */
295 OuterInnerRels *outer_inner;
298 /* change a run-time parameter hints */
299 typedef struct SetHint
302 char *name; /* name of variable */
308 typedef enum RowsValueType {
309 RVT_ABSOLUTE, /* Rows(... #1000) */
310 RVT_ADD, /* Rows(... +1000) */
311 RVT_SUB, /* Rows(... -1000) */
312 RVT_MULTI, /* Rows(... *1.2) */
314 typedef struct RowsHint
321 Relids inner_joinrelids;
323 RowsValueType value_type;
328 typedef struct ParallelHint
332 char *nworkers_str; /* original string of nworkers */
333 int nworkers; /* num of workers specified by Worker */
334 bool force_parallel; /* force parallel scan */
338 * Describes a context of hint processing.
342 char *hint_str; /* original hint string */
345 int nall_hints; /* # of valid all hints */
346 int max_all_hints; /* # of slots for all hints */
347 Hint **all_hints; /* parsed all hints */
349 /* # of each hints */
350 int num_hints[NUM_HINT_TYPE];
352 /* for scan method hints */
353 ScanMethodHint **scan_hints; /* parsed scan hints */
355 /* Initial values of parameters */
356 int init_scan_mask; /* enable_* mask */
357 int init_nworkers; /* max_parallel_workers_per_gather */
358 /* min_parallel_table_scan_size*/
359 int init_min_para_tablescan_size;
360 /* min_parallel_index_scan_size*/
361 int init_min_para_indexscan_size;
362 int init_paratup_cost; /* parallel_tuple_cost */
363 int init_parasetup_cost;/* parallel_setup_cost */
365 PlannerInfo *current_root; /* PlannerInfo for the followings */
366 Index parent_relid; /* inherit parent of table relid */
367 ScanMethodHint *parent_scan_hint; /* scan hint for the parent */
368 ParallelHint *parent_parallel_hint; /* parallel hint for the parent */
369 List *parent_index_infos; /* list of parent table's index */
371 JoinMethodHint **join_hints; /* parsed join hints */
372 int init_join_mask; /* initial value join parameter */
373 List **join_hint_level;
374 LeadingHint **leading_hint; /* parsed Leading hints */
375 SetHint **set_hints; /* parsed Set hints */
376 GucContext context; /* which GUC parameters can we set? */
377 RowsHint **rows_hints; /* parsed Rows hints */
378 ParallelHint **parallel_hints; /* parsed Parallel hints */
382 * Describes a hint parser module which is bound with particular hint keyword.
384 typedef struct HintParser
387 HintCreateFunction create_func;
388 HintKeyword hint_keyword;
391 /* Module callbacks */
395 static void push_hint(HintState *hstate);
396 static void pop_hint(void);
398 static void pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query);
399 static void pg_hint_plan_ProcessUtility(PlannedStmt *pstmt,
400 const char *queryString,
401 ProcessUtilityContext context,
402 ParamListInfo params, QueryEnvironment *queryEnv,
403 DestReceiver *dest, char *completionTag);
404 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
405 ParamListInfo boundParams);
406 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
410 /* Scan method hint callbacks */
411 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
412 HintKeyword hint_keyword);
413 static void ScanMethodHintDelete(ScanMethodHint *hint);
414 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
415 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
416 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
417 Query *parse, const char *str);
419 /* Join method hint callbacks */
420 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
421 HintKeyword hint_keyword);
422 static void JoinMethodHintDelete(JoinMethodHint *hint);
423 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
424 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
425 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
426 Query *parse, const char *str);
428 /* Leading hint callbacks */
429 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
430 HintKeyword hint_keyword);
431 static void LeadingHintDelete(LeadingHint *hint);
432 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
433 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
434 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
435 Query *parse, const char *str);
437 /* Set hint callbacks */
438 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
439 HintKeyword hint_keyword);
440 static void SetHintDelete(SetHint *hint);
441 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
442 static int SetHintCmp(const SetHint *a, const SetHint *b);
443 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
446 /* Rows hint callbacks */
447 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
448 HintKeyword hint_keyword);
449 static void RowsHintDelete(RowsHint *hint);
450 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
451 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
452 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
453 Query *parse, const char *str);
455 /* Parallel hint callbacks */
456 static Hint *ParallelHintCreate(const char *hint_str, const char *keyword,
457 HintKeyword hint_keyword);
458 static void ParallelHintDelete(ParallelHint *hint);
459 static void ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf);
460 static int ParallelHintCmp(const ParallelHint *a, const ParallelHint *b);
461 static const char *ParallelHintParse(ParallelHint *hint, HintState *hstate,
462 Query *parse, const char *str);
464 static void quote_value(StringInfo buf, const char *value);
466 static const char *parse_quoted_value(const char *str, char **word,
469 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
472 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
473 void pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
474 Index rti, RangeTblEntry *rte);
475 static void create_plain_partial_paths(PlannerInfo *root,
477 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
478 ListCell *other_rels);
479 static void make_rels_by_clauseless_joins(PlannerInfo *root,
481 ListCell *other_rels);
482 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
483 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
485 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
486 Index rti, RangeTblEntry *rte);
487 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
490 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
492 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
494 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
498 static int set_config_option_noerror(const char *name, const char *value,
499 GucContext context, GucSource source,
500 GucAction action, bool changeVal, int elevel);
501 static void setup_scan_method_enforcement(ScanMethodHint *scanhint,
503 static int set_config_int32_option(const char *name, int32 value,
507 static bool pg_hint_plan_enable_hint = true;
508 static int debug_level = 0;
509 static int pg_hint_plan_parse_message_level = INFO;
510 static int pg_hint_plan_debug_message_level = LOG;
511 /* Default is off, to keep backward compatibility. */
512 static bool pg_hint_plan_enable_hint_table = false;
514 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
515 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
516 /* (This could not be above 1) */
517 static int max_hint_nworkers = -1; /* Maximum nworkers of Workers hints */
519 static const struct config_enum_entry parse_messages_level_options[] = {
520 {"debug", DEBUG2, true},
521 {"debug5", DEBUG5, false},
522 {"debug4", DEBUG4, false},
523 {"debug3", DEBUG3, false},
524 {"debug2", DEBUG2, false},
525 {"debug1", DEBUG1, false},
527 {"info", INFO, false},
528 {"notice", NOTICE, false},
529 {"warning", WARNING, false},
530 {"error", ERROR, false},
532 * {"fatal", FATAL, true},
533 * {"panic", PANIC, true},
538 static const struct config_enum_entry parse_debug_level_options[] = {
541 {"detailed", 2, false},
542 {"verbose", 3, false},
554 /* Saved hook values in case of unload */
555 static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
556 static planner_hook_type prev_planner = NULL;
557 static join_search_hook_type prev_join_search = NULL;
558 static set_rel_pathlist_hook_type prev_set_rel_pathlist = NULL;
559 static ProcessUtility_hook_type prev_ProcessUtility_hook = NULL;
561 /* Hold reference to currently active hint */
562 static HintState *current_hint_state = NULL;
565 * List of hint contexts. We treat the head of the list as the Top of the
566 * context stack, so current_hint_state always points the first element of this
569 static List *HintStateStack = NIL;
571 static const HintParser parsers[] = {
572 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
573 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
574 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
575 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
576 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
577 HINT_KEYWORD_BITMAPSCANREGEXP},
578 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
579 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
580 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
581 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
582 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
583 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
584 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
585 HINT_KEYWORD_INDEXONLYSCANREGEXP},
586 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
588 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
589 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
590 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
591 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
592 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
593 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
595 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
596 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
597 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
598 {HINT_PARALLEL, ParallelHintCreate, HINT_KEYWORD_PARALLEL},
600 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
603 PLpgSQL_plugin plugin_funcs = {
607 pg_hint_plan_plpgsql_stmt_beg,
608 pg_hint_plan_plpgsql_stmt_end,
614 * Module load callbacks
619 PLpgSQL_plugin **var_ptr;
621 /* Define custom GUC variables. */
622 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
623 "Force planner to use plans specified in the hint comment preceding to the query.",
625 &pg_hint_plan_enable_hint,
633 DefineCustomEnumVariable("pg_hint_plan.debug_print",
634 "Logs results of hint parsing.",
638 parse_debug_level_options,
645 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
646 "Message level of parse errors.",
648 &pg_hint_plan_parse_message_level,
650 parse_messages_level_options,
657 DefineCustomEnumVariable("pg_hint_plan.message_level",
658 "Message level of debug messages.",
660 &pg_hint_plan_debug_message_level,
662 parse_messages_level_options,
669 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
670 "Let pg_hint_plan look up the hint table.",
672 &pg_hint_plan_enable_hint_table,
681 prev_post_parse_analyze_hook = post_parse_analyze_hook;
682 post_parse_analyze_hook = pg_hint_plan_post_parse_analyze;
683 prev_planner = planner_hook;
684 planner_hook = pg_hint_plan_planner;
685 prev_join_search = join_search_hook;
686 join_search_hook = pg_hint_plan_join_search;
687 prev_set_rel_pathlist = set_rel_pathlist_hook;
688 set_rel_pathlist_hook = pg_hint_plan_set_rel_pathlist;
689 prev_ProcessUtility_hook = ProcessUtility_hook;
690 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
692 /* setup PL/pgSQL plugin hook */
693 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
694 *var_ptr = &plugin_funcs;
696 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
700 * Module unload callback
706 PLpgSQL_plugin **var_ptr;
708 /* Uninstall hooks. */
709 post_parse_analyze_hook = prev_post_parse_analyze_hook;
710 planner_hook = prev_planner;
711 join_search_hook = prev_join_search;
712 set_rel_pathlist_hook = prev_set_rel_pathlist;
713 ProcessUtility_hook = prev_ProcessUtility_hook;
715 /* uninstall PL/pgSQL plugin hook */
716 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
721 * create and delete functions the hint object
725 ScanMethodHintCreate(const char *hint_str, const char *keyword,
726 HintKeyword hint_keyword)
728 ScanMethodHint *hint;
730 hint = palloc(sizeof(ScanMethodHint));
731 hint->base.hint_str = hint_str;
732 hint->base.keyword = keyword;
733 hint->base.hint_keyword = hint_keyword;
734 hint->base.type = HINT_TYPE_SCAN_METHOD;
735 hint->base.state = HINT_STATE_NOTUSED;
736 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
737 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
738 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
739 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
740 hint->relname = NULL;
741 hint->indexnames = NIL;
742 hint->regexp = false;
743 hint->enforce_mask = 0;
745 return (Hint *) hint;
749 ScanMethodHintDelete(ScanMethodHint *hint)
755 pfree(hint->relname);
756 list_free_deep(hint->indexnames);
761 JoinMethodHintCreate(const char *hint_str, const char *keyword,
762 HintKeyword hint_keyword)
764 JoinMethodHint *hint;
766 hint = palloc(sizeof(JoinMethodHint));
767 hint->base.hint_str = hint_str;
768 hint->base.keyword = keyword;
769 hint->base.hint_keyword = hint_keyword;
770 hint->base.type = HINT_TYPE_JOIN_METHOD;
771 hint->base.state = HINT_STATE_NOTUSED;
772 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
773 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
774 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
775 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
777 hint->inner_nrels = 0;
778 hint->relnames = NULL;
779 hint->enforce_mask = 0;
780 hint->joinrelids = NULL;
781 hint->inner_joinrelids = NULL;
783 return (Hint *) hint;
787 JoinMethodHintDelete(JoinMethodHint *hint)
796 for (i = 0; i < hint->nrels; i++)
797 pfree(hint->relnames[i]);
798 pfree(hint->relnames);
801 bms_free(hint->joinrelids);
802 bms_free(hint->inner_joinrelids);
807 LeadingHintCreate(const char *hint_str, const char *keyword,
808 HintKeyword hint_keyword)
812 hint = palloc(sizeof(LeadingHint));
813 hint->base.hint_str = hint_str;
814 hint->base.keyword = keyword;
815 hint->base.hint_keyword = hint_keyword;
816 hint->base.type = HINT_TYPE_LEADING;
817 hint->base.state = HINT_STATE_NOTUSED;
818 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
819 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
820 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
821 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
822 hint->relations = NIL;
823 hint->outer_inner = NULL;
825 return (Hint *) hint;
829 LeadingHintDelete(LeadingHint *hint)
834 list_free_deep(hint->relations);
835 if (hint->outer_inner)
836 pfree(hint->outer_inner);
841 SetHintCreate(const char *hint_str, const char *keyword,
842 HintKeyword hint_keyword)
846 hint = palloc(sizeof(SetHint));
847 hint->base.hint_str = hint_str;
848 hint->base.keyword = keyword;
849 hint->base.hint_keyword = hint_keyword;
850 hint->base.type = HINT_TYPE_SET;
851 hint->base.state = HINT_STATE_NOTUSED;
852 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
853 hint->base.desc_func = (HintDescFunction) SetHintDesc;
854 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
855 hint->base.parse_func = (HintParseFunction) SetHintParse;
860 return (Hint *) hint;
864 SetHintDelete(SetHint *hint)
874 list_free(hint->words);
879 RowsHintCreate(const char *hint_str, const char *keyword,
880 HintKeyword hint_keyword)
884 hint = palloc(sizeof(RowsHint));
885 hint->base.hint_str = hint_str;
886 hint->base.keyword = keyword;
887 hint->base.hint_keyword = hint_keyword;
888 hint->base.type = HINT_TYPE_ROWS;
889 hint->base.state = HINT_STATE_NOTUSED;
890 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
891 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
892 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
893 hint->base.parse_func = (HintParseFunction) RowsHintParse;
895 hint->inner_nrels = 0;
896 hint->relnames = NULL;
897 hint->joinrelids = NULL;
898 hint->inner_joinrelids = NULL;
899 hint->rows_str = NULL;
900 hint->value_type = RVT_ABSOLUTE;
903 return (Hint *) hint;
907 RowsHintDelete(RowsHint *hint)
916 for (i = 0; i < hint->nrels; i++)
917 pfree(hint->relnames[i]);
918 pfree(hint->relnames);
921 bms_free(hint->joinrelids);
922 bms_free(hint->inner_joinrelids);
927 ParallelHintCreate(const char *hint_str, const char *keyword,
928 HintKeyword hint_keyword)
932 hint = palloc(sizeof(ScanMethodHint));
933 hint->base.hint_str = hint_str;
934 hint->base.keyword = keyword;
935 hint->base.hint_keyword = hint_keyword;
936 hint->base.type = HINT_TYPE_PARALLEL;
937 hint->base.state = HINT_STATE_NOTUSED;
938 hint->base.delete_func = (HintDeleteFunction) ParallelHintDelete;
939 hint->base.desc_func = (HintDescFunction) ParallelHintDesc;
940 hint->base.cmp_func = (HintCmpFunction) ParallelHintCmp;
941 hint->base.parse_func = (HintParseFunction) ParallelHintParse;
942 hint->relname = NULL;
944 hint->nworkers_str = "0";
946 return (Hint *) hint;
950 ParallelHintDelete(ParallelHint *hint)
956 pfree(hint->relname);
962 HintStateCreate(void)
966 hstate = palloc(sizeof(HintState));
967 hstate->hint_str = NULL;
968 hstate->nall_hints = 0;
969 hstate->max_all_hints = 0;
970 hstate->all_hints = NULL;
971 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
972 hstate->scan_hints = NULL;
973 hstate->init_scan_mask = 0;
974 hstate->init_nworkers = 0;
975 hstate->init_min_para_tablescan_size = 0;
976 hstate->init_min_para_indexscan_size = 0;
977 hstate->init_paratup_cost = 0;
978 hstate->init_parasetup_cost = 0;
979 hstate->current_root = NULL;
980 hstate->parent_relid = 0;
981 hstate->parent_scan_hint = NULL;
982 hstate->parent_parallel_hint = NULL;
983 hstate->parent_index_infos = NIL;
984 hstate->join_hints = NULL;
985 hstate->init_join_mask = 0;
986 hstate->join_hint_level = NULL;
987 hstate->leading_hint = NULL;
988 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
989 hstate->set_hints = NULL;
990 hstate->rows_hints = NULL;
991 hstate->parallel_hints = NULL;
997 HintStateDelete(HintState *hstate)
1004 if (hstate->hint_str)
1005 pfree(hstate->hint_str);
1007 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1008 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
1009 if (hstate->all_hints)
1010 pfree(hstate->all_hints);
1011 if (hstate->parent_index_infos)
1012 list_free(hstate->parent_index_infos);
1016 * Copy given value into buf, with quoting with '"' if necessary.
1019 quote_value(StringInfo buf, const char *value)
1021 bool need_quote = false;
1024 for (str = value; *str != '\0'; str++)
1026 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
1029 appendStringInfoCharMacro(buf, '"');
1034 for (str = value; *str != '\0'; str++)
1037 appendStringInfoCharMacro(buf, '"');
1039 appendStringInfoCharMacro(buf, *str);
1043 appendStringInfoCharMacro(buf, '"');
1047 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
1051 appendStringInfo(buf, "%s(", hint->base.keyword);
1052 if (hint->relname != NULL)
1054 quote_value(buf, hint->relname);
1055 foreach(l, hint->indexnames)
1057 appendStringInfoCharMacro(buf, ' ');
1058 quote_value(buf, (char *) lfirst(l));
1061 appendStringInfoString(buf, ")");
1063 appendStringInfoChar(buf, '\n');
1067 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
1071 appendStringInfo(buf, "%s(", hint->base.keyword);
1072 if (hint->relnames != NULL)
1074 quote_value(buf, hint->relnames[0]);
1075 for (i = 1; i < hint->nrels; i++)
1077 appendStringInfoCharMacro(buf, ' ');
1078 quote_value(buf, hint->relnames[i]);
1081 appendStringInfoString(buf, ")");
1083 appendStringInfoChar(buf, '\n');
1087 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
1089 if (outer_inner->relation == NULL)
1096 appendStringInfoCharMacro(buf, '(');
1097 foreach(l, outer_inner->outer_inner_pair)
1102 appendStringInfoCharMacro(buf, ' ');
1104 OuterInnerDesc(lfirst(l), buf);
1107 appendStringInfoCharMacro(buf, ')');
1110 quote_value(buf, outer_inner->relation);
1114 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
1116 appendStringInfo(buf, "%s(", HINT_LEADING);
1117 if (hint->outer_inner == NULL)
1124 foreach(l, hint->relations)
1129 appendStringInfoCharMacro(buf, ' ');
1131 quote_value(buf, (char *) lfirst(l));
1135 OuterInnerDesc(hint->outer_inner, buf);
1137 appendStringInfoString(buf, ")");
1139 appendStringInfoChar(buf, '\n');
1143 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1145 bool is_first = true;
1148 appendStringInfo(buf, "%s(", HINT_SET);
1149 foreach(l, hint->words)
1154 appendStringInfoCharMacro(buf, ' ');
1156 quote_value(buf, (char *) lfirst(l));
1158 appendStringInfo(buf, ")");
1160 appendStringInfoChar(buf, '\n');
1164 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1168 appendStringInfo(buf, "%s(", hint->base.keyword);
1169 if (hint->relnames != NULL)
1171 quote_value(buf, hint->relnames[0]);
1172 for (i = 1; i < hint->nrels; i++)
1174 appendStringInfoCharMacro(buf, ' ');
1175 quote_value(buf, hint->relnames[i]);
1178 appendStringInfo(buf, " %s", hint->rows_str);
1179 appendStringInfoString(buf, ")");
1181 appendStringInfoChar(buf, '\n');
1185 ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf)
1187 appendStringInfo(buf, "%s(", hint->base.keyword);
1188 if (hint->relname != NULL)
1190 quote_value(buf, hint->relname);
1192 /* number of workers */
1193 appendStringInfoCharMacro(buf, ' ');
1194 quote_value(buf, hint->nworkers_str);
1195 /* application mode of num of workers */
1196 appendStringInfoCharMacro(buf, ' ');
1197 appendStringInfoString(buf,
1198 (hint->force_parallel ? "hard" : "soft"));
1200 appendStringInfoString(buf, ")");
1202 appendStringInfoChar(buf, '\n');
1206 * Append string which represents all hints in a given state to buf, with
1207 * preceding title with them.
1210 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1211 HintStatus state, bool nolf)
1215 appendStringInfo(buf, "%s:", title);
1217 appendStringInfoChar(buf, '\n');
1220 for (i = 0; i < hstate->nall_hints; i++)
1222 if (hstate->all_hints[i]->state != state)
1225 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1229 if (nolf && nshown == 0)
1230 appendStringInfoString(buf, "(none)");
1234 * Dump contents of given hstate to server log with log level LOG.
1237 HintStateDump(HintState *hstate)
1243 elog(pg_hint_plan_debug_message_level, "pg_hint_plan:\nno hint");
1247 initStringInfo(&buf);
1249 appendStringInfoString(&buf, "pg_hint_plan:\n");
1250 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1251 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1252 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1253 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1255 ereport(pg_hint_plan_debug_message_level,
1256 (errmsg ("%s", buf.data)));
1262 HintStateDump2(HintState *hstate)
1268 elog(pg_hint_plan_debug_message_level,
1269 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1273 initStringInfo(&buf);
1274 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1275 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1276 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1277 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1278 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1279 appendStringInfoChar(&buf, '}');
1281 ereport(pg_hint_plan_debug_message_level,
1282 (errmsg("%s", buf.data),
1284 errhidecontext(true)));
1294 RelnameCmp(const void *a, const void *b)
1296 const char *relnamea = *((const char **) a);
1297 const char *relnameb = *((const char **) b);
1299 return strcmp(relnamea, relnameb);
1303 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1305 return RelnameCmp(&a->relname, &b->relname);
1309 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1313 if (a->nrels != b->nrels)
1314 return a->nrels - b->nrels;
1316 for (i = 0; i < a->nrels; i++)
1319 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1327 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1333 SetHintCmp(const SetHint *a, const SetHint *b)
1335 return strcmp(a->name, b->name);
1339 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1343 if (a->nrels != b->nrels)
1344 return a->nrels - b->nrels;
1346 for (i = 0; i < a->nrels; i++)
1349 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1357 ParallelHintCmp(const ParallelHint *a, const ParallelHint *b)
1359 return RelnameCmp(&a->relname, &b->relname);
1363 HintCmp(const void *a, const void *b)
1365 const Hint *hinta = *((const Hint **) a);
1366 const Hint *hintb = *((const Hint **) b);
1368 if (hinta->type != hintb->type)
1369 return hinta->type - hintb->type;
1370 if (hinta->state == HINT_STATE_ERROR)
1372 if (hintb->state == HINT_STATE_ERROR)
1374 return hinta->cmp_func(hinta, hintb);
1378 * Returns byte offset of hint b from hint a. If hint a was specified before
1379 * b, positive value is returned.
1382 HintCmpWithPos(const void *a, const void *b)
1384 const Hint *hinta = *((const Hint **) a);
1385 const Hint *hintb = *((const Hint **) b);
1388 result = HintCmp(a, b);
1390 result = hinta->hint_str - hintb->hint_str;
1399 parse_keyword(const char *str, StringInfo buf)
1403 while (!isspace(*str) && *str != '(' && *str != '\0')
1404 appendStringInfoCharMacro(buf, *str++);
1410 skip_parenthesis(const char *str, char parenthesis)
1414 if (*str != parenthesis)
1416 if (parenthesis == '(')
1417 hint_ereport(str, ("Opening parenthesis is necessary."));
1418 else if (parenthesis == ')')
1419 hint_ereport(str, ("Closing parenthesis is necessary."));
1430 * Parse a token from str, and store malloc'd copy into word. A token can be
1431 * quoted with '"'. Return value is pointer to unparsed portion of original
1432 * string, or NULL if an error occurred.
1434 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1437 parse_quoted_value(const char *str, char **word, bool truncate)
1442 /* Skip leading spaces. */
1445 initStringInfo(&buf);
1458 /* Double quotation must be closed. */
1462 hint_ereport(str, ("Unterminated quoted string."));
1467 * Skip escaped double quotation.
1469 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1470 * block comments) to be an object name, so users must specify
1471 * alias for such object names.
1473 * Those special names can be allowed if we care escaped slashes
1474 * and asterisks, but we don't.
1483 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1487 appendStringInfoCharMacro(&buf, *str++);
1492 hint_ereport(str, ("Zero-length delimited string."));
1499 /* Truncate name if it's too long */
1501 truncate_identifier(buf.data, strlen(buf.data), true);
1508 static OuterInnerRels *
1509 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1511 OuterInnerRels *outer_inner;
1513 outer_inner = palloc(sizeof(OuterInnerRels));
1514 outer_inner->relation = name;
1515 outer_inner->outer_inner_pair = outer_inner_list;
1521 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1523 List *outer_inner_pair = NIL;
1525 if ((str = skip_parenthesis(str, '(')) == NULL)
1530 /* Store words in parentheses into outer_inner_list. */
1531 while(*str != ')' && *str != '\0')
1533 OuterInnerRels *outer_inner_rels;
1537 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1545 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1548 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1551 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1556 (str = skip_parenthesis(str, ')')) == NULL)
1558 list_free(outer_inner_pair);
1562 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1568 parse_parentheses_Leading(const char *str, List **name_list,
1569 OuterInnerRels **outer_inner)
1572 bool truncate = true;
1574 if ((str = skip_parenthesis(str, '(')) == NULL)
1580 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1585 /* Store words in parentheses into name_list. */
1586 while(*str != ')' && *str != '\0')
1588 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1590 list_free(*name_list);
1594 *name_list = lappend(*name_list, name);
1599 if ((str = skip_parenthesis(str, ')')) == NULL)
1605 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1608 bool truncate = true;
1610 if ((str = skip_parenthesis(str, '(')) == NULL)
1615 /* Store words in parentheses into name_list. */
1616 while(*str != ')' && *str != '\0')
1618 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1620 list_free(*name_list);
1624 *name_list = lappend(*name_list, name);
1627 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1628 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1629 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1630 keyword == HINT_KEYWORD_SET)
1636 if ((str = skip_parenthesis(str, ')')) == NULL)
1642 parse_hints(HintState *hstate, Query *parse, const char *str)
1647 initStringInfo(&buf);
1648 while (*str != '\0')
1650 const HintParser *parser;
1652 /* in error message, we output the comment including the keyword. */
1653 head = (char *) str;
1655 /* parse only the keyword of the hint. */
1656 resetStringInfo(&buf);
1657 str = parse_keyword(str, &buf);
1659 for (parser = parsers; parser->keyword != NULL; parser++)
1661 char *keyword = parser->keyword;
1664 if (pg_strcasecmp(buf.data, keyword) != 0)
1667 hint = parser->create_func(head, keyword, parser->hint_keyword);
1669 /* parser of each hint does parse in a parenthesis. */
1670 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1672 hint->delete_func(hint);
1678 * Add hint information into all_hints array. If we don't have
1679 * enough space, double the array.
1681 if (hstate->nall_hints == 0)
1683 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1684 hstate->all_hints = (Hint **)
1685 palloc(sizeof(Hint *) * hstate->max_all_hints);
1687 else if (hstate->nall_hints == hstate->max_all_hints)
1689 hstate->max_all_hints *= 2;
1690 hstate->all_hints = (Hint **)
1691 repalloc(hstate->all_hints,
1692 sizeof(Hint *) * hstate->max_all_hints);
1695 hstate->all_hints[hstate->nall_hints] = hint;
1696 hstate->nall_hints++;
1703 if (parser->keyword == NULL)
1706 ("Unrecognized hint keyword \"%s\".", buf.data));
1717 * Get hints from table by client-supplied query string and application name.
1720 get_hints_from_table(const char *client_query, const char *client_application)
1722 const char *search_query =
1724 " FROM hint_plan.hints "
1725 " WHERE norm_query_string = $1 "
1726 " AND ( application_name = $2 "
1727 " OR application_name = '' ) "
1728 " ORDER BY application_name DESC";
1729 static SPIPlanPtr plan = NULL;
1731 Oid argtypes[2] = { TEXTOID, TEXTOID };
1733 char nulls[2] = {' ', ' '};
1739 bool snapshot_set = false;
1741 hint_inhibit_level++;
1743 if (!ActiveSnapshotSet())
1745 PushActiveSnapshot(GetTransactionSnapshot());
1746 snapshot_set = true;
1754 p = SPI_prepare(search_query, 2, argtypes);
1755 plan = SPI_saveplan(p);
1759 qry = cstring_to_text(client_query);
1760 app = cstring_to_text(client_application);
1761 values[0] = PointerGetDatum(qry);
1762 values[1] = PointerGetDatum(app);
1764 SPI_execute_plan(plan, values, nulls, true, 1);
1766 if (SPI_processed > 0)
1770 hints = SPI_getvalue(SPI_tuptable->vals[0],
1771 SPI_tuptable->tupdesc, 1);
1773 * Here we use SPI_palloc to ensure that hints string is valid even
1774 * after SPI_finish call. We can't use simple palloc because it
1775 * allocates memory in SPI's context and that context is deleted in
1778 buf = SPI_palloc(strlen(hints) + 1);
1786 PopActiveSnapshot();
1788 hint_inhibit_level--;
1792 hint_inhibit_level--;
1801 * Get client-supplied query string. Addtion to that the jumbled query is
1802 * supplied if the caller requested. From the restriction of JumbleQuery, some
1803 * kind of query needs special amendments. Reutrns NULL if this query doesn't
1804 * change the current hint. This function returns NULL also when something
1805 * wrong has happend and let the caller continue using the current hints.
1808 get_query_string(ParseState *pstate, Query *query, Query **jumblequery)
1810 const char *p = debug_query_string;
1813 * If debug_query_string is set, it is the top level statement. But in some
1814 * cases we reach here with debug_query_string set NULL for example in the
1815 * case of DESCRIBE message handling or EXECUTE command. We may still see a
1816 * candidate top-level query in pstate in the case.
1819 p = pstate->p_sourcetext;
1821 /* We don't see a query string, return NULL */
1825 if (jumblequery != NULL)
1826 *jumblequery = query;
1828 if (query->commandType == CMD_UTILITY)
1830 Query *target_query = (Query *)query->utilityStmt;
1833 * Some CMD_UTILITY statements have a subquery that we can hint on.
1834 * Since EXPLAIN can be placed before other kind of utility statements
1835 * and EXECUTE can be contained other kind of utility statements, these
1836 * conditions are not mutually exclusive and should be considered in
1839 if (IsA(target_query, ExplainStmt))
1841 ExplainStmt *stmt = (ExplainStmt *)target_query;
1843 Assert(IsA(stmt->query, Query));
1844 target_query = (Query *)stmt->query;
1846 /* strip out the top-level query for further processing */
1847 if (target_query->commandType == CMD_UTILITY &&
1848 target_query->utilityStmt != NULL)
1849 target_query = (Query *)target_query->utilityStmt;
1852 if (IsA(target_query, DeclareCursorStmt))
1854 DeclareCursorStmt *stmt = (DeclareCursorStmt *)target_query;
1855 Query *query = (Query *)stmt->query;
1857 /* the target must be CMD_SELECT in this case */
1858 Assert(IsA(query, Query) && query->commandType == CMD_SELECT);
1859 target_query = query;
1862 if (IsA(target_query, CreateTableAsStmt))
1864 CreateTableAsStmt *stmt = (CreateTableAsStmt *) target_query;
1866 Assert(IsA(stmt->query, Query));
1867 target_query = (Query *) stmt->query;
1869 /* strip out the top-level query for further processing */
1870 if (target_query->commandType == CMD_UTILITY &&
1871 target_query->utilityStmt != NULL)
1872 target_query = (Query *)target_query->utilityStmt;
1875 if (IsA(target_query, ExecuteStmt))
1878 * Use the prepared query for EXECUTE. The Query for jumble
1879 * also replaced with the corresponding one.
1881 ExecuteStmt *stmt = (ExecuteStmt *)target_query;
1882 PreparedStatement *entry;
1884 entry = FetchPreparedStatement(stmt->name, true);
1885 p = entry->plansource->query_string;
1886 target_query = (Query *) linitial (entry->plansource->query_list);
1889 /* JumbleQuery accespts only a non-utility Query */
1890 if (!IsA(target_query, Query) ||
1891 target_query->utilityStmt != NULL)
1892 target_query = NULL;
1895 *jumblequery = target_query;
1898 * Return NULL if pstate is not of top-level query. We don't need this
1899 * when jumble info is not requested or cannot do this when pstate is NULL.
1901 else if (!jumblequery && pstate && pstate->p_sourcetext != p &&
1902 strcmp(pstate->p_sourcetext, p) != 0)
1909 * Get hints from the head block comment in client-supplied query string.
1912 get_hints_from_comment(const char *p)
1914 const char *hint_head;
1922 /* extract query head comment. */
1923 hint_head = strstr(p, HINT_START);
1924 if (hint_head == NULL)
1926 for (;p < hint_head; p++)
1929 * Allow these characters precedes hint comment:
1931 * - alphabets which are in ASCII range
1932 * - space, tabs and new-lines
1933 * - underscores, for identifier
1934 * - commas, for SELECT clause, EXPLAIN and PREPARE
1935 * - parentheses, for EXPLAIN and PREPARE
1937 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1938 * avoid behavior which depends on locale setting.
1940 if (!(*p >= '0' && *p <= '9') &&
1941 !(*p >= 'A' && *p <= 'Z') &&
1942 !(*p >= 'a' && *p <= 'z') &&
1946 *p != '(' && *p != ')')
1950 len = strlen(HINT_START);
1955 /* find hint end keyword. */
1956 if ((tail = strstr(p, HINT_END)) == NULL)
1958 hint_ereport(head, ("Unterminated block comment."));
1962 /* We don't support nested block comments. */
1963 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1965 hint_ereport(head, ("Nested block comments are not supported."));
1969 /* Make a copy of hint. */
1971 head = palloc(len + 1);
1972 memcpy(head, p, len);
1980 * Parse hints that got, create hint struct from parse tree and parse hints.
1983 create_hintstate(Query *parse, const char *hints)
1992 /* -1 means that no Parallel hint is specified. */
1993 max_hint_nworkers = -1;
1996 hstate = HintStateCreate();
1997 hstate->hint_str = (char *) hints;
1999 /* parse each hint. */
2000 parse_hints(hstate, parse, p);
2002 /* When nothing specified a hint, we free HintState and returns NULL. */
2003 if (hstate->nall_hints == 0)
2005 HintStateDelete(hstate);
2009 /* Sort hints in order of original position. */
2010 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
2013 /* Count number of hints per hint-type. */
2014 for (i = 0; i < hstate->nall_hints; i++)
2016 Hint *cur_hint = hstate->all_hints[i];
2017 hstate->num_hints[cur_hint->type]++;
2021 * If an object (or a set of objects) has multiple hints of same hint-type,
2022 * only the last hint is valid and others are ignored in planning.
2023 * Hints except the last are marked as 'duplicated' to remember the order.
2025 for (i = 0; i < hstate->nall_hints - 1; i++)
2027 Hint *cur_hint = hstate->all_hints[i];
2028 Hint *next_hint = hstate->all_hints[i + 1];
2031 * Leading hint is marked as 'duplicated' in transform_join_hints.
2033 if (cur_hint->type == HINT_TYPE_LEADING &&
2034 next_hint->type == HINT_TYPE_LEADING)
2038 * Note that we need to pass addresses of hint pointers, because
2039 * HintCmp is designed to sort array of Hint* by qsort.
2041 if (HintCmp(&cur_hint, &next_hint) == 0)
2043 hint_ereport(cur_hint->hint_str,
2044 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
2045 cur_hint->state = HINT_STATE_DUPLICATION;
2050 * Make sure that per-type array pointers point proper position in the
2051 * array which consists of all hints.
2053 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
2054 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
2055 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
2056 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
2057 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
2058 hstate->set_hints = (SetHint **) (hstate->leading_hint +
2059 hstate->num_hints[HINT_TYPE_LEADING]);
2060 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
2061 hstate->num_hints[HINT_TYPE_SET]);
2062 hstate->parallel_hints = (ParallelHint **) (hstate->set_hints +
2063 hstate->num_hints[HINT_TYPE_ROWS]);
2069 * Parse inside of parentheses of scan-method hints.
2072 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
2075 const char *keyword = hint->base.keyword;
2076 HintKeyword hint_keyword = hint->base.hint_keyword;
2077 List *name_list = NIL;
2080 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2083 /* Parse relation name and index name(s) if given hint accepts. */
2084 length = list_length(name_list);
2086 /* at least twp parameters required */
2090 ("%s hint requires a relation.", hint->base.keyword));
2091 hint->base.state = HINT_STATE_ERROR;
2095 hint->relname = linitial(name_list);
2096 hint->indexnames = list_delete_first(name_list);
2098 /* check whether the hint accepts index name(s) */
2099 if (length > 1 && !SCAN_HINT_ACCEPTS_INDEX_NAMES(hint_keyword))
2102 ("%s hint accepts only one relation.",
2103 hint->base.keyword));
2104 hint->base.state = HINT_STATE_ERROR;
2108 /* Set a bit for specified hint. */
2109 switch (hint_keyword)
2111 case HINT_KEYWORD_SEQSCAN:
2112 hint->enforce_mask = ENABLE_SEQSCAN;
2114 case HINT_KEYWORD_INDEXSCAN:
2115 hint->enforce_mask = ENABLE_INDEXSCAN;
2117 case HINT_KEYWORD_INDEXSCANREGEXP:
2118 hint->enforce_mask = ENABLE_INDEXSCAN;
2119 hint->regexp = true;
2121 case HINT_KEYWORD_BITMAPSCAN:
2122 hint->enforce_mask = ENABLE_BITMAPSCAN;
2124 case HINT_KEYWORD_BITMAPSCANREGEXP:
2125 hint->enforce_mask = ENABLE_BITMAPSCAN;
2126 hint->regexp = true;
2128 case HINT_KEYWORD_TIDSCAN:
2129 hint->enforce_mask = ENABLE_TIDSCAN;
2131 case HINT_KEYWORD_NOSEQSCAN:
2132 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
2134 case HINT_KEYWORD_NOINDEXSCAN:
2135 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
2137 case HINT_KEYWORD_NOBITMAPSCAN:
2138 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
2140 case HINT_KEYWORD_NOTIDSCAN:
2141 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
2143 case HINT_KEYWORD_INDEXONLYSCAN:
2144 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2146 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
2147 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2148 hint->regexp = true;
2150 case HINT_KEYWORD_NOINDEXONLYSCAN:
2151 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
2154 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2163 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2166 const char *keyword = hint->base.keyword;
2167 HintKeyword hint_keyword = hint->base.hint_keyword;
2168 List *name_list = NIL;
2170 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2173 hint->nrels = list_length(name_list);
2175 if (hint->nrels > 0)
2181 * Transform relation names from list to array to sort them with qsort
2184 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2185 foreach (l, name_list)
2187 hint->relnames[i] = lfirst(l);
2192 list_free(name_list);
2194 /* A join hint requires at least two relations */
2195 if (hint->nrels < 2)
2198 ("%s hint requires at least two relations.",
2199 hint->base.keyword));
2200 hint->base.state = HINT_STATE_ERROR;
2204 /* Sort hints in alphabetical order of relation names. */
2205 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2207 switch (hint_keyword)
2209 case HINT_KEYWORD_NESTLOOP:
2210 hint->enforce_mask = ENABLE_NESTLOOP;
2212 case HINT_KEYWORD_MERGEJOIN:
2213 hint->enforce_mask = ENABLE_MERGEJOIN;
2215 case HINT_KEYWORD_HASHJOIN:
2216 hint->enforce_mask = ENABLE_HASHJOIN;
2218 case HINT_KEYWORD_NONESTLOOP:
2219 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2221 case HINT_KEYWORD_NOMERGEJOIN:
2222 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2224 case HINT_KEYWORD_NOHASHJOIN:
2225 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2228 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2237 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2240 if (outer_inner->outer_inner_pair == NIL)
2242 if (outer_inner->relation)
2248 if (list_length(outer_inner->outer_inner_pair) == 2)
2250 foreach(l, outer_inner->outer_inner_pair)
2252 if (!OuterInnerPairCheck(lfirst(l)))
2263 OuterInnerList(OuterInnerRels *outer_inner)
2265 List *outer_inner_list = NIL;
2267 OuterInnerRels *outer_inner_rels;
2269 foreach(l, outer_inner->outer_inner_pair)
2271 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2273 if (outer_inner_rels->relation != NULL)
2274 outer_inner_list = lappend(outer_inner_list,
2275 outer_inner_rels->relation);
2277 outer_inner_list = list_concat(outer_inner_list,
2278 OuterInnerList(outer_inner_rels));
2280 return outer_inner_list;
2284 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2287 List *name_list = NIL;
2288 OuterInnerRels *outer_inner = NULL;
2290 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2294 if (outer_inner != NULL)
2295 name_list = OuterInnerList(outer_inner);
2297 hint->relations = name_list;
2298 hint->outer_inner = outer_inner;
2300 /* A Leading hint requires at least two relations */
2301 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2303 hint_ereport(hint->base.hint_str,
2304 ("%s hint requires at least two relations.",
2306 hint->base.state = HINT_STATE_ERROR;
2308 else if (hint->outer_inner != NULL &&
2309 !OuterInnerPairCheck(hint->outer_inner))
2311 hint_ereport(hint->base.hint_str,
2312 ("%s hint requires two sets of relations when parentheses nests.",
2314 hint->base.state = HINT_STATE_ERROR;
2321 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2323 List *name_list = NIL;
2325 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2329 hint->words = name_list;
2331 /* We need both name and value to set GUC parameter. */
2332 if (list_length(name_list) == 2)
2334 hint->name = linitial(name_list);
2335 hint->value = lsecond(name_list);
2339 hint_ereport(hint->base.hint_str,
2340 ("%s hint requires name and value of GUC parameter.",
2342 hint->base.state = HINT_STATE_ERROR;
2349 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2352 HintKeyword hint_keyword = hint->base.hint_keyword;
2353 List *name_list = NIL;
2357 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2360 /* Last element must be rows specification */
2361 hint->nrels = list_length(name_list) - 1;
2363 if (hint->nrels > 0)
2369 * Transform relation names from list to array to sort them with qsort
2372 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2373 foreach (l, name_list)
2375 if (hint->nrels <= i)
2377 hint->relnames[i] = lfirst(l);
2382 /* Retieve rows estimation */
2383 rows_str = list_nth(name_list, hint->nrels);
2384 hint->rows_str = rows_str; /* store as-is for error logging */
2385 if (rows_str[0] == '#')
2387 hint->value_type = RVT_ABSOLUTE;
2390 else if (rows_str[0] == '+')
2392 hint->value_type = RVT_ADD;
2395 else if (rows_str[0] == '-')
2397 hint->value_type = RVT_SUB;
2400 else if (rows_str[0] == '*')
2402 hint->value_type = RVT_MULTI;
2407 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2408 hint->base.state = HINT_STATE_ERROR;
2411 hint->rows = strtod(rows_str, &end_ptr);
2414 hint_ereport(rows_str,
2415 ("%s hint requires valid number as rows estimation.",
2416 hint->base.keyword));
2417 hint->base.state = HINT_STATE_ERROR;
2421 /* A join hint requires at least two relations */
2422 if (hint->nrels < 2)
2425 ("%s hint requires at least two relations.",
2426 hint->base.keyword));
2427 hint->base.state = HINT_STATE_ERROR;
2431 list_free(name_list);
2433 /* Sort relnames in alphabetical order. */
2434 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2440 ParallelHintParse(ParallelHint *hint, HintState *hstate, Query *parse,
2443 HintKeyword hint_keyword = hint->base.hint_keyword;
2444 List *name_list = NIL;
2448 bool force_parallel = false;
2450 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2453 /* Parse relation name and index name(s) if given hint accepts. */
2454 length = list_length(name_list);
2456 if (length < 2 || length > 3)
2459 ("wrong number of arguments (%d): %s",
2460 length, hint->base.keyword));
2461 hint->base.state = HINT_STATE_ERROR;
2465 hint->relname = linitial(name_list);
2467 /* The second parameter is number of workers */
2468 hint->nworkers_str = list_nth(name_list, 1);
2469 nworkers = strtod(hint->nworkers_str, &end_ptr);
2470 if (*end_ptr || nworkers < 0 || nworkers > max_worker_processes)
2473 hint_ereport(hint->nworkers_str,
2474 ("number of workers must be a number: %s",
2475 hint->base.keyword));
2476 else if (nworkers < 0)
2477 hint_ereport(hint->nworkers_str,
2478 ("number of workers must be positive: %s",
2479 hint->base.keyword));
2480 else if (nworkers > max_worker_processes)
2481 hint_ereport(hint->nworkers_str,
2482 ("number of workers = %d is larger than max_worker_processes(%d): %s",
2483 nworkers, max_worker_processes, hint->base.keyword));
2485 hint->base.state = HINT_STATE_ERROR;
2488 hint->nworkers = nworkers;
2490 /* optional third parameter is specified */
2493 const char *modeparam = (const char *)list_nth(name_list, 2);
2494 if (pg_strcasecmp(modeparam, "hard") == 0)
2495 force_parallel = true;
2496 else if (pg_strcasecmp(modeparam, "soft") != 0)
2498 hint_ereport(modeparam,
2499 ("enforcement must be soft or hard: %s",
2500 hint->base.keyword));
2501 hint->base.state = HINT_STATE_ERROR;
2505 hint->force_parallel = force_parallel;
2507 if (hint->base.state != HINT_STATE_ERROR &&
2508 nworkers > max_hint_nworkers)
2509 max_hint_nworkers = nworkers;
2515 * set GUC parameter functions
2519 get_current_scan_mask()
2524 mask |= ENABLE_SEQSCAN;
2525 if (enable_indexscan)
2526 mask |= ENABLE_INDEXSCAN;
2527 if (enable_bitmapscan)
2528 mask |= ENABLE_BITMAPSCAN;
2530 mask |= ENABLE_TIDSCAN;
2531 if (enable_indexonlyscan)
2532 mask |= ENABLE_INDEXONLYSCAN;
2538 get_current_join_mask()
2542 if (enable_nestloop)
2543 mask |= ENABLE_NESTLOOP;
2544 if (enable_mergejoin)
2545 mask |= ENABLE_MERGEJOIN;
2546 if (enable_hashjoin)
2547 mask |= ENABLE_HASHJOIN;
2553 * Sets GUC prameters without throwing exception. Reutrns false if something
2557 set_config_option_noerror(const char *name, const char *value,
2558 GucContext context, GucSource source,
2559 GucAction action, bool changeVal, int elevel)
2562 MemoryContext ccxt = CurrentMemoryContext;
2566 result = set_config_option(name, value, context, source,
2567 action, changeVal, 0, false);
2573 /* Save error info */
2574 MemoryContextSwitchTo(ccxt);
2575 errdata = CopyErrorData();
2579 (errcode(errdata->sqlerrcode),
2580 errmsg("%s", errdata->message),
2581 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2582 errdata->hint ? errhint("%s", errdata->hint) : 0));
2584 FreeErrorData(errdata);
2592 * Sets GUC parameter of int32 type without throwing exceptions. Returns false
2593 * if something wrong.
2596 set_config_int32_option(const char *name, int32 value, GucContext context)
2598 char buf[16]; /* enough for int32 */
2600 if (snprintf(buf, 16, "%d", value) < 0)
2602 ereport(pg_hint_plan_parse_message_level,
2603 (errmsg ("Failed to convert integer to string: %d", value)));
2608 set_config_option_noerror(name, buf, context,
2609 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2610 pg_hint_plan_parse_message_level);
2613 /* setup scan method enforcement according to given options */
2615 setup_guc_enforcement(SetHint **options, int noptions, GucContext context)
2619 for (i = 0; i < noptions; i++)
2621 SetHint *hint = options[i];
2624 if (!hint_state_enabled(hint))
2627 result = set_config_option_noerror(hint->name, hint->value, context,
2628 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2629 pg_hint_plan_parse_message_level);
2631 hint->base.state = HINT_STATE_USED;
2633 hint->base.state = HINT_STATE_ERROR;
2640 * Setup parallel execution environment.
2642 * If hint is not NULL, set up using it, elsewise reset to initial environment.
2645 setup_parallel_plan_enforcement(ParallelHint *hint, HintState *state)
2649 hint->base.state = HINT_STATE_USED;
2650 set_config_int32_option("max_parallel_workers_per_gather",
2651 hint->nworkers, state->context);
2654 set_config_int32_option("max_parallel_workers_per_gather",
2655 state->init_nworkers, state->context);
2657 /* force means that enforce parallel as far as possible */
2658 if (hint && hint->force_parallel && hint->nworkers > 0)
2660 set_config_int32_option("parallel_tuple_cost", 0, state->context);
2661 set_config_int32_option("parallel_setup_cost", 0, state->context);
2662 set_config_int32_option("min_parallel_table_scan_size", 0,
2664 set_config_int32_option("min_parallel_index_scan_size", 0,
2669 set_config_int32_option("parallel_tuple_cost",
2670 state->init_paratup_cost, state->context);
2671 set_config_int32_option("parallel_setup_cost",
2672 state->init_parasetup_cost, state->context);
2673 set_config_int32_option("min_parallel_table_scan_size",
2674 state->init_min_para_tablescan_size,
2676 set_config_int32_option("min_parallel_index_scan_size",
2677 state->init_min_para_indexscan_size,
2682 #define SET_CONFIG_OPTION(name, type_bits) \
2683 set_config_option_noerror((name), \
2684 (mask & (type_bits)) ? "true" : "false", \
2685 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2689 * Setup GUC environment to enforce scan methods. If scanhint is NULL, reset
2690 * GUCs to the saved state in state.
2693 setup_scan_method_enforcement(ScanMethodHint *scanhint, HintState *state)
2695 unsigned char enforce_mask = state->init_scan_mask;
2696 GucContext context = state->context;
2701 enforce_mask = scanhint->enforce_mask;
2702 scanhint->base.state = HINT_STATE_USED;
2705 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2706 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2707 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2709 mask = enforce_mask;
2711 mask = enforce_mask & current_hint_state->init_scan_mask;
2713 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2714 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2715 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2716 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2717 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2721 set_join_config_options(unsigned char enforce_mask, GucContext context)
2725 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2726 enforce_mask == ENABLE_HASHJOIN)
2727 mask = enforce_mask;
2729 mask = enforce_mask & current_hint_state->init_join_mask;
2731 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2732 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2733 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2737 * Push a hint into hint stack which is implemented with List struct. Head of
2738 * list is top of stack.
2741 push_hint(HintState *hstate)
2743 /* Prepend new hint to the list means pushing to stack. */
2744 HintStateStack = lcons(hstate, HintStateStack);
2746 /* Pushed hint is the one which should be used hereafter. */
2747 current_hint_state = hstate;
2750 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2754 /* Hint stack must not be empty. */
2755 if(HintStateStack == NIL)
2756 elog(ERROR, "hint stack is empty");
2759 * Take a hint at the head from the list, and free it. Switch
2760 * current_hint_state to point new head (NULL if the list is empty).
2762 HintStateStack = list_delete_first(HintStateStack);
2763 HintStateDelete(current_hint_state);
2764 if(HintStateStack == NIL)
2765 current_hint_state = NULL;
2767 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
2771 * Retrieve and store hint string from given query or from the hint table.
2774 get_current_hint_string(ParseState *pstate, Query *query)
2776 const char *query_str;
2777 MemoryContext oldcontext;
2779 /* do nothing under hint table search */
2780 if (hint_inhibit_level > 0)
2783 /* We alredy have one, don't parse it again. */
2784 if (current_hint_retrieved)
2787 /* Don't parse the current query hereafter */
2788 current_hint_retrieved = true;
2790 if (!pg_hint_plan_enable_hint)
2792 if (current_hint_str)
2794 pfree((void *)current_hint_str);
2795 current_hint_str = NULL;
2800 /* increment the query number */
2802 if (debug_level > 1)
2803 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2806 /* search the hint table for a hint if requested */
2807 if (pg_hint_plan_enable_hint_table)
2810 pgssJumbleState jstate;
2812 char *normalized_query = NULL;
2814 query_str = get_query_string(pstate, query, &jumblequery);
2816 /* If this query is not for hint, just return */
2820 /* clear the previous hint string */
2821 if (current_hint_str)
2823 pfree((void *)current_hint_str);
2824 current_hint_str = NULL;
2830 * XXX: normalization code is copied from pg_stat_statements.c.
2831 * Make sure to keep up-to-date with it.
2833 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2834 jstate.jumble_len = 0;
2835 jstate.clocations_buf_size = 32;
2836 jstate.clocations = (pgssLocationLen *)
2837 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2838 jstate.clocations_count = 0;
2840 JumbleQuery(&jstate, jumblequery);
2843 * Normalize the query string by replacing constants with '?'
2846 * Search hint string which is stored keyed by query string
2847 * and application name. The query string is normalized to allow
2850 * Adding 1 byte to query_len ensures that the returned string has
2851 * a terminating NULL.
2853 query_len = strlen(query_str) + 1;
2855 generate_normalized_query(&jstate, query_str,
2856 query->stmt_location,
2858 GetDatabaseEncoding());
2861 * find a hint for the normalized query. the result should be in
2864 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2866 get_hints_from_table(normalized_query, application_name);
2867 MemoryContextSwitchTo(oldcontext);
2869 if (debug_level > 1)
2871 if (current_hint_str)
2872 ereport(pg_hint_plan_debug_message_level,
2873 (errmsg("pg_hint_plan[qno=0x%x]: "
2874 "post_parse_analyze_hook: "
2875 "hints from table: \"%s\": "
2876 "normalized_query=\"%s\", "
2877 "application name =\"%s\"",
2878 qno, current_hint_str,
2879 normalized_query, application_name),
2880 errhidestmt(msgqno != qno),
2881 errhidecontext(msgqno != qno)));
2883 ereport(pg_hint_plan_debug_message_level,
2884 (errmsg("pg_hint_plan[qno=0x%x]: "
2885 "no match found in table: "
2886 "application name = \"%s\", "
2887 "normalized_query=\"%s\"",
2888 qno, application_name,
2890 errhidestmt(msgqno != qno),
2891 errhidecontext(msgqno != qno)));
2897 /* retrun if we have hint here */
2898 if (current_hint_str)
2902 query_str = get_query_string(pstate, query, NULL);
2907 * get hints from the comment. However we may have the same query
2908 * string with the previous call, but the extra comparison seems no
2911 if (current_hint_str)
2912 pfree((void *)current_hint_str);
2914 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2915 current_hint_str = get_hints_from_comment(query_str);
2916 MemoryContextSwitchTo(oldcontext);
2919 if (debug_level > 1)
2921 if (debug_level == 1 && query_str && debug_query_string &&
2922 strcmp(query_str, debug_query_string))
2923 ereport(pg_hint_plan_debug_message_level,
2924 (errmsg("hints in comment=\"%s\"",
2925 current_hint_str ? current_hint_str : "(none)"),
2926 errhidestmt(msgqno != qno),
2927 errhidecontext(msgqno != qno)));
2929 ereport(pg_hint_plan_debug_message_level,
2930 (errmsg("hints in comment=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2931 current_hint_str ? current_hint_str : "(none)",
2932 query_str ? query_str : "(none)",
2933 debug_query_string ? debug_query_string : "(none)"),
2934 errhidestmt(msgqno != qno),
2935 errhidecontext(msgqno != qno)));
2941 * Retrieve hint string from the current query.
2944 pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query)
2946 if (prev_post_parse_analyze_hook)
2947 prev_post_parse_analyze_hook(pstate, query);
2949 /* always retrieve hint from the top-level query string */
2950 if (plpgsql_recurse_level == 0)
2951 current_hint_retrieved = false;
2953 get_current_hint_string(pstate, query);
2957 * We need to reset current_hint_retrieved flag always when a command execution
2958 * is finished. This is true even for a pure utility command that doesn't
2959 * involve planning phase.
2962 pg_hint_plan_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
2963 ProcessUtilityContext context,
2964 ParamListInfo params, QueryEnvironment *queryEnv,
2965 DestReceiver *dest, char *completionTag)
2967 if (prev_ProcessUtility_hook)
2968 prev_ProcessUtility_hook(pstmt, queryString, context, params, queryEnv,
2969 dest, completionTag);
2971 if (plpgsql_recurse_level == 0)
2972 current_hint_retrieved = false;
2976 * Read and set up hint information
2978 static PlannedStmt *
2979 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2982 PlannedStmt *result;
2986 * Use standard planner if pg_hint_plan is disabled or current nesting
2987 * depth is nesting depth of SPI calls. Other hook functions try to change
2988 * plan with current_hint_state if any, so set it to NULL.
2990 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2992 if (debug_level > 1)
2993 ereport(pg_hint_plan_debug_message_level,
2994 (errmsg ("pg_hint_plan%s: planner: enable_hint=%d,"
2995 " hint_inhibit_level=%d",
2996 qnostr, pg_hint_plan_enable_hint,
2997 hint_inhibit_level),
2998 errhidestmt(msgqno != qno)));
3001 goto standard_planner_proc;
3005 * Support for nested plpgsql functions. This is quite ugly but this is the
3006 * only point I could find where I can get the query string.
3008 if (plpgsql_recurse_level > 0)
3010 MemoryContext oldcontext;
3012 if (current_hint_str)
3013 pfree((void *)current_hint_str);
3015 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
3017 get_hints_from_comment((char *)error_context_stack->arg);
3018 MemoryContextSwitchTo(oldcontext);
3022 * Query execution in extended protocol can be started without the analyze
3023 * phase. In the case retrieve hint string here.
3025 if (!current_hint_str)
3026 get_current_hint_string(NULL, parse);
3028 /* No hint, go the normal way */
3029 if (!current_hint_str)
3030 goto standard_planner_proc;
3032 /* parse the hint into hint state struct */
3033 hstate = create_hintstate(parse, pstrdup(current_hint_str));
3035 /* run standard planner if the statement has not valid hint */
3037 goto standard_planner_proc;
3040 * Push new hint struct to the hint stack to disable previous hint context.
3044 /* Set scan enforcement here. */
3045 save_nestlevel = NewGUCNestLevel();
3047 /* Apply Set hints, then save it as the initial state */
3048 setup_guc_enforcement(current_hint_state->set_hints,
3049 current_hint_state->num_hints[HINT_TYPE_SET],
3050 current_hint_state->context);
3052 current_hint_state->init_scan_mask = get_current_scan_mask();
3053 current_hint_state->init_join_mask = get_current_join_mask();
3054 current_hint_state->init_min_para_tablescan_size =
3055 min_parallel_table_scan_size;
3056 current_hint_state->init_min_para_indexscan_size =
3057 min_parallel_index_scan_size;
3058 current_hint_state->init_paratup_cost = parallel_tuple_cost;
3059 current_hint_state->init_parasetup_cost = parallel_setup_cost;
3062 * max_parallel_workers_per_gather should be non-zero here if Workers hint
3065 if (max_hint_nworkers > 0 && max_parallel_workers_per_gather < 1)
3066 set_config_int32_option("max_parallel_workers_per_gather",
3067 1, current_hint_state->context);
3068 current_hint_state->init_nworkers = max_parallel_workers_per_gather;
3070 if (debug_level > 1)
3072 ereport(pg_hint_plan_debug_message_level,
3073 (errhidestmt(msgqno != qno),
3074 errmsg("pg_hint_plan%s: planner", qnostr)));
3079 * Use PG_TRY mechanism to recover GUC parameters and current_hint_state to
3080 * the state when this planner started when error occurred in planner.
3085 result = (*prev_planner) (parse, cursorOptions, boundParams);
3087 result = standard_planner(parse, cursorOptions, boundParams);
3092 * Rollback changes of GUC parameters, and pop current hint context
3093 * from hint stack to rewind the state.
3095 AtEOXact_GUC(true, save_nestlevel);
3103 * current_hint_str is useless after planning of the top-level query.
3105 if (plpgsql_recurse_level < 1 && current_hint_str)
3107 pfree((void *)current_hint_str);
3108 current_hint_str = NULL;
3109 current_hint_retrieved = false;
3112 /* Print hint in debug mode. */
3113 if (debug_level == 1)
3114 HintStateDump(current_hint_state);
3115 else if (debug_level > 1)
3116 HintStateDump2(current_hint_state);
3119 * Rollback changes of GUC parameters, and pop current hint context from
3120 * hint stack to rewind the state.
3122 AtEOXact_GUC(true, save_nestlevel);
3127 standard_planner_proc:
3128 if (debug_level > 1)
3130 ereport(pg_hint_plan_debug_message_level,
3131 (errhidestmt(msgqno != qno),
3132 errmsg("pg_hint_plan%s: planner: no valid hint",
3136 current_hint_state = NULL;
3138 return (*prev_planner) (parse, cursorOptions, boundParams);
3140 return standard_planner(parse, cursorOptions, boundParams);
3144 * Find scan method hint to be applied to the given relation
3147 static ScanMethodHint *
3148 find_scan_hint(PlannerInfo *root, Index relid)
3152 ScanMethodHint *real_name_hint = NULL;
3153 ScanMethodHint *alias_hint = NULL;
3156 /* This should not be a join rel */
3158 rel = root->simple_rel_array[relid];
3161 * This function is called for any RelOptInfo or its inheritance parent if
3162 * any. If we are called from inheritance planner, the RelOptInfo for the
3163 * parent of target child relation is not set in the planner info.
3165 * Otherwise we should check that the reloptinfo is base relation or
3166 * inheritance children.
3169 rel->reloptkind != RELOPT_BASEREL &&
3170 rel->reloptkind != RELOPT_OTHER_MEMBER_REL)
3174 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3176 rte = root->simple_rte_array[relid];
3179 /* We don't hint on other than relation and foreign tables */
3180 if (rte->rtekind != RTE_RELATION ||
3181 rte->relkind == RELKIND_FOREIGN_TABLE)
3184 /* Find scan method hint, which matches given names, from the list. */
3185 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
3187 ScanMethodHint *hint = current_hint_state->scan_hints[i];
3189 /* We ignore disabled hints. */
3190 if (!hint_state_enabled(hint))
3194 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3197 /* check the real name for appendrel children */
3198 if (!real_name_hint &&
3199 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3201 char *realname = get_rel_name(rte->relid);
3203 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3204 real_name_hint = hint;
3207 /* No more match expected, break */
3208 if(alias_hint && real_name_hint)
3212 /* real name match precedes alias match */
3214 return real_name_hint;
3219 static ParallelHint *
3220 find_parallel_hint(PlannerInfo *root, Index relid)
3224 ParallelHint *real_name_hint = NULL;
3225 ParallelHint *alias_hint = NULL;
3228 /* This should not be a join rel */
3230 rel = root->simple_rel_array[relid];
3233 * Parallel planning is appliable only on base relation, which has
3240 * We have set root->glob->parallelModeOK if needed. What we should do here
3241 * is just following the decision of planner.
3243 if (!rel->consider_parallel)
3247 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3249 rte = root->simple_rte_array[relid];
3252 /* Find parallel method hint, which matches given names, from the list. */
3253 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_PARALLEL]; i++)
3255 ParallelHint *hint = current_hint_state->parallel_hints[i];
3257 /* We ignore disabled hints. */
3258 if (!hint_state_enabled(hint))
3262 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3265 /* check the real name for appendrel children */
3266 if (!real_name_hint &&
3267 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3269 char *realname = get_rel_name(rte->relid);
3271 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3272 real_name_hint = hint;
3275 /* No more match expected, break */
3276 if(alias_hint && real_name_hint)
3280 /* real name match precedes alias match */
3282 return real_name_hint;
3290 * Returns TRUE on match, FALSE on no match.
3292 * s1 --- the data to match against
3293 * s2 --- the pattern
3295 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
3298 regexpeq(const char *s1, const char *s2)
3304 strcpy(name.data, s1);
3305 regexp = cstring_to_text(s2);
3307 result = DirectFunctionCall2Coll(nameregexeq,
3308 DEFAULT_COLLATION_OID,
3309 NameGetDatum(&name),
3310 PointerGetDatum(regexp));
3311 return DatumGetBool(result);
3315 /* Remove indexes instructed not to use by hint. */
3317 restrict_indexes(PlannerInfo *root, ScanMethodHint *hint, RelOptInfo *rel,
3318 bool using_parent_hint)
3324 RangeTblEntry *rte = root->simple_rte_array[rel->relid];
3325 Oid relationObjectId = rte->relid;
3328 * We delete all the IndexOptInfo list and prevent you from being usable by
3331 if (hint->enforce_mask == ENABLE_SEQSCAN ||
3332 hint->enforce_mask == ENABLE_TIDSCAN)
3334 list_free_deep(rel->indexlist);
3335 rel->indexlist = NIL;
3336 hint->base.state = HINT_STATE_USED;
3342 * When a list of indexes is not specified, we just use all indexes.
3344 if (hint->indexnames == NIL)
3348 * Leaving only an specified index, we delete it from a IndexOptInfo list
3352 if (debug_level > 0)
3353 initStringInfo(&buf);
3355 for (cell = list_head(rel->indexlist); cell; cell = next)
3357 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
3358 char *indexname = get_rel_name(info->indexoid);
3360 bool use_index = false;
3364 foreach(l, hint->indexnames)
3366 char *hintname = (char *) lfirst(l);
3370 result = regexpeq(indexname, hintname);
3372 result = RelnameCmp(&indexname, &hintname) == 0;
3377 if (debug_level > 0)
3379 appendStringInfoCharMacro(&buf, ' ');
3380 quote_value(&buf, indexname);
3388 * Apply index restriction of parent hint to children. Since index
3389 * inheritance is not explicitly described we should search for an
3390 * children's index with the same definition to that of the parent.
3392 if (using_parent_hint && !use_index)
3394 foreach(l, current_hint_state->parent_index_infos)
3398 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
3401 * we check the 'same' index by comparing uniqueness, access
3402 * method and index key columns.
3404 if (p_info->indisunique != info->unique ||
3405 p_info->method != info->relam ||
3406 list_length(p_info->column_names) != info->ncolumns)
3409 /* Check if index key columns match */
3410 for (i = 0; i < info->ncolumns; i++)
3412 char *c_attname = NULL;
3413 char *p_attname = NULL;
3415 p_attname = list_nth(p_info->column_names, i);
3418 * if both of the key of the same position are expressions,
3419 * ignore them for now and check later.
3421 if (info->indexkeys[i] == 0 && !p_attname)
3424 /* deny if one is expression while another is not */
3425 if (info->indexkeys[i] == 0 || !p_attname)
3428 c_attname = get_attname(relationObjectId,
3429 info->indexkeys[i], false);
3431 /* deny if any of column attributes don't match */
3432 if (strcmp(p_attname, c_attname) != 0 ||
3433 p_info->indcollation[i] != info->indexcollations[i] ||
3434 p_info->opclass[i] != info->opcintype[i]||
3435 ((p_info->indoption[i] & INDOPTION_DESC) != 0)
3436 != info->reverse_sort[i] ||
3437 ((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0)
3438 != info->nulls_first[i])
3442 /* deny this if any difference found */
3443 if (i != info->ncolumns)
3446 /* check on key expressions */
3447 if ((p_info->expression_str && (info->indexprs != NIL)) ||
3448 (p_info->indpred_str && (info->indpred != NIL)))
3450 /* fetch the index of this child */
3451 ht_idx = SearchSysCache1(INDEXRELID,
3452 ObjectIdGetDatum(info->indexoid));
3454 /* check expressions if both expressions are available */
3455 if (p_info->expression_str &&
3456 !heap_attisnull(ht_idx, Anum_pg_index_indexprs, NULL))
3463 * to change the expression's parameter of child's
3466 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3467 Anum_pg_index_indexprs,
3470 result = DirectFunctionCall2(pg_get_expr,
3475 /* deny if expressions don't match */
3476 if (strcmp(p_info->expression_str,
3477 text_to_cstring(DatumGetTextP(result))) != 0)
3480 ReleaseSysCache(ht_idx);
3485 /* compare index predicates */
3486 if (p_info->indpred_str &&
3487 !heap_attisnull(ht_idx, Anum_pg_index_indpred, NULL))
3493 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3494 Anum_pg_index_indpred,
3497 result = DirectFunctionCall2(pg_get_expr,
3502 if (strcmp(p_info->indpred_str,
3503 text_to_cstring(DatumGetTextP(result))) != 0)
3506 ReleaseSysCache(ht_idx);
3512 ReleaseSysCache(ht_idx);
3514 else if (p_info->expression_str || (info->indexprs != NIL))
3516 else if (p_info->indpred_str || (info->indpred != NIL))
3521 /* to log the candidate of index */
3522 if (debug_level > 0)
3524 appendStringInfoCharMacro(&buf, ' ');
3525 quote_value(&buf, indexname);
3533 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
3540 if (debug_level == 1)
3542 StringInfoData rel_buf;
3543 char *disprelname = "";
3546 * If this hint targetted the parent, use the real name of this
3547 * child. Otherwise use hint specification.
3549 if (using_parent_hint)
3550 disprelname = get_rel_name(rte->relid);
3552 disprelname = hint->relname;
3555 initStringInfo(&rel_buf);
3556 quote_value(&rel_buf, disprelname);
3558 ereport(pg_hint_plan_debug_message_level,
3559 (errmsg("available indexes for %s(%s):%s",
3564 pfree(rel_buf.data);
3569 * Return information of index definition.
3571 static ParentIndexInfo *
3572 get_parent_index_info(Oid indexoid, Oid relid)
3574 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3575 Relation indexRelation;
3576 Form_pg_index index;
3580 indexRelation = index_open(indexoid, RowExclusiveLock);
3582 index = indexRelation->rd_index;
3584 p_info->indisunique = index->indisunique;
3585 p_info->method = indexRelation->rd_rel->relam;
3587 p_info->column_names = NIL;
3588 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3589 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3590 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3593 * Collect relation attribute names of index columns for index
3594 * identification, not index attribute names. NULL means expression index
3597 for (i = 0; i < index->indnatts; i++)
3599 attname = get_attname(relid, index->indkey.values[i], true);
3600 p_info->column_names = lappend(p_info->column_names, attname);
3602 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3603 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3604 p_info->indoption[i] = indexRelation->rd_indoption[i];
3608 * to check to match the expression's parameter of index with child indexes
3610 p_info->expression_str = NULL;
3611 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs,
3618 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3619 Anum_pg_index_indexprs, &isnull);
3621 result = DirectFunctionCall2(pg_get_expr,
3623 ObjectIdGetDatum(relid));
3625 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3629 * to check to match the predicate's parameter of index with child indexes
3631 p_info->indpred_str = NULL;
3632 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred,
3639 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3640 Anum_pg_index_indpred, &isnull);
3642 result = DirectFunctionCall2(pg_get_expr,
3644 ObjectIdGetDatum(relid));
3646 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3649 index_close(indexRelation, NoLock);
3655 * cancel hint enforcement
3658 reset_hint_enforcement()
3660 setup_scan_method_enforcement(NULL, current_hint_state);
3661 setup_parallel_plan_enforcement(NULL, current_hint_state);
3665 * Set planner guc parameters according to corresponding scan hints. Returns
3666 * bitmap of HintTypeBitmap. If shint or phint is not NULL, set used hint
3667 * there respectively.
3670 setup_hint_enforcement(PlannerInfo *root, RelOptInfo *rel,
3671 ScanMethodHint **rshint, ParallelHint **rphint)
3673 Index new_parent_relid = 0;
3675 ScanMethodHint *shint = NULL;
3676 ParallelHint *phint = NULL;
3677 bool inhparent = root->simple_rte_array[rel->relid]->inh;
3678 Oid relationObjectId = root->simple_rte_array[rel->relid]->relid;
3681 /* reset returns if requested */
3682 if (rshint != NULL) *rshint = NULL;
3683 if (rphint != NULL) *rphint = NULL;
3686 * We could register the parent relation of the following children here
3687 * when inhparent == true but inheritnce planner doesn't call this function
3688 * for parents. Since we cannot distinguish who called this function we
3689 * cannot do other than always seeking the parent regardless of who called
3694 /* set up only parallel hints for parent relation */
3695 phint = find_parallel_hint(root, rel->relid);
3698 setup_parallel_plan_enforcement(phint, current_hint_state);
3699 if (rphint) *rphint = phint;
3700 ret |= HINT_BM_PARALLEL;
3704 if (debug_level > 1)
3705 ereport(pg_hint_plan_debug_message_level,
3707 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3708 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3709 " current_hint_state=%p, hint_inhibit_level=%d",
3710 qnostr, relationObjectId,
3711 get_rel_name(relationObjectId),
3712 inhparent, current_hint_state, hint_inhibit_level)));
3716 /* Forget about the parent of another subquery */
3717 if (root != current_hint_state->current_root)
3718 current_hint_state->parent_relid = 0;
3720 /* Find the parent for this relation other than the registered parent */
3721 foreach (l, root->append_rel_list)
3723 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3725 if (appinfo->child_relid == rel->relid)
3727 if (current_hint_state->parent_relid != appinfo->parent_relid)
3729 new_parent_relid = appinfo->parent_relid;
3730 current_hint_state->current_root = root;
3738 /* This relation doesn't have a parent. Cancel current_hint_state. */
3739 current_hint_state->parent_relid = 0;
3740 current_hint_state->parent_scan_hint = NULL;
3741 current_hint_state->parent_parallel_hint = NULL;
3744 if (new_parent_relid > 0)
3747 * Here we found a new parent for the current relation. Scan continues
3748 * hint to other childrens of this parent so remember it to avoid
3749 * redundant setup cost.
3751 current_hint_state->parent_relid = new_parent_relid;
3753 /* Find hints for the parent */
3754 current_hint_state->parent_scan_hint =
3755 find_scan_hint(root, current_hint_state->parent_relid);
3757 current_hint_state->parent_parallel_hint =
3758 find_parallel_hint(root, current_hint_state->parent_relid);
3761 * If hint is found for the parent, apply it for this child instead
3764 if (current_hint_state->parent_scan_hint)
3766 ScanMethodHint * pshint = current_hint_state->parent_scan_hint;
3768 pshint->base.state = HINT_STATE_USED;
3770 /* Apply index mask in the same manner to the parent. */
3771 if (pshint->indexnames)
3774 Relation parent_rel;
3777 root->simple_rte_array[current_hint_state->parent_relid]->relid;
3778 parent_rel = heap_open(parentrel_oid, NoLock);
3780 /* Search the parent relation for indexes match the hint spec */
3781 foreach(l, RelationGetIndexList(parent_rel))
3783 Oid indexoid = lfirst_oid(l);
3784 char *indexname = get_rel_name(indexoid);
3786 ParentIndexInfo *parent_index_info;
3788 foreach(lc, pshint->indexnames)
3790 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3797 get_parent_index_info(indexoid, parentrel_oid);
3798 current_hint_state->parent_index_infos =
3799 lappend(current_hint_state->parent_index_infos,
3802 heap_close(parent_rel, NoLock);
3807 shint = find_scan_hint(root, rel->relid);
3809 shint = current_hint_state->parent_scan_hint;
3813 bool using_parent_hint =
3814 (shint == current_hint_state->parent_scan_hint);
3816 ret |= HINT_BM_SCAN_METHOD;
3818 /* Setup scan enforcement environment */
3819 setup_scan_method_enforcement(shint, current_hint_state);
3821 /* restrict unwanted inexes */
3822 restrict_indexes(root, shint, rel, using_parent_hint);
3824 if (debug_level > 1)
3826 char *additional_message = "";
3828 if (shint == current_hint_state->parent_scan_hint)
3829 additional_message = " by parent hint";
3831 ereport(pg_hint_plan_debug_message_level,
3833 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3834 " index deletion%s:"
3835 " relation=%u(%s), inhparent=%d, "
3836 "current_hint_state=%p,"
3837 " hint_inhibit_level=%d, scanmask=0x%x",
3838 qnostr, additional_message,
3840 get_rel_name(relationObjectId),
3841 inhparent, current_hint_state,
3843 shint->enforce_mask)));
3847 /* Do the same for parallel plan enforcement */
3848 phint = find_parallel_hint(root, rel->relid);
3850 phint = current_hint_state->parent_parallel_hint;
3852 setup_parallel_plan_enforcement(phint, current_hint_state);
3855 ret |= HINT_BM_PARALLEL;
3857 /* Nothing to apply. Reset the scan mask to intial state */
3858 if (!shint && ! phint)
3860 if (debug_level > 1)
3861 ereport(pg_hint_plan_debug_message_level,
3862 (errhidestmt (true),
3863 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3865 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3866 " hint_inhibit_level=%d, scanmask=0x%x",
3867 qnostr, relationObjectId,
3868 get_rel_name(relationObjectId),
3869 inhparent, current_hint_state, hint_inhibit_level,
3870 current_hint_state->init_scan_mask)));
3872 setup_scan_method_enforcement(NULL, current_hint_state);
3877 if (rshint != NULL) *rshint = shint;
3878 if (rphint != NULL) *rphint = phint;
3884 * Return index of relation which matches given aliasname, or 0 if not found.
3885 * If same aliasname was used multiple times in a query, return -1.
3888 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3894 for (i = 1; i < root->simple_rel_array_size; i++)
3898 if (root->simple_rel_array[i] == NULL)
3901 Assert(i == root->simple_rel_array[i]->relid);
3903 if (RelnameCmp(&aliasname,
3904 &root->simple_rte_array[i]->eref->aliasname) != 0)
3907 foreach(l, initial_rels)
3909 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3911 if (rel->reloptkind == RELOPT_BASEREL)
3913 if (rel->relid != i)
3918 Assert(rel->reloptkind == RELOPT_JOINREL);
3920 if (!bms_is_member(i, rel->relids))
3927 ("Relation name \"%s\" is ambiguous.",
3942 * Return join hint which matches given joinrelids.
3944 static JoinMethodHint *
3945 find_join_hint(Relids joinrelids)
3950 join_hint = current_hint_state->join_hint_level[bms_num_members(joinrelids)];
3952 foreach(l, join_hint)
3954 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3956 if (bms_equal(joinrelids, hint->joinrelids))
3964 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3965 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3967 OuterInnerRels *outer_rels;
3968 OuterInnerRels *inner_rels;
3969 Relids outer_relids;
3970 Relids inner_relids;
3972 JoinMethodHint *hint;
3974 if (outer_inner->relation != NULL)
3976 return bms_make_singleton(
3977 find_relid_aliasname(root, outer_inner->relation,
3979 leading_hint->base.hint_str));
3982 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3983 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3985 outer_relids = OuterInnerJoinCreate(outer_rels,
3991 inner_relids = OuterInnerJoinCreate(inner_rels,
3998 join_relids = bms_add_members(outer_relids, inner_relids);
4000 if (bms_num_members(join_relids) > nbaserel)
4004 * If we don't have join method hint, create new one for the
4005 * join combination with all join methods are enabled.
4007 hint = find_join_hint(join_relids);
4011 * Here relnames is not set, since Relids bitmap is sufficient to
4012 * control paths of this query afterward.
4014 hint = (JoinMethodHint *) JoinMethodHintCreate(
4015 leading_hint->base.hint_str,
4017 HINT_KEYWORD_LEADING);
4018 hint->base.state = HINT_STATE_USED;
4019 hint->nrels = bms_num_members(join_relids);
4020 hint->enforce_mask = ENABLE_ALL_JOIN;
4021 hint->joinrelids = bms_copy(join_relids);
4022 hint->inner_nrels = bms_num_members(inner_relids);
4023 hint->inner_joinrelids = bms_copy(inner_relids);
4025 hstate->join_hint_level[hint->nrels] =
4026 lappend(hstate->join_hint_level[hint->nrels], hint);
4030 hint->inner_nrels = bms_num_members(inner_relids);
4031 hint->inner_joinrelids = bms_copy(inner_relids);
4038 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
4039 int nrels, char **relnames)
4042 Relids relids = NULL;
4046 for (j = 0; j < nrels; j++)
4048 relname = relnames[j];
4050 relid = find_relid_aliasname(root, relname, initial_rels,
4054 base->state = HINT_STATE_ERROR;
4057 * the aliasname is not found(relid == 0) or same aliasname was used
4058 * multiple times in a query(relid == -1)
4065 if (bms_is_member(relid, relids))
4067 hint_ereport(base->hint_str,
4068 ("Relation name \"%s\" is duplicated.", relname));
4069 base->state = HINT_STATE_ERROR;
4073 relids = bms_add_member(relids, relid);
4078 * Transform join method hint into handy form.
4080 * - create bitmap of relids from alias names, to make it easier to check
4081 * whether a join path matches a join method hint.
4082 * - add join method hints which are necessary to enforce join order
4083 * specified by Leading hint
4086 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
4087 List *initial_rels, JoinMethodHint **join_method_hints)
4095 LeadingHint *lhint = NULL;
4098 * Create bitmap of relids from alias names for each join method hint.
4099 * Bitmaps are more handy than strings in join searching.
4101 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
4103 JoinMethodHint *hint = hstate->join_hints[i];
4105 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4108 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4109 initial_rels, hint->nrels, hint->relnames);
4111 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
4114 hstate->join_hint_level[hint->nrels] =
4115 lappend(hstate->join_hint_level[hint->nrels], hint);
4119 * Create bitmap of relids from alias names for each rows hint.
4120 * Bitmaps are more handy than strings in join searching.
4122 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
4124 RowsHint *hint = hstate->rows_hints[i];
4126 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4129 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4130 initial_rels, hint->nrels, hint->relnames);
4133 /* Do nothing if no Leading hint was supplied. */
4134 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
4138 * Decide whether to use Leading hint
4140 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
4142 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
4145 if (leading_hint->base.state == HINT_STATE_ERROR)
4151 foreach(l, leading_hint->relations)
4153 relname = (char *)lfirst(l);;
4155 relid = find_relid_aliasname(root, relname, initial_rels,
4156 leading_hint->base.hint_str);
4158 leading_hint->base.state = HINT_STATE_ERROR;
4163 if (bms_is_member(relid, relids))
4165 hint_ereport(leading_hint->base.hint_str,
4166 ("Relation name \"%s\" is duplicated.", relname));
4167 leading_hint->base.state = HINT_STATE_ERROR;
4171 relids = bms_add_member(relids, relid);
4174 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
4179 hint_ereport(lhint->base.hint_str,
4180 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
4181 lhint->base.state = HINT_STATE_DUPLICATION;
4183 leading_hint->base.state = HINT_STATE_USED;
4184 lhint = leading_hint;
4187 /* check to exist Leading hint marked with 'used'. */
4192 * We need join method hints which fit specified join order in every join
4193 * level. For example, Leading(A B C) virtually requires following join
4194 * method hints, if no join method hint supplied:
4196 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
4197 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
4199 * If we already have join method hint which fits specified join order in
4200 * that join level, we leave it as-is and don't add new hints.
4204 if (lhint->outer_inner == NULL)
4206 foreach(l, lhint->relations)
4208 JoinMethodHint *hint;
4210 relname = (char *)lfirst(l);
4213 * Find relid of the relation which has given name. If we have the
4214 * name given in Leading hint multiple times in the join, nothing to
4217 relid = find_relid_aliasname(root, relname, initial_rels,
4220 /* Create bitmap of relids for current join level. */
4221 joinrelids = bms_add_member(joinrelids, relid);
4224 /* We never have join method hint for single relation. */
4229 * If we don't have join method hint, create new one for the
4230 * join combination with all join methods are enabled.
4232 hint = find_join_hint(joinrelids);
4236 * Here relnames is not set, since Relids bitmap is sufficient
4237 * to control paths of this query afterward.
4239 hint = (JoinMethodHint *) JoinMethodHintCreate(
4240 lhint->base.hint_str,
4242 HINT_KEYWORD_LEADING);
4243 hint->base.state = HINT_STATE_USED;
4244 hint->nrels = njoinrels;
4245 hint->enforce_mask = ENABLE_ALL_JOIN;
4246 hint->joinrelids = bms_copy(joinrelids);
4249 join_method_hints[njoinrels] = hint;
4251 if (njoinrels >= nbaserel)
4254 bms_free(joinrelids);
4260 * Delete all join hints which have different combination from Leading
4263 for (i = 2; i <= njoinrels; i++)
4265 list_free(hstate->join_hint_level[i]);
4267 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
4272 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
4279 njoinrels = bms_num_members(joinrelids);
4280 Assert(njoinrels >= 2);
4283 * Delete all join hints which have different combination from Leading
4286 for (i = 2;i <= njoinrels; i++)
4288 if (hstate->join_hint_level[i] != NIL)
4290 ListCell *prev = NULL;
4291 ListCell *next = NULL;
4292 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
4295 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
4299 if (hint->inner_nrels == 0 &&
4300 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
4301 bms_equal(bms_union(hint->joinrelids, joinrelids),
4304 hstate->join_hint_level[i] =
4305 list_delete_cell(hstate->join_hint_level[i], l,
4314 bms_free(joinrelids);
4317 if (hint_state_enabled(lhint))
4319 set_join_config_options(DISABLE_ALL_JOIN, current_hint_state->context);
4326 * wrapper of make_join_rel()
4328 * call make_join_rel() after changing enable_* parameters according to given
4332 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
4335 JoinMethodHint *hint;
4339 joinrelids = bms_union(rel1->relids, rel2->relids);
4340 hint = find_join_hint(joinrelids);
4341 bms_free(joinrelids);
4344 return pg_hint_plan_make_join_rel(root, rel1, rel2);
4346 if (hint->inner_nrels == 0)
4348 save_nestlevel = NewGUCNestLevel();
4350 set_join_config_options(hint->enforce_mask,
4351 current_hint_state->context);
4353 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4354 hint->base.state = HINT_STATE_USED;
4357 * Restore the GUC variables we set above.
4359 AtEOXact_GUC(true, save_nestlevel);
4362 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4371 add_paths_to_joinrel_wrapper(PlannerInfo *root,
4372 RelOptInfo *joinrel,
4373 RelOptInfo *outerrel,
4374 RelOptInfo *innerrel,
4376 SpecialJoinInfo *sjinfo,
4380 JoinMethodHint *join_hint;
4383 joinrelids = bms_union(outerrel->relids, innerrel->relids);
4384 join_hint = find_join_hint(joinrelids);
4385 bms_free(joinrelids);
4387 if (join_hint && join_hint->inner_nrels != 0)
4389 save_nestlevel = NewGUCNestLevel();
4391 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
4394 set_join_config_options(join_hint->enforce_mask,
4395 current_hint_state->context);
4397 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4398 sjinfo, restrictlist);
4399 join_hint->base.state = HINT_STATE_USED;
4403 set_join_config_options(DISABLE_ALL_JOIN,
4404 current_hint_state->context);
4405 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4406 sjinfo, restrictlist);
4410 * Restore the GUC variables we set above.
4412 AtEOXact_GUC(true, save_nestlevel);
4415 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4416 sjinfo, restrictlist);
4420 get_num_baserels(List *initial_rels)
4425 foreach(l, initial_rels)
4427 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
4429 if (rel->reloptkind == RELOPT_BASEREL)
4431 else if (rel->reloptkind ==RELOPT_JOINREL)
4432 nbaserel+= bms_num_members(rel->relids);
4435 /* other values not expected here */
4436 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
4444 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
4447 JoinMethodHint **join_method_hints;
4451 bool leading_hint_enable;
4454 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
4455 * valid hint is supplied or current nesting depth is nesting depth of SPI
4458 if (!current_hint_state || hint_inhibit_level > 0)
4460 if (prev_join_search)
4461 return (*prev_join_search) (root, levels_needed, initial_rels);
4462 else if (enable_geqo && levels_needed >= geqo_threshold)
4463 return geqo(root, levels_needed, initial_rels);
4465 return standard_join_search(root, levels_needed, initial_rels);
4469 * In the case using GEQO, only scan method hints and Set hints have
4470 * effect. Join method and join order is not controllable by hints.
4472 if (enable_geqo && levels_needed >= geqo_threshold)
4473 return geqo(root, levels_needed, initial_rels);
4475 nbaserel = get_num_baserels(initial_rels);
4476 current_hint_state->join_hint_level =
4477 palloc0(sizeof(List *) * (nbaserel + 1));
4478 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4480 leading_hint_enable = transform_join_hints(current_hint_state,
4482 initial_rels, join_method_hints);
4484 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4487 * Adjust number of parallel workers of the result rel to the largest
4488 * number of the component paths.
4490 if (current_hint_state->num_hints[HINT_TYPE_PARALLEL] > 0)
4495 foreach (lc, initial_rels)
4498 RelOptInfo *rel = (RelOptInfo *) lfirst(lc);
4500 foreach (lcp, rel->partial_pathlist)
4502 Path *path = (Path *) lfirst(lcp);
4504 if (nworkers < path-> parallel_workers)
4505 nworkers = path-> parallel_workers;
4509 foreach (lc, rel->partial_pathlist)
4511 Path *path = (Path *) lfirst(lc);
4513 if (path->parallel_safe && path->parallel_workers < nworkers)
4514 path->parallel_workers = nworkers;
4518 for (i = 2; i <= nbaserel; i++)
4520 list_free(current_hint_state->join_hint_level[i]);
4522 /* free Leading hint only */
4523 if (join_method_hints[i] != NULL &&
4524 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4525 JoinMethodHintDelete(join_method_hints[i]);
4527 pfree(current_hint_state->join_hint_level);
4528 pfree(join_method_hints);
4530 if (leading_hint_enable)
4531 set_join_config_options(current_hint_state->init_join_mask,
4532 current_hint_state->context);
4538 * Force number of wokers if instructed by hint
4541 pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
4542 Index rti, RangeTblEntry *rte)
4544 ParallelHint *phint;
4548 /* call the previous hook */
4549 if (prev_set_rel_pathlist)
4550 prev_set_rel_pathlist(root, rel, rti, rte);
4552 /* Nothing to do if no hint available */
4553 if (current_hint_state == NULL)
4556 /* Don't touch dummy rels. */
4557 if (IS_DUMMY_REL(rel))
4561 * We can accept only plain relations, foreign tables and table saples are
4562 * also unacceptable. See set_rel_pathlist.
4564 if ((rel->rtekind != RTE_RELATION &&
4565 rel->rtekind != RTE_SUBQUERY)||
4566 rte->relkind == RELKIND_FOREIGN_TABLE ||
4567 rte->tablesample != NULL)
4571 * Even though UNION ALL node doesn't have particular name so usually it is
4572 * unhintable, turn on parallel when it contains parallel nodes.
4574 if (rel->rtekind == RTE_SUBQUERY)
4577 bool inhibit_nonparallel = false;
4579 if (rel->partial_pathlist == NIL)
4582 foreach(lc, rel->partial_pathlist)
4585 AppendPath *apath = (AppendPath *) lfirst(lc);
4586 int parallel_workers = 0;
4588 if (!IsA(apath, AppendPath))
4591 foreach (lcp, apath->subpaths)
4593 Path *spath = (Path *) lfirst(lcp);
4595 if (spath->parallel_aware &&
4596 parallel_workers < spath->parallel_workers)
4597 parallel_workers = spath->parallel_workers;
4600 apath->path.parallel_workers = parallel_workers;
4601 inhibit_nonparallel = true;
4604 if (inhibit_nonparallel)
4608 foreach(lc, rel->pathlist)
4610 Path *path = (Path *) lfirst(lc);
4612 if (path->startup_cost < disable_cost)
4614 path->startup_cost += disable_cost;
4615 path->total_cost += disable_cost;
4623 /* We cannot handle if this requires an outer */
4624 if (rel->lateral_relids)
4627 /* Return if this relation gets no enfocement */
4628 if ((found_hints = setup_hint_enforcement(root, rel, NULL, &phint)) == 0)
4631 /* Here, we regenerate paths with the current hint restriction */
4632 if (found_hints & HINT_BM_SCAN_METHOD || found_hints & HINT_BM_PARALLEL)
4635 * When hint is specified on non-parent relations, discard existing
4636 * paths and regenerate based on the hint considered. Otherwise we
4637 * already have hinted childx paths then just adjust the number of
4638 * planned number of workers.
4640 if (root->simple_rte_array[rel->relid]->inh)
4642 /* enforce number of workers if requested */
4643 if (phint && phint->force_parallel)
4645 if (phint->nworkers == 0)
4647 list_free_deep(rel->partial_pathlist);
4648 rel->partial_pathlist = NIL;
4652 /* prioritize partial paths */
4653 foreach (l, rel->partial_pathlist)
4655 Path *ppath = (Path *) lfirst(l);
4657 if (ppath->parallel_safe)
4659 ppath->parallel_workers = phint->nworkers;
4660 ppath->startup_cost = 0;
4661 ppath->total_cost = 0;
4665 /* disable non-partial paths */
4666 foreach (l, rel->pathlist)
4668 Path *ppath = (Path *) lfirst(l);
4670 if (ppath->startup_cost < disable_cost)
4672 ppath->startup_cost += disable_cost;
4673 ppath->total_cost += disable_cost;
4681 /* Just discard all the paths considered so far */
4682 list_free_deep(rel->pathlist);
4683 rel->pathlist = NIL;
4684 list_free_deep(rel->partial_pathlist);
4685 rel->partial_pathlist = NIL;
4687 /* Regenerate paths with the current enforcement */
4688 set_plain_rel_pathlist(root, rel, rte);
4690 /* Additional work to enforce parallel query execution */
4691 if (phint && phint->nworkers > 0)
4694 * For Parallel Append to be planned properly, we shouldn't set
4695 * the costs of non-partial paths to disable-value. Lower the
4696 * priority of non-parallel paths by setting partial path costs
4699 foreach (l, rel->partial_pathlist)
4701 Path *path = (Path *) lfirst(l);
4703 path->startup_cost = 0;
4704 path->total_cost = 0;
4707 /* enforce number of workers if requested */
4708 if (phint->force_parallel)
4710 foreach (l, rel->partial_pathlist)
4712 Path *ppath = (Path *) lfirst(l);
4714 if (ppath->parallel_safe)
4715 ppath->parallel_workers = phint->nworkers;
4719 /* Generate gather paths */
4720 if (rel->reloptkind == RELOPT_BASEREL)
4721 generate_gather_paths(root, rel, false);
4726 reset_hint_enforcement();
4731 * Build access paths for a base relation
4733 * This function was copied and edited from set_rel_pathlist() in
4734 * src/backend/optimizer/path/allpaths.c in order not to copy other static
4735 * functions not required here.
4738 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4739 Index rti, RangeTblEntry *rte)
4741 if (IS_DUMMY_REL(rel))
4743 /* We already proved the relation empty, so nothing more to do */
4747 /* It's an "append relation", process accordingly */
4748 set_append_rel_pathlist(root, rel, rti, rte);
4752 if (rel->rtekind == RTE_RELATION)
4754 if (rte->relkind == RELKIND_RELATION)
4756 if(rte->tablesample != NULL)
4757 elog(ERROR, "sampled relation is not supported");
4759 /* Plain relation */
4760 set_plain_rel_pathlist(root, rel, rte);
4763 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4766 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4770 * Allow a plugin to editorialize on the set of Paths for this base
4771 * relation. It could add new paths (such as CustomPaths) by calling
4772 * add_path(), or delete or modify paths added by the core code.
4774 if (set_rel_pathlist_hook)
4775 (*set_rel_pathlist_hook) (root, rel, rti, rte);
4777 /* Now find the cheapest of the paths for this rel */
4782 * stmt_beg callback is called when each query in PL/pgSQL function is about
4783 * to be executed. At that timing, we save query string in the global variable
4784 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4785 * variable for the purpose, because its content is only necessary until
4786 * planner hook is called for the query, so recursive PL/pgSQL function calls
4787 * don't harm this mechanism.
4790 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4792 plpgsql_recurse_level++;
4796 * stmt_end callback is called then each query in PL/pgSQL function has
4797 * finished. At that timing, we clear plpgsql_query_string to tell planner
4798 * hook that next call is not for a query written in PL/pgSQL block.
4801 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4803 plpgsql_recurse_level--;
4806 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4811 if (!isTopLevel || phase != RESOURCE_RELEASE_AFTER_LOCKS)
4813 /* Cancel plpgsql nest level*/
4814 plpgsql_recurse_level = 0;
4817 #define standard_join_search pg_hint_plan_standard_join_search
4818 #define join_search_one_level pg_hint_plan_join_search_one_level
4819 #define make_join_rel make_join_rel_wrapper
4822 #undef make_join_rel
4823 #define make_join_rel pg_hint_plan_make_join_rel
4824 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4825 #include "make_join_rel.c"
4827 #include "pg_stat_statements.c"