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 "miscadmin.h"
14 #include "nodes/nodeFuncs.h"
15 #include "optimizer/clauses.h"
16 #include "optimizer/cost.h"
17 #include "optimizer/geqo.h"
18 #include "optimizer/joininfo.h"
19 #include "optimizer/pathnode.h"
20 #include "optimizer/paths.h"
21 #include "optimizer/plancat.h"
22 #include "optimizer/planner.h"
23 #include "optimizer/prep.h"
24 #include "optimizer/restrictinfo.h"
25 #include "tcop/tcopprot.h"
26 #include "tcop/utility.h"
27 #include "utils/lsyscache.h"
28 #include "utils/memutils.h"
30 #ifdef PG_MODULE_MAGIC
34 #if PG_VERSION_NUM < 90100
35 #error unsupported PostgreSQL version
38 #define BLOCK_COMMENT_START "/*"
39 #define BLOCK_COMMENT_END "*/"
40 #define HINT_COMMENT_KEYWORD "+"
41 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
42 #define HINT_END BLOCK_COMMENT_END
45 #define HINT_SEQSCAN "SeqScan"
46 #define HINT_INDEXSCAN "IndexScan"
47 #define HINT_BITMAPSCAN "BitmapScan"
48 #define HINT_TIDSCAN "TidScan"
49 #define HINT_NOSEQSCAN "NoSeqScan"
50 #define HINT_NOINDEXSCAN "NoIndexScan"
51 #define HINT_NOBITMAPSCAN "NoBitmapScan"
52 #define HINT_NOTIDSCAN "NoTidScan"
53 #if PG_VERSION_NUM >= 90200
54 #define HINT_INDEXONLYSCAN "IndexonlyScan"
55 #define HINT_NOINDEXONLYSCAN "NoIndexonlyScan"
57 #define HINT_NESTLOOP "NestLoop"
58 #define HINT_MERGEJOIN "MergeJoin"
59 #define HINT_HASHJOIN "HashJoin"
60 #define HINT_NONESTLOOP "NoNestLoop"
61 #define HINT_NOMERGEJOIN "NoMergeJoin"
62 #define HINT_NOHASHJOIN "NoHashJoin"
63 #define HINT_LEADING "Leading"
64 #define HINT_SET "Set"
67 #define HINT_ARRAY_DEFAULT_INITSIZE 8
69 #define parse_ereport(str, detail) \
70 ereport(pg_hint_plan_parse_messages, \
71 (errmsg("hint syntax error at or near \"%s\"", (str)), \
74 #define skip_space(str) \
75 while (isspace(*str)) \
80 ENABLE_SEQSCAN = 0x01,
81 ENABLE_INDEXSCAN = 0x02,
82 ENABLE_BITMAPSCAN = 0x04,
83 ENABLE_TIDSCAN = 0x08,
84 #if PG_VERSION_NUM >= 90200
85 ENABLE_INDEXONLYSCAN = 0x10
91 ENABLE_NESTLOOP = 0x01,
92 ENABLE_MERGEJOIN = 0x02,
93 ENABLE_HASHJOIN = 0x04
96 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | ENABLE_BITMAPSCAN \
98 #if PG_VERSION_NUM >= 90200
99 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | ENABLE_BITMAPSCAN \
100 | ENABLE_TIDSCAN | ENABLE_INDEXONLYSCAN)
102 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
103 #define DISABLE_ALL_SCAN 0
104 #define DISABLE_ALL_JOIN 0
106 typedef struct Hint Hint;
107 typedef struct PlanHint PlanHint;
109 typedef Hint *(*HintCreateFunction) (const char *hint_str, const char *keyword);
110 typedef void (*HintDeleteFunction) (Hint *hint);
111 typedef void (*HintDumpFunction) (Hint *hint, StringInfo buf);
112 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
113 typedef const char *(*HintParseFunction) (Hint *hint, PlanHint *plan, Query *parse, const char *str);
116 #define NUM_HINT_TYPE 4
117 typedef enum HintType
119 HINT_TYPE_SCAN_METHOD,
120 HINT_TYPE_JOIN_METHOD,
126 typedef enum HintStatus
128 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
129 HINT_STATE_USED, /* hint is used */
130 HINT_STATE_DUPLICATION, /* specified hint duplication */
131 /* execute error (parse error does not include it) */
135 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
136 (hint)->base.state == HINT_STATE_USED)
138 /* common data for all hints. */
141 const char *hint_str; /* must not do pfree */
142 const char *keyword; /* must not do pfree */
145 HintDeleteFunction delete_func;
146 HintDumpFunction dump_func;
147 HintCmpFunction cmp_func;
148 HintParseFunction parser_func;
151 /* scan method hints */
152 typedef struct ScanMethodHint
157 unsigned char enforce_mask;
160 /* join method hints */
161 typedef struct JoinMethodHint
166 unsigned char enforce_mask;
170 /* join order hints */
171 typedef struct LeadingHint
174 List *relations; /* relation names specified in Leading hint */
177 /* change a run-time parameter hints */
178 typedef struct SetHint
181 char *name; /* name of variable */
186 * Describes a context of hint processing.
190 char *hint_str; /* original hint string */
193 int nall_hints; /* # of valid all hints */
194 int max_all_hints; /* # of slots for all hints */
195 Hint **all_hints; /* parsed all hints */
197 /* # of each hints */
198 int num_hints[NUM_HINT_TYPE];
200 /* for scan method hints */
201 ScanMethodHint **scan_hints; /* parsed scan hints */
202 int init_scan_mask; /* initial value scan parameter */
203 Index parent_relid; /* inherit parent table relid */
205 /* for join method hints */
206 JoinMethodHint **join_hints; /* parsed join hints */
207 int init_join_mask; /* initial value join parameter */
208 List **join_hint_level;
210 /* for Leading hints */
211 LeadingHint **leading_hints; /* parsed Leading hints */
214 SetHint **set_hints; /* parsed Set hints */
215 GucContext context; /* which GUC parameters can we set? */
219 * Describes a hint parser module which is bound with particular hint keyword.
221 typedef struct HintParser
224 HintCreateFunction create_func;
227 /* Module callbacks */
231 void pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
232 ParamListInfo params, bool isTopLevel,
233 DestReceiver *dest, char *completionTag);
234 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
235 ParamListInfo boundParams);
236 static void pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
237 bool inhparent, RelOptInfo *rel);
238 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
241 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword);
242 static void ScanMethodHintDelete(ScanMethodHint *hint);
243 static void ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf);
244 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
245 static const char *ScanMethodHintParse(ScanMethodHint *hint, PlanHint *plan, Query *parse, const char *str);
246 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword);
247 static void JoinMethodHintDelete(JoinMethodHint *hint);
248 static void JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf);
249 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
250 static const char *JoinMethodHintParse(JoinMethodHint *hint, PlanHint *plan, Query *parse, const char *str);
251 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword);
252 static void LeadingHintDelete(LeadingHint *hint);
253 static void LeadingHintDump(LeadingHint *hint, StringInfo buf);
254 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
255 static const char *LeadingHintParse(LeadingHint *hint, PlanHint *plan, Query *parse, const char *str);
256 static Hint *SetHintCreate(const char *hint_str, const char *keyword);
257 static void SetHintDelete(SetHint *hint);
258 static void SetHintDump(SetHint *hint, StringInfo buf);
259 static int SetHintCmp(const SetHint *a, const SetHint *b);
260 static const char *SetHintParse(SetHint *hint, PlanHint *plan, Query *parse, const char *str);
262 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels);
263 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
264 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel, ListCell *other_rels);
265 static void make_rels_by_clauseless_joins(PlannerInfo *root, RelOptInfo *old_rel, ListCell *other_rels);
266 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
267 static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
268 Index rti, RangeTblEntry *rte);
269 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
271 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
272 Index rti, RangeTblEntry *rte);
273 static List *accumulate_append_subpath(List *subpaths, Path *path);
274 static void set_dummy_rel_pathlist(RelOptInfo *rel);
275 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2);
279 static bool pg_hint_plan_enable = true;
280 static bool pg_hint_plan_debug_print = false;
281 static int pg_hint_plan_parse_messages = INFO;
283 static const struct config_enum_entry parse_messages_level_options[] = {
284 {"debug", DEBUG2, true},
285 {"debug5", DEBUG5, false},
286 {"debug4", DEBUG4, false},
287 {"debug3", DEBUG3, false},
288 {"debug2", DEBUG2, false},
289 {"debug1", DEBUG1, false},
291 {"info", INFO, false},
292 {"notice", NOTICE, false},
293 {"warning", WARNING, false},
294 {"error", ERROR, false},
296 {"fatal", FATAL, true},
297 {"panic", PANIC, true},
302 /* Saved hook values in case of unload */
303 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
304 static planner_hook_type prev_planner = NULL;
305 static get_relation_info_hook_type prev_get_relation_info = NULL;
306 static join_search_hook_type prev_join_search = NULL;
308 /* フック関数をまたがって使用する情報を管理する */
309 static PlanHint *global = NULL;
312 * EXECUTEコマンド実行時に、ステートメント名を格納する。
313 * その他のコマンドの場合は、NULLに設定する。
315 static char *stmt_name = NULL;
317 static const HintParser parsers[] = {
318 {HINT_SEQSCAN, ScanMethodHintCreate},
319 {HINT_INDEXSCAN, ScanMethodHintCreate},
320 {HINT_BITMAPSCAN, ScanMethodHintCreate},
321 {HINT_TIDSCAN, ScanMethodHintCreate},
322 {HINT_NOSEQSCAN, ScanMethodHintCreate},
323 {HINT_NOINDEXSCAN, ScanMethodHintCreate},
324 {HINT_NOBITMAPSCAN, ScanMethodHintCreate},
325 {HINT_NOTIDSCAN, ScanMethodHintCreate},
326 #if PG_VERSION_NUM >= 90200
327 {HINT_INDEXONLYSCAN, ScanMethodHintCreate},
328 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate},
330 {HINT_NESTLOOP, JoinMethodHintCreate},
331 {HINT_MERGEJOIN, JoinMethodHintCreate},
332 {HINT_HASHJOIN, JoinMethodHintCreate},
333 {HINT_NONESTLOOP, JoinMethodHintCreate},
334 {HINT_NOMERGEJOIN, JoinMethodHintCreate},
335 {HINT_NOHASHJOIN, JoinMethodHintCreate},
336 {HINT_LEADING, LeadingHintCreate},
337 {HINT_SET, SetHintCreate},
342 * Module load callbacks
347 /* Define custom GUC variables. */
348 DefineCustomBoolVariable("pg_hint_plan.enable",
349 "Instructions or hints to the planner using block comments.",
351 &pg_hint_plan_enable,
359 DefineCustomBoolVariable("pg_hint_plan.debug_print",
360 "Logs each query's parse results of the hint.",
362 &pg_hint_plan_debug_print,
370 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
371 "Messege level of the parse error.",
373 &pg_hint_plan_parse_messages,
375 parse_messages_level_options,
383 prev_ProcessUtility = ProcessUtility_hook;
384 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
385 prev_planner = planner_hook;
386 planner_hook = pg_hint_plan_planner;
387 prev_get_relation_info = get_relation_info_hook;
388 get_relation_info_hook = pg_hint_plan_get_relation_info;
389 prev_join_search = join_search_hook;
390 join_search_hook = pg_hint_plan_join_search;
394 * Module unload callback
400 /* Uninstall hooks. */
401 ProcessUtility_hook = prev_ProcessUtility;
402 planner_hook = prev_planner;
403 get_relation_info_hook = prev_get_relation_info;
404 join_search_hook = prev_join_search;
408 ProcessUtility_hook_error_callback(void *arg)
414 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
415 ParamListInfo params, bool isTopLevel,
416 DestReceiver *dest, char *completionTag)
419 ErrorContextCallback errcontext;
421 if (!pg_hint_plan_enable)
423 if (prev_ProcessUtility)
424 (*prev_ProcessUtility) (parsetree, queryString, params,
425 isTopLevel, dest, completionTag);
427 standard_ProcessUtility(parsetree, queryString, params,
428 isTopLevel, dest, completionTag);
434 if (IsA(node , ExplainStmt))
437 * EXPLAIN対象のクエリのパースツリーを取得する
442 stmt = (ExplainStmt *) node;
444 Assert(IsA(stmt->query, Query));
445 query = (Query *) stmt->query;
447 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
448 node = query->utilityStmt;
452 * EXECUTEコマンドならば、PREPARE時に指定されたクエリ文字列を取得し、ヒント
455 if (IsA(node , ExecuteStmt))
459 /* Set up callback to statement name reset. */
460 errcontext.callback = ProcessUtility_hook_error_callback;
461 errcontext.arg = NULL;
462 errcontext.previous = error_context_stack;
463 error_context_stack = &errcontext;
465 stmt = (ExecuteStmt *) node;
466 stmt_name = stmt->name;
469 if (prev_ProcessUtility)
470 (*prev_ProcessUtility) (parsetree, queryString, params,
471 isTopLevel, dest, completionTag);
473 standard_ProcessUtility(parsetree, queryString, params,
474 isTopLevel, dest, completionTag);
480 /* Remove error callback. */
481 error_context_stack = errcontext.previous;
486 ScanMethodHintCreate(const char *hint_str, const char *keyword)
488 ScanMethodHint *hint;
490 hint = palloc(sizeof(ScanMethodHint));
491 hint->base.hint_str = hint_str;
492 hint->base.keyword = keyword;
493 hint->base.type = HINT_TYPE_SCAN_METHOD;
494 hint->base.state = HINT_STATE_NOTUSED;
495 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
496 hint->base.dump_func = (HintDumpFunction) ScanMethodHintDump;
497 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
498 hint->base.parser_func = (HintParseFunction) ScanMethodHintParse;
499 hint->relname = NULL;
500 hint->indexnames = NIL;
501 hint->enforce_mask = 0;
503 return (Hint *) hint;
507 ScanMethodHintDelete(ScanMethodHint *hint)
513 pfree(hint->relname);
514 list_free_deep(hint->indexnames);
519 dump_quote_value(StringInfo buf, const char *value)
521 bool need_quote = false;
524 for (str = value; *str != '\0'; str++)
526 if (isspace(*str) || *str == ')' || *str == '"')
529 appendStringInfoCharMacro(buf, '"');
534 for (str = value; *str != '\0'; str++)
537 appendStringInfoCharMacro(buf, '"');
539 appendStringInfoCharMacro(buf, *str);
543 appendStringInfoCharMacro(buf, '"');
546 static void ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf)
550 appendStringInfo(buf, "%s(", hint->base.keyword);
551 dump_quote_value(buf, hint->relname);
552 foreach(l, hint->indexnames)
554 appendStringInfoCharMacro(buf, ' ');
555 dump_quote_value(buf, (char *) lfirst(l));
557 appendStringInfoString(buf, ")\n");
561 JoinMethodHintCreate(const char *hint_str, const char *keyword)
563 JoinMethodHint *hint;
565 hint = palloc(sizeof(JoinMethodHint));
566 hint->base.hint_str = hint_str;
567 hint->base.keyword = keyword;
568 hint->base.type = HINT_TYPE_JOIN_METHOD;
569 hint->base.state = HINT_STATE_NOTUSED;
570 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
571 hint->base.dump_func = (HintDumpFunction) JoinMethodHintDump;
572 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
573 hint->base.parser_func = (HintParseFunction) JoinMethodHintParse;
575 hint->relnames = NULL;
576 hint->enforce_mask = 0;
577 hint->joinrelids = NULL;
579 return (Hint *) hint;
583 JoinMethodHintDelete(JoinMethodHint *hint)
592 for (i = 0; i < hint->nrels; i++)
593 pfree(hint->relnames[i]);
594 pfree(hint->relnames);
596 bms_free(hint->joinrelids);
600 static void JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf)
604 appendStringInfo(buf, "%s(", hint->base.keyword);
605 dump_quote_value(buf, hint->relnames[0]);
606 for (i = 1; i < hint->nrels; i++)
608 appendStringInfoCharMacro(buf, ' ');
609 dump_quote_value(buf, hint->relnames[i]);
611 appendStringInfoString(buf, ")\n");
616 LeadingHintCreate(const char *hint_str, const char *keyword)
620 hint = palloc(sizeof(LeadingHint));
621 hint->base.hint_str = hint_str;
622 hint->base.keyword = keyword;
623 hint->base.type = HINT_TYPE_LEADING;
624 hint->base.state = HINT_STATE_NOTUSED;
625 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
626 hint->base.dump_func = (HintDumpFunction) LeadingHintDump;
627 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
628 hint->base.parser_func = (HintParseFunction) LeadingHintParse;
629 hint->relations = NIL;
631 return (Hint *) hint;
635 LeadingHintDelete(LeadingHint *hint)
640 list_free_deep(hint->relations);
644 static void LeadingHintDump(LeadingHint *hint, StringInfo buf)
649 appendStringInfo(buf, "%s(", HINT_LEADING);
651 foreach(l, hint->relations)
656 appendStringInfoCharMacro(buf, ' ');
658 dump_quote_value(buf, (char *)lfirst(l));
661 appendStringInfoString(buf, ")\n");
665 SetHintCreate(const char *hint_str, const char *keyword)
669 hint = palloc(sizeof(SetHint));
670 hint->base.hint_str = hint_str;
671 hint->base.keyword = keyword;
672 hint->base.type = HINT_TYPE_SET;
673 hint->base.state = HINT_STATE_NOTUSED;
674 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
675 hint->base.dump_func = (HintDumpFunction) SetHintDump;
676 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
677 hint->base.parser_func = (HintParseFunction) SetHintParse;
681 return (Hint *) hint;
685 SetHintDelete(SetHint *hint)
697 static void SetHintDump(SetHint *hint, StringInfo buf)
699 appendStringInfo(buf, "%s(", HINT_SET);
700 dump_quote_value(buf, hint->name);
701 appendStringInfoCharMacro(buf, ' ');
702 dump_quote_value(buf, hint->value);
703 appendStringInfo(buf, ")\n");
711 hint = palloc(sizeof(PlanHint));
712 hint->hint_str = NULL;
713 hint->nall_hints = 0;
714 hint->max_all_hints = 0;
715 hint->all_hints = NULL;
716 memset(hint->num_hints, 0, sizeof(hint->num_hints));
717 hint->scan_hints = NULL;
718 hint->init_scan_mask = 0;
719 hint->parent_relid = 0;
720 hint->join_hints = NULL;
721 hint->init_join_mask = 0;
722 hint->join_hint_level = NULL;
723 hint->leading_hints = NULL;
724 hint->context = superuser() ? PGC_SUSET : PGC_USERSET;
725 hint->set_hints = NULL;
731 PlanHintDelete(PlanHint *hint)
739 pfree(hint->hint_str);
741 for (i = 0; i < hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
742 hint->all_hints[i]->delete_func(hint->all_hints[i]);
744 pfree(hint->all_hints);
748 all_hint_dump(PlanHint *hint, StringInfo buf, const char *title, HintStatus state)
752 appendStringInfo(buf, "%s:\n", title);
753 for (i = 0; i < hint->nall_hints; i++)
755 if (hint->all_hints[i]->state != state)
758 hint->all_hints[i]->dump_func(hint->all_hints[i], buf);
763 PlanHintDump(PlanHint *hint)
769 elog(LOG, "pg_hint_plan:\nno hint");
773 initStringInfo(&buf);
775 appendStringInfoString(&buf, "pg_hint_plan:\n");
776 all_hint_dump(hint, &buf, "used hint", HINT_STATE_USED);
777 all_hint_dump(hint, &buf, "not used hint", HINT_STATE_NOTUSED);
778 all_hint_dump(hint, &buf, "duplication hint", HINT_STATE_DUPLICATION);
779 all_hint_dump(hint, &buf, "error hint", HINT_STATE_ERROR);
781 elog(LOG, "%s", buf.data);
787 RelnameCmp(const void *a, const void *b)
789 const char *relnamea = *((const char **) a);
790 const char *relnameb = *((const char **) b);
792 return strcmp(relnamea, relnameb);
796 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
798 return RelnameCmp(&a->relname, &b->relname);
802 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
806 if (a->nrels != b->nrels)
807 return a->nrels - b->nrels;
809 for (i = 0; i < a->nrels; i++)
812 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
820 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
826 SetHintCmp(const SetHint *a, const SetHint *b)
828 return strcmp(a->name, b->name);
832 AllHintCmp(const void *a, const void *b, bool order)
834 const Hint *hinta = *((const Hint **) a);
835 const Hint *hintb = *((const Hint **) b);
838 if (hinta->type != hintb->type)
839 return hinta->type - hintb->type;
841 if ((result = hinta->cmp_func(hinta, hintb)) != 0 || !order)
845 return hinta->hint_str - hintb->hint_str;
849 AllHintCmpIsOrder(const void *a, const void *b)
851 return AllHintCmp(a, b, true);
854 #if PG_VERSION_NUM < 90200
856 set_config_option_wrapper(const char *name, const char *value,
857 GucContext context, GucSource source,
858 GucAction action, bool changeVal, int elevel)
861 MemoryContext ccxt = CurrentMemoryContext;
865 result = set_config_option(name, value, context, source,
876 ecxt = MemoryContextSwitchTo(ccxt);
877 errdata = CopyErrorData();
878 ereport(elevel, (errcode(errdata->sqlerrcode),
879 errmsg("%s", errdata->message),
880 errdata->detail ? errdetail("%s", errdata->detail) : 0,
881 errdata->hint ? errhint("%s", errdata->hint) : 0));
882 FreeErrorData(errdata);
884 MemoryContextSwitchTo(ecxt);
891 #define set_config_option(name, value, context, source, \
892 action, changeVal, elevel) \
893 set_config_option_wrapper(name, value, context, source, \
894 action, changeVal, elevel)
898 set_config_options(SetHint **options, int noptions, GucContext context)
903 save_nestlevel = NewGUCNestLevel();
905 for (i = 0; i < noptions; i++)
907 SetHint *hint = options[i];
910 if (!hint_state_enabled(hint))
913 result = set_config_option(hint->name, hint->value, context,
914 PGC_S_SESSION, GUC_ACTION_SAVE, true,
915 pg_hint_plan_parse_messages);
917 hint->base.state = HINT_STATE_USED;
919 hint->base.state = HINT_STATE_ERROR;
922 return save_nestlevel;
925 #define SET_CONFIG_OPTION(name, type_bits) \
926 set_config_option((name), \
927 (enforce_mask & (type_bits)) ? "true" : "false", \
928 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
931 set_scan_config_options(unsigned char enforce_mask, GucContext context)
933 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
934 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
935 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
936 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
937 #if PG_VERSION_NUM >= 90200
938 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXSCAN);
943 set_join_config_options(unsigned char enforce_mask, GucContext context)
945 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
946 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
947 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
955 parse_keyword(const char *str, StringInfo buf)
959 while (!isspace(*str) && *str != '(' && *str != '\0')
960 appendStringInfoCharMacro(buf, *str++);
966 skip_opened_parenthesis(const char *str)
972 parse_ereport(str, ("Opened parenthesis is necessary."));
982 skip_closed_parenthesis(const char *str)
988 parse_ereport(str, ("Closed parenthesis is necessary."));
998 * 二重引用符で囲まれているかもしれないトークンを読み取り word 引数に palloc
999 * で確保したバッファに格納してそのポインタを返す。
1001 * 正常にパースできた場合は残りの文字列の先頭位置を、異常があった場合は NULL を
1005 parse_quote_value(const char *str, char **word, char *value_type)
1010 /* 先頭のスペースは読み飛ばす。 */
1013 initStringInfo(&buf);
1026 /* 二重引用符が閉じられていない場合はパース中断 */
1030 parse_ereport(str, ("Unterminated quoted %s.", value_type));
1035 * エスケープ対象のダブルクウォートをスキップする。
1036 * もしブロックコメントの開始文字列や終了文字列もオブジェクト名とし
1037 * て使用したい場合は、/ と * もエスケープ対象とすることで使用できる
1038 * が、処理対象としていない。もしテーブル名にこれらの文字が含まれる
1039 * 場合は、エイリアスを指定する必要がある。
1049 if (isspace(*str) || *str == ')' || *str == '"' || *str == '\0')
1052 appendStringInfoCharMacro(&buf, *str++);
1058 parse_ereport(str, ("%s is necessary.", value_type));
1068 parse_hints(PlanHint *plan, Query *parse, const char *str)
1073 initStringInfo(&buf);
1074 while (*str != '\0')
1076 const HintParser *parser;
1078 /* in error message, we output the comment including the keyword. */
1079 head = (char *) str;
1081 /* parse only the keyword of the hint. */
1082 resetStringInfo(&buf);
1083 str = parse_keyword(str, &buf);
1085 for (parser = parsers; parser->keyword != NULL; parser++)
1087 char *keyword = parser->keyword;
1090 if (strcasecmp(buf.data, keyword) != 0)
1093 hint = parser->create_func(head, keyword);
1095 /* parser of each hint does parse in a parenthesis. */
1096 if ((str = skip_opened_parenthesis(str)) == NULL ||
1097 (str = hint->parser_func(hint, plan, parse, str)) == NULL ||
1098 (str = skip_closed_parenthesis(str)) == NULL)
1100 hint->delete_func(hint);
1106 * 出来上がったヒント情報を追加。スロットが足りない場合は二倍に拡張する。
1108 if (plan->nall_hints == 0)
1110 plan->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1111 plan->all_hints = palloc(sizeof(Hint *) * plan->max_all_hints);
1113 else if (plan->nall_hints == plan->max_all_hints)
1115 plan->max_all_hints *= 2;
1116 plan->all_hints = repalloc(plan->all_hints,
1117 sizeof(Hint *) * plan->max_all_hints);
1120 plan->all_hints[plan->nall_hints] = hint;
1128 if (parser->keyword == NULL)
1130 parse_ereport(head, ("Keyword \"%s\" does not exist.", buf.data));
1140 * Do basic parsing of the query head comment.
1143 parse_head_comment(Query *parse)
1152 /* get client-supplied query string. */
1155 PreparedStatement *entry;
1157 entry = FetchPreparedStatement(stmt_name, true);
1158 p = entry->plansource->query_string;
1161 p = debug_query_string;
1166 /* extract query head comment. */
1167 len = strlen(HINT_START);
1169 if (strncmp(p, HINT_START, len))
1176 /* find hint end keyword. */
1177 if ((tail = strstr(p, HINT_END)) == NULL)
1179 parse_ereport(head, ("Unterminated block comment."));
1183 /* 入れ子にしたブロックコメントはサポートしない */
1184 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1185 parse_ereport(head, ("Block comments nest doesn't supported."));
1189 head = palloc(len + 1);
1190 memcpy(head, p, len);
1194 plan = PlanHintCreate();
1195 plan->hint_str = head;
1197 /* parse each hint. */
1198 parse_hints(plan, parse, p);
1200 /* When nothing specified a hint, we free PlanHint and returns NULL. */
1201 if (plan->nall_hints == 0)
1203 PlanHintDelete(plan);
1207 /* パースしたヒントを並び替える */
1208 qsort(plan->all_hints, plan->nall_hints, sizeof(Hint *), AllHintCmpIsOrder);
1211 for (i = 0; i < plan->nall_hints; i++)
1213 Hint *hint = plan->all_hints[i];
1215 plan->num_hints[hint->type]++;
1217 if (i + 1 >= plan->nall_hints)
1220 if (AllHintCmp(plan->all_hints + i, plan->all_hints + i + 1, false) == 0)
1222 const char *HintTypeName[] = {"scan method", "join method",
1225 parse_ereport(plan->all_hints[i]->hint_str,
1226 ("Conflict %s hint.", HintTypeName[hint->type]));
1227 plan->all_hints[i]->state = HINT_STATE_DUPLICATION;
1231 plan->scan_hints = (ScanMethodHint **) plan->all_hints;
1232 plan->join_hints = (JoinMethodHint **) plan->all_hints +
1233 plan->num_hints[HINT_TYPE_SCAN_METHOD];
1234 plan->leading_hints = (LeadingHint **) plan->all_hints +
1235 plan->num_hints[HINT_TYPE_SCAN_METHOD] +
1236 plan->num_hints[HINT_TYPE_JOIN_METHOD];
1237 plan->set_hints = (SetHint **) plan->all_hints +
1238 plan->num_hints[HINT_TYPE_SCAN_METHOD] +
1239 plan->num_hints[HINT_TYPE_JOIN_METHOD] +
1240 plan->num_hints[HINT_TYPE_LEADING];
1246 * スキャン方式ヒントのカッコ内をパースする
1249 ScanMethodHintParse(ScanMethodHint *hint, PlanHint *plan, Query *parse, const char *str)
1251 const char *keyword = hint->base.keyword;
1254 * スキャン方式のヒントでリレーション名が読み取れない場合はヒント無効
1256 if ((str = parse_quote_value(str, &hint->relname, "ralation name")) == NULL)
1262 * インデックスリストを受け付けるヒントであれば、インデックス参照をパース
1265 if (strcmp(keyword, HINT_INDEXSCAN) == 0 ||
1266 #if PG_VERSION_NUM >= 90200
1267 strcmp(keyword, HINT_INDEXONLYSCAN) == 0 ||
1269 strcmp(keyword, HINT_BITMAPSCAN) == 0)
1271 while (*str != ')' && *str != '\0')
1275 str = parse_quote_value(str, &indexname, "index name");
1279 hint->indexnames = lappend(hint->indexnames, indexname);
1285 * ヒントごとに決まっている許容スキャン方式をビットマスクとして設定
1287 if (strcasecmp(keyword, HINT_SEQSCAN) == 0)
1288 hint->enforce_mask = ENABLE_SEQSCAN;
1289 else if (strcasecmp(keyword, HINT_INDEXSCAN) == 0)
1290 hint->enforce_mask = ENABLE_INDEXSCAN;
1291 else if (strcasecmp(keyword, HINT_BITMAPSCAN) == 0)
1292 hint->enforce_mask = ENABLE_BITMAPSCAN;
1293 else if (strcasecmp(keyword, HINT_TIDSCAN) == 0)
1294 hint->enforce_mask = ENABLE_TIDSCAN;
1295 else if (strcasecmp(keyword, HINT_NOSEQSCAN) == 0)
1296 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1297 else if (strcasecmp(keyword, HINT_NOINDEXSCAN) == 0)
1298 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1299 else if (strcasecmp(keyword, HINT_NOBITMAPSCAN) == 0)
1300 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1301 else if (strcasecmp(keyword, HINT_NOTIDSCAN) == 0)
1302 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1305 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1313 JoinMethodHintParse(JoinMethodHint *hint, PlanHint *plan, Query *parse, const char *str)
1316 const char *keyword = hint->base.keyword;
1320 hint->relnames = palloc(sizeof(char *));
1322 while ((str = parse_quote_value(str, &relname, "table name")) != NULL)
1325 hint->relnames = repalloc(hint->relnames, sizeof(char *) * hint->nrels);
1326 hint->relnames[hint->nrels - 1] = relname;
1336 /* Join 対象のテーブルは最低でも2つ指定する必要がある */
1337 if (hint->nrels < 2)
1339 parse_ereport(str, ("Specified relation more than two."));
1340 hint->base.state = HINT_STATE_ERROR;
1344 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1346 if (strcasecmp(keyword, HINT_NESTLOOP) == 0)
1347 hint->enforce_mask = ENABLE_NESTLOOP;
1348 else if (strcasecmp(keyword, HINT_MERGEJOIN) == 0)
1349 hint->enforce_mask = ENABLE_MERGEJOIN;
1350 else if (strcasecmp(keyword, HINT_HASHJOIN) == 0)
1351 hint->enforce_mask = ENABLE_HASHJOIN;
1352 else if (strcasecmp(keyword, HINT_NONESTLOOP) == 0)
1353 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1354 else if (strcasecmp(keyword, HINT_NOMERGEJOIN) == 0)
1355 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1356 else if (strcasecmp(keyword, HINT_NOHASHJOIN) == 0)
1357 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1360 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1368 LeadingHintParse(LeadingHint *hint, PlanHint *plan, Query *parse, const char *str)
1376 if ((str = parse_quote_value(str, &relname, "relation name")) == NULL)
1379 hint->relations = lappend(hint->relations, relname);
1384 /* テーブル指定が2つ未満の場合は、Leading ヒントはエラーとする */
1385 if (list_length(hint->relations) < 2)
1387 parse_ereport(hint->base.hint_str,
1388 ("In %s hint, specified relation name 2 or more.", HINT_LEADING));
1389 hint->base.state = HINT_STATE_ERROR;
1396 SetHintParse(SetHint *hint, PlanHint *plan, Query *parse, const char *str)
1398 if ((str = parse_quote_value(str, &hint->name, "parameter name")) == NULL ||
1399 (str = parse_quote_value(str, &hint->value, "parameter value")) == NULL)
1405 static PlannedStmt *
1406 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1409 PlannedStmt *result;
1412 * hintが指定されない、または空のhintを指定された場合は通常のparser処理をお
1414 * 他のフック関数で実行されるhint処理をスキップするために、global 変数をNULL
1417 if (!pg_hint_plan_enable || (global = parse_head_comment(parse)) == NULL)
1422 return (*prev_planner) (parse, cursorOptions, boundParams);
1424 return standard_planner(parse, cursorOptions, boundParams);
1427 /* Set hint で指定されたGUCパラメータを設定する */
1428 save_nestlevel = set_config_options(global->set_hints, global->num_hints[HINT_TYPE_SET],
1432 global->init_scan_mask |= ENABLE_SEQSCAN;
1433 if (enable_indexscan)
1434 global->init_scan_mask |= ENABLE_INDEXSCAN;
1435 if (enable_bitmapscan)
1436 global->init_scan_mask |= ENABLE_BITMAPSCAN;
1438 global->init_scan_mask |= ENABLE_TIDSCAN;
1439 #if PG_VERSION_NUM >= 90200
1440 if (enable_indexonlyscan)
1441 global->init_scan_mask |= ENABLE_INDEXONLYSCAN;
1443 if (enable_nestloop)
1444 global->init_join_mask |= ENABLE_NESTLOOP;
1445 if (enable_mergejoin)
1446 global->init_join_mask |= ENABLE_MERGEJOIN;
1447 if (enable_hashjoin)
1448 global->init_join_mask |= ENABLE_HASHJOIN;
1451 result = (*prev_planner) (parse, cursorOptions, boundParams);
1453 result = standard_planner(parse, cursorOptions, boundParams);
1456 * Restore the GUC variables we set above.
1458 AtEOXact_GUC(true, save_nestlevel);
1461 * Print hint if debugging.
1463 if (pg_hint_plan_debug_print)
1464 PlanHintDump(global);
1466 PlanHintDelete(global);
1473 * aliasnameと一致するSCANヒントを探す
1475 static ScanMethodHint *
1476 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
1482 * RELOPT_BASEREL でなければ、scan method ヒントが適用しない。
1483 * 子テーブルの場合はRELOPT_OTHER_MEMBER_RELとなるが、サポート対象外とする。
1484 * また、通常のリレーション以外は、スキャン方式を選択できない。
1486 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
1489 rte = root->simple_rte_array[rel->relid];
1491 /* 外部表はスキャン方式が選択できない。 */
1492 if (rte->relkind == RELKIND_FOREIGN_TABLE)
1496 * スキャン方式のヒントのリストから、検索対象のリレーションと名称が一致する
1499 for (i = 0; i < global->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1501 ScanMethodHint *hint = global->scan_hints[i];
1503 /* すでに無効となっているヒントは検索対象にしない。 */
1504 if (!hint_state_enabled(hint))
1507 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
1515 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
1516 bool inhparent, RelOptInfo *rel)
1518 ScanMethodHint *hint;
1523 if (prev_get_relation_info)
1524 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
1526 /* 有効なヒントが指定されなかった場合は処理をスキップする。 */
1532 /* cache does relids of parent table */
1533 global->parent_relid = rel->relid;
1535 else if (global->parent_relid != 0)
1537 /* If this rel is an appendrel child, */
1540 /* append_rel_list contains all append rels; ignore others */
1541 foreach(l, root->append_rel_list)
1543 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1545 /* This rel is child table. */
1546 if (appinfo->parent_relid == global->parent_relid)
1550 /* This rel is not inherit table. */
1551 global->parent_relid = 0;
1554 /* scan hint が指定されない場合は、GUCパラメータをリセットする。 */
1555 if ((hint = find_scan_hint(root, rel)) == NULL)
1557 set_scan_config_options(global->init_scan_mask, global->context);
1560 set_scan_config_options(hint->enforce_mask, global->context);
1561 hint->base.state = HINT_STATE_USED;
1563 /* インデックスを全て削除し、スキャンに使えなくする */
1564 if (hint->enforce_mask == ENABLE_SEQSCAN ||
1565 hint->enforce_mask == ENABLE_TIDSCAN)
1567 list_free_deep(rel->indexlist);
1568 rel->indexlist = NIL;
1569 hint->base.state = HINT_STATE_USED;
1574 /* 後でパスを作り直すため、ここではなにもしない */
1575 if (hint->indexnames == NULL)
1578 /* 指定されたインデックスのみをのこす */
1580 for (cell = list_head(rel->indexlist); cell; cell = next)
1582 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
1583 char *indexname = get_rel_name(info->indexoid);
1585 bool use_index = false;
1589 foreach(l, hint->indexnames)
1591 if (RelnameCmp(&indexname, &lfirst(l)) == 0)
1599 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
1608 * aliasnameがクエリ中に指定した別名と一致する場合は、そのインデックスを返し、一致
1610 * aliasnameがクエリ中に複数回指定された場合は、-1を返す。
1613 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
1619 for (i = 1; i < root->simple_rel_array_size; i++)
1623 if (root->simple_rel_array[i] == NULL)
1626 Assert(i == root->simple_rel_array[i]->relid);
1628 if (RelnameCmp(&aliasname, &root->simple_rte_array[i]->eref->aliasname)
1632 foreach(l, initial_rels)
1634 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
1636 if (rel->reloptkind == RELOPT_BASEREL)
1638 if (rel->relid != i)
1643 Assert(rel->reloptkind == RELOPT_JOINREL);
1645 if (!bms_is_member(i, rel->relids))
1651 parse_ereport(str, ("Relation name \"%s\" is ambiguous.", aliasname));
1665 * relidビットマスクと一致するヒントを探す
1667 static JoinMethodHint *
1668 find_join_hint(Relids joinrelids)
1673 join_hint = global->join_hint_level[bms_num_members(joinrelids)];
1674 foreach(l, join_hint)
1676 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
1677 if (bms_equal(joinrelids, hint->joinrelids))
1685 * 結合方式のヒントを使用しやすい構造に変換する。
1688 transform_join_hints(PlanHint *plan, PlannerInfo *root, int nbaserel,
1689 List *initial_rels, JoinMethodHint **join_method_hints)
1698 for (i = 0; i < plan->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
1700 JoinMethodHint *hint = plan->join_hints[i];
1703 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
1706 bms_free(hint->joinrelids);
1707 hint->joinrelids = NULL;
1709 for (j = 0; j < hint->nrels; j++)
1711 char *relname = hint->relnames[j];
1713 relid = find_relid_aliasname(root, relname, initial_rels,
1714 hint->base.hint_str);
1717 hint->base.state = HINT_STATE_ERROR;
1722 if (bms_is_member(relid, hint->joinrelids))
1724 parse_ereport(hint->base.hint_str,
1725 ("Relation name \"%s\" is duplicate.", relname));
1726 hint->base.state = HINT_STATE_ERROR;
1730 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
1733 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
1736 plan->join_hint_level[hint->nrels] =
1737 lappend(plan->join_hint_level[hint->nrels], hint);
1741 * 有効なLeading ヒントが指定されている場合は、結合順にあわせてjoin method hint
1744 if (plan->num_hints[HINT_TYPE_LEADING] == 0)
1747 lhint = plan->leading_hints[plan->num_hints[HINT_TYPE_LEADING] - 1];
1748 if (!hint_state_enabled(lhint))
1751 /* Leading hint は、全ての join 方式が有効な hint として登録する */
1754 foreach(l, lhint->relations)
1756 char *relname = (char *)lfirst(l);
1757 JoinMethodHint *hint;
1759 relid = find_relid_aliasname(root, relname, initial_rels, plan->hint_str);
1763 bms_free(joinrelids);
1770 if (bms_is_member(relid, joinrelids))
1772 parse_ereport(lhint->base.hint_str,
1773 ("Relation name \"%s\" is duplicate.", relname));
1774 lhint->base.state = HINT_STATE_ERROR;
1775 bms_free(joinrelids);
1779 joinrelids = bms_add_member(joinrelids, relid);
1785 hint = find_join_hint(joinrelids);
1789 * Here relnames is not set, since Relids bitmap is sufficient to
1790 * control paths of this query afterwards.
1792 hint = (JoinMethodHint *) JoinMethodHintCreate(lhint->base.hint_str,
1794 hint->base.state = HINT_STATE_USED;
1795 hint->nrels = njoinrels;
1796 hint->enforce_mask = ENABLE_ALL_JOIN;
1797 hint->joinrelids = bms_copy(joinrelids);
1800 join_method_hints[njoinrels] = hint;
1802 if (njoinrels >= nbaserel)
1806 bms_free(joinrelids);
1811 for (i = 2; i <= njoinrels; i++)
1813 /* Leading で指定した組み合わせ以外の join hint を削除する */
1814 list_free(plan->join_hint_level[i]);
1816 plan->join_hint_level[i] =
1817 lappend(NIL, join_method_hints[i]);
1820 if (hint_state_enabled(lhint))
1821 set_join_config_options(DISABLE_ALL_JOIN, global->context);
1823 lhint->base.state = HINT_STATE_USED;
1828 rebuild_scan_path(PlanHint *plan, PlannerInfo *root, int level, List *initial_rels)
1832 foreach(l, initial_rels)
1834 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
1836 ScanMethodHint *hint;
1839 * スキャン方式が選択できるリレーションのみ、スキャンパスを再生成
1842 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
1845 rte = root->simple_rte_array[rel->relid];
1847 /* 外部表はスキャン方式が選択できない。 */
1848 if (rte->relkind == RELKIND_FOREIGN_TABLE)
1852 * scan method hint が指定されていなければ、初期値のGUCパラメータでscan
1855 if ((hint = find_scan_hint(root, rel)) == NULL)
1856 set_scan_config_options(plan->init_scan_mask, plan->context);
1859 set_scan_config_options(hint->enforce_mask, plan->context);
1860 hint->base.state = HINT_STATE_USED;
1863 list_free_deep(rel->pathlist);
1864 rel->pathlist = NIL;
1867 /* It's an "append relation", process accordingly */
1868 set_append_rel_pathlist(root, rel, rel->relid, rte);
1872 set_plain_rel_pathlist(root, rel, rte);
1877 * Restore the GUC variables we set above.
1879 set_scan_config_options(plan->init_scan_mask, plan->context);
1883 * make_join_rel() をラップする関数
1885 * ヒントにしたがって、enabele_* パラメータを変更した上で、make_join_rel()を
1889 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
1892 JoinMethodHint *hint;
1896 joinrelids = bms_union(rel1->relids, rel2->relids);
1897 hint = find_join_hint(joinrelids);
1898 bms_free(joinrelids);
1901 return pg_hint_plan_make_join_rel(root, rel1, rel2);
1903 save_nestlevel = NewGUCNestLevel();
1905 set_join_config_options(hint->enforce_mask, global->context);
1907 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
1908 hint->base.state = HINT_STATE_USED;
1911 * Restore the GUC variables we set above.
1913 AtEOXact_GUC(true, save_nestlevel);
1919 get_num_baserels(List *initial_rels)
1924 foreach(l, initial_rels)
1926 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
1928 if (rel->reloptkind == RELOPT_BASEREL)
1930 else if (rel->reloptkind ==RELOPT_JOINREL)
1931 nbaserel+= bms_num_members(rel->relids);
1934 /* other values not expected here */
1935 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
1943 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
1945 JoinMethodHint **join_method_hints;
1951 * pg_hint_planが無効、または有効なヒントが1つも指定されなかった場合は、標準
1956 if (prev_join_search)
1957 return (*prev_join_search) (root, levels_needed, initial_rels);
1958 else if (enable_geqo && levels_needed >= geqo_threshold)
1959 return geqo(root, levels_needed, initial_rels);
1961 return standard_join_search(root, levels_needed, initial_rels);
1964 /* We apply scan method hint rebuild scan path. */
1965 rebuild_scan_path(global, root, levels_needed, initial_rels);
1968 * GEQOを使用する条件を満たした場合は、GEQOを用いた結合方式の検索を行う。
1969 * このとき、スキャン方式のヒントとSetヒントのみが有効になり、結合方式や結合
1970 * 順序はヒント句は無効になりGEQOのアルゴリズムで決定される。
1972 if (enable_geqo && levels_needed >= geqo_threshold)
1973 return geqo(root, levels_needed, initial_rels);
1975 nbaserel = get_num_baserels(initial_rels);
1976 global->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
1977 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
1979 transform_join_hints(global, root, nbaserel, initial_rels, join_method_hints);
1981 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
1983 for (i = 2; i <= nbaserel; i++)
1985 list_free(global->join_hint_level[i]);
1987 /* free Leading hint only */
1988 if (join_method_hints[i] != NULL &&
1989 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
1990 JoinMethodHintDelete(join_method_hints[i]);
1992 pfree(global->join_hint_level);
1993 pfree(join_method_hints);
1995 if (global->num_hints[HINT_TYPE_LEADING] > 0 &&
1996 hint_state_enabled(global->leading_hints[global->num_hints[HINT_TYPE_LEADING] - 1]))
1997 set_join_config_options(global->init_join_mask, global->context);
2004 * Build access paths for a base relation
2007 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
2008 Index rti, RangeTblEntry *rte)
2012 /* It's an "append relation", process accordingly */
2013 set_append_rel_pathlist(root, rel, rti, rte);
2017 if (rel->rtekind == RTE_RELATION)
2019 if (rte->relkind == RELKIND_RELATION)
2021 /* Plain relation */
2022 set_plain_rel_pathlist(root, rel, rte);
2025 elog(ERROR, "unexpected relkind: %c", rte->relkind);
2028 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
2032 #define standard_join_search pg_hint_plan_standard_join_search
2033 #define join_search_one_level pg_hint_plan_join_search_one_level
2034 #define make_join_rel make_join_rel_wrapper
2037 #undef make_join_rel
2038 #define make_join_rel pg_hint_plan_make_join_rel
2039 #define add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype, sjinfo, restrictlist) \
2041 ScanMethodHint *hint = NULL; \
2042 if ((hint = find_scan_hint((root), (innerrel))) != NULL) \
2044 set_scan_config_options(hint->enforce_mask, global->context); \
2045 hint->base.state = HINT_STATE_USED; \
2047 add_paths_to_joinrel((root), (joinrel), (outerrel), (innerrel), (jointype), (sjinfo), (restrictlist)); \
2049 set_scan_config_options(global->init_scan_mask, global->context); \
2051 #include "make_join_rel.c"