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"
31 #ifdef PG_MODULE_MAGIC
35 #if PG_VERSION_NUM < 90100
36 #error unsupported PostgreSQL version
39 #define BLOCK_COMMENT_START "/*"
40 #define BLOCK_COMMENT_END "*/"
41 #define HINT_COMMENT_KEYWORD "+"
42 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
43 #define HINT_END BLOCK_COMMENT_END
46 #define HINT_SEQSCAN "SeqScan"
47 #define HINT_INDEXSCAN "IndexScan"
48 #define HINT_BITMAPSCAN "BitmapScan"
49 #define HINT_TIDSCAN "TidScan"
50 #define HINT_NOSEQSCAN "NoSeqScan"
51 #define HINT_NOINDEXSCAN "NoIndexScan"
52 #define HINT_NOBITMAPSCAN "NoBitmapScan"
53 #define HINT_NOTIDSCAN "NoTidScan"
54 #define HINT_NESTLOOP "NestLoop"
55 #define HINT_MERGEJOIN "MergeJoin"
56 #define HINT_HASHJOIN "HashJoin"
57 #define HINT_NONESTLOOP "NoNestLoop"
58 #define HINT_NOMERGEJOIN "NoMergeJoin"
59 #define HINT_NOHASHJOIN "NoHashJoin"
60 #define HINT_LEADING "Leading"
61 #define HINT_SET "Set"
63 #define HINT_ARRAY_DEFAULT_INITSIZE 8
65 #define parse_ereport(str, detail) \
66 ereport(pg_hint_plan_parse_messages, \
67 (errmsg("hint syntax error at or near \"%s\"", (str)), \
70 #define skip_space(str) \
71 while (isspace(*str)) \
76 ENABLE_SEQSCAN = 0x01,
77 ENABLE_INDEXSCAN = 0x02,
78 ENABLE_BITMAPSCAN = 0x04,
79 ENABLE_TIDSCAN = 0x08,
84 ENABLE_NESTLOOP = 0x01,
85 ENABLE_MERGEJOIN = 0x02,
86 ENABLE_HASHJOIN = 0x04
89 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
90 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN)
91 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
92 #define DISABLE_ALL_SCAN 0
93 #define DISABLE_ALL_JOIN 0
95 typedef struct Hint Hint;
96 typedef struct HintState HintState;
98 typedef Hint *(*HintCreateFunction) (const char *hint_str,
100 typedef void (*HintDeleteFunction) (Hint *hint);
101 typedef void (*HintDumpFunction) (Hint *hint, StringInfo buf);
102 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
103 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
104 Query *parse, const char *str);
107 #define NUM_HINT_TYPE 4
108 typedef enum HintType
110 HINT_TYPE_SCAN_METHOD,
111 HINT_TYPE_JOIN_METHOD,
117 typedef enum HintStatus
119 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
120 HINT_STATE_USED, /* hint is used */
121 HINT_STATE_DUPLICATION, /* specified hint duplication */
122 HINT_STATE_ERROR /* execute error (parse error does not include
126 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
127 (hint)->base.state == HINT_STATE_USED)
129 /* common data for all hints. */
132 const char *hint_str; /* must not do pfree */
133 const char *keyword; /* must not do pfree */
136 HintDeleteFunction delete_func;
137 HintDumpFunction dump_func;
138 HintCmpFunction cmp_func;
139 HintParseFunction parser_func;
142 /* scan method hints */
143 typedef struct ScanMethodHint
148 unsigned char enforce_mask;
151 /* join method hints */
152 typedef struct JoinMethodHint
157 unsigned char enforce_mask;
161 /* join order hints */
162 typedef struct LeadingHint
165 List *relations; /* relation names specified in Leading hint */
168 /* change a run-time parameter hints */
169 typedef struct SetHint
172 char *name; /* name of variable */
177 * Describes a context of hint processing.
181 char *hint_str; /* original hint string */
184 int nall_hints; /* # of valid all hints */
185 int max_all_hints; /* # of slots for all hints */
186 Hint **all_hints; /* parsed all hints */
188 /* # of each hints */
189 int num_hints[NUM_HINT_TYPE];
191 /* for scan method hints */
192 ScanMethodHint **scan_hints; /* parsed scan hints */
193 int init_scan_mask; /* initial value scan parameter */
194 Index parent_relid; /* inherit parent table relid */
195 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
197 /* for join method hints */
198 JoinMethodHint **join_hints; /* parsed join hints */
199 int init_join_mask; /* initial value join parameter */
200 List **join_hint_level;
202 /* for Leading hint */
203 LeadingHint *leading_hint; /* parsed last specified Leading hint */
206 SetHint **set_hints; /* parsed Set hints */
207 GucContext context; /* which GUC parameters can we set? */
211 * Describes a hint parser module which is bound with particular hint keyword.
213 typedef struct HintParser
216 HintCreateFunction create_func;
219 /* Module callbacks */
223 static void push_hint(HintState *hstate);
224 static void pop_hint(void);
226 static void pg_hint_plan_ProcessUtility(Node *parsetree,
227 const char *queryString,
228 ParamListInfo params, bool isTopLevel,
230 char *completionTag);
231 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
232 ParamListInfo boundParams);
233 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
234 Oid relationObjectId,
235 bool inhparent, RelOptInfo *rel);
236 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
240 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword);
241 static void ScanMethodHintDelete(ScanMethodHint *hint);
242 static void ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf);
243 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
244 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
245 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, HintState *hstate,
251 Query *parse, const char *str);
252 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword);
253 static void LeadingHintDelete(LeadingHint *hint);
254 static void LeadingHintDump(LeadingHint *hint, StringInfo buf);
255 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
256 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
257 Query *parse, const char *str);
258 static Hint *SetHintCreate(const char *hint_str, const char *keyword);
259 static void SetHintDelete(SetHint *hint);
260 static void SetHintDump(SetHint *hint, StringInfo buf);
261 static int SetHintCmp(const SetHint *a, const SetHint *b);
262 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
265 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
268 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
269 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
270 ListCell *other_rels);
271 static void make_rels_by_clauseless_joins(PlannerInfo *root,
273 ListCell *other_rels);
274 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
275 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
276 Index rti, RangeTblEntry *rte);
277 static List *accumulate_append_subpath(List *subpaths, Path *path);
278 static void set_dummy_rel_pathlist(RelOptInfo *rel);
279 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
283 static bool pg_hint_plan_enable = true;
284 static bool pg_hint_plan_debug_print = false;
285 static int pg_hint_plan_parse_messages = INFO;
287 static const struct config_enum_entry parse_messages_level_options[] = {
288 {"debug", DEBUG2, true},
289 {"debug5", DEBUG5, false},
290 {"debug4", DEBUG4, false},
291 {"debug3", DEBUG3, false},
292 {"debug2", DEBUG2, false},
293 {"debug1", DEBUG1, false},
295 {"info", INFO, false},
296 {"notice", NOTICE, false},
297 {"warning", WARNING, false},
298 {"error", ERROR, false},
300 * {"fatal", FATAL, true},
301 * {"panic", PANIC, true},
306 /* Saved hook values in case of unload */
307 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
308 static planner_hook_type prev_planner = NULL;
309 static get_relation_info_hook_type prev_get_relation_info = NULL;
310 static join_search_hook_type prev_join_search = NULL;
312 /* フック関数をまたがって使用する情報を管理する */
313 static HintState *current_hint = NULL;
315 /* 有効なヒントをスタック構造で管理する */
316 static List *HintStateStack = NIL;
319 * EXECUTEコマンド実行時に、ステートメント名を格納する。
320 * その他のコマンドの場合は、NULLに設定する。
322 static char *stmt_name = NULL;
324 static const HintParser parsers[] = {
325 {HINT_SEQSCAN, ScanMethodHintCreate},
326 {HINT_INDEXSCAN, ScanMethodHintCreate},
327 {HINT_BITMAPSCAN, ScanMethodHintCreate},
328 {HINT_TIDSCAN, ScanMethodHintCreate},
329 {HINT_NOSEQSCAN, ScanMethodHintCreate},
330 {HINT_NOINDEXSCAN, ScanMethodHintCreate},
331 {HINT_NOBITMAPSCAN, ScanMethodHintCreate},
332 {HINT_NOTIDSCAN, ScanMethodHintCreate},
333 {HINT_NESTLOOP, JoinMethodHintCreate},
334 {HINT_MERGEJOIN, JoinMethodHintCreate},
335 {HINT_HASHJOIN, JoinMethodHintCreate},
336 {HINT_NONESTLOOP, JoinMethodHintCreate},
337 {HINT_NOMERGEJOIN, JoinMethodHintCreate},
338 {HINT_NOHASHJOIN, JoinMethodHintCreate},
339 {HINT_LEADING, LeadingHintCreate},
340 {HINT_SET, SetHintCreate},
345 * Module load callbacks
350 /* Define custom GUC variables. */
351 DefineCustomBoolVariable("pg_hint_plan.enable",
352 "Force planner to use plans specified in the hint comment preceding to the query.",
354 &pg_hint_plan_enable,
362 DefineCustomBoolVariable("pg_hint_plan.debug_print",
363 "Logs results of hint parsing.",
365 &pg_hint_plan_debug_print,
373 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
374 "Messege level of parse errors.",
376 &pg_hint_plan_parse_messages,
378 parse_messages_level_options,
386 prev_ProcessUtility = ProcessUtility_hook;
387 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
388 prev_planner = planner_hook;
389 planner_hook = pg_hint_plan_planner;
390 prev_get_relation_info = get_relation_info_hook;
391 get_relation_info_hook = pg_hint_plan_get_relation_info;
392 prev_join_search = join_search_hook;
393 join_search_hook = pg_hint_plan_join_search;
397 * Module unload callback
403 /* Uninstall hooks. */
404 ProcessUtility_hook = prev_ProcessUtility;
405 planner_hook = prev_planner;
406 get_relation_info_hook = prev_get_relation_info;
407 join_search_hook = prev_join_search;
411 * create and delete functions the hint object
415 ScanMethodHintCreate(const char *hint_str, const char *keyword)
417 ScanMethodHint *hint;
419 hint = palloc(sizeof(ScanMethodHint));
420 hint->base.hint_str = hint_str;
421 hint->base.keyword = keyword;
422 hint->base.type = HINT_TYPE_SCAN_METHOD;
423 hint->base.state = HINT_STATE_NOTUSED;
424 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
425 hint->base.dump_func = (HintDumpFunction) ScanMethodHintDump;
426 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
427 hint->base.parser_func = (HintParseFunction) ScanMethodHintParse;
428 hint->relname = NULL;
429 hint->indexnames = NIL;
430 hint->enforce_mask = 0;
432 return (Hint *) hint;
436 ScanMethodHintDelete(ScanMethodHint *hint)
442 pfree(hint->relname);
443 list_free_deep(hint->indexnames);
448 JoinMethodHintCreate(const char *hint_str, const char *keyword)
450 JoinMethodHint *hint;
452 hint = palloc(sizeof(JoinMethodHint));
453 hint->base.hint_str = hint_str;
454 hint->base.keyword = keyword;
455 hint->base.type = HINT_TYPE_JOIN_METHOD;
456 hint->base.state = HINT_STATE_NOTUSED;
457 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
458 hint->base.dump_func = (HintDumpFunction) JoinMethodHintDump;
459 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
460 hint->base.parser_func = (HintParseFunction) JoinMethodHintParse;
462 hint->relnames = NULL;
463 hint->enforce_mask = 0;
464 hint->joinrelids = NULL;
466 return (Hint *) hint;
470 JoinMethodHintDelete(JoinMethodHint *hint)
479 for (i = 0; i < hint->nrels; i++)
480 pfree(hint->relnames[i]);
481 pfree(hint->relnames);
483 bms_free(hint->joinrelids);
488 LeadingHintCreate(const char *hint_str, const char *keyword)
492 hint = palloc(sizeof(LeadingHint));
493 hint->base.hint_str = hint_str;
494 hint->base.keyword = keyword;
495 hint->base.type = HINT_TYPE_LEADING;
496 hint->base.state = HINT_STATE_NOTUSED;
497 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
498 hint->base.dump_func = (HintDumpFunction) LeadingHintDump;
499 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
500 hint->base.parser_func = (HintParseFunction) LeadingHintParse;
501 hint->relations = NIL;
503 return (Hint *) hint;
507 LeadingHintDelete(LeadingHint *hint)
512 list_free_deep(hint->relations);
517 SetHintCreate(const char *hint_str, const char *keyword)
521 hint = palloc(sizeof(SetHint));
522 hint->base.hint_str = hint_str;
523 hint->base.keyword = keyword;
524 hint->base.type = HINT_TYPE_SET;
525 hint->base.state = HINT_STATE_NOTUSED;
526 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
527 hint->base.dump_func = (HintDumpFunction) SetHintDump;
528 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
529 hint->base.parser_func = (HintParseFunction) SetHintParse;
533 return (Hint *) hint;
537 SetHintDelete(SetHint *hint)
550 HintStateCreate(void)
554 hstate = palloc(sizeof(HintState));
555 hstate->hint_str = NULL;
556 hstate->nall_hints = 0;
557 hstate->max_all_hints = 0;
558 hstate->all_hints = NULL;
559 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
560 hstate->scan_hints = NULL;
561 hstate->init_scan_mask = 0;
562 hstate->parent_relid = 0;
563 hstate->parent_hint = NULL;
564 hstate->join_hints = NULL;
565 hstate->init_join_mask = 0;
566 hstate->join_hint_level = NULL;
567 hstate->leading_hint = NULL;
568 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
569 hstate->set_hints = NULL;
575 HintStateDelete(HintState *hstate)
582 if (hstate->hint_str)
583 pfree(hstate->hint_str);
585 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
586 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
587 if (hstate->all_hints)
588 pfree(hstate->all_hints);
596 dump_quote_value(StringInfo buf, const char *value)
598 bool need_quote = false;
601 for (str = value; *str != '\0'; str++)
603 if (isspace(*str) || *str == ')' || *str == '"')
606 appendStringInfoCharMacro(buf, '"');
611 for (str = value; *str != '\0'; str++)
614 appendStringInfoCharMacro(buf, '"');
616 appendStringInfoCharMacro(buf, *str);
620 appendStringInfoCharMacro(buf, '"');
624 ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf)
628 appendStringInfo(buf, "%s(", hint->base.keyword);
629 dump_quote_value(buf, hint->relname);
630 foreach(l, hint->indexnames)
632 appendStringInfoCharMacro(buf, ' ');
633 dump_quote_value(buf, (char *) lfirst(l));
635 appendStringInfoString(buf, ")\n");
639 JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf)
643 appendStringInfo(buf, "%s(", hint->base.keyword);
644 dump_quote_value(buf, hint->relnames[0]);
645 for (i = 1; i < hint->nrels; i++)
647 appendStringInfoCharMacro(buf, ' ');
648 dump_quote_value(buf, hint->relnames[i]);
650 appendStringInfoString(buf, ")\n");
655 LeadingHintDump(LeadingHint *hint, StringInfo buf)
660 appendStringInfo(buf, "%s(", HINT_LEADING);
662 foreach(l, hint->relations)
667 appendStringInfoCharMacro(buf, ' ');
669 dump_quote_value(buf, (char *) lfirst(l));
672 appendStringInfoString(buf, ")\n");
676 SetHintDump(SetHint *hint, StringInfo buf)
678 appendStringInfo(buf, "%s(", HINT_SET);
679 dump_quote_value(buf, hint->name);
680 appendStringInfoCharMacro(buf, ' ');
681 dump_quote_value(buf, hint->value);
682 appendStringInfo(buf, ")\n");
686 all_hint_dump(HintState *hstate, StringInfo buf, const char *title,
691 appendStringInfo(buf, "%s:\n", title);
692 for (i = 0; i < hstate->nall_hints; i++)
694 if (hstate->all_hints[i]->state != state)
697 hstate->all_hints[i]->dump_func(hstate->all_hints[i], buf);
702 HintStateDump(HintState *hstate)
708 elog(LOG, "pg_hint_plan:\nno hint");
712 initStringInfo(&buf);
714 appendStringInfoString(&buf, "pg_hint_plan:\n");
715 all_hint_dump(hstate, &buf, "used hint", HINT_STATE_USED);
716 all_hint_dump(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
717 all_hint_dump(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
718 all_hint_dump(hstate, &buf, "error hint", HINT_STATE_ERROR);
720 elog(LOG, "%s", buf.data);
730 RelnameCmp(const void *a, const void *b)
732 const char *relnamea = *((const char **) a);
733 const char *relnameb = *((const char **) b);
735 return strcmp(relnamea, relnameb);
739 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
741 return RelnameCmp(&a->relname, &b->relname);
745 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
749 if (a->nrels != b->nrels)
750 return a->nrels - b->nrels;
752 for (i = 0; i < a->nrels; i++)
755 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
763 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
769 SetHintCmp(const SetHint *a, const SetHint *b)
771 return strcmp(a->name, b->name);
775 HintCmp(const void *a, const void *b)
777 const Hint *hinta = *((const Hint **) a);
778 const Hint *hintb = *((const Hint **) b);
780 if (hinta->type != hintb->type)
781 return hinta->type - hintb->type;
783 return hinta->cmp_func(hinta, hintb);
789 HintCmpIsOrder(const void *a, const void *b)
791 const Hint *hinta = *((const Hint **) a);
792 const Hint *hintb = *((const Hint **) b);
795 result = HintCmp(a, b);
797 result = hinta->hint_str - hintb->hint_str;
807 parse_keyword(const char *str, StringInfo buf)
811 while (!isspace(*str) && *str != '(' && *str != '\0')
812 appendStringInfoCharMacro(buf, *str++);
818 skip_opened_parenthesis(const char *str)
824 parse_ereport(str, ("Opening parenthesis is necessary."));
834 skip_closed_parenthesis(const char *str)
840 parse_ereport(str, ("Closing parenthesis is necessary."));
850 * 二重引用符で囲まれているかもしれないトークンを読み取り word 引数に palloc
851 * で確保したバッファに格納してそのポインタを返す。
853 * 正常にパースできた場合は残りの文字列の先頭位置を、異常があった場合は NULL を
855 * truncateがtrueの場合は、NAMEDATALENに切り詰める。
858 parse_quote_value(const char *str, char **word, char *value_type, bool truncate)
866 initStringInfo(&buf);
879 /* 二重引用符が閉じられていない場合はパース中断 */
883 parse_ereport(str, ("Unterminated quoted %s.", value_type));
888 * エスケープ対象のダブルクウォートをスキップする。
889 * もしブロックコメントの開始文字列や終了文字列もオブジェクト名とし
890 * て使用したい場合は、/ と * もエスケープ対象とすることで使用できる
891 * が、処理対象としていない。もしテーブル名にこれらの文字が含まれる
892 * 場合は、エイリアスを指定する必要がある。
901 else if (isspace(*str) || *str == ')' || *str == '"' || *str == '\0')
904 appendStringInfoCharMacro(&buf, *str++);
911 type = pstrdup(value_type);
912 type[0] = toupper(type[0]);
913 parse_ereport(str, ("%s is necessary.", type));
921 /* Truncate name if it's overlength */
923 truncate_identifier(buf.data, strlen(buf.data), true);
931 parse_hints(HintState *hstate, Query *parse, const char *str)
936 initStringInfo(&buf);
939 const HintParser *parser;
941 /* in error message, we output the comment including the keyword. */
944 /* parse only the keyword of the hint. */
945 resetStringInfo(&buf);
946 str = parse_keyword(str, &buf);
948 for (parser = parsers; parser->keyword != NULL; parser++)
950 char *keyword = parser->keyword;
953 if (strcasecmp(buf.data, keyword) != 0)
956 hint = parser->create_func(head, keyword);
958 /* parser of each hint does parse in a parenthesis. */
959 if ((str = skip_opened_parenthesis(str)) == NULL ||
960 (str = hint->parser_func(hint, hstate, parse, str)) == NULL ||
961 (str = skip_closed_parenthesis(str)) == NULL)
963 hint->delete_func(hint);
969 * 出来上がったヒント情報を追加。スロットが足りない場合は二倍に拡張
972 if (hstate->nall_hints == 0)
974 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
975 hstate->all_hints = (Hint **)
976 palloc(sizeof(Hint *) * hstate->max_all_hints);
978 else if (hstate->nall_hints == hstate->max_all_hints)
980 hstate->max_all_hints *= 2;
981 hstate->all_hints = (Hint **)
982 repalloc(hstate->all_hints,
983 sizeof(Hint *) * hstate->max_all_hints);
986 hstate->all_hints[hstate->nall_hints] = hint;
987 hstate->nall_hints++;
994 if (parser->keyword == NULL)
997 ("Unrecognized hint keyword \"%s\".", buf.data));
1007 * Do basic parsing of the query head comment.
1010 parse_head_comment(Query *parse)
1019 /* get client-supplied query string. */
1022 PreparedStatement *entry;
1024 entry = FetchPreparedStatement(stmt_name, true);
1025 p = entry->plansource->query_string;
1028 p = debug_query_string;
1033 /* extract query head comment. */
1034 len = strlen(HINT_START);
1036 if (strncmp(p, HINT_START, len))
1043 /* find hint end keyword. */
1044 if ((tail = strstr(p, HINT_END)) == NULL)
1046 parse_ereport(head, ("Unterminated block comment."));
1050 /* 入れ子にしたブロックコメントはサポートしない */
1051 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1053 parse_ereport(head, ("Nested block comments are not supported."));
1059 head = palloc(len + 1);
1060 memcpy(head, p, len);
1064 hstate = HintStateCreate();
1065 hstate->hint_str = head;
1067 /* parse each hint. */
1068 parse_hints(hstate, parse, p);
1070 /* When nothing specified a hint, we free HintState and returns NULL. */
1071 if (hstate->nall_hints == 0)
1073 HintStateDelete(hstate);
1077 /* パースしたヒントを並び替える */
1078 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1082 for (i = 0; i < hstate->nall_hints; i++)
1084 Hint *hint = hstate->all_hints[i];
1086 hstate->num_hints[hint->type]++;
1088 if (i + 1 >= hstate->nall_hints)
1091 if (HintCmp(hstate->all_hints + i, hstate->all_hints + i + 1) == 0)
1093 const char *HintTypeName[] = {
1094 "scan method", "join method", "leading", "set"
1097 parse_ereport(hstate->all_hints[i]->hint_str,
1098 ("Conflict %s hint.", HintTypeName[hint->type]));
1099 hstate->all_hints[i]->state = HINT_STATE_DUPLICATION;
1103 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1104 hstate->join_hints = (JoinMethodHint **) hstate->all_hints +
1105 hstate->num_hints[HINT_TYPE_SCAN_METHOD];
1106 hstate->leading_hint = (LeadingHint *) hstate->all_hints[
1107 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1108 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1109 hstate->num_hints[HINT_TYPE_LEADING] - 1];
1110 hstate->set_hints = (SetHint **) hstate->all_hints +
1111 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1112 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1113 hstate->num_hints[HINT_TYPE_LEADING];
1119 * スキャン方式ヒントのカッコ内をパースする
1122 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1125 const char *keyword = hint->base.keyword;
1128 * スキャン方式のヒントでリレーション名が読み取れない場合はヒント無効
1130 if ((str = parse_quote_value(str, &hint->relname, "relation name", true))
1137 * インデックスリストを受け付けるヒントであれば、インデックス参照をパース
1140 if (strcmp(keyword, HINT_INDEXSCAN) == 0 ||
1141 strcmp(keyword, HINT_BITMAPSCAN) == 0)
1143 while (*str != ')' && *str != '\0')
1147 str = parse_quote_value(str, &indexname, "index name", true);
1151 hint->indexnames = lappend(hint->indexnames, indexname);
1157 * ヒントごとに決まっている許容スキャン方式をビットマスクとして設定
1159 if (strcasecmp(keyword, HINT_SEQSCAN) == 0)
1160 hint->enforce_mask = ENABLE_SEQSCAN;
1161 else if (strcasecmp(keyword, HINT_INDEXSCAN) == 0)
1162 hint->enforce_mask = ENABLE_INDEXSCAN;
1163 else if (strcasecmp(keyword, HINT_BITMAPSCAN) == 0)
1164 hint->enforce_mask = ENABLE_BITMAPSCAN;
1165 else if (strcasecmp(keyword, HINT_TIDSCAN) == 0)
1166 hint->enforce_mask = ENABLE_TIDSCAN;
1167 else if (strcasecmp(keyword, HINT_NOSEQSCAN) == 0)
1168 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1169 else if (strcasecmp(keyword, HINT_NOINDEXSCAN) == 0)
1170 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1171 else if (strcasecmp(keyword, HINT_NOBITMAPSCAN) == 0)
1172 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1173 else if (strcasecmp(keyword, HINT_NOTIDSCAN) == 0)
1174 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1177 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1185 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1189 const char *keyword = hint->base.keyword;
1193 hint->relnames = palloc(sizeof(char *));
1195 while ((str = parse_quote_value(str, &relname, "relation name", true))
1199 hint->relnames = repalloc(hint->relnames, sizeof(char *) * hint->nrels);
1200 hint->relnames[hint->nrels - 1] = relname;
1210 /* Join 対象のテーブルは最低でも2つ指定する必要がある */
1211 if (hint->nrels < 2)
1214 ("%s hint requires at least two relations.",
1215 hint->base.keyword));
1216 hint->base.state = HINT_STATE_ERROR;
1220 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1222 if (strcasecmp(keyword, HINT_NESTLOOP) == 0)
1223 hint->enforce_mask = ENABLE_NESTLOOP;
1224 else if (strcasecmp(keyword, HINT_MERGEJOIN) == 0)
1225 hint->enforce_mask = ENABLE_MERGEJOIN;
1226 else if (strcasecmp(keyword, HINT_HASHJOIN) == 0)
1227 hint->enforce_mask = ENABLE_HASHJOIN;
1228 else if (strcasecmp(keyword, HINT_NONESTLOOP) == 0)
1229 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1230 else if (strcasecmp(keyword, HINT_NOMERGEJOIN) == 0)
1231 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1232 else if (strcasecmp(keyword, HINT_NOHASHJOIN) == 0)
1233 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1236 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1244 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1253 if ((str = parse_quote_value(str, &relname, "relation name", true))
1257 hint->relations = lappend(hint->relations, relname);
1262 /* テーブル指定が2つ未満の場合は、Leading ヒントはエラーとする */
1263 if (list_length(hint->relations) < 2)
1265 parse_ereport(hint->base.hint_str,
1266 ("%s hint requires at least two relations.",
1268 hint->base.state = HINT_STATE_ERROR;
1275 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1277 if ((str = parse_quote_value(str, &hint->name, "parameter name", true))
1279 (str = parse_quote_value(str, &hint->value, "parameter value", false))
1287 * set GUC parameter functions
1291 set_config_option_wrapper(const char *name, const char *value,
1292 GucContext context, GucSource source,
1293 GucAction action, bool changeVal, int elevel)
1296 MemoryContext ccxt = CurrentMemoryContext;
1300 result = set_config_option(name, value, context, source,
1307 /* Save error info */
1308 MemoryContextSwitchTo(ccxt);
1309 errdata = CopyErrorData();
1312 ereport(elevel, (errcode(errdata->sqlerrcode),
1313 errmsg("%s", errdata->message),
1314 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1315 errdata->hint ? errhint("%s", errdata->hint) : 0));
1316 FreeErrorData(errdata);
1324 set_config_options(SetHint **options, int noptions, GucContext context)
1329 save_nestlevel = NewGUCNestLevel();
1331 for (i = 0; i < noptions; i++)
1333 SetHint *hint = options[i];
1336 if (!hint_state_enabled(hint))
1339 result = set_config_option_wrapper(hint->name, hint->value, context,
1340 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1341 pg_hint_plan_parse_messages);
1343 hint->base.state = HINT_STATE_USED;
1345 hint->base.state = HINT_STATE_ERROR;
1348 return save_nestlevel;
1351 #define SET_CONFIG_OPTION(name, type_bits) \
1352 set_config_option_wrapper((name), \
1353 (mask & (type_bits)) ? "true" : "false", \
1354 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1357 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1361 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1362 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1364 mask = enforce_mask;
1366 mask = enforce_mask & current_hint->init_scan_mask;
1368 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1369 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1370 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1371 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1375 set_join_config_options(unsigned char enforce_mask, GucContext context)
1379 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1380 enforce_mask == ENABLE_HASHJOIN)
1381 mask = enforce_mask;
1383 mask = enforce_mask & current_hint->init_join_mask;
1385 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1386 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1387 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1391 * pg_hint_plan hook functions
1395 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1396 ParamListInfo params, bool isTopLevel,
1397 DestReceiver *dest, char *completionTag)
1401 if (!pg_hint_plan_enable)
1403 if (prev_ProcessUtility)
1404 (*prev_ProcessUtility) (parsetree, queryString, params,
1405 isTopLevel, dest, completionTag);
1407 standard_ProcessUtility(parsetree, queryString, params,
1408 isTopLevel, dest, completionTag);
1414 if (IsA(node, ExplainStmt))
1417 * EXPLAIN対象のクエリのパースツリーを取得する
1422 stmt = (ExplainStmt *) node;
1424 Assert(IsA(stmt->query, Query));
1425 query = (Query *) stmt->query;
1427 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1428 node = query->utilityStmt;
1432 * EXECUTEコマンドならば、PREPARE時に指定されたクエリ文字列を取得し、ヒント
1435 if (IsA(node, ExecuteStmt))
1439 stmt = (ExecuteStmt *) node;
1440 stmt_name = stmt->name;
1447 if (prev_ProcessUtility)
1448 (*prev_ProcessUtility) (parsetree, queryString, params,
1449 isTopLevel, dest, completionTag);
1451 standard_ProcessUtility(parsetree, queryString, params,
1452 isTopLevel, dest, completionTag);
1466 if (prev_ProcessUtility)
1467 (*prev_ProcessUtility) (parsetree, queryString, params,
1468 isTopLevel, dest, completionTag);
1470 standard_ProcessUtility(parsetree, queryString, params,
1471 isTopLevel, dest, completionTag);
1475 * ヒント用スタック構造にヒントをプッシュする。なお、List構造体でヒント用スタッ
1476 * ク構造を実装していて、リストの先頭がスタックの一番上に該当する。
1479 push_hint(HintState *hstate)
1481 /* 新しいヒントをスタックに積む。 */
1482 HintStateStack = lcons(hstate, HintStateStack);
1485 * 先ほどスタックに積んだヒントを現在のヒントとしてcurrent_hintに格納する。
1487 current_hint = hstate;
1491 * ヒント用スタック構造から不要になったヒントをポップする。取り出されたヒントは
1497 /* ヒントのスタックが空の場合はエラーを返す */
1498 if(HintStateStack == NIL)
1499 elog(ERROR, "hint stack is empty");
1502 * ヒントのスタックから一番上のものを取り出して解放する。 current_hintは
1503 * 常に最上段ヒントを指す(スタックが空の場合はNULL)。
1505 HintStateStack = list_delete_first(HintStateStack);
1506 HintStateDelete(current_hint);
1507 if(HintStateStack == NIL)
1508 current_hint = NULL;
1510 current_hint = (HintState *) lfirst(list_head(HintStateStack));
1513 static PlannedStmt *
1514 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1517 PlannedStmt *result;
1521 * pg_hint_planが無効である場合は通常のparser処理をおこなう。
1522 * 他のフック関数で実行されるhint処理をスキップするために、current_hint 変数
1525 if (!pg_hint_plan_enable)
1527 current_hint = NULL;
1530 return (*prev_planner) (parse, cursorOptions, boundParams);
1532 return standard_planner(parse, cursorOptions, boundParams);
1536 hstate = parse_head_comment(parse);
1539 * hintが指定されない、または空のhintを指定された場合は通常のparser処理をお
1541 * 他のフック関数で実行されるhint処理をスキップするために、current_hint 変数
1546 current_hint = NULL;
1549 return (*prev_planner) (parse, cursorOptions, boundParams);
1551 return standard_planner(parse, cursorOptions, boundParams);
1554 /* 現在のヒントをスタックに積む。 */
1557 /* Set hint で指定されたGUCパラメータを設定する */
1558 save_nestlevel = set_config_options(current_hint->set_hints,
1559 current_hint->num_hints[HINT_TYPE_SET],
1560 current_hint->context);
1563 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
1564 if (enable_indexscan)
1565 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
1566 if (enable_bitmapscan)
1567 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
1569 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
1570 if (enable_nestloop)
1571 current_hint->init_join_mask |= ENABLE_NESTLOOP;
1572 if (enable_mergejoin)
1573 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
1574 if (enable_hashjoin)
1575 current_hint->init_join_mask |= ENABLE_HASHJOIN;
1578 * プラン作成中にエラーとなった場合、GUCパラメータと current_hintを
1579 * pg_hint_plan_planner 関数の実行前の状態に戻す。
1584 result = (*prev_planner) (parse, cursorOptions, boundParams);
1586 result = standard_planner(parse, cursorOptions, boundParams);
1591 * プランナ起動前の状態に戻すため、GUCパラメータを復元し、ヒント情報を
1594 AtEOXact_GUC(true, save_nestlevel);
1601 * Print hint if debugging.
1603 if (pg_hint_plan_debug_print)
1604 HintStateDump(current_hint);
1607 * プランナ起動前の状態に戻すため、GUCパラメータを復元し、ヒント情報を一つ
1610 AtEOXact_GUC(true, save_nestlevel);
1617 * aliasnameと一致するSCANヒントを探す
1619 static ScanMethodHint *
1620 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
1626 * RELOPT_BASEREL でなければ、scan method ヒントが適用しない。
1627 * 子テーブルの場合はRELOPT_OTHER_MEMBER_RELとなるが、サポート対象外とする。
1628 * また、通常のリレーション以外は、スキャン方式を選択できない。
1630 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
1633 rte = root->simple_rte_array[rel->relid];
1635 /* 外部表はスキャン方式が選択できない。 */
1636 if (rte->relkind == RELKIND_FOREIGN_TABLE)
1640 * スキャン方式のヒントのリストから、検索対象のリレーションと名称が一致する
1643 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1645 ScanMethodHint *hint = current_hint->scan_hints[i];
1647 /* すでに無効となっているヒントは検索対象にしない。 */
1648 if (!hint_state_enabled(hint))
1651 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
1659 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel)
1666 * We delete all the IndexOptInfo list and prevent you from being usable by
1669 if (hint->enforce_mask == ENABLE_SEQSCAN ||
1670 hint->enforce_mask == ENABLE_TIDSCAN)
1672 list_free_deep(rel->indexlist);
1673 rel->indexlist = NIL;
1674 hint->base.state = HINT_STATE_USED;
1680 * When a list of indexes is not specified, we just use all indexes.
1682 if (hint->indexnames == NIL)
1686 * Leaving only an specified index, we delete it from a IndexOptInfo list
1690 for (cell = list_head(rel->indexlist); cell; cell = next)
1692 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
1693 char *indexname = get_rel_name(info->indexoid);
1695 bool use_index = false;
1699 foreach(l, hint->indexnames)
1701 if (RelnameCmp(&indexname, &lfirst(l)) == 0)
1709 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
1718 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
1719 bool inhparent, RelOptInfo *rel)
1721 ScanMethodHint *hint;
1723 if (prev_get_relation_info)
1724 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
1726 /* 有効なヒントが指定されなかった場合は処理をスキップする。 */
1732 /* store does relids of parent table. */
1733 current_hint->parent_relid = rel->relid;
1735 else if (current_hint->parent_relid != 0)
1738 * We use the same GUC parameter if this table is the child table of a
1739 * table called pg_hint_plan_get_relation_info just before that.
1743 /* append_rel_list contains all append rels; ignore others */
1744 foreach(l, root->append_rel_list)
1746 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1748 /* This rel is child table. */
1749 if (appinfo->parent_relid == current_hint->parent_relid &&
1750 appinfo->child_relid == rel->relid)
1752 if (current_hint->parent_hint)
1753 delete_indexes(current_hint->parent_hint, rel);
1759 /* This rel is not inherit table. */
1760 current_hint->parent_relid = 0;
1761 current_hint->parent_hint = NULL;
1764 /* scan hint が指定されない場合は、GUCパラメータをリセットする。 */
1765 if ((hint = find_scan_hint(root, rel)) == NULL)
1767 set_scan_config_options(current_hint->init_scan_mask,
1768 current_hint->context);
1771 set_scan_config_options(hint->enforce_mask, current_hint->context);
1772 hint->base.state = HINT_STATE_USED;
1774 current_hint->parent_hint = hint;
1776 delete_indexes(hint, rel);
1780 * aliasnameがクエリ中に指定した別名と一致する場合は、そのインデックスを返し、一
1782 * aliasnameがクエリ中に複数回指定された場合は、-1を返す。
1785 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
1791 for (i = 1; i < root->simple_rel_array_size; i++)
1795 if (root->simple_rel_array[i] == NULL)
1798 Assert(i == root->simple_rel_array[i]->relid);
1800 if (RelnameCmp(&aliasname,
1801 &root->simple_rte_array[i]->eref->aliasname) != 0)
1804 foreach(l, initial_rels)
1806 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
1808 if (rel->reloptkind == RELOPT_BASEREL)
1810 if (rel->relid != i)
1815 Assert(rel->reloptkind == RELOPT_JOINREL);
1817 if (!bms_is_member(i, rel->relids))
1824 ("Relation name \"%s\" is ambiguous.",
1839 * relidビットマスクと一致するヒントを探す
1841 static JoinMethodHint *
1842 find_join_hint(Relids joinrelids)
1847 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
1849 foreach(l, join_hint)
1851 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
1853 if (bms_equal(joinrelids, hint->joinrelids))
1861 * 結合方式のヒントを使用しやすい構造に変換する。
1864 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
1865 List *initial_rels, JoinMethodHint **join_method_hints)
1874 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
1876 JoinMethodHint *hint = hstate->join_hints[i];
1879 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
1882 bms_free(hint->joinrelids);
1883 hint->joinrelids = NULL;
1885 for (j = 0; j < hint->nrels; j++)
1887 char *relname = hint->relnames[j];
1889 relid = find_relid_aliasname(root, relname, initial_rels,
1890 hint->base.hint_str);
1893 hint->base.state = HINT_STATE_ERROR;
1898 if (bms_is_member(relid, hint->joinrelids))
1900 parse_ereport(hint->base.hint_str,
1901 ("Relation name \"%s\" is duplicated.", relname));
1902 hint->base.state = HINT_STATE_ERROR;
1906 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
1909 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
1912 hstate->join_hint_level[hint->nrels] =
1913 lappend(hstate->join_hint_level[hint->nrels], hint);
1917 * 有効なLeading ヒントが指定されている場合は、結合順にあわせて join method
1918 * hint のフォーマットに変換する。
1920 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
1923 lhint = hstate->leading_hint;
1924 if (!hint_state_enabled(lhint))
1927 /* Leading hint は、全ての join 方式が有効な hint として登録する */
1930 foreach(l, lhint->relations)
1932 char *relname = (char *)lfirst(l);
1933 JoinMethodHint *hint;
1936 find_relid_aliasname(root, relname, initial_rels,
1941 bms_free(joinrelids);
1948 if (bms_is_member(relid, joinrelids))
1950 parse_ereport(lhint->base.hint_str,
1951 ("Relation name \"%s\" is duplicated.", relname));
1952 lhint->base.state = HINT_STATE_ERROR;
1953 bms_free(joinrelids);
1957 joinrelids = bms_add_member(joinrelids, relid);
1963 hint = find_join_hint(joinrelids);
1967 * Here relnames is not set, since Relids bitmap is sufficient to
1968 * control paths of this query afterwards.
1970 hint = (JoinMethodHint *) JoinMethodHintCreate(lhint->base.hint_str,
1972 hint->base.state = HINT_STATE_USED;
1973 hint->nrels = njoinrels;
1974 hint->enforce_mask = ENABLE_ALL_JOIN;
1975 hint->joinrelids = bms_copy(joinrelids);
1978 join_method_hints[njoinrels] = hint;
1980 if (njoinrels >= nbaserel)
1984 bms_free(joinrelids);
1989 for (i = 2; i <= njoinrels; i++)
1991 /* Leading で指定した組み合わせ以外の join hint を削除する */
1992 list_free(hstate->join_hint_level[i]);
1994 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
1997 if (hint_state_enabled(lhint))
1998 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2000 lhint->base.state = HINT_STATE_USED;
2005 * set_plain_rel_pathlist
2006 * Build access paths for a plain relation (no subquery, no inheritance)
2008 * This function was copied and edited from set_plain_rel_pathlist() in
2009 * src/backend/optimizer/path/allpaths.c
2012 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2014 /* Consider sequential scan */
2015 add_path(rel, create_seqscan_path(root, rel));
2017 /* Consider index scans */
2018 create_index_paths(root, rel);
2020 /* Consider TID scans */
2021 create_tidscan_paths(root, rel);
2023 /* Now find the cheapest of the paths for this rel */
2028 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
2033 foreach(l, initial_rels)
2035 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2037 ScanMethodHint *hint;
2040 * スキャン方式が選択できるリレーションのみ、スキャンパスを再生成する。
2042 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2045 rte = root->simple_rte_array[rel->relid];
2047 /* 外部表はスキャン方式が選択できない。 */
2048 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2052 * scan method hint が指定されていなければ、初期値のGUCパラメータでscan
2055 if ((hint = find_scan_hint(root, rel)) == NULL)
2056 set_scan_config_options(hstate->init_scan_mask,
2060 set_scan_config_options(hint->enforce_mask, hstate->context);
2061 hint->base.state = HINT_STATE_USED;
2064 list_free_deep(rel->pathlist);
2065 rel->pathlist = NIL;
2068 /* It's an "append relation", process accordingly */
2069 set_append_rel_pathlist(root, rel, rel->relid, rte);
2073 set_plain_rel_pathlist(root, rel, rte);
2078 * Restore the GUC variables we set above.
2080 set_scan_config_options(hstate->init_scan_mask, hstate->context);
2084 * make_join_rel() をラップする関数
2086 * ヒントにしたがって、enabele_* パラメータを変更した上で、make_join_rel()を
2090 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
2093 JoinMethodHint *hint;
2097 joinrelids = bms_union(rel1->relids, rel2->relids);
2098 hint = find_join_hint(joinrelids);
2099 bms_free(joinrelids);
2102 return pg_hint_plan_make_join_rel(root, rel1, rel2);
2104 save_nestlevel = NewGUCNestLevel();
2106 set_join_config_options(hint->enforce_mask, current_hint->context);
2108 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2109 hint->base.state = HINT_STATE_USED;
2112 * Restore the GUC variables we set above.
2114 AtEOXact_GUC(true, save_nestlevel);
2120 get_num_baserels(List *initial_rels)
2125 foreach(l, initial_rels)
2127 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2129 if (rel->reloptkind == RELOPT_BASEREL)
2131 else if (rel->reloptkind ==RELOPT_JOINREL)
2132 nbaserel+= bms_num_members(rel->relids);
2135 /* other values not expected here */
2136 elog(ERROR, "Unrecognized reloptkind type: %d", rel->reloptkind);
2144 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
2147 JoinMethodHint **join_method_hints;
2153 * pg_hint_planが無効、または有効なヒントが1つも指定されなかった場合は、標準
2158 if (prev_join_search)
2159 return (*prev_join_search) (root, levels_needed, initial_rels);
2160 else if (enable_geqo && levels_needed >= geqo_threshold)
2161 return geqo(root, levels_needed, initial_rels);
2163 return standard_join_search(root, levels_needed, initial_rels);
2166 /* We apply scan method hint rebuild scan path. */
2167 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
2170 * GEQOを使用する条件を満たした場合は、GEQOを用いた結合方式の検索を行う。
2171 * このとき、スキャン方式のヒントとSetヒントのみが有効になり、結合方式や結合
2172 * 順序はヒント句は無効になりGEQOのアルゴリズムで決定される。
2174 if (enable_geqo && levels_needed >= geqo_threshold)
2175 return geqo(root, levels_needed, initial_rels);
2177 nbaserel = get_num_baserels(initial_rels);
2178 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
2179 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
2181 transform_join_hints(current_hint, root, nbaserel, initial_rels,
2184 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
2186 for (i = 2; i <= nbaserel; i++)
2188 list_free(current_hint->join_hint_level[i]);
2190 /* free Leading hint only */
2191 if (join_method_hints[i] != NULL &&
2192 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
2193 JoinMethodHintDelete(join_method_hints[i]);
2195 pfree(current_hint->join_hint_level);
2196 pfree(join_method_hints);
2198 if (current_hint->num_hints[HINT_TYPE_LEADING] > 0 &&
2199 hint_state_enabled(current_hint->leading_hint))
2200 set_join_config_options(current_hint->init_join_mask,
2201 current_hint->context);
2208 * Build access paths for a base relation
2210 * This function was copied and edited from set_rel_pathlist() in
2211 * src/backend/optimizer/path/allpaths.c
2214 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
2215 Index rti, RangeTblEntry *rte)
2219 /* It's an "append relation", process accordingly */
2220 set_append_rel_pathlist(root, rel, rti, rte);
2224 if (rel->rtekind == RTE_RELATION)
2226 if (rte->relkind == RELKIND_RELATION)
2228 /* Plain relation */
2229 set_plain_rel_pathlist(root, rel, rte);
2232 elog(ERROR, "Unexpected relkind: %c", rte->relkind);
2235 elog(ERROR, "Unexpected rtekind: %d", (int) rel->rtekind);
2239 #define standard_join_search pg_hint_plan_standard_join_search
2240 #define join_search_one_level pg_hint_plan_join_search_one_level
2241 #define make_join_rel make_join_rel_wrapper
2244 #undef make_join_rel
2245 #define make_join_rel pg_hint_plan_make_join_rel
2246 #define add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype, sjinfo, restrictlist) \
2248 ScanMethodHint *hint = NULL; \
2249 if ((hint = find_scan_hint((root), (innerrel))) != NULL) \
2251 set_scan_config_options(hint->enforce_mask, current_hint->context); \
2252 hint->base.state = HINT_STATE_USED; \
2254 add_paths_to_joinrel((root), (joinrel), (outerrel), (innerrel), (jointype), (sjinfo), (restrictlist)); \
2256 set_scan_config_options(current_hint->init_scan_mask, current_hint->context); \
2258 #include "make_join_rel.c"