1 /*-------------------------------------------------------------------------
4 * do instructions or hints to the planner using C-style block comments
7 * Copyright (c) 2012, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
9 *-------------------------------------------------------------------------
12 #include "commands/prepare.h"
13 #include "mb/pg_wchar.h"
14 #include "miscadmin.h"
15 #include "nodes/nodeFuncs.h"
16 #include "optimizer/clauses.h"
17 #include "optimizer/cost.h"
18 #include "optimizer/geqo.h"
19 #include "optimizer/joininfo.h"
20 #include "optimizer/pathnode.h"
21 #include "optimizer/paths.h"
22 #include "optimizer/plancat.h"
23 #include "optimizer/planner.h"
24 #include "optimizer/prep.h"
25 #include "optimizer/restrictinfo.h"
26 #include "parser/scansup.h"
27 #include "tcop/utility.h"
28 #include "utils/lsyscache.h"
29 #include "utils/memutils.h"
30 #if PG_VERSION_NUM >= 90200
31 #include "catalog/pg_class.h"
34 #ifdef PG_MODULE_MAGIC
38 #if PG_VERSION_NUM < 90100
39 #error unsupported PostgreSQL version
42 #define BLOCK_COMMENT_START "/*"
43 #define BLOCK_COMMENT_END "*/"
44 #define HINT_COMMENT_KEYWORD "+"
45 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
46 #define HINT_END BLOCK_COMMENT_END
49 #define HINT_SEQSCAN "SeqScan"
50 #define HINT_INDEXSCAN "IndexScan"
51 #define HINT_BITMAPSCAN "BitmapScan"
52 #define HINT_TIDSCAN "TidScan"
53 #define HINT_NOSEQSCAN "NoSeqScan"
54 #define HINT_NOINDEXSCAN "NoIndexScan"
55 #define HINT_NOBITMAPSCAN "NoBitmapScan"
56 #define HINT_NOTIDSCAN "NoTidScan"
57 #if PG_VERSION_NUM >= 90200
58 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
59 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
61 #define HINT_NESTLOOP "NestLoop"
62 #define HINT_MERGEJOIN "MergeJoin"
63 #define HINT_HASHJOIN "HashJoin"
64 #define HINT_NONESTLOOP "NoNestLoop"
65 #define HINT_NOMERGEJOIN "NoMergeJoin"
66 #define HINT_NOHASHJOIN "NoHashJoin"
67 #define HINT_LEADING "Leading"
68 #define HINT_SET "Set"
70 #define HINT_ARRAY_DEFAULT_INITSIZE 8
72 #define hint_ereport(str, detail) \
73 ereport(pg_hint_plan_parse_messages, \
74 (errmsg("hint syntax error at or near \"%s\"", (str)), \
77 #define skip_space(str) \
78 while (isspace(*str)) \
83 ENABLE_SEQSCAN = 0x01,
84 ENABLE_INDEXSCAN = 0x02,
85 ENABLE_BITMAPSCAN = 0x04,
86 ENABLE_TIDSCAN = 0x08,
87 #if PG_VERSION_NUM >= 90200
88 ENABLE_INDEXONLYSCAN = 0x10
94 ENABLE_NESTLOOP = 0x01,
95 ENABLE_MERGEJOIN = 0x02,
96 ENABLE_HASHJOIN = 0x04
99 #if PG_VERSION_NUM >= 90200
100 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
101 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
102 ENABLE_INDEXONLYSCAN)
104 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
105 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN)
107 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
108 #define DISABLE_ALL_SCAN 0
109 #define DISABLE_ALL_JOIN 0
111 /* hint keyword of enum type*/
112 typedef enum HintKeyword
114 HINT_KEYWORD_SEQSCAN,
115 HINT_KEYWORD_INDEXSCAN,
116 HINT_KEYWORD_BITMAPSCAN,
117 HINT_KEYWORD_TIDSCAN,
118 HINT_KEYWORD_NOSEQSCAN,
119 HINT_KEYWORD_NOINDEXSCAN,
120 HINT_KEYWORD_NOBITMAPSCAN,
121 HINT_KEYWORD_NOTIDSCAN,
122 #if PG_VERSION_NUM >= 90200
123 HINT_KEYWORD_INDEXONLYSCAN,
124 HINT_KEYWORD_NOINDEXONLYSCAN,
126 HINT_KEYWORD_NESTLOOP,
127 HINT_KEYWORD_MERGEJOIN,
128 HINT_KEYWORD_HASHJOIN,
129 HINT_KEYWORD_NONESTLOOP,
130 HINT_KEYWORD_NOMERGEJOIN,
131 HINT_KEYWORD_NOHASHJOIN,
132 HINT_KEYWORD_LEADING,
134 HINT_KEYWORD_UNRECOGNIZED
137 typedef struct Hint Hint;
138 typedef struct HintState HintState;
140 typedef Hint *(*HintCreateFunction) (const char *hint_str,
142 HintKeyword hint_keyword);
143 typedef void (*HintDeleteFunction) (Hint *hint);
144 typedef void (*HintDumpFunction) (Hint *hint, StringInfo buf);
145 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
146 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
147 Query *parse, const char *str);
150 #define NUM_HINT_TYPE 4
151 typedef enum HintType
153 HINT_TYPE_SCAN_METHOD,
154 HINT_TYPE_JOIN_METHOD,
159 static const char *HintTypeName[] = {
167 typedef enum HintStatus
169 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
170 HINT_STATE_USED, /* hint is used */
171 HINT_STATE_DUPLICATION, /* specified hint duplication */
172 HINT_STATE_ERROR /* execute error (parse error does not include
176 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
177 (hint)->base.state == HINT_STATE_USED)
179 /* common data for all hints. */
182 const char *hint_str; /* must not do pfree */
183 const char *keyword; /* must not do pfree */
184 HintKeyword hint_keyword;
187 HintDeleteFunction delete_func;
188 HintDumpFunction dump_func;
189 HintCmpFunction cmp_func;
190 HintParseFunction parse_func;
193 /* scan method hints */
194 typedef struct ScanMethodHint
199 unsigned char enforce_mask;
202 /* join method hints */
203 typedef struct JoinMethodHint
209 unsigned char enforce_mask;
211 Relids inner_joinrelids;
214 /* join order hints */
215 typedef struct OuterInnerRels
218 List *outer_inner_pair;
221 typedef struct LeadingHint
224 List *relations; /* relation names specified in Leading hint */
225 OuterInnerRels *outer_inner;
228 /* change a run-time parameter hints */
229 typedef struct SetHint
232 char *name; /* name of variable */
238 * Describes a context of hint processing.
242 char *hint_str; /* original hint string */
245 int nall_hints; /* # of valid all hints */
246 int max_all_hints; /* # of slots for all hints */
247 Hint **all_hints; /* parsed all hints */
249 /* # of each hints */
250 int num_hints[NUM_HINT_TYPE];
252 /* for scan method hints */
253 ScanMethodHint **scan_hints; /* parsed scan hints */
254 int init_scan_mask; /* initial value scan parameter */
255 Index parent_relid; /* inherit parent table relid */
256 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
258 /* for join method hints */
259 JoinMethodHint **join_hints; /* parsed join hints */
260 int init_join_mask; /* initial value join parameter */
261 List **join_hint_level;
263 /* for Leading hint */
264 LeadingHint **leading_hint; /* parsed last specified Leading hint */
267 SetHint **set_hints; /* parsed Set hints */
268 GucContext context; /* which GUC parameters can we set? */
272 * Describes a hint parser module which is bound with particular hint keyword.
274 typedef struct HintParser
277 HintCreateFunction create_func;
278 HintKeyword hint_keyword;
281 /* Module callbacks */
285 static void push_hint(HintState *hstate);
286 static void pop_hint(void);
288 static void pg_hint_plan_ProcessUtility(Node *parsetree,
289 const char *queryString,
290 ParamListInfo params, bool isTopLevel,
292 char *completionTag);
293 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
294 ParamListInfo boundParams);
295 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
296 Oid relationObjectId,
297 bool inhparent, RelOptInfo *rel);
298 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
302 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
303 HintKeyword hint_keyword);
304 static void ScanMethodHintDelete(ScanMethodHint *hint);
305 static void ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf);
306 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
307 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
308 Query *parse, const char *str);
309 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
310 HintKeyword hint_keyword);
311 static void JoinMethodHintDelete(JoinMethodHint *hint);
312 static void JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf);
313 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
314 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
315 Query *parse, const char *str);
316 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
317 HintKeyword hint_keyword);
318 static void LeadingHintDelete(LeadingHint *hint);
319 static void LeadingHintDump(LeadingHint *hint, StringInfo buf);
320 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
321 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
322 Query *parse, const char *str);
323 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
324 HintKeyword hint_keyword);
325 static void SetHintDelete(SetHint *hint);
326 static void SetHintDump(SetHint *hint, StringInfo buf);
327 static int SetHintCmp(const SetHint *a, const SetHint *b);
328 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
331 static void dump_quote_value(StringInfo buf, const char *value);
333 static const char *parse_quote_value_term_char(const char *str, char **word,
334 bool truncate, char term_char);
336 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
339 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
340 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
341 ListCell *other_rels);
342 static void make_rels_by_clauseless_joins(PlannerInfo *root,
344 ListCell *other_rels);
345 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
346 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
347 Index rti, RangeTblEntry *rte);
348 #if PG_VERSION_NUM >= 90200
349 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
350 List *live_childrels,
351 List *all_child_pathkeys);
353 static List *accumulate_append_subpath(List *subpaths, Path *path);
354 #if PG_VERSION_NUM < 90200
355 static void set_dummy_rel_pathlist(RelOptInfo *rel);
357 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
361 static bool pg_hint_plan_enable_hint = true;
362 static bool pg_hint_plan_debug_print = false;
363 static int pg_hint_plan_parse_messages = INFO;
365 static const struct config_enum_entry parse_messages_level_options[] = {
366 {"debug", DEBUG2, true},
367 {"debug5", DEBUG5, false},
368 {"debug4", DEBUG4, false},
369 {"debug3", DEBUG3, false},
370 {"debug2", DEBUG2, false},
371 {"debug1", DEBUG1, false},
373 {"info", INFO, false},
374 {"notice", NOTICE, false},
375 {"warning", WARNING, false},
376 {"error", ERROR, false},
378 * {"fatal", FATAL, true},
379 * {"panic", PANIC, true},
384 /* Saved hook values in case of unload */
385 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
386 static planner_hook_type prev_planner = NULL;
387 static get_relation_info_hook_type prev_get_relation_info = NULL;
388 static join_search_hook_type prev_join_search = NULL;
390 /* Hold reference to currently active hint */
391 static HintState *current_hint = NULL;
394 * List of hint contexts. We treat the head of the list as the Top of the
395 * context stack, so current_hint always points the first element of this list.
397 static List *HintStateStack = NIL;
400 * Holds statement name during executing EXECUTE command. NULL for other
403 static char *stmt_name = NULL;
405 static const HintParser parsers[] = {
406 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
407 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
408 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
409 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
410 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
411 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
412 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
413 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
414 #if PG_VERSION_NUM >= 90200
415 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
416 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
418 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
419 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
420 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
421 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
422 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
423 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
424 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
425 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
426 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
430 * Module load callbacks
435 /* Define custom GUC variables. */
436 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
437 "Force planner to use plans specified in the hint comment preceding to the query.",
439 &pg_hint_plan_enable_hint,
447 DefineCustomBoolVariable("pg_hint_plan.debug_print",
448 "Logs results of hint parsing.",
450 &pg_hint_plan_debug_print,
458 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
459 "Message level of parse errors.",
461 &pg_hint_plan_parse_messages,
463 parse_messages_level_options,
471 prev_ProcessUtility = ProcessUtility_hook;
472 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
473 prev_planner = planner_hook;
474 planner_hook = pg_hint_plan_planner;
475 prev_get_relation_info = get_relation_info_hook;
476 get_relation_info_hook = pg_hint_plan_get_relation_info;
477 prev_join_search = join_search_hook;
478 join_search_hook = pg_hint_plan_join_search;
482 * Module unload callback
488 /* Uninstall hooks. */
489 ProcessUtility_hook = prev_ProcessUtility;
490 planner_hook = prev_planner;
491 get_relation_info_hook = prev_get_relation_info;
492 join_search_hook = prev_join_search;
496 * create and delete functions the hint object
500 ScanMethodHintCreate(const char *hint_str, const char *keyword,
501 HintKeyword hint_keyword)
503 ScanMethodHint *hint;
505 hint = palloc(sizeof(ScanMethodHint));
506 hint->base.hint_str = hint_str;
507 hint->base.keyword = keyword;
508 hint->base.hint_keyword = hint_keyword;
509 hint->base.type = HINT_TYPE_SCAN_METHOD;
510 hint->base.state = HINT_STATE_NOTUSED;
511 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
512 hint->base.dump_func = (HintDumpFunction) ScanMethodHintDump;
513 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
514 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
515 hint->relname = NULL;
516 hint->indexnames = NIL;
517 hint->enforce_mask = 0;
519 return (Hint *) hint;
523 ScanMethodHintDelete(ScanMethodHint *hint)
529 pfree(hint->relname);
530 list_free_deep(hint->indexnames);
535 JoinMethodHintCreate(const char *hint_str, const char *keyword,
536 HintKeyword hint_keyword)
538 JoinMethodHint *hint;
540 hint = palloc(sizeof(JoinMethodHint));
541 hint->base.hint_str = hint_str;
542 hint->base.keyword = keyword;
543 hint->base.hint_keyword = hint_keyword;
544 hint->base.type = HINT_TYPE_JOIN_METHOD;
545 hint->base.state = HINT_STATE_NOTUSED;
546 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
547 hint->base.dump_func = (HintDumpFunction) JoinMethodHintDump;
548 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
549 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
551 hint->inner_nrels = 0;
552 hint->relnames = NULL;
553 hint->enforce_mask = 0;
554 hint->joinrelids = NULL;
555 hint->inner_joinrelids = NULL;
557 return (Hint *) hint;
561 JoinMethodHintDelete(JoinMethodHint *hint)
570 for (i = 0; i < hint->nrels; i++)
571 pfree(hint->relnames[i]);
572 pfree(hint->relnames);
575 bms_free(hint->joinrelids);
576 bms_free(hint->inner_joinrelids);
581 LeadingHintCreate(const char *hint_str, const char *keyword,
582 HintKeyword hint_keyword)
586 hint = palloc(sizeof(LeadingHint));
587 hint->base.hint_str = hint_str;
588 hint->base.keyword = keyword;
589 hint->base.hint_keyword = hint_keyword;
590 hint->base.type = HINT_TYPE_LEADING;
591 hint->base.state = HINT_STATE_NOTUSED;
592 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
593 hint->base.dump_func = (HintDumpFunction) LeadingHintDump;
594 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
595 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
596 hint->relations = NIL;
597 hint->outer_inner = NULL;
599 return (Hint *) hint;
603 LeadingHintDelete(LeadingHint *hint)
608 list_free_deep(hint->relations);
609 free(hint->outer_inner);
614 SetHintCreate(const char *hint_str, const char *keyword,
615 HintKeyword hint_keyword)
619 hint = palloc(sizeof(SetHint));
620 hint->base.hint_str = hint_str;
621 hint->base.keyword = keyword;
622 hint->base.hint_keyword = hint_keyword;
623 hint->base.type = HINT_TYPE_SET;
624 hint->base.state = HINT_STATE_NOTUSED;
625 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
626 hint->base.dump_func = (HintDumpFunction) SetHintDump;
627 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
628 hint->base.parse_func = (HintParseFunction) SetHintParse;
633 return (Hint *) hint;
637 SetHintDelete(SetHint *hint)
647 list_free(hint->words);
652 HintStateCreate(void)
656 hstate = palloc(sizeof(HintState));
657 hstate->hint_str = NULL;
658 hstate->nall_hints = 0;
659 hstate->max_all_hints = 0;
660 hstate->all_hints = NULL;
661 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
662 hstate->scan_hints = NULL;
663 hstate->init_scan_mask = 0;
664 hstate->parent_relid = 0;
665 hstate->parent_hint = NULL;
666 hstate->join_hints = NULL;
667 hstate->init_join_mask = 0;
668 hstate->join_hint_level = NULL;
669 hstate->leading_hint = NULL;
670 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
671 hstate->set_hints = NULL;
677 HintStateDelete(HintState *hstate)
684 if (hstate->hint_str)
685 pfree(hstate->hint_str);
687 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
688 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
689 if (hstate->all_hints)
690 pfree(hstate->all_hints);
698 * Quote value as needed and dump it to buf.
701 dump_quote_value(StringInfo buf, const char *value)
703 bool need_quote = false;
706 for (str = value; *str != '\0'; str++)
708 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
711 appendStringInfoCharMacro(buf, '"');
716 for (str = value; *str != '\0'; str++)
719 appendStringInfoCharMacro(buf, '"');
721 appendStringInfoCharMacro(buf, *str);
725 appendStringInfoCharMacro(buf, '"');
729 ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf)
733 appendStringInfo(buf, "%s(", hint->base.keyword);
734 if (hint->relname != NULL)
736 dump_quote_value(buf, hint->relname);
737 foreach(l, hint->indexnames)
739 appendStringInfoCharMacro(buf, ' ');
740 dump_quote_value(buf, (char *) lfirst(l));
743 appendStringInfoString(buf, ")\n");
747 JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf)
751 appendStringInfo(buf, "%s(", hint->base.keyword);
752 if (hint->relnames != NULL)
754 dump_quote_value(buf, hint->relnames[0]);
755 for (i = 1; i < hint->nrels; i++)
757 appendStringInfoCharMacro(buf, ' ');
758 dump_quote_value(buf, hint->relnames[i]);
761 appendStringInfoString(buf, ")\n");
766 OuterInnerDump(OuterInnerRels *outer_inner, StringInfo buf)
768 if (outer_inner->relation == NULL)
775 appendStringInfoCharMacro(buf, '(');
776 foreach(l, outer_inner->outer_inner_pair)
781 appendStringInfoCharMacro(buf, ' ');
783 OuterInnerDump(lfirst(l), buf);
786 appendStringInfoCharMacro(buf, ')');
789 dump_quote_value(buf, outer_inner->relation);
793 LeadingHintDump(LeadingHint *hint, StringInfo buf)
798 appendStringInfo(buf, "%s(", HINT_LEADING);
800 if (hint->outer_inner == NULL)
802 foreach(l, hint->relations)
807 appendStringInfoCharMacro(buf, ' ');
809 dump_quote_value(buf, (char *) lfirst(l));
813 OuterInnerDump(hint->outer_inner, buf);
815 appendStringInfoString(buf, ")\n");
819 SetHintDump(SetHint *hint, StringInfo buf)
821 bool is_first = true;
824 appendStringInfo(buf, "%s(", HINT_SET);
825 foreach(l, hint->words)
830 appendStringInfoCharMacro(buf, ' ');
832 dump_quote_value(buf, (char *) lfirst(l));
834 appendStringInfo(buf, ")\n");
838 all_hint_dump(HintState *hstate, StringInfo buf, const char *title,
843 appendStringInfo(buf, "%s:\n", title);
844 for (i = 0; i < hstate->nall_hints; i++)
846 if (hstate->all_hints[i]->state != state)
849 hstate->all_hints[i]->dump_func(hstate->all_hints[i], buf);
854 HintStateDump(HintState *hstate)
860 elog(LOG, "pg_hint_plan:\nno hint");
864 initStringInfo(&buf);
866 appendStringInfoString(&buf, "pg_hint_plan:\n");
867 all_hint_dump(hstate, &buf, "used hint", HINT_STATE_USED);
868 all_hint_dump(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
869 all_hint_dump(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
870 all_hint_dump(hstate, &buf, "error hint", HINT_STATE_ERROR);
872 elog(LOG, "%s", buf.data);
882 RelnameCmp(const void *a, const void *b)
884 const char *relnamea = *((const char **) a);
885 const char *relnameb = *((const char **) b);
887 return strcmp(relnamea, relnameb);
891 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
893 return RelnameCmp(&a->relname, &b->relname);
897 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
901 if (a->nrels != b->nrels)
902 return a->nrels - b->nrels;
904 for (i = 0; i < a->nrels; i++)
907 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
915 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
921 SetHintCmp(const SetHint *a, const SetHint *b)
923 return strcmp(a->name, b->name);
927 HintCmp(const void *a, const void *b)
929 const Hint *hinta = *((const Hint **) a);
930 const Hint *hintb = *((const Hint **) b);
932 if (hinta->type != hintb->type)
933 return hinta->type - hintb->type;
934 if (hinta->state == HINT_STATE_ERROR)
936 if (hintb->state == HINT_STATE_ERROR)
938 return hinta->cmp_func(hinta, hintb);
942 * Returns byte offset of hint b from hint a. If hint a was specified before
943 * b, positive value is returned.
946 HintCmpWithPos(const void *a, const void *b)
948 const Hint *hinta = *((const Hint **) a);
949 const Hint *hintb = *((const Hint **) b);
952 result = HintCmp(a, b);
954 result = hinta->hint_str - hintb->hint_str;
963 parse_keyword(const char *str, StringInfo buf)
967 while (!isspace(*str) && *str != '(' && *str != '\0')
968 appendStringInfoCharMacro(buf, *str++);
974 skip_parenthesis(const char *str, char parenthesis)
978 if (*str != parenthesis)
980 if (parenthesis == '(')
981 hint_ereport(str, ("Opening parenthesis is necessary."));
982 else if (parenthesis == ')')
983 hint_ereport(str, ("Closing parenthesis is necessary."));
994 * Parse a token from str, and store malloc'd copy into word. A token can be
995 * quoted with '"'. Return value is pointer to unparsed portion of original
996 * string, or NULL if an error occurred.
998 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1001 parse_quote_value(const char *str, char **word, bool truncate)
1003 return parse_quote_value_term_char(str, word, truncate, '\0');
1007 * In term_char, We specified the special character which a terminal of a word.
1008 * When we do not have a special character, We specified '\0'.
1011 parse_quote_value_term_char(const char *str, char **word, bool truncate,
1017 /* Skip leading spaces. */
1020 initStringInfo(&buf);
1033 /* Double quotation must be closed. */
1037 hint_ereport(str, ("Unterminated quoted string."));
1042 * Skip escaped double quotation.
1044 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1045 * block comments) to be an object name, so users must specify
1046 * alias for such object names.
1048 * Those special names can be allowed if we care escaped slashes
1049 * and asterisks, but we don't.
1058 else if (isspace(*str) || *str == ')' || *str == '"' || *str == '\0' ||
1062 appendStringInfoCharMacro(&buf, *str++);
1067 hint_ereport(str, ("Zero-length delimited string."));
1074 /* Truncate name if it's too long */
1076 truncate_identifier(buf.data, strlen(buf.data), true);
1083 static OuterInnerRels *
1084 OuterInnerRelsCreate(OuterInnerRels *outer_inner, char *name, List *outer_inner_list)
1086 outer_inner = palloc(sizeof(OuterInnerRels));
1087 outer_inner->relation = name;
1088 outer_inner->outer_inner_pair = outer_inner_list;
1094 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1097 bool truncate = true;
1099 OuterInnerRels *outer_inner_rels;
1100 outer_inner_rels = NULL;
1104 /* Store words in parentheses into outer_inner_list. */
1105 while(*str != ')' && *str != '\0')
1110 outer_inner_rels = OuterInnerRelsCreate(outer_inner_rels,
1113 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1115 else if ((str = parse_quote_value_term_char(str, &name, truncate, '(')) == NULL)
1117 list_free((*outer_inner)->outer_inner_pair);
1121 outer_inner_rels = OuterInnerRelsCreate(outer_inner_rels, name, NIL);
1123 (*outer_inner)->outer_inner_pair = lappend(
1124 (*outer_inner)->outer_inner_pair,
1135 parse_parentheses_Leading(const char *str, List **name_list,
1136 OuterInnerRels **outer_inner)
1139 bool truncate = true;
1141 if ((str = skip_parenthesis(str, '(')) == NULL)
1149 *outer_inner = OuterInnerRelsCreate(*outer_inner, NULL, NIL);
1150 str = parse_parentheses_Leading_in(str, outer_inner);
1154 /* Store words in parentheses into name_list. */
1155 while(*str != ')' && *str != '\0')
1157 if ((str = parse_quote_value(str, &name, truncate)) == NULL)
1159 list_free(*name_list);
1163 *name_list = lappend(*name_list, name);
1168 if ((str = skip_parenthesis(str, ')')) == NULL)
1174 parse_parentheses(const char *str, List **name_list, HintType type)
1177 bool truncate = true;
1179 if ((str = skip_parenthesis(str, '(')) == NULL)
1184 /* Store words in parentheses into name_list. */
1185 while(*str != ')' && *str != '\0')
1187 if ((str = parse_quote_value(str, &name, truncate)) == NULL)
1189 list_free(*name_list);
1193 *name_list = lappend(*name_list, name);
1196 if (type == HINT_TYPE_SET)
1202 if ((str = skip_parenthesis(str, ')')) == NULL)
1208 parse_hints(HintState *hstate, Query *parse, const char *str)
1213 initStringInfo(&buf);
1214 while (*str != '\0')
1216 const HintParser *parser;
1218 /* in error message, we output the comment including the keyword. */
1219 head = (char *) str;
1221 /* parse only the keyword of the hint. */
1222 resetStringInfo(&buf);
1223 str = parse_keyword(str, &buf);
1225 for (parser = parsers; parser->keyword != NULL; parser++)
1227 char *keyword = parser->keyword;
1230 if (strcasecmp(buf.data, keyword) != 0)
1233 hint = parser->create_func(head, keyword, parser->hint_keyword);
1235 /* parser of each hint does parse in a parenthesis. */
1236 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1238 hint->delete_func(hint);
1244 * Add hint information into all_hints array. If we don't have
1245 * enough space, double the array.
1247 if (hstate->nall_hints == 0)
1249 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1250 hstate->all_hints = (Hint **)
1251 palloc(sizeof(Hint *) * hstate->max_all_hints);
1253 else if (hstate->nall_hints == hstate->max_all_hints)
1255 hstate->max_all_hints *= 2;
1256 hstate->all_hints = (Hint **)
1257 repalloc(hstate->all_hints,
1258 sizeof(Hint *) * hstate->max_all_hints);
1261 hstate->all_hints[hstate->nall_hints] = hint;
1262 hstate->nall_hints++;
1269 if (parser->keyword == NULL)
1272 ("Unrecognized hint keyword \"%s\".", buf.data));
1282 * Do basic parsing of the query head comment.
1285 parse_head_comment(Query *parse)
1294 /* get client-supplied query string. */
1297 PreparedStatement *entry;
1299 entry = FetchPreparedStatement(stmt_name, true);
1300 p = entry->plansource->query_string;
1303 p = debug_query_string;
1308 /* extract query head comment. */
1309 len = strlen(HINT_START);
1311 if (strncmp(p, HINT_START, len))
1318 /* find hint end keyword. */
1319 if ((tail = strstr(p, HINT_END)) == NULL)
1321 hint_ereport(head, ("Unterminated block comment."));
1325 /* We don't support nested block comments. */
1326 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1328 hint_ereport(head, ("Nested block comments are not supported."));
1332 /* Make a copy of hint. */
1334 head = palloc(len + 1);
1335 memcpy(head, p, len);
1339 hstate = HintStateCreate();
1340 hstate->hint_str = head;
1342 /* parse each hint. */
1343 parse_hints(hstate, parse, p);
1345 /* When nothing specified a hint, we free HintState and returns NULL. */
1346 if (hstate->nall_hints == 0)
1348 HintStateDelete(hstate);
1352 /* Sort hints in order of original position. */
1353 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1356 /* Count number of hints per hint-type. */
1357 for (i = 0; i < hstate->nall_hints; i++)
1359 Hint *cur_hint = hstate->all_hints[i];
1360 hstate->num_hints[cur_hint->type]++;
1364 * If an object (or a set of objects) has multiple hints of same hint-type,
1365 * only the last hint is valid and others are igonred in planning.
1366 * Hints except the last are marked as 'duplicated' to remember the order.
1368 for (i = 0; i < hstate->nall_hints - 1; i++)
1370 Hint *cur_hint = hstate->all_hints[i];
1371 Hint *next_hint = hstate->all_hints[i + 1];
1374 * TODO : Leadingヒントの重複チェックは、transform_join_hints関数の実行
1377 if (i >= hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1378 hstate->num_hints[HINT_TYPE_JOIN_METHOD] &&
1379 i < hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1380 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1381 hstate->num_hints[HINT_TYPE_LEADING])
1385 * Note that we need to pass addresses of hint pointers, because
1386 * HintCmp is designed to sort array of Hint* by qsort.
1388 if (HintCmp(&cur_hint, &next_hint) == 0)
1390 hint_ereport(cur_hint->hint_str,
1391 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1392 cur_hint->state = HINT_STATE_DUPLICATION;
1397 * Make sure that per-type array pointers point proper position in the
1398 * array which consists of all hints.
1400 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1401 hstate->join_hints = (JoinMethodHint **) hstate->all_hints +
1402 hstate->num_hints[HINT_TYPE_SCAN_METHOD];
1403 hstate->leading_hint = (LeadingHint **) hstate->all_hints +
1404 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1405 hstate->num_hints[HINT_TYPE_JOIN_METHOD];
1406 hstate->set_hints = (SetHint **) hstate->all_hints +
1407 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1408 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1409 hstate->num_hints[HINT_TYPE_LEADING];
1415 * Parse inside of parentheses of scan-method hints.
1418 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1421 const char *keyword = hint->base.keyword;
1422 HintKeyword hint_keyword = hint->base.hint_keyword;
1423 List *name_list = NIL;
1426 if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1429 /* Parse relation name and index name(s) if given hint accepts. */
1430 length = list_length(name_list);
1433 hint->relname = linitial(name_list);
1434 hint->indexnames = list_delete_first(name_list);
1436 /* check whether the hint accepts index name(s). */
1437 if (hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1438 #if PG_VERSION_NUM >= 90200
1439 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1441 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1445 ("%s hint accepts only one relation.",
1446 hint->base.keyword));
1447 hint->base.state = HINT_STATE_ERROR;
1454 ("%s hint requires a relation.",
1455 hint->base.keyword));
1456 hint->base.state = HINT_STATE_ERROR;
1460 /* Set a bit for specified hint. */
1461 switch (hint_keyword)
1463 case HINT_KEYWORD_SEQSCAN:
1464 hint->enforce_mask = ENABLE_SEQSCAN;
1466 case HINT_KEYWORD_INDEXSCAN:
1467 hint->enforce_mask = ENABLE_INDEXSCAN;
1469 case HINT_KEYWORD_BITMAPSCAN:
1470 hint->enforce_mask = ENABLE_BITMAPSCAN;
1472 case HINT_KEYWORD_TIDSCAN:
1473 hint->enforce_mask = ENABLE_TIDSCAN;
1475 case HINT_KEYWORD_NOSEQSCAN:
1476 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1478 case HINT_KEYWORD_NOINDEXSCAN:
1479 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1481 case HINT_KEYWORD_NOBITMAPSCAN:
1482 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1484 case HINT_KEYWORD_NOTIDSCAN:
1485 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1487 #if PG_VERSION_NUM >= 90200
1488 case HINT_KEYWORD_INDEXONLYSCAN:
1489 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1491 case HINT_KEYWORD_NOINDEXONLYSCAN:
1492 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1496 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1505 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1508 const char *keyword = hint->base.keyword;
1509 HintKeyword hint_keyword = hint->base.hint_keyword;
1510 List *name_list = NIL;
1512 if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1515 hint->nrels = list_length(name_list);
1517 if (hint->nrels > 0)
1523 * Transform relation names from list to array to sort them with qsort
1526 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1527 foreach (l, name_list)
1529 hint->relnames[i] = lfirst(l);
1534 list_free(name_list);
1536 /* A join hint requires at least two relations */
1537 if (hint->nrels < 2)
1540 ("%s hint requires at least two relations.",
1541 hint->base.keyword));
1542 hint->base.state = HINT_STATE_ERROR;
1546 /* Sort hints in alphabetical order of relation names. */
1547 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1549 switch (hint_keyword)
1551 case HINT_KEYWORD_NESTLOOP:
1552 hint->enforce_mask = ENABLE_NESTLOOP;
1554 case HINT_KEYWORD_MERGEJOIN:
1555 hint->enforce_mask = ENABLE_MERGEJOIN;
1557 case HINT_KEYWORD_HASHJOIN:
1558 hint->enforce_mask = ENABLE_HASHJOIN;
1560 case HINT_KEYWORD_NONESTLOOP:
1561 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1563 case HINT_KEYWORD_NOMERGEJOIN:
1564 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1566 case HINT_KEYWORD_NOHASHJOIN:
1567 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1570 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1579 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1582 if (outer_inner->outer_inner_pair == NIL)
1584 if (outer_inner->relation)
1590 if (list_length(outer_inner->outer_inner_pair) == 2)
1592 foreach(l, outer_inner->outer_inner_pair)
1594 if (!OuterInnerPairCheck(lfirst(l)))
1605 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1608 List *name_list = NIL;
1609 OuterInnerRels *outer_inner = NULL;
1612 parse_parentheses_Leading(str, &name_list, &outer_inner)) == NULL)
1615 hint->relations = name_list;
1616 hint->outer_inner = outer_inner;
1618 /* A Leading hint requires at least two relations */
1619 if (list_length(hint->relations) < 2 && hint->outer_inner == NULL)
1621 hint_ereport(hint->base.hint_str,
1622 ("%s hint requires at least two relations.",
1624 hint->base.state = HINT_STATE_ERROR;
1626 else if (hint->outer_inner != NULL &&
1627 !OuterInnerPairCheck(hint->outer_inner))
1629 hint_ereport(hint->base.hint_str,
1630 ("%s hint requires two sets of relations when parentheses nests.",
1632 hint->base.state = HINT_STATE_ERROR;
1639 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1641 List *name_list = NIL;
1643 if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1646 hint->words = name_list;
1648 /* We need both name and value to set GUC parameter. */
1649 if (list_length(name_list) == 2)
1651 hint->name = linitial(name_list);
1652 hint->value = lsecond(name_list);
1656 hint_ereport(hint->base.hint_str,
1657 ("%s hint requires name and value of GUC parameter.",
1659 hint->base.state = HINT_STATE_ERROR;
1666 * set GUC parameter functions
1670 set_config_option_wrapper(const char *name, const char *value,
1671 GucContext context, GucSource source,
1672 GucAction action, bool changeVal, int elevel)
1675 MemoryContext ccxt = CurrentMemoryContext;
1679 #if PG_VERSION_NUM >= 90200
1680 result = set_config_option(name, value, context, source,
1681 action, changeVal, 0);
1683 result = set_config_option(name, value, context, source,
1691 /* Save error info */
1692 MemoryContextSwitchTo(ccxt);
1693 errdata = CopyErrorData();
1696 ereport(elevel, (errcode(errdata->sqlerrcode),
1697 errmsg("%s", errdata->message),
1698 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1699 errdata->hint ? errhint("%s", errdata->hint) : 0));
1700 FreeErrorData(errdata);
1708 set_config_options(SetHint **options, int noptions, GucContext context)
1713 save_nestlevel = NewGUCNestLevel();
1715 for (i = 0; i < noptions; i++)
1717 SetHint *hint = options[i];
1720 if (!hint_state_enabled(hint))
1723 result = set_config_option_wrapper(hint->name, hint->value, context,
1724 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1725 pg_hint_plan_parse_messages);
1727 hint->base.state = HINT_STATE_USED;
1729 hint->base.state = HINT_STATE_ERROR;
1732 return save_nestlevel;
1735 #define SET_CONFIG_OPTION(name, type_bits) \
1736 set_config_option_wrapper((name), \
1737 (mask & (type_bits)) ? "true" : "false", \
1738 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1741 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1745 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1746 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1747 #if PG_VERSION_NUM >= 90200
1748 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1751 mask = enforce_mask;
1753 mask = enforce_mask & current_hint->init_scan_mask;
1755 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1756 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1757 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1758 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1759 #if PG_VERSION_NUM >= 90200
1760 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1765 set_join_config_options(unsigned char enforce_mask, GucContext context)
1769 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1770 enforce_mask == ENABLE_HASHJOIN)
1771 mask = enforce_mask;
1773 mask = enforce_mask & current_hint->init_join_mask;
1775 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1776 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1777 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1781 * pg_hint_plan hook functions
1785 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1786 ParamListInfo params, bool isTopLevel,
1787 DestReceiver *dest, char *completionTag)
1791 if (!pg_hint_plan_enable_hint)
1793 if (prev_ProcessUtility)
1794 (*prev_ProcessUtility) (parsetree, queryString, params,
1795 isTopLevel, dest, completionTag);
1797 standard_ProcessUtility(parsetree, queryString, params,
1798 isTopLevel, dest, completionTag);
1804 if (IsA(node, ExplainStmt))
1807 * Draw out parse tree of actual query from Query struct of EXPLAIN
1813 stmt = (ExplainStmt *) node;
1815 Assert(IsA(stmt->query, Query));
1816 query = (Query *) stmt->query;
1818 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1819 node = query->utilityStmt;
1823 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
1824 * specified to preceding PREPARE command to use it as source of hints.
1826 if (IsA(node, ExecuteStmt))
1830 stmt = (ExecuteStmt *) node;
1831 stmt_name = stmt->name;
1833 #if PG_VERSION_NUM >= 90200
1835 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
1838 if (IsA(node, CreateTableAsStmt))
1840 CreateTableAsStmt *stmt;
1843 stmt = (CreateTableAsStmt *) node;
1844 Assert(IsA(stmt->query, Query));
1845 query = (Query *) stmt->query;
1847 if (query->commandType == CMD_UTILITY &&
1848 IsA(query->utilityStmt, ExecuteStmt))
1850 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
1851 stmt_name = estmt->name;
1859 if (prev_ProcessUtility)
1860 (*prev_ProcessUtility) (parsetree, queryString, params,
1861 isTopLevel, dest, completionTag);
1863 standard_ProcessUtility(parsetree, queryString, params,
1864 isTopLevel, dest, completionTag);
1878 if (prev_ProcessUtility)
1879 (*prev_ProcessUtility) (parsetree, queryString, params,
1880 isTopLevel, dest, completionTag);
1882 standard_ProcessUtility(parsetree, queryString, params,
1883 isTopLevel, dest, completionTag);
1887 * Push a hint into hint stack which is implemented with List struct. Head of
1888 * list is top of stack.
1891 push_hint(HintState *hstate)
1893 /* Prepend new hint to the list means pushing to stack. */
1894 HintStateStack = lcons(hstate, HintStateStack);
1896 /* Pushed hint is the one which should be used hereafter. */
1897 current_hint = hstate;
1900 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
1904 /* Hint stack must not be empty. */
1905 if(HintStateStack == NIL)
1906 elog(ERROR, "hint stack is empty");
1909 * Take a hint at the head from the list, and free it. Switch current_hint
1910 * to point new head (NULL if the list is empty).
1912 HintStateStack = list_delete_first(HintStateStack);
1913 HintStateDelete(current_hint);
1914 if(HintStateStack == NIL)
1915 current_hint = NULL;
1917 current_hint = (HintState *) lfirst(list_head(HintStateStack));
1920 static PlannedStmt *
1921 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1924 PlannedStmt *result;
1928 * Use standard planner if pg_hint_plan is disabled. Other hook functions
1929 * try to change plan with current_hint if any, so set it to NULL.
1931 if (!pg_hint_plan_enable_hint)
1933 current_hint = NULL;
1936 return (*prev_planner) (parse, cursorOptions, boundParams);
1938 return standard_planner(parse, cursorOptions, boundParams);
1941 /* Create hint struct from parse tree. */
1942 hstate = parse_head_comment(parse);
1945 * Use standard planner if the statement has not valid hint. Other hook
1946 * functions try to change plan with current_hint if any, so set it to
1951 current_hint = NULL;
1954 return (*prev_planner) (parse, cursorOptions, boundParams);
1956 return standard_planner(parse, cursorOptions, boundParams);
1960 * Push new hint struct to the hint stack to disable previous hint context.
1964 /* Set GUC parameters which are specified with Set hint. */
1965 save_nestlevel = set_config_options(current_hint->set_hints,
1966 current_hint->num_hints[HINT_TYPE_SET],
1967 current_hint->context);
1970 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
1971 if (enable_indexscan)
1972 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
1973 if (enable_bitmapscan)
1974 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
1976 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
1977 #if PG_VERSION_NUM >= 90200
1978 if (enable_indexonlyscan)
1979 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
1981 if (enable_nestloop)
1982 current_hint->init_join_mask |= ENABLE_NESTLOOP;
1983 if (enable_mergejoin)
1984 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
1985 if (enable_hashjoin)
1986 current_hint->init_join_mask |= ENABLE_HASHJOIN;
1989 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
1990 * state when this planner started when error occurred in planner.
1995 result = (*prev_planner) (parse, cursorOptions, boundParams);
1997 result = standard_planner(parse, cursorOptions, boundParams);
2002 * Rollback changes of GUC parameters, and pop current hint context
2003 * from hint stack to rewind the state.
2005 AtEOXact_GUC(true, save_nestlevel);
2011 /* Print hint in debug mode. */
2012 if (pg_hint_plan_debug_print)
2013 HintStateDump(current_hint);
2016 * Rollback changes of GUC parameters, and pop current hint context from
2017 * hint stack to rewind the state.
2019 AtEOXact_GUC(true, save_nestlevel);
2026 * Return scan method hint which matches given aliasname.
2028 static ScanMethodHint *
2029 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2035 * We can't apply scan method hint if the relation is:
2036 * - not a base relation
2037 * - not an ordinary relation (such as join and subquery)
2039 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2042 rte = root->simple_rte_array[rel->relid];
2044 /* We can't force scan method of foreign tables */
2045 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2048 /* Find scan method hint, which matches given names, from the list. */
2049 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2051 ScanMethodHint *hint = current_hint->scan_hints[i];
2053 /* We ignore disabled hints. */
2054 if (!hint_state_enabled(hint))
2057 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2065 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2073 * We delete all the IndexOptInfo list and prevent you from being usable by
2076 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2077 hint->enforce_mask == ENABLE_TIDSCAN)
2079 list_free_deep(rel->indexlist);
2080 rel->indexlist = NIL;
2081 hint->base.state = HINT_STATE_USED;
2087 * When a list of indexes is not specified, we just use all indexes.
2089 if (hint->indexnames == NIL)
2093 * Leaving only an specified index, we delete it from a IndexOptInfo list
2097 if (pg_hint_plan_debug_print)
2098 initStringInfo(&buf);
2100 for (cell = list_head(rel->indexlist); cell; cell = next)
2102 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2103 char *indexname = get_rel_name(info->indexoid);
2105 bool use_index = false;
2109 foreach(l, hint->indexnames)
2111 if (RelnameCmp(&indexname, &lfirst(l)) == 0)
2114 if (pg_hint_plan_debug_print)
2116 appendStringInfoCharMacro(&buf, ' ');
2117 dump_quote_value(&buf, indexname);
2125 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2132 if (pg_hint_plan_debug_print)
2135 StringInfoData rel_buf;
2137 if (OidIsValid(relationObjectId))
2138 relname = get_rel_name(relationObjectId);
2140 relname = hint->relname;
2142 initStringInfo(&rel_buf);
2143 dump_quote_value(&rel_buf, relname);
2146 (errmsg("available indexes for %s(%s):%s",
2151 pfree(rel_buf.data);
2156 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2157 bool inhparent, RelOptInfo *rel)
2159 ScanMethodHint *hint;
2161 if (prev_get_relation_info)
2162 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2164 /* Do nothing if we don't have valid hint in this context. */
2170 /* store does relids of parent table. */
2171 current_hint->parent_relid = rel->relid;
2173 else if (current_hint->parent_relid != 0)
2176 * We use the same GUC parameter if this table is the child table of a
2177 * table called pg_hint_plan_get_relation_info just before that.
2181 /* append_rel_list contains all append rels; ignore others */
2182 foreach(l, root->append_rel_list)
2184 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2186 /* This rel is child table. */
2187 if (appinfo->parent_relid == current_hint->parent_relid &&
2188 appinfo->child_relid == rel->relid)
2190 if (current_hint->parent_hint)
2191 delete_indexes(current_hint->parent_hint, rel,
2198 /* This rel is not inherit table. */
2199 current_hint->parent_relid = 0;
2200 current_hint->parent_hint = NULL;
2204 * If scan method hint was given, reset GUC parameters which control
2205 * planner behavior about choosing scan methods.
2207 if ((hint = find_scan_hint(root, rel)) == NULL)
2209 set_scan_config_options(current_hint->init_scan_mask,
2210 current_hint->context);
2213 set_scan_config_options(hint->enforce_mask, current_hint->context);
2214 hint->base.state = HINT_STATE_USED;
2216 current_hint->parent_hint = hint;
2218 delete_indexes(hint, rel, InvalidOid);
2222 * Return index of relation which matches given aliasname, or 0 if not found.
2223 * If same aliasname was used multiple times in a query, return -1.
2226 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
2232 for (i = 1; i < root->simple_rel_array_size; i++)
2236 if (root->simple_rel_array[i] == NULL)
2239 Assert(i == root->simple_rel_array[i]->relid);
2241 if (RelnameCmp(&aliasname,
2242 &root->simple_rte_array[i]->eref->aliasname) != 0)
2245 foreach(l, initial_rels)
2247 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2249 if (rel->reloptkind == RELOPT_BASEREL)
2251 if (rel->relid != i)
2256 Assert(rel->reloptkind == RELOPT_JOINREL);
2258 if (!bms_is_member(i, rel->relids))
2265 ("Relation name \"%s\" is ambiguous.",
2280 * Return join hint which matches given joinrelids.
2282 static JoinMethodHint *
2283 find_join_hint(Relids joinrelids)
2288 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
2290 foreach(l, join_hint)
2292 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
2294 if (bms_equal(joinrelids, hint->joinrelids))
2302 OuterInnerList(OuterInnerRels *outer_inner)
2304 List *outer_inner_list = NIL;
2306 OuterInnerRels *outer_inner_rels;
2308 foreach(l, outer_inner->outer_inner_pair)
2310 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2312 if (outer_inner_rels->relation != NULL)
2313 outer_inner_list = lappend(outer_inner_list,
2314 outer_inner_rels->relation);
2316 outer_inner_list = list_concat(outer_inner_list,
2317 OuterInnerList(outer_inner_rels));
2319 return outer_inner_list;
2323 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
2324 PlannerInfo *root, List *initial_rels, HintState *hstate, int *njoinrels,
2327 OuterInnerRels *outer_rels;
2328 OuterInnerRels *inner_rels;
2329 Relids outer_relids;
2330 Relids inner_relids;
2332 JoinMethodHint *hint;
2334 if (outer_inner->relation != NULL)
2337 return bms_make_singleton(
2338 find_relid_aliasname(root, outer_inner->relation,
2340 leading_hint->base.hint_str));
2343 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
2344 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
2346 outer_relids = OuterInnerJoinCreate(outer_rels,
2353 inner_relids = OuterInnerJoinCreate(inner_rels,
2361 join_relids = bms_add_members(outer_relids, inner_relids);
2363 if (bms_num_members(join_relids) > nbaserel || *njoinrels > nbaserel)
2367 * If we don't have join method hint, create new one for the
2368 * join combination with all join methods are enabled.
2370 hint = find_join_hint(join_relids);
2374 * Here relnames is not set, since Relids bitmap is sufficient to
2375 * control paths of this query afterward.
2377 hint = (JoinMethodHint *) JoinMethodHintCreate(
2378 leading_hint->base.hint_str,
2380 HINT_KEYWORD_LEADING);
2381 hint->base.state = HINT_STATE_USED;
2382 hint->nrels = bms_num_members(join_relids);
2383 hint->enforce_mask = ENABLE_ALL_JOIN;
2384 hint->joinrelids = bms_copy(join_relids);
2385 hint->inner_nrels = bms_num_members(inner_relids);
2386 hint->inner_joinrelids = bms_copy(inner_relids);
2388 hstate->join_hint_level[hint->nrels] =
2389 lappend(hstate->join_hint_level[hint->nrels], hint);
2393 hint->inner_nrels = bms_num_members(inner_relids);
2394 hint->inner_joinrelids = bms_copy(inner_relids);
2401 * Transform join method hint into handy form.
2403 * - create bitmap of relids from alias names, to make it easier to check
2404 * whether a join path matches a join method hint.
2405 * - add join method hints which are necessary to enforce join order
2406 * specified by Leading hint
2409 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2410 List *initial_rels, JoinMethodHint **join_method_hints,
2419 bool exist_effective_leading;
2422 * Create bitmap of relids from alias names for each join method hint.
2423 * Bitmaps are more handy than strings in join searching.
2425 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2427 JoinMethodHint *hint = hstate->join_hints[i];
2430 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
2433 bms_free(hint->joinrelids);
2434 hint->joinrelids = NULL;
2436 for (j = 0; j < hint->nrels; j++)
2438 relname = hint->relnames[j];
2440 relid = find_relid_aliasname(root, relname, initial_rels,
2441 hint->base.hint_str);
2444 hint->base.state = HINT_STATE_ERROR;
2449 if (bms_is_member(relid, hint->joinrelids))
2451 hint_ereport(hint->base.hint_str,
2452 ("Relation name \"%s\" is duplicated.", relname));
2453 hint->base.state = HINT_STATE_ERROR;
2457 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
2460 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
2463 hstate->join_hint_level[hint->nrels] =
2464 lappend(hstate->join_hint_level[hint->nrels], hint);
2467 /* Do nothing if no Leading hint was supplied. */
2468 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2472 * Decide to use Leading hint。
2474 exist_effective_leading = false;
2475 for (i = hstate->num_hints[HINT_TYPE_LEADING] - 1; i >= 0; i--) {
2476 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
2481 if (leading_hint->base.state == HINT_STATE_ERROR)
2484 if (leading_hint->outer_inner != NULL)
2485 relname_list = OuterInnerList(leading_hint->outer_inner);
2487 relname_list = leading_hint->relations;
2492 foreach(l, relname_list)
2494 relname = (char *)lfirst(l);;
2496 relid = find_relid_aliasname(root, relname, initial_rels,
2497 leading_hint->base.hint_str);
2499 leading_hint->base.state = HINT_STATE_ERROR;
2504 if (bms_is_member(relid, relids))
2506 hint_ereport(leading_hint->base.hint_str,
2507 ("Relation name \"%s\" is duplicated.", relname));
2508 leading_hint->base.state = HINT_STATE_ERROR;
2512 relids = bms_add_member(relids, relid);
2515 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
2518 if (exist_effective_leading)
2520 hint_ereport(leading_hint->base.hint_str,
2521 ("Conflict %s hint.", HintTypeName[leading_hint->base.type]));
2522 leading_hint->base.state = HINT_STATE_DUPLICATION;
2526 leading_hint->base.state = HINT_STATE_USED;
2527 exist_effective_leading = true;
2528 lhint = leading_hint;
2531 if (exist_effective_leading == false)
2535 * We need join method hints which fit specified join order in every join
2536 * level. For example, Leading(A B C) virtually requires following join
2537 * method hints, if no join method hint supplied:
2539 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
2540 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
2542 * If we already have join method hint which fits specified join order in
2543 * that join level, we leave it as-is and don't add new hints.
2547 if (lhint->outer_inner == NULL)
2549 foreach(l, lhint->relations)
2551 JoinMethodHint *hint;
2553 relname = (char *)lfirst(l);
2556 * Find relid of the relation which has given name. If we have the
2557 * name given in Leading hint multiple times in the join, nothing to
2560 relid = find_relid_aliasname(root, relname, initial_rels,
2563 /* Create bitmap of relids for current join level. */
2564 joinrelids = bms_add_member(joinrelids, relid);
2567 /* We never have join method hint for single relation. */
2572 * If we don't have join method hint, create new one for the
2573 * join combination with all join methods are enabled.
2575 hint = find_join_hint(joinrelids);
2579 * Here relnames is not set, since Relids bitmap is sufficient
2580 * to control paths of this query afterward.
2582 hint = (JoinMethodHint *) JoinMethodHintCreate(
2583 lhint->base.hint_str,
2585 HINT_KEYWORD_LEADING);
2586 hint->base.state = HINT_STATE_USED;
2587 hint->nrels = njoinrels;
2588 hint->enforce_mask = ENABLE_ALL_JOIN;
2589 hint->joinrelids = bms_copy(joinrelids);
2592 join_method_hints[njoinrels] = hint;
2594 if (njoinrels >= nbaserel)
2597 bms_free(joinrelids);
2603 * Delete all join hints which have different combination from Leading
2606 for (i = 2; i <= njoinrels; i++)
2608 list_free(hstate->join_hint_level[i]);
2610 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
2615 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
2624 * Delete all join hints which have different combination from Leading
2627 for (i = 2;i <= nbaserel; i++)
2629 if (hstate->join_hint_level[i] != NIL)
2631 ListCell *prev = NULL;
2632 ListCell *next = NULL;
2633 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
2636 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
2640 if (hint->inner_nrels == 0 &&
2641 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
2642 bms_equal(bms_union(hint->joinrelids, joinrelids),
2645 hstate->join_hint_level[i] =
2646 list_delete_cell(hstate->join_hint_level[i], l,
2655 bms_free(joinrelids);
2661 if (hint_state_enabled(lhint))
2662 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2666 * set_plain_rel_pathlist
2667 * Build access paths for a plain relation (no subquery, no inheritance)
2669 * This function was copied and edited from set_plain_rel_pathlist() in
2670 * src/backend/optimizer/path/allpaths.c
2673 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2675 /* Consider sequential scan */
2676 #if PG_VERSION_NUM >= 90200
2677 add_path(rel, create_seqscan_path(root, rel, NULL));
2679 add_path(rel, create_seqscan_path(root, rel));
2682 /* Consider index scans */
2683 create_index_paths(root, rel);
2685 /* Consider TID scans */
2686 create_tidscan_paths(root, rel);
2688 /* Now find the cheapest of the paths for this rel */
2693 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
2698 foreach(l, initial_rels)
2700 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2702 ScanMethodHint *hint;
2704 /* Skip relations which we can't choose scan method. */
2705 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2708 rte = root->simple_rte_array[rel->relid];
2710 /* We can't force scan method of foreign tables */
2711 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2715 * Create scan paths with GUC parameters which are at the beginning of
2716 * planner if scan method hint is not specified, otherwise use
2717 * specified hints and mark the hint as used.
2719 if ((hint = find_scan_hint(root, rel)) == NULL)
2720 set_scan_config_options(hstate->init_scan_mask,
2724 set_scan_config_options(hint->enforce_mask, hstate->context);
2725 hint->base.state = HINT_STATE_USED;
2728 list_free_deep(rel->pathlist);
2729 rel->pathlist = NIL;
2732 /* It's an "append relation", process accordingly */
2733 set_append_rel_pathlist(root, rel, rel->relid, rte);
2737 set_plain_rel_pathlist(root, rel, rte);
2742 * Restore the GUC variables we set above.
2744 set_scan_config_options(hstate->init_scan_mask, hstate->context);
2748 * wrapper of make_join_rel()
2750 * call make_join_rel() after changing enable_* parameters according to given
2754 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
2757 JoinMethodHint *hint;
2761 joinrelids = bms_union(rel1->relids, rel2->relids);
2762 hint = find_join_hint(joinrelids);
2763 bms_free(joinrelids);
2766 return pg_hint_plan_make_join_rel(root, rel1, rel2);
2768 if (hint->inner_nrels == 0)
2770 save_nestlevel = NewGUCNestLevel();
2772 set_join_config_options(hint->enforce_mask, current_hint->context);
2774 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2775 hint->base.state = HINT_STATE_USED;
2778 * Restore the GUC variables we set above.
2780 AtEOXact_GUC(true, save_nestlevel);
2783 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2792 add_paths_to_joinrel_wrapper(PlannerInfo *root,
2793 RelOptInfo *joinrel,
2794 RelOptInfo *outerrel,
2795 RelOptInfo *innerrel,
2797 SpecialJoinInfo *sjinfo,
2800 ScanMethodHint *scan_hint = NULL;
2802 JoinMethodHint *join_hint;
2805 if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
2807 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
2808 scan_hint->base.state = HINT_STATE_USED;
2811 joinrelids = bms_union(outerrel->relids, innerrel->relids);
2812 join_hint = find_join_hint(joinrelids);
2813 bms_free(joinrelids);
2815 if (join_hint && join_hint->inner_nrels != 0)
2817 save_nestlevel = NewGUCNestLevel();
2819 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
2822 set_join_config_options(join_hint->enforce_mask,
2823 current_hint->context);
2825 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
2826 sjinfo, restrictlist);
2827 join_hint->base.state = HINT_STATE_USED;
2831 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2832 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
2833 sjinfo, restrictlist);
2837 * Restore the GUC variables we set above.
2839 AtEOXact_GUC(true, save_nestlevel);
2842 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
2843 sjinfo, restrictlist);
2845 if (scan_hint != NULL)
2846 set_scan_config_options(current_hint->init_scan_mask,
2847 current_hint->context);
2851 get_num_baserels(List *initial_rels)
2856 foreach(l, initial_rels)
2858 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2860 if (rel->reloptkind == RELOPT_BASEREL)
2862 else if (rel->reloptkind ==RELOPT_JOINREL)
2863 nbaserel+= bms_num_members(rel->relids);
2866 /* other values not expected here */
2867 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
2875 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
2878 JoinMethodHint **join_method_hints;
2879 LeadingHint *leading_hint = NULL;
2885 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
2886 * valid hint is supplied.
2890 if (prev_join_search)
2891 return (*prev_join_search) (root, levels_needed, initial_rels);
2892 else if (enable_geqo && levels_needed >= geqo_threshold)
2893 return geqo(root, levels_needed, initial_rels);
2895 return standard_join_search(root, levels_needed, initial_rels);
2898 /* We apply scan method hint rebuild scan path. */
2899 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
2902 * In the case using GEQO, only scan method hints and Set hints have
2903 * effect. Join method and join order is not controllable by hints.
2905 if (enable_geqo && levels_needed >= geqo_threshold)
2906 return geqo(root, levels_needed, initial_rels);
2908 nbaserel = get_num_baserels(initial_rels);
2909 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
2910 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
2912 transform_join_hints(current_hint, root, nbaserel, initial_rels,
2913 join_method_hints, leading_hint);
2915 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
2917 for (i = 2; i <= nbaserel; i++)
2919 list_free(current_hint->join_hint_level[i]);
2921 /* free Leading hint only */
2922 if (join_method_hints[i] != NULL &&
2923 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
2924 JoinMethodHintDelete(join_method_hints[i]);
2926 pfree(current_hint->join_hint_level);
2927 pfree(join_method_hints);
2929 if (current_hint->num_hints[HINT_TYPE_LEADING] > 0 &&
2930 leading_hint != NULL &&
2931 hint_state_enabled(leading_hint))
2932 set_join_config_options(current_hint->init_join_mask,
2933 current_hint->context);
2940 * Build access paths for a base relation
2942 * This function was copied and edited from set_rel_pathlist() in
2943 * src/backend/optimizer/path/allpaths.c
2946 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
2947 Index rti, RangeTblEntry *rte)
2949 #if PG_VERSION_NUM >= 90200
2950 if (IS_DUMMY_REL(rel))
2952 /* We already proved the relation empty, so nothing more to do */
2959 /* It's an "append relation", process accordingly */
2960 set_append_rel_pathlist(root, rel, rti, rte);
2964 if (rel->rtekind == RTE_RELATION)
2966 if (rte->relkind == RELKIND_RELATION)
2968 /* Plain relation */
2969 set_plain_rel_pathlist(root, rel, rte);
2972 elog(ERROR, "unexpected relkind: %c", rte->relkind);
2975 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
2979 #define standard_join_search pg_hint_plan_standard_join_search
2980 #define join_search_one_level pg_hint_plan_join_search_one_level
2981 #define make_join_rel make_join_rel_wrapper
2984 #undef make_join_rel
2985 #define make_join_rel pg_hint_plan_make_join_rel
2986 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
2987 #include "make_join_rel.c"