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 "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 #define HINT_NESTLOOP "NestLoop"
54 #define HINT_MERGEJOIN "MergeJoin"
55 #define HINT_HASHJOIN "HashJoin"
56 #define HINT_NONESTLOOP "NoNestLoop"
57 #define HINT_NOMERGEJOIN "NoMergeJoin"
58 #define HINT_NOHASHJOIN "NoHashJoin"
59 #define HINT_LEADING "Leading"
60 #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 | ENABLE_BITMAPSCAN \
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 PlanHint PlanHint;
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, PlanHint *plan,
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 pg_hint_plan_ProcessUtility(Node *parsetree,
224 const char *queryString,
225 ParamListInfo params, bool isTopLevel,
227 char *completionTag);
228 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
229 ParamListInfo boundParams);
230 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
231 Oid relationObjectId,
232 bool inhparent, RelOptInfo *rel);
233 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
237 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword);
238 static void ScanMethodHintDelete(ScanMethodHint *hint);
239 static void ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf);
240 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
241 static const char *ScanMethodHintParse(ScanMethodHint *hint, PlanHint *plan,
242 Query *parse, const char *str);
243 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword);
244 static void JoinMethodHintDelete(JoinMethodHint *hint);
245 static void JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf);
246 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
247 static const char *JoinMethodHintParse(JoinMethodHint *hint, PlanHint *plan,
248 Query *parse, const char *str);
249 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword);
250 static void LeadingHintDelete(LeadingHint *hint);
251 static void LeadingHintDump(LeadingHint *hint, StringInfo buf);
252 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
253 static const char *LeadingHintParse(LeadingHint *hint, PlanHint *plan,
254 Query *parse, const char *str);
255 static Hint *SetHintCreate(const char *hint_str, const char *keyword);
256 static void SetHintDelete(SetHint *hint);
257 static void SetHintDump(SetHint *hint, StringInfo buf);
258 static int SetHintCmp(const SetHint *a, const SetHint *b);
259 static const char *SetHintParse(SetHint *hint, PlanHint *plan, Query *parse,
262 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
265 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
266 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
267 ListCell *other_rels);
268 static void make_rels_by_clauseless_joins(PlannerInfo *root,
270 ListCell *other_rels);
271 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
272 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
273 Index rti, RangeTblEntry *rte);
274 static List *accumulate_append_subpath(List *subpaths, Path *path);
275 static void set_dummy_rel_pathlist(RelOptInfo *rel);
276 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
281 static bool pg_hint_plan_enable = true;
282 static bool pg_hint_plan_debug_print = false;
283 static int pg_hint_plan_parse_messages = INFO;
285 static const struct config_enum_entry parse_messages_level_options[] = {
286 {"debug", DEBUG2, true},
287 {"debug5", DEBUG5, false},
288 {"debug4", DEBUG4, false},
289 {"debug3", DEBUG3, false},
290 {"debug2", DEBUG2, false},
291 {"debug1", DEBUG1, false},
293 {"info", INFO, false},
294 {"notice", NOTICE, false},
295 {"warning", WARNING, false},
296 {"error", ERROR, false},
298 * {"fatal", FATAL, true},
299 * {"panic", PANIC, true},
304 /* Saved hook values in case of unload */
305 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
306 static planner_hook_type prev_planner = NULL;
307 static get_relation_info_hook_type prev_get_relation_info = NULL;
308 static join_search_hook_type prev_join_search = NULL;
310 /* フック関数をまたがって使用する情報を管理する */
311 static PlanHint *global = NULL;
314 * EXECUTEコマンド実行時に、ステートメント名を格納する。
315 * その他のコマンドの場合は、NULLに設定する。
317 static char *stmt_name = NULL;
319 static const HintParser parsers[] = {
320 {HINT_SEQSCAN, ScanMethodHintCreate},
321 {HINT_INDEXSCAN, ScanMethodHintCreate},
322 {HINT_BITMAPSCAN, ScanMethodHintCreate},
323 {HINT_TIDSCAN, ScanMethodHintCreate},
324 {HINT_NOSEQSCAN, ScanMethodHintCreate},
325 {HINT_NOINDEXSCAN, ScanMethodHintCreate},
326 {HINT_NOBITMAPSCAN, ScanMethodHintCreate},
327 {HINT_NOTIDSCAN, ScanMethodHintCreate},
328 {HINT_NESTLOOP, JoinMethodHintCreate},
329 {HINT_MERGEJOIN, JoinMethodHintCreate},
330 {HINT_HASHJOIN, JoinMethodHintCreate},
331 {HINT_NONESTLOOP, JoinMethodHintCreate},
332 {HINT_NOMERGEJOIN, JoinMethodHintCreate},
333 {HINT_NOHASHJOIN, JoinMethodHintCreate},
334 {HINT_LEADING, LeadingHintCreate},
335 {HINT_SET, SetHintCreate},
340 * Module load callbacks
345 /* Define custom GUC variables. */
346 DefineCustomBoolVariable("pg_hint_plan.enable",
347 "Instructions or hints to the planner using block comments.",
349 &pg_hint_plan_enable,
357 DefineCustomBoolVariable("pg_hint_plan.debug_print",
358 "Logs each query's parse results of the hint.",
360 &pg_hint_plan_debug_print,
368 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
369 "Messege level of the parse error.",
371 &pg_hint_plan_parse_messages,
373 parse_messages_level_options,
381 prev_ProcessUtility = ProcessUtility_hook;
382 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
383 prev_planner = planner_hook;
384 planner_hook = pg_hint_plan_planner;
385 prev_get_relation_info = get_relation_info_hook;
386 get_relation_info_hook = pg_hint_plan_get_relation_info;
387 prev_join_search = join_search_hook;
388 join_search_hook = pg_hint_plan_join_search;
392 * Module unload callback
398 /* Uninstall hooks. */
399 ProcessUtility_hook = prev_ProcessUtility;
400 planner_hook = prev_planner;
401 get_relation_info_hook = prev_get_relation_info;
402 join_search_hook = prev_join_search;
406 * create and delete functions the hint object
410 ScanMethodHintCreate(const char *hint_str, const char *keyword)
412 ScanMethodHint *hint;
414 hint = palloc(sizeof(ScanMethodHint));
415 hint->base.hint_str = hint_str;
416 hint->base.keyword = keyword;
417 hint->base.type = HINT_TYPE_SCAN_METHOD;
418 hint->base.state = HINT_STATE_NOTUSED;
419 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
420 hint->base.dump_func = (HintDumpFunction) ScanMethodHintDump;
421 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
422 hint->base.parser_func = (HintParseFunction) ScanMethodHintParse;
423 hint->relname = NULL;
424 hint->indexnames = NIL;
425 hint->enforce_mask = 0;
427 return (Hint *) hint;
431 ScanMethodHintDelete(ScanMethodHint *hint)
437 pfree(hint->relname);
438 list_free_deep(hint->indexnames);
443 JoinMethodHintCreate(const char *hint_str, const char *keyword)
445 JoinMethodHint *hint;
447 hint = palloc(sizeof(JoinMethodHint));
448 hint->base.hint_str = hint_str;
449 hint->base.keyword = keyword;
450 hint->base.type = HINT_TYPE_JOIN_METHOD;
451 hint->base.state = HINT_STATE_NOTUSED;
452 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
453 hint->base.dump_func = (HintDumpFunction) JoinMethodHintDump;
454 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
455 hint->base.parser_func = (HintParseFunction) JoinMethodHintParse;
457 hint->relnames = NULL;
458 hint->enforce_mask = 0;
459 hint->joinrelids = NULL;
461 return (Hint *) hint;
465 JoinMethodHintDelete(JoinMethodHint *hint)
474 for (i = 0; i < hint->nrels; i++)
475 pfree(hint->relnames[i]);
476 pfree(hint->relnames);
478 bms_free(hint->joinrelids);
483 LeadingHintCreate(const char *hint_str, const char *keyword)
487 hint = palloc(sizeof(LeadingHint));
488 hint->base.hint_str = hint_str;
489 hint->base.keyword = keyword;
490 hint->base.type = HINT_TYPE_LEADING;
491 hint->base.state = HINT_STATE_NOTUSED;
492 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
493 hint->base.dump_func = (HintDumpFunction) LeadingHintDump;
494 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
495 hint->base.parser_func = (HintParseFunction) LeadingHintParse;
496 hint->relations = NIL;
498 return (Hint *) hint;
502 LeadingHintDelete(LeadingHint *hint)
507 list_free_deep(hint->relations);
512 SetHintCreate(const char *hint_str, const char *keyword)
516 hint = palloc(sizeof(SetHint));
517 hint->base.hint_str = hint_str;
518 hint->base.keyword = keyword;
519 hint->base.type = HINT_TYPE_SET;
520 hint->base.state = HINT_STATE_NOTUSED;
521 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
522 hint->base.dump_func = (HintDumpFunction) SetHintDump;
523 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
524 hint->base.parser_func = (HintParseFunction) SetHintParse;
528 return (Hint *) hint;
532 SetHintDelete(SetHint *hint)
549 hint = palloc(sizeof(PlanHint));
550 hint->hint_str = NULL;
551 hint->nall_hints = 0;
552 hint->max_all_hints = 0;
553 hint->all_hints = NULL;
554 memset(hint->num_hints, 0, sizeof(hint->num_hints));
555 hint->scan_hints = NULL;
556 hint->init_scan_mask = 0;
557 hint->parent_relid = 0;
558 hint->parent_hint = NULL;
559 hint->join_hints = NULL;
560 hint->init_join_mask = 0;
561 hint->join_hint_level = NULL;
562 hint->leading_hint = NULL;
563 hint->context = superuser() ? PGC_SUSET : PGC_USERSET;
564 hint->set_hints = NULL;
570 PlanHintDelete(PlanHint *hint)
578 pfree(hint->hint_str);
580 for (i = 0; i < hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
581 hint->all_hints[i]->delete_func(hint->all_hints[i]);
583 pfree(hint->all_hints);
591 dump_quote_value(StringInfo buf, const char *value)
593 bool need_quote = false;
596 for (str = value; *str != '\0'; str++)
598 if (isspace(*str) || *str == ')' || *str == '"')
601 appendStringInfoCharMacro(buf, '"');
606 for (str = value; *str != '\0'; str++)
609 appendStringInfoCharMacro(buf, '"');
611 appendStringInfoCharMacro(buf, *str);
615 appendStringInfoCharMacro(buf, '"');
619 ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf)
623 appendStringInfo(buf, "%s(", hint->base.keyword);
624 dump_quote_value(buf, hint->relname);
625 foreach(l, hint->indexnames)
627 appendStringInfoCharMacro(buf, ' ');
628 dump_quote_value(buf, (char *) lfirst(l));
630 appendStringInfoString(buf, ")\n");
634 JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf)
638 appendStringInfo(buf, "%s(", hint->base.keyword);
639 dump_quote_value(buf, hint->relnames[0]);
640 for (i = 1; i < hint->nrels; i++)
642 appendStringInfoCharMacro(buf, ' ');
643 dump_quote_value(buf, hint->relnames[i]);
645 appendStringInfoString(buf, ")\n");
650 LeadingHintDump(LeadingHint *hint, StringInfo buf)
655 appendStringInfo(buf, "%s(", HINT_LEADING);
657 foreach(l, hint->relations)
662 appendStringInfoCharMacro(buf, ' ');
664 dump_quote_value(buf, (char *) lfirst(l));
667 appendStringInfoString(buf, ")\n");
671 SetHintDump(SetHint *hint, StringInfo buf)
673 appendStringInfo(buf, "%s(", HINT_SET);
674 dump_quote_value(buf, hint->name);
675 appendStringInfoCharMacro(buf, ' ');
676 dump_quote_value(buf, hint->value);
677 appendStringInfo(buf, ")\n");
681 all_hint_dump(PlanHint *hint, StringInfo buf, const char *title,
686 appendStringInfo(buf, "%s:\n", title);
687 for (i = 0; i < hint->nall_hints; i++)
689 if (hint->all_hints[i]->state != state)
692 hint->all_hints[i]->dump_func(hint->all_hints[i], buf);
697 PlanHintDump(PlanHint *hint)
703 elog(LOG, "pg_hint_plan:\nno hint");
707 initStringInfo(&buf);
709 appendStringInfoString(&buf, "pg_hint_plan:\n");
710 all_hint_dump(hint, &buf, "used hint", HINT_STATE_USED);
711 all_hint_dump(hint, &buf, "not used hint", HINT_STATE_NOTUSED);
712 all_hint_dump(hint, &buf, "duplication hint", HINT_STATE_DUPLICATION);
713 all_hint_dump(hint, &buf, "error hint", HINT_STATE_ERROR);
715 elog(LOG, "%s", buf.data);
725 RelnameCmp(const void *a, const void *b)
727 const char *relnamea = *((const char **) a);
728 const char *relnameb = *((const char **) b);
730 return strcmp(relnamea, relnameb);
734 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
736 return RelnameCmp(&a->relname, &b->relname);
740 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
744 if (a->nrels != b->nrels)
745 return a->nrels - b->nrels;
747 for (i = 0; i < a->nrels; i++)
750 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
758 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
764 SetHintCmp(const SetHint *a, const SetHint *b)
766 return strcmp(a->name, b->name);
770 AllHintCmp(const void *a, const void *b, bool order)
772 const Hint *hinta = *((const Hint **) a);
773 const Hint *hintb = *((const Hint **) b);
776 if (hinta->type != hintb->type)
777 return hinta->type - hintb->type;
779 if ((result = hinta->cmp_func(hinta, hintb)) != 0 || !order)
783 return hinta->hint_str - hintb->hint_str;
787 AllHintCmpIsOrder(const void *a, const void *b)
789 return AllHintCmp(a, b, true);
797 parse_keyword(const char *str, StringInfo buf)
801 while (!isspace(*str) && *str != '(' && *str != '\0')
802 appendStringInfoCharMacro(buf, *str++);
808 skip_opened_parenthesis(const char *str)
814 parse_ereport(str, ("Opened parenthesis is necessary."));
824 skip_closed_parenthesis(const char *str)
830 parse_ereport(str, ("Closed parenthesis is necessary."));
840 * truncate_identifier() --- truncate an identifier to NAMEDATALEN-1 bytes.
842 * The given string is modified in-place, if necessary. A warning is
843 * issued if requested.
845 * We require the caller to pass in the string length since this saves a
846 * strlen() call in some common usages.
848 * This function was copied and edited from truncate_identifier() in
849 * src/backend/optimizer/path/allpaths.c
852 truncate_identifier(char *ident, int len, bool warn, const char *str)
854 if (len >= NAMEDATALEN)
856 len = pg_mbcliplen(ident, len, NAMEDATALEN - 1);
860 * We avoid using %.*s here because it can misbehave if the data
861 * is not valid in what libc thinks is the prevailing encoding.
863 char buf[NAMEDATALEN];
865 memcpy(buf, ident, len);
868 ("Identifier \"%s\" will be truncated to \"%s\".",
876 * 二重引用符で囲まれているかもしれないトークンを読み取り word 引数に palloc
877 * で確保したバッファに格納してそのポインタを返す。
879 * 正常にパースできた場合は残りの文字列の先頭位置を、異常があった場合は NULL を
881 * truncateがtrueの場合は、NAMEDATALENに切り詰める。
884 parse_quote_value(const char *str, char **word, char *value_type, bool truncate)
892 initStringInfo(&buf);
905 /* 二重引用符が閉じられていない場合はパース中断 */
909 parse_ereport(str, ("Unterminated quoted %s.", value_type));
914 * エスケープ対象のダブルクウォートをスキップする。
915 * もしブロックコメントの開始文字列や終了文字列もオブジェクト名とし
916 * て使用したい場合は、/ と * もエスケープ対象とすることで使用できる
917 * が、処理対象としていない。もしテーブル名にこれらの文字が含まれる
918 * 場合は、エイリアスを指定する必要がある。
927 else if (isspace(*str) || *str == ')' || *str == '"' || *str == '\0')
930 appendStringInfoCharMacro(&buf, *str++);
937 type = pstrdup(value_type);
938 type[0] = toupper(type[0]);
939 parse_ereport(str, ("%s is necessary.", type));
948 if (truncate && strlen(buf.data) >= NAMEDATALEN)
949 truncate_identifier(buf.data, strlen(buf.data), true, str);
957 parse_hints(PlanHint *plan, Query *parse, const char *str)
962 initStringInfo(&buf);
965 const HintParser *parser;
967 /* in error message, we output the comment including the keyword. */
970 /* parse only the keyword of the hint. */
971 resetStringInfo(&buf);
972 str = parse_keyword(str, &buf);
974 for (parser = parsers; parser->keyword != NULL; parser++)
976 char *keyword = parser->keyword;
979 if (strcasecmp(buf.data, keyword) != 0)
982 hint = parser->create_func(head, keyword);
984 /* parser of each hint does parse in a parenthesis. */
985 if ((str = skip_opened_parenthesis(str)) == NULL ||
986 (str = hint->parser_func(hint, plan, parse, str)) == NULL ||
987 (str = skip_closed_parenthesis(str)) == NULL)
989 hint->delete_func(hint);
995 * 出来上がったヒント情報を追加。スロットが足りない場合は二倍に拡張する。
997 if (plan->nall_hints == 0)
999 plan->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1000 plan->all_hints = palloc(sizeof(Hint *) * plan->max_all_hints);
1002 else if (plan->nall_hints == plan->max_all_hints)
1004 plan->max_all_hints *= 2;
1005 plan->all_hints = repalloc(plan->all_hints,
1006 sizeof(Hint *) * plan->max_all_hints);
1009 plan->all_hints[plan->nall_hints] = hint;
1017 if (parser->keyword == NULL)
1019 parse_ereport(head, ("Keyword \"%s\" does not exist.", buf.data));
1029 * Do basic parsing of the query head comment.
1032 parse_head_comment(Query *parse)
1041 /* get client-supplied query string. */
1044 PreparedStatement *entry;
1046 entry = FetchPreparedStatement(stmt_name, true);
1047 p = entry->plansource->query_string;
1050 p = debug_query_string;
1055 /* extract query head comment. */
1056 len = strlen(HINT_START);
1058 if (strncmp(p, HINT_START, len))
1065 /* find hint end keyword. */
1066 if ((tail = strstr(p, HINT_END)) == NULL)
1068 parse_ereport(head, ("Unterminated block comment."));
1072 /* 入れ子にしたブロックコメントはサポートしない */
1073 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1075 parse_ereport(head, ("Block comments nest doesn't supported."));
1081 head = palloc(len + 1);
1082 memcpy(head, p, len);
1086 plan = PlanHintCreate();
1087 plan->hint_str = head;
1089 /* parse each hint. */
1090 parse_hints(plan, parse, p);
1092 /* When nothing specified a hint, we free PlanHint and returns NULL. */
1093 if (plan->nall_hints == 0)
1095 PlanHintDelete(plan);
1099 /* パースしたヒントを並び替える */
1100 qsort(plan->all_hints, plan->nall_hints, sizeof(Hint *), AllHintCmpIsOrder);
1103 for (i = 0; i < plan->nall_hints; i++)
1105 Hint *hint = plan->all_hints[i];
1107 plan->num_hints[hint->type]++;
1109 if (i + 1 >= plan->nall_hints)
1112 if (AllHintCmp(plan->all_hints + i, plan->all_hints + i + 1, false) ==
1115 const char *HintTypeName[] = {"scan method", "join method",
1118 parse_ereport(plan->all_hints[i]->hint_str,
1119 ("Conflict %s hint.", HintTypeName[hint->type]));
1120 plan->all_hints[i]->state = HINT_STATE_DUPLICATION;
1124 plan->scan_hints = (ScanMethodHint **) plan->all_hints;
1125 plan->join_hints = (JoinMethodHint **) plan->all_hints +
1126 plan->num_hints[HINT_TYPE_SCAN_METHOD];
1127 plan->leading_hint = (LeadingHint *) plan->all_hints[
1128 plan->num_hints[HINT_TYPE_SCAN_METHOD] +
1129 plan->num_hints[HINT_TYPE_JOIN_METHOD] +
1130 plan->num_hints[HINT_TYPE_LEADING] - 1];
1131 plan->set_hints = (SetHint **) plan->all_hints +
1132 plan->num_hints[HINT_TYPE_SCAN_METHOD] +
1133 plan->num_hints[HINT_TYPE_JOIN_METHOD] +
1134 plan->num_hints[HINT_TYPE_LEADING];
1140 * スキャン方式ヒントのカッコ内をパースする
1143 ScanMethodHintParse(ScanMethodHint *hint, PlanHint *plan, Query *parse,
1146 const char *keyword = hint->base.keyword;
1149 * スキャン方式のヒントでリレーション名が読み取れない場合はヒント無効
1151 if ((str = parse_quote_value(str, &hint->relname, "relation name", true))
1158 * インデックスリストを受け付けるヒントであれば、インデックス参照をパース
1161 if (strcmp(keyword, HINT_INDEXSCAN) == 0 ||
1162 strcmp(keyword, HINT_BITMAPSCAN) == 0)
1164 while (*str != ')' && *str != '\0')
1168 str = parse_quote_value(str, &indexname, "index name", true);
1172 hint->indexnames = lappend(hint->indexnames, indexname);
1178 * ヒントごとに決まっている許容スキャン方式をビットマスクとして設定
1180 if (strcasecmp(keyword, HINT_SEQSCAN) == 0)
1181 hint->enforce_mask = ENABLE_SEQSCAN;
1182 else if (strcasecmp(keyword, HINT_INDEXSCAN) == 0)
1183 hint->enforce_mask = ENABLE_INDEXSCAN;
1184 else if (strcasecmp(keyword, HINT_BITMAPSCAN) == 0)
1185 hint->enforce_mask = ENABLE_BITMAPSCAN;
1186 else if (strcasecmp(keyword, HINT_TIDSCAN) == 0)
1187 hint->enforce_mask = ENABLE_TIDSCAN;
1188 else if (strcasecmp(keyword, HINT_NOSEQSCAN) == 0)
1189 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1190 else if (strcasecmp(keyword, HINT_NOINDEXSCAN) == 0)
1191 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1192 else if (strcasecmp(keyword, HINT_NOBITMAPSCAN) == 0)
1193 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1194 else if (strcasecmp(keyword, HINT_NOTIDSCAN) == 0)
1195 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1198 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1206 JoinMethodHintParse(JoinMethodHint *hint, PlanHint *plan, Query *parse,
1210 const char *keyword = hint->base.keyword;
1214 hint->relnames = palloc(sizeof(char *));
1216 while ((str = parse_quote_value(str, &relname, "relation name", true))
1220 hint->relnames = repalloc(hint->relnames, sizeof(char *) * hint->nrels);
1221 hint->relnames[hint->nrels - 1] = relname;
1231 /* Join 対象のテーブルは最低でも2つ指定する必要がある */
1232 if (hint->nrels < 2)
1234 parse_ereport(str, ("Specified relation more than two."));
1235 hint->base.state = HINT_STATE_ERROR;
1239 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1241 if (strcasecmp(keyword, HINT_NESTLOOP) == 0)
1242 hint->enforce_mask = ENABLE_NESTLOOP;
1243 else if (strcasecmp(keyword, HINT_MERGEJOIN) == 0)
1244 hint->enforce_mask = ENABLE_MERGEJOIN;
1245 else if (strcasecmp(keyword, HINT_HASHJOIN) == 0)
1246 hint->enforce_mask = ENABLE_HASHJOIN;
1247 else if (strcasecmp(keyword, HINT_NONESTLOOP) == 0)
1248 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1249 else if (strcasecmp(keyword, HINT_NOMERGEJOIN) == 0)
1250 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1251 else if (strcasecmp(keyword, HINT_NOHASHJOIN) == 0)
1252 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1255 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1263 LeadingHintParse(LeadingHint *hint, PlanHint *plan, Query *parse,
1272 if ((str = parse_quote_value(str, &relname, "relation name", true))
1276 hint->relations = lappend(hint->relations, relname);
1281 /* テーブル指定が2つ未満の場合は、Leading ヒントはエラーとする */
1282 if (list_length(hint->relations) < 2)
1284 parse_ereport(hint->base.hint_str,
1285 ("In %s hint, specified relation name 2 or more.",
1287 hint->base.state = HINT_STATE_ERROR;
1294 SetHintParse(SetHint *hint, PlanHint *plan, Query *parse, const char *str)
1296 if ((str = parse_quote_value(str, &hint->name, "parameter name", true))
1298 (str = parse_quote_value(str, &hint->value, "parameter value", false))
1306 * set GUC parameter functions
1310 set_config_option_wrapper(const char *name, const char *value,
1311 GucContext context, GucSource source,
1312 GucAction action, bool changeVal, int elevel)
1315 MemoryContext ccxt = CurrentMemoryContext;
1319 result = set_config_option(name, value, context, source,
1327 ecxt = MemoryContextSwitchTo(ccxt);
1328 errdata = CopyErrorData();
1330 ereport(elevel, (errcode(errdata->sqlerrcode),
1331 errmsg("%s", errdata->message),
1332 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1333 errdata->hint ? errhint("%s", errdata->hint) : 0));
1334 FreeErrorData(errdata);
1336 MemoryContextSwitchTo(ecxt);
1344 set_config_options(SetHint **options, int noptions, GucContext context)
1349 save_nestlevel = NewGUCNestLevel();
1351 for (i = 0; i < noptions; i++)
1353 SetHint *hint = options[i];
1356 if (!hint_state_enabled(hint))
1359 result = set_config_option_wrapper(hint->name, hint->value, context,
1360 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1361 pg_hint_plan_parse_messages);
1363 hint->base.state = HINT_STATE_USED;
1365 hint->base.state = HINT_STATE_ERROR;
1368 return save_nestlevel;
1371 #define SET_CONFIG_OPTION(name, type_bits) \
1372 set_config_option_wrapper((name), \
1373 (mask & (type_bits)) ? "true" : "false", \
1374 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1377 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1381 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1382 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1384 mask = enforce_mask;
1386 mask = enforce_mask & global->init_scan_mask;
1388 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1389 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1390 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1391 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1395 set_join_config_options(unsigned char enforce_mask, GucContext context)
1399 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1400 enforce_mask == ENABLE_HASHJOIN)
1401 mask = enforce_mask;
1403 mask = enforce_mask & global->init_join_mask;
1405 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1406 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1407 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1411 * pg_hint_plan hook functions
1415 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1416 ParamListInfo params, bool isTopLevel,
1417 DestReceiver *dest, char *completionTag)
1421 if (!pg_hint_plan_enable)
1423 if (prev_ProcessUtility)
1424 (*prev_ProcessUtility) (parsetree, queryString, params,
1425 isTopLevel, dest, completionTag);
1427 standard_ProcessUtility(parsetree, queryString, params,
1428 isTopLevel, dest, completionTag);
1434 if (IsA(node, ExplainStmt))
1437 * EXPLAIN対象のクエリのパースツリーを取得する
1442 stmt = (ExplainStmt *) node;
1444 Assert(IsA(stmt->query, Query));
1445 query = (Query *) stmt->query;
1447 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1448 node = query->utilityStmt;
1452 * EXECUTEコマンドならば、PREPARE時に指定されたクエリ文字列を取得し、ヒント
1455 if (IsA(node, ExecuteStmt))
1459 stmt = (ExecuteStmt *) node;
1460 stmt_name = stmt->name;
1467 if (prev_ProcessUtility)
1468 (*prev_ProcessUtility) (parsetree, queryString, params,
1469 isTopLevel, dest, completionTag);
1471 standard_ProcessUtility(parsetree, queryString, params,
1472 isTopLevel, dest, completionTag);
1486 if (prev_ProcessUtility)
1487 (*prev_ProcessUtility) (parsetree, queryString, params,
1488 isTopLevel, dest, completionTag);
1490 standard_ProcessUtility(parsetree, queryString, params,
1491 isTopLevel, dest, completionTag);
1494 static PlannedStmt *
1495 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1498 PlannedStmt *result;
1501 * hintが指定されない、または空のhintを指定された場合は通常のparser処理をお
1503 * 他のフック関数で実行されるhint処理をスキップするために、global 変数をNULL
1506 if (!pg_hint_plan_enable || (global = parse_head_comment(parse)) == NULL)
1511 return (*prev_planner) (parse, cursorOptions, boundParams);
1513 return standard_planner(parse, cursorOptions, boundParams);
1516 /* Set hint で指定されたGUCパラメータを設定する */
1517 save_nestlevel = set_config_options(global->set_hints,
1518 global->num_hints[HINT_TYPE_SET],
1522 global->init_scan_mask |= ENABLE_SEQSCAN;
1523 if (enable_indexscan)
1524 global->init_scan_mask |= ENABLE_INDEXSCAN;
1525 if (enable_bitmapscan)
1526 global->init_scan_mask |= ENABLE_BITMAPSCAN;
1528 global->init_scan_mask |= ENABLE_TIDSCAN;
1529 if (enable_nestloop)
1530 global->init_join_mask |= ENABLE_NESTLOOP;
1531 if (enable_mergejoin)
1532 global->init_join_mask |= ENABLE_MERGEJOIN;
1533 if (enable_hashjoin)
1534 global->init_join_mask |= ENABLE_HASHJOIN;
1537 result = (*prev_planner) (parse, cursorOptions, boundParams);
1539 result = standard_planner(parse, cursorOptions, boundParams);
1542 * Restore the GUC variables we set above.
1544 AtEOXact_GUC(true, save_nestlevel);
1547 * Print hint if debugging.
1549 if (pg_hint_plan_debug_print)
1550 PlanHintDump(global);
1552 PlanHintDelete(global);
1559 * aliasnameと一致するSCANヒントを探す
1561 static ScanMethodHint *
1562 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
1568 * RELOPT_BASEREL でなければ、scan method ヒントが適用しない。
1569 * 子テーブルの場合はRELOPT_OTHER_MEMBER_RELとなるが、サポート対象外とする。
1570 * また、通常のリレーション以外は、スキャン方式を選択できない。
1572 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
1575 rte = root->simple_rte_array[rel->relid];
1577 /* 外部表はスキャン方式が選択できない。 */
1578 if (rte->relkind == RELKIND_FOREIGN_TABLE)
1582 * スキャン方式のヒントのリストから、検索対象のリレーションと名称が一致する
1585 for (i = 0; i < global->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1587 ScanMethodHint *hint = global->scan_hints[i];
1589 /* すでに無効となっているヒントは検索対象にしない。 */
1590 if (!hint_state_enabled(hint))
1593 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
1601 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel)
1608 * We delete all the IndexOptInfo list and prevent you from being usable by
1611 if (hint->enforce_mask == ENABLE_SEQSCAN ||
1612 hint->enforce_mask == ENABLE_TIDSCAN)
1614 list_free_deep(rel->indexlist);
1615 rel->indexlist = NIL;
1616 hint->base.state = HINT_STATE_USED;
1622 * When a list of indexes is not specified, we just use all indexes.
1624 if (hint->indexnames == NIL)
1628 * Leaving only an specified index, we delete it from a IndexOptInfo list
1632 for (cell = list_head(rel->indexlist); cell; cell = next)
1634 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
1635 char *indexname = get_rel_name(info->indexoid);
1637 bool use_index = false;
1641 foreach(l, hint->indexnames)
1643 if (RelnameCmp(&indexname, &lfirst(l)) == 0)
1651 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
1660 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
1661 bool inhparent, RelOptInfo *rel)
1663 ScanMethodHint *hint;
1665 if (prev_get_relation_info)
1666 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
1668 /* 有効なヒントが指定されなかった場合は処理をスキップする。 */
1674 /* store does relids of parent table. */
1675 global->parent_relid = rel->relid;
1677 else if (global->parent_relid != 0)
1680 * We use the same GUC parameter if this table is the child table of a
1681 * table called pg_hint_plan_get_relation_info just before that.
1685 /* append_rel_list contains all append rels; ignore others */
1686 foreach(l, root->append_rel_list)
1688 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1690 /* This rel is child table. */
1691 if (appinfo->parent_relid == global->parent_relid &&
1692 appinfo->child_relid == rel->relid)
1694 if (global->parent_hint)
1695 delete_indexes(global->parent_hint, rel);
1701 /* This rel is not inherit table. */
1702 global->parent_relid = 0;
1703 global->parent_hint = NULL;
1706 /* scan hint が指定されない場合は、GUCパラメータをリセットする。 */
1707 if ((hint = find_scan_hint(root, rel)) == NULL)
1709 set_scan_config_options(global->init_scan_mask, global->context);
1712 set_scan_config_options(hint->enforce_mask, global->context);
1713 hint->base.state = HINT_STATE_USED;
1715 global->parent_hint = hint;
1717 delete_indexes(hint, rel);
1721 * aliasnameがクエリ中に指定した別名と一致する場合は、そのインデックスを返し、一致
1723 * aliasnameがクエリ中に複数回指定された場合は、-1を返す。
1726 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
1732 for (i = 1; i < root->simple_rel_array_size; i++)
1736 if (root->simple_rel_array[i] == NULL)
1739 Assert(i == root->simple_rel_array[i]->relid);
1741 if (RelnameCmp(&aliasname, &root->simple_rte_array[i]->eref->aliasname)
1745 foreach(l, initial_rels)
1747 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
1749 if (rel->reloptkind == RELOPT_BASEREL)
1751 if (rel->relid != i)
1756 Assert(rel->reloptkind == RELOPT_JOINREL);
1758 if (!bms_is_member(i, rel->relids))
1765 ("Relation name \"%s\" is ambiguous.",
1780 * relidビットマスクと一致するヒントを探す
1782 static JoinMethodHint *
1783 find_join_hint(Relids joinrelids)
1788 join_hint = global->join_hint_level[bms_num_members(joinrelids)];
1790 foreach(l, join_hint)
1792 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
1794 if (bms_equal(joinrelids, hint->joinrelids))
1802 * 結合方式のヒントを使用しやすい構造に変換する。
1805 transform_join_hints(PlanHint *plan, PlannerInfo *root, int nbaserel,
1806 List *initial_rels, JoinMethodHint **join_method_hints)
1815 for (i = 0; i < plan->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
1817 JoinMethodHint *hint = plan->join_hints[i];
1820 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
1823 bms_free(hint->joinrelids);
1824 hint->joinrelids = NULL;
1826 for (j = 0; j < hint->nrels; j++)
1828 char *relname = hint->relnames[j];
1830 relid = find_relid_aliasname(root, relname, initial_rels,
1831 hint->base.hint_str);
1834 hint->base.state = HINT_STATE_ERROR;
1839 if (bms_is_member(relid, hint->joinrelids))
1841 parse_ereport(hint->base.hint_str,
1842 ("Relation name \"%s\" is duplicate.", relname));
1843 hint->base.state = HINT_STATE_ERROR;
1847 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
1850 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
1853 plan->join_hint_level[hint->nrels] =
1854 lappend(plan->join_hint_level[hint->nrels], hint);
1858 * 有効なLeading ヒントが指定されている場合は、結合順にあわせてjoin method hint
1861 if (plan->num_hints[HINT_TYPE_LEADING] == 0)
1864 lhint = plan->leading_hint;
1865 if (!hint_state_enabled(lhint))
1868 /* Leading hint は、全ての join 方式が有効な hint として登録する */
1871 foreach(l, lhint->relations)
1873 char *relname = (char *)lfirst(l);
1874 JoinMethodHint *hint;
1877 find_relid_aliasname(root, relname, initial_rels, plan->hint_str);
1881 bms_free(joinrelids);
1888 if (bms_is_member(relid, joinrelids))
1890 parse_ereport(lhint->base.hint_str,
1891 ("Relation name \"%s\" is duplicate.", relname));
1892 lhint->base.state = HINT_STATE_ERROR;
1893 bms_free(joinrelids);
1897 joinrelids = bms_add_member(joinrelids, relid);
1903 hint = find_join_hint(joinrelids);
1907 * Here relnames is not set, since Relids bitmap is sufficient to
1908 * control paths of this query afterwards.
1910 hint = (JoinMethodHint *) JoinMethodHintCreate(lhint->base.hint_str,
1912 hint->base.state = HINT_STATE_USED;
1913 hint->nrels = njoinrels;
1914 hint->enforce_mask = ENABLE_ALL_JOIN;
1915 hint->joinrelids = bms_copy(joinrelids);
1918 join_method_hints[njoinrels] = hint;
1920 if (njoinrels >= nbaserel)
1924 bms_free(joinrelids);
1929 for (i = 2; i <= njoinrels; i++)
1931 /* Leading で指定した組み合わせ以外の join hint を削除する */
1932 list_free(plan->join_hint_level[i]);
1934 plan->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
1937 if (hint_state_enabled(lhint))
1938 set_join_config_options(DISABLE_ALL_JOIN, global->context);
1940 lhint->base.state = HINT_STATE_USED;
1945 * set_plain_rel_pathlist
1946 * Build access paths for a plain relation (no subquery, no inheritance)
1948 * This function was copied and edited from set_plain_rel_pathlist() in
1949 * src/backend/optimizer/path/allpaths.c
1952 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
1954 /* Consider sequential scan */
1955 add_path(rel, create_seqscan_path(root, rel));
1957 /* Consider index scans */
1958 create_index_paths(root, rel);
1960 /* Consider TID scans */
1961 create_tidscan_paths(root, rel);
1963 /* Now find the cheapest of the paths for this rel */
1968 rebuild_scan_path(PlanHint *plan, PlannerInfo *root, int level,
1973 foreach(l, initial_rels)
1975 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
1977 ScanMethodHint *hint;
1980 * スキャン方式が選択できるリレーションのみ、スキャンパスを再生成
1983 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
1986 rte = root->simple_rte_array[rel->relid];
1988 /* 外部表はスキャン方式が選択できない。 */
1989 if (rte->relkind == RELKIND_FOREIGN_TABLE)
1993 * scan method hint が指定されていなければ、初期値のGUCパラメータでscan
1996 if ((hint = find_scan_hint(root, rel)) == NULL)
1997 set_scan_config_options(plan->init_scan_mask, plan->context);
2000 set_scan_config_options(hint->enforce_mask, plan->context);
2001 hint->base.state = HINT_STATE_USED;
2004 list_free_deep(rel->pathlist);
2005 rel->pathlist = NIL;
2008 /* It's an "append relation", process accordingly */
2009 set_append_rel_pathlist(root, rel, rel->relid, rte);
2013 set_plain_rel_pathlist(root, rel, rte);
2018 * Restore the GUC variables we set above.
2020 set_scan_config_options(plan->init_scan_mask, plan->context);
2024 * make_join_rel() をラップする関数
2026 * ヒントにしたがって、enabele_* パラメータを変更した上で、make_join_rel()を
2030 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
2033 JoinMethodHint *hint;
2037 joinrelids = bms_union(rel1->relids, rel2->relids);
2038 hint = find_join_hint(joinrelids);
2039 bms_free(joinrelids);
2042 return pg_hint_plan_make_join_rel(root, rel1, rel2);
2044 save_nestlevel = NewGUCNestLevel();
2046 set_join_config_options(hint->enforce_mask, global->context);
2048 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2049 hint->base.state = HINT_STATE_USED;
2052 * Restore the GUC variables we set above.
2054 AtEOXact_GUC(true, save_nestlevel);
2060 get_num_baserels(List *initial_rels)
2065 foreach(l, initial_rels)
2067 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2069 if (rel->reloptkind == RELOPT_BASEREL)
2071 else if (rel->reloptkind ==RELOPT_JOINREL)
2072 nbaserel+= bms_num_members(rel->relids);
2075 /* other values not expected here */
2076 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
2084 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
2087 JoinMethodHint **join_method_hints;
2093 * pg_hint_planが無効、または有効なヒントが1つも指定されなかった場合は、標準
2098 if (prev_join_search)
2099 return (*prev_join_search) (root, levels_needed, initial_rels);
2100 else if (enable_geqo && levels_needed >= geqo_threshold)
2101 return geqo(root, levels_needed, initial_rels);
2103 return standard_join_search(root, levels_needed, initial_rels);
2106 /* We apply scan method hint rebuild scan path. */
2107 rebuild_scan_path(global, root, levels_needed, initial_rels);
2110 * GEQOを使用する条件を満たした場合は、GEQOを用いた結合方式の検索を行う。
2111 * このとき、スキャン方式のヒントとSetヒントのみが有効になり、結合方式や結合
2112 * 順序はヒント句は無効になりGEQOのアルゴリズムで決定される。
2114 if (enable_geqo && levels_needed >= geqo_threshold)
2115 return geqo(root, levels_needed, initial_rels);
2117 nbaserel = get_num_baserels(initial_rels);
2118 global->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
2119 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
2121 transform_join_hints(global, root, nbaserel, initial_rels,
2124 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
2126 for (i = 2; i <= nbaserel; i++)
2128 list_free(global->join_hint_level[i]);
2130 /* free Leading hint only */
2131 if (join_method_hints[i] != NULL &&
2132 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
2133 JoinMethodHintDelete(join_method_hints[i]);
2135 pfree(global->join_hint_level);
2136 pfree(join_method_hints);
2138 if (global->num_hints[HINT_TYPE_LEADING] > 0 &&
2139 hint_state_enabled(global->leading_hint))
2140 set_join_config_options(global->init_join_mask, global->context);
2147 * Build access paths for a base relation
2149 * This function was copied and edited from set_rel_pathlist() in
2150 * src/backend/optimizer/path/allpaths.c
2153 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
2154 Index rti, RangeTblEntry *rte)
2158 /* It's an "append relation", process accordingly */
2159 set_append_rel_pathlist(root, rel, rti, rte);
2163 if (rel->rtekind == RTE_RELATION)
2165 if (rte->relkind == RELKIND_RELATION)
2167 /* Plain relation */
2168 set_plain_rel_pathlist(root, rel, rte);
2171 elog(ERROR, "unexpected relkind: %c", rte->relkind);
2174 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
2178 #define standard_join_search pg_hint_plan_standard_join_search
2179 #define join_search_one_level pg_hint_plan_join_search_one_level
2180 #define make_join_rel make_join_rel_wrapper
2183 #undef make_join_rel
2184 #define make_join_rel pg_hint_plan_make_join_rel
2185 #define add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype, sjinfo, restrictlist) \
2187 ScanMethodHint *hint = NULL; \
2188 if ((hint = find_scan_hint((root), (innerrel))) != NULL) \
2190 set_scan_config_options(hint->enforce_mask, global->context); \
2191 hint->base.state = HINT_STATE_USED; \
2193 add_paths_to_joinrel((root), (joinrel), (outerrel), (innerrel), (jointype), (sjinfo), (restrictlist)); \
2195 set_scan_config_options(global->init_scan_mask, global->context); \
2197 #include "make_join_rel.c"