1 /*-------------------------------------------------------------------------
4 * do instructions or hints to the planner using C-style block comments
7 * Copyright (c) 2012, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
9 *-------------------------------------------------------------------------
12 #include "commands/prepare.h"
13 #include "mb/pg_wchar.h"
14 #include "miscadmin.h"
15 #include "nodes/nodeFuncs.h"
16 #include "optimizer/clauses.h"
17 #include "optimizer/cost.h"
18 #include "optimizer/geqo.h"
19 #include "optimizer/joininfo.h"
20 #include "optimizer/pathnode.h"
21 #include "optimizer/paths.h"
22 #include "optimizer/plancat.h"
23 #include "optimizer/planner.h"
24 #include "optimizer/prep.h"
25 #include "optimizer/restrictinfo.h"
26 #include "parser/scansup.h"
27 #include "tcop/utility.h"
28 #include "utils/lsyscache.h"
29 #include "utils/memutils.h"
30 #if PG_VERSION_NUM >= 90200
31 #include "catalog/pg_class.h"
34 #ifdef PG_MODULE_MAGIC
38 #if PG_VERSION_NUM < 90100
39 #error unsupported PostgreSQL version
42 #define BLOCK_COMMENT_START "/*"
43 #define BLOCK_COMMENT_END "*/"
44 #define HINT_COMMENT_KEYWORD "+"
45 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
46 #define HINT_END BLOCK_COMMENT_END
49 #define HINT_SEQSCAN "SeqScan"
50 #define HINT_INDEXSCAN "IndexScan"
51 #define HINT_BITMAPSCAN "BitmapScan"
52 #define HINT_TIDSCAN "TidScan"
53 #define HINT_NOSEQSCAN "NoSeqScan"
54 #define HINT_NOINDEXSCAN "NoIndexScan"
55 #define HINT_NOBITMAPSCAN "NoBitmapScan"
56 #define HINT_NOTIDSCAN "NoTidScan"
57 #if PG_VERSION_NUM >= 90200
58 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
59 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
61 #define HINT_NESTLOOP "NestLoop"
62 #define HINT_MERGEJOIN "MergeJoin"
63 #define HINT_HASHJOIN "HashJoin"
64 #define HINT_NONESTLOOP "NoNestLoop"
65 #define HINT_NOMERGEJOIN "NoMergeJoin"
66 #define HINT_NOHASHJOIN "NoHashJoin"
67 #define HINT_LEADING "Leading"
68 #define HINT_SET "Set"
70 #define HINT_ARRAY_DEFAULT_INITSIZE 8
72 #define parse_ereport(str, detail) \
73 ereport(pg_hint_plan_parse_messages, \
74 (errmsg("hint syntax error at or near \"%s\"", (str)), \
77 #define skip_space(str) \
78 while (isspace(*str)) \
83 ENABLE_SEQSCAN = 0x01,
84 ENABLE_INDEXSCAN = 0x02,
85 ENABLE_BITMAPSCAN = 0x04,
86 ENABLE_TIDSCAN = 0x08,
87 #if PG_VERSION_NUM >= 90200
88 ENABLE_INDEXONLYSCAN = 0x10
94 ENABLE_NESTLOOP = 0x01,
95 ENABLE_MERGEJOIN = 0x02,
96 ENABLE_HASHJOIN = 0x04
99 #if PG_VERSION_NUM >= 90200
100 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
101 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
102 ENABLE_INDEXONLYSCAN)
104 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
105 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN)
107 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
108 #define DISABLE_ALL_SCAN 0
109 #define DISABLE_ALL_JOIN 0
111 typedef struct Hint Hint;
112 typedef struct HintState HintState;
114 typedef Hint *(*HintCreateFunction) (const char *hint_str,
115 const char *keyword);
116 typedef void (*HintDeleteFunction) (Hint *hint);
117 typedef void (*HintDumpFunction) (Hint *hint, StringInfo buf);
118 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
119 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
120 Query *parse, const char *str);
123 #define NUM_HINT_TYPE 4
124 typedef enum HintType
126 HINT_TYPE_SCAN_METHOD,
127 HINT_TYPE_JOIN_METHOD,
132 static const char *HintTypeName[] = {
140 typedef enum HintStatus
142 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
143 HINT_STATE_USED, /* hint is used */
144 HINT_STATE_DUPLICATION, /* specified hint duplication */
145 HINT_STATE_ERROR /* execute error (parse error does not include
149 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
150 (hint)->base.state == HINT_STATE_USED)
152 /* common data for all hints. */
155 const char *hint_str; /* must not do pfree */
156 const char *keyword; /* must not do pfree */
159 HintDeleteFunction delete_func;
160 HintDumpFunction dump_func;
161 HintCmpFunction cmp_func;
162 HintParseFunction parser_func;
165 /* scan method hints */
166 typedef struct ScanMethodHint
171 unsigned char enforce_mask;
174 /* join method hints */
175 typedef struct JoinMethodHint
180 unsigned char enforce_mask;
184 /* join order hints */
185 typedef struct LeadingHint
188 List *relations; /* relation names specified in Leading hint */
191 /* change a run-time parameter hints */
192 typedef struct SetHint
195 char *name; /* name of variable */
200 * Describes a context of hint processing.
204 char *hint_str; /* original hint string */
207 int nall_hints; /* # of valid all hints */
208 int max_all_hints; /* # of slots for all hints */
209 Hint **all_hints; /* parsed all hints */
211 /* # of each hints */
212 int num_hints[NUM_HINT_TYPE];
214 /* for scan method hints */
215 ScanMethodHint **scan_hints; /* parsed scan hints */
216 int init_scan_mask; /* initial value scan parameter */
217 Index parent_relid; /* inherit parent table relid */
218 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
220 /* for join method hints */
221 JoinMethodHint **join_hints; /* parsed join hints */
222 int init_join_mask; /* initial value join parameter */
223 List **join_hint_level;
225 /* for Leading hint */
226 LeadingHint *leading_hint; /* parsed last specified Leading hint */
229 SetHint **set_hints; /* parsed Set hints */
230 GucContext context; /* which GUC parameters can we set? */
234 * Describes a hint parser module which is bound with particular hint keyword.
236 typedef struct HintParser
239 HintCreateFunction create_func;
242 /* Module callbacks */
246 static void push_hint(HintState *hstate);
247 static void pop_hint(void);
249 static void pg_hint_plan_ProcessUtility(Node *parsetree,
250 const char *queryString,
251 ParamListInfo params, bool isTopLevel,
253 char *completionTag);
254 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
255 ParamListInfo boundParams);
256 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
257 Oid relationObjectId,
258 bool inhparent, RelOptInfo *rel);
259 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
263 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword);
264 static void ScanMethodHintDelete(ScanMethodHint *hint);
265 static void ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf);
266 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
267 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
268 Query *parse, const char *str);
269 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword);
270 static void JoinMethodHintDelete(JoinMethodHint *hint);
271 static void JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf);
272 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
273 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
274 Query *parse, const char *str);
275 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword);
276 static void LeadingHintDelete(LeadingHint *hint);
277 static void LeadingHintDump(LeadingHint *hint, StringInfo buf);
278 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
279 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
280 Query *parse, const char *str);
281 static Hint *SetHintCreate(const char *hint_str, const char *keyword);
282 static void SetHintDelete(SetHint *hint);
283 static void SetHintDump(SetHint *hint, StringInfo buf);
284 static int SetHintCmp(const SetHint *a, const SetHint *b);
285 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
288 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
291 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
292 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
293 ListCell *other_rels);
294 static void make_rels_by_clauseless_joins(PlannerInfo *root,
296 ListCell *other_rels);
297 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
298 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
299 Index rti, RangeTblEntry *rte);
300 #if PG_VERSION_NUM >= 90200
301 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
302 List *live_childrels,
303 List *all_child_pathkeys);
305 static List *accumulate_append_subpath(List *subpaths, Path *path);
306 #if PG_VERSION_NUM < 90200
307 static void set_dummy_rel_pathlist(RelOptInfo *rel);
309 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
313 static bool pg_hint_plan_enable = true;
314 static bool pg_hint_plan_debug_print = false;
315 static int pg_hint_plan_parse_messages = INFO;
317 static const struct config_enum_entry parse_messages_level_options[] = {
318 {"debug", DEBUG2, true},
319 {"debug5", DEBUG5, false},
320 {"debug4", DEBUG4, false},
321 {"debug3", DEBUG3, false},
322 {"debug2", DEBUG2, false},
323 {"debug1", DEBUG1, false},
325 {"info", INFO, false},
326 {"notice", NOTICE, false},
327 {"warning", WARNING, false},
328 {"error", ERROR, false},
330 * {"fatal", FATAL, true},
331 * {"panic", PANIC, true},
336 /* Saved hook values in case of unload */
337 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
338 static planner_hook_type prev_planner = NULL;
339 static get_relation_info_hook_type prev_get_relation_info = NULL;
340 static join_search_hook_type prev_join_search = NULL;
342 /* フック関数をまたがって使用する情報を管理する */
343 static HintState *current_hint = NULL;
345 /* 有効なヒントをスタック構造で管理する */
346 static List *HintStateStack = NIL;
349 * EXECUTEコマンド実行時に、ステートメント名を格納する。
350 * その他のコマンドの場合は、NULLに設定する。
352 static char *stmt_name = NULL;
354 static const HintParser parsers[] = {
355 {HINT_SEQSCAN, ScanMethodHintCreate},
356 {HINT_INDEXSCAN, ScanMethodHintCreate},
357 {HINT_BITMAPSCAN, ScanMethodHintCreate},
358 {HINT_TIDSCAN, ScanMethodHintCreate},
359 {HINT_NOSEQSCAN, ScanMethodHintCreate},
360 {HINT_NOINDEXSCAN, ScanMethodHintCreate},
361 {HINT_NOBITMAPSCAN, ScanMethodHintCreate},
362 {HINT_NOTIDSCAN, ScanMethodHintCreate},
363 #if PG_VERSION_NUM >= 90200
364 {HINT_INDEXONLYSCAN, ScanMethodHintCreate},
365 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate},
367 {HINT_NESTLOOP, JoinMethodHintCreate},
368 {HINT_MERGEJOIN, JoinMethodHintCreate},
369 {HINT_HASHJOIN, JoinMethodHintCreate},
370 {HINT_NONESTLOOP, JoinMethodHintCreate},
371 {HINT_NOMERGEJOIN, JoinMethodHintCreate},
372 {HINT_NOHASHJOIN, JoinMethodHintCreate},
373 {HINT_LEADING, LeadingHintCreate},
374 {HINT_SET, SetHintCreate},
379 * Module load callbacks
384 /* Define custom GUC variables. */
385 DefineCustomBoolVariable("pg_hint_plan.enable",
386 "Force planner to use plans specified in the hint comment preceding to the query.",
388 &pg_hint_plan_enable,
396 DefineCustomBoolVariable("pg_hint_plan.debug_print",
397 "Logs results of hint parsing.",
399 &pg_hint_plan_debug_print,
407 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
408 "Messege level of parse errors.",
410 &pg_hint_plan_parse_messages,
412 parse_messages_level_options,
420 prev_ProcessUtility = ProcessUtility_hook;
421 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
422 prev_planner = planner_hook;
423 planner_hook = pg_hint_plan_planner;
424 prev_get_relation_info = get_relation_info_hook;
425 get_relation_info_hook = pg_hint_plan_get_relation_info;
426 prev_join_search = join_search_hook;
427 join_search_hook = pg_hint_plan_join_search;
431 * Module unload callback
437 /* Uninstall hooks. */
438 ProcessUtility_hook = prev_ProcessUtility;
439 planner_hook = prev_planner;
440 get_relation_info_hook = prev_get_relation_info;
441 join_search_hook = prev_join_search;
445 * create and delete functions the hint object
449 ScanMethodHintCreate(const char *hint_str, const char *keyword)
451 ScanMethodHint *hint;
453 hint = palloc(sizeof(ScanMethodHint));
454 hint->base.hint_str = hint_str;
455 hint->base.keyword = keyword;
456 hint->base.type = HINT_TYPE_SCAN_METHOD;
457 hint->base.state = HINT_STATE_NOTUSED;
458 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
459 hint->base.dump_func = (HintDumpFunction) ScanMethodHintDump;
460 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
461 hint->base.parser_func = (HintParseFunction) ScanMethodHintParse;
462 hint->relname = NULL;
463 hint->indexnames = NIL;
464 hint->enforce_mask = 0;
466 return (Hint *) hint;
470 ScanMethodHintDelete(ScanMethodHint *hint)
476 pfree(hint->relname);
477 list_free_deep(hint->indexnames);
482 JoinMethodHintCreate(const char *hint_str, const char *keyword)
484 JoinMethodHint *hint;
486 hint = palloc(sizeof(JoinMethodHint));
487 hint->base.hint_str = hint_str;
488 hint->base.keyword = keyword;
489 hint->base.type = HINT_TYPE_JOIN_METHOD;
490 hint->base.state = HINT_STATE_NOTUSED;
491 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
492 hint->base.dump_func = (HintDumpFunction) JoinMethodHintDump;
493 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
494 hint->base.parser_func = (HintParseFunction) JoinMethodHintParse;
496 hint->relnames = NULL;
497 hint->enforce_mask = 0;
498 hint->joinrelids = NULL;
500 return (Hint *) hint;
504 JoinMethodHintDelete(JoinMethodHint *hint)
513 for (i = 0; i < hint->nrels; i++)
514 pfree(hint->relnames[i]);
515 pfree(hint->relnames);
517 bms_free(hint->joinrelids);
522 LeadingHintCreate(const char *hint_str, const char *keyword)
526 hint = palloc(sizeof(LeadingHint));
527 hint->base.hint_str = hint_str;
528 hint->base.keyword = keyword;
529 hint->base.type = HINT_TYPE_LEADING;
530 hint->base.state = HINT_STATE_NOTUSED;
531 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
532 hint->base.dump_func = (HintDumpFunction) LeadingHintDump;
533 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
534 hint->base.parser_func = (HintParseFunction) LeadingHintParse;
535 hint->relations = NIL;
537 return (Hint *) hint;
541 LeadingHintDelete(LeadingHint *hint)
546 list_free_deep(hint->relations);
551 SetHintCreate(const char *hint_str, const char *keyword)
555 hint = palloc(sizeof(SetHint));
556 hint->base.hint_str = hint_str;
557 hint->base.keyword = keyword;
558 hint->base.type = HINT_TYPE_SET;
559 hint->base.state = HINT_STATE_NOTUSED;
560 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
561 hint->base.dump_func = (HintDumpFunction) SetHintDump;
562 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
563 hint->base.parser_func = (HintParseFunction) SetHintParse;
567 return (Hint *) hint;
571 SetHintDelete(SetHint *hint)
584 HintStateCreate(void)
588 hstate = palloc(sizeof(HintState));
589 hstate->hint_str = NULL;
590 hstate->nall_hints = 0;
591 hstate->max_all_hints = 0;
592 hstate->all_hints = NULL;
593 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
594 hstate->scan_hints = NULL;
595 hstate->init_scan_mask = 0;
596 hstate->parent_relid = 0;
597 hstate->parent_hint = NULL;
598 hstate->join_hints = NULL;
599 hstate->init_join_mask = 0;
600 hstate->join_hint_level = NULL;
601 hstate->leading_hint = NULL;
602 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
603 hstate->set_hints = NULL;
609 HintStateDelete(HintState *hstate)
616 if (hstate->hint_str)
617 pfree(hstate->hint_str);
619 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
620 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
621 if (hstate->all_hints)
622 pfree(hstate->all_hints);
630 dump_quote_value(StringInfo buf, const char *value)
632 bool need_quote = false;
635 for (str = value; *str != '\0'; str++)
637 if (isspace(*str) || *str == ')' || *str == '"')
640 appendStringInfoCharMacro(buf, '"');
645 for (str = value; *str != '\0'; str++)
648 appendStringInfoCharMacro(buf, '"');
650 appendStringInfoCharMacro(buf, *str);
654 appendStringInfoCharMacro(buf, '"');
658 ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf)
662 appendStringInfo(buf, "%s(", hint->base.keyword);
663 dump_quote_value(buf, hint->relname);
664 foreach(l, hint->indexnames)
666 appendStringInfoCharMacro(buf, ' ');
667 dump_quote_value(buf, (char *) lfirst(l));
669 appendStringInfoString(buf, ")\n");
673 JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf)
677 appendStringInfo(buf, "%s(", hint->base.keyword);
678 dump_quote_value(buf, hint->relnames[0]);
679 for (i = 1; i < hint->nrels; i++)
681 appendStringInfoCharMacro(buf, ' ');
682 dump_quote_value(buf, hint->relnames[i]);
684 appendStringInfoString(buf, ")\n");
689 LeadingHintDump(LeadingHint *hint, StringInfo buf)
694 appendStringInfo(buf, "%s(", HINT_LEADING);
696 foreach(l, hint->relations)
701 appendStringInfoCharMacro(buf, ' ');
703 dump_quote_value(buf, (char *) lfirst(l));
706 appendStringInfoString(buf, ")\n");
710 SetHintDump(SetHint *hint, StringInfo buf)
712 appendStringInfo(buf, "%s(", HINT_SET);
713 dump_quote_value(buf, hint->name);
714 appendStringInfoCharMacro(buf, ' ');
715 dump_quote_value(buf, hint->value);
716 appendStringInfo(buf, ")\n");
720 all_hint_dump(HintState *hstate, StringInfo buf, const char *title,
725 appendStringInfo(buf, "%s:\n", title);
726 for (i = 0; i < hstate->nall_hints; i++)
728 if (hstate->all_hints[i]->state != state)
731 hstate->all_hints[i]->dump_func(hstate->all_hints[i], buf);
736 HintStateDump(HintState *hstate)
742 elog(LOG, "pg_hint_plan:\nno hint");
746 initStringInfo(&buf);
748 appendStringInfoString(&buf, "pg_hint_plan:\n");
749 all_hint_dump(hstate, &buf, "used hint", HINT_STATE_USED);
750 all_hint_dump(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
751 all_hint_dump(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
752 all_hint_dump(hstate, &buf, "error hint", HINT_STATE_ERROR);
754 elog(LOG, "%s", buf.data);
764 RelnameCmp(const void *a, const void *b)
766 const char *relnamea = *((const char **) a);
767 const char *relnameb = *((const char **) b);
769 return strcmp(relnamea, relnameb);
773 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
775 return RelnameCmp(&a->relname, &b->relname);
779 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
783 if (a->nrels != b->nrels)
784 return a->nrels - b->nrels;
786 for (i = 0; i < a->nrels; i++)
789 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
797 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
803 SetHintCmp(const SetHint *a, const SetHint *b)
805 return strcmp(a->name, b->name);
809 HintCmp(const void *a, const void *b)
811 const Hint *hinta = *((const Hint **) a);
812 const Hint *hintb = *((const Hint **) b);
814 if (hinta->type != hintb->type)
815 return hinta->type - hintb->type;
817 return hinta->cmp_func(hinta, hintb);
822 HintCmpWithPos(const void *a, const void *b)
824 const Hint *hinta = *((const Hint **) a);
825 const Hint *hintb = *((const Hint **) b);
828 result = HintCmp(a, b);
830 result = hinta->hint_str - hintb->hint_str;
840 parse_keyword(const char *str, StringInfo buf)
844 while (!isspace(*str) && *str != '(' && *str != '\0')
845 appendStringInfoCharMacro(buf, *str++);
851 skip_opened_parenthesis(const char *str)
857 parse_ereport(str, ("Opening parenthesis is necessary."));
867 skip_closed_parenthesis(const char *str)
873 parse_ereport(str, ("Closing parenthesis is necessary."));
883 * 二重引用符で囲まれているかもしれないトークンを読み取り word 引数に palloc
884 * で確保したバッファに格納してそのポインタを返す。
886 * 正常にパースできた場合は残りの文字列の先頭位置を、異常があった場合は NULL を
888 * truncateがtrueの場合は、NAMEDATALENに切り詰める。
891 parse_quote_value(const char *str, char **word, char *value_type, bool truncate)
899 initStringInfo(&buf);
912 /* 二重引用符が閉じられていない場合はパース中断 */
916 parse_ereport(str, ("Unterminated quoted %s.", value_type));
921 * エスケープ対象のダブルクウォートをスキップする。
922 * もしブロックコメントの開始文字列や終了文字列もオブジェクト名とし
923 * て使用したい場合は、/ と * もエスケープ対象とすることで使用できる
924 * が、処理対象としていない。もしテーブル名にこれらの文字が含まれる
925 * 場合は、エイリアスを指定する必要がある。
934 else if (isspace(*str) || *str == ')' || *str == '"' || *str == '\0')
937 appendStringInfoCharMacro(&buf, *str++);
944 type = pstrdup(value_type);
945 type[0] = toupper(type[0]);
946 parse_ereport(str, ("%s is necessary.", type));
954 /* Truncate name if it's overlength */
956 truncate_identifier(buf.data, strlen(buf.data), true);
964 parse_hints(HintState *hstate, Query *parse, const char *str)
969 initStringInfo(&buf);
972 const HintParser *parser;
974 /* in error message, we output the comment including the keyword. */
977 /* parse only the keyword of the hint. */
978 resetStringInfo(&buf);
979 str = parse_keyword(str, &buf);
981 for (parser = parsers; parser->keyword != NULL; parser++)
983 char *keyword = parser->keyword;
986 if (strcasecmp(buf.data, keyword) != 0)
989 hint = parser->create_func(head, keyword);
991 /* parser of each hint does parse in a parenthesis. */
992 if ((str = skip_opened_parenthesis(str)) == NULL ||
993 (str = hint->parser_func(hint, hstate, parse, str)) == NULL ||
994 (str = skip_closed_parenthesis(str)) == NULL)
996 hint->delete_func(hint);
1002 * 出来上がったヒント情報を追加。スロットが足りない場合は二倍に拡張
1005 if (hstate->nall_hints == 0)
1007 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1008 hstate->all_hints = (Hint **)
1009 palloc(sizeof(Hint *) * hstate->max_all_hints);
1011 else if (hstate->nall_hints == hstate->max_all_hints)
1013 hstate->max_all_hints *= 2;
1014 hstate->all_hints = (Hint **)
1015 repalloc(hstate->all_hints,
1016 sizeof(Hint *) * hstate->max_all_hints);
1019 hstate->all_hints[hstate->nall_hints] = hint;
1020 hstate->nall_hints++;
1027 if (parser->keyword == NULL)
1030 ("Unrecognized hint keyword \"%s\".", buf.data));
1040 * Do basic parsing of the query head comment.
1043 parse_head_comment(Query *parse)
1052 /* get client-supplied query string. */
1055 PreparedStatement *entry;
1057 entry = FetchPreparedStatement(stmt_name, true);
1058 p = entry->plansource->query_string;
1061 p = debug_query_string;
1066 /* extract query head comment. */
1067 len = strlen(HINT_START);
1069 if (strncmp(p, HINT_START, len))
1076 /* find hint end keyword. */
1077 if ((tail = strstr(p, HINT_END)) == NULL)
1079 parse_ereport(head, ("Unterminated block comment."));
1083 /* 入れ子にしたブロックコメントはサポートしない */
1084 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1086 parse_ereport(head, ("Nested block comments are not supported."));
1092 head = palloc(len + 1);
1093 memcpy(head, p, len);
1097 hstate = HintStateCreate();
1098 hstate->hint_str = head;
1100 /* parse each hint. */
1101 parse_hints(hstate, parse, p);
1103 /* When nothing specified a hint, we free HintState and returns NULL. */
1104 if (hstate->nall_hints == 0)
1106 HintStateDelete(hstate);
1110 /* パースしたヒントを並び替える */
1111 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1115 for (i = 0; i < hstate->nall_hints; i++)
1117 Hint *cur_hint = hstate->all_hints[i];
1120 /* Count up hints per hint-type. */
1121 hstate->num_hints[cur_hint->type]++;
1123 /* If we don't have next, nothing to compare. */
1124 if (i + 1 >= hstate->nall_hints)
1126 next_hint = hstate->all_hints[i + 1];
1129 * We need to pass address of hint pointers, because HintCmp has
1130 * been designed to be used with qsort.
1132 if (HintCmp(&cur_hint, &next_hint) == 0)
1134 parse_ereport(cur_hint->hint_str,
1135 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1136 cur_hint->state = HINT_STATE_DUPLICATION;
1141 * Make sure that per-type array pointers point proper position in the
1142 * array which consists of all hints.
1144 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1145 hstate->join_hints = (JoinMethodHint **) hstate->all_hints +
1146 hstate->num_hints[HINT_TYPE_SCAN_METHOD];
1147 hstate->leading_hint = (LeadingHint *) hstate->all_hints[
1148 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1149 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1150 hstate->num_hints[HINT_TYPE_LEADING] - 1];
1151 hstate->set_hints = (SetHint **) hstate->all_hints +
1152 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1153 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1154 hstate->num_hints[HINT_TYPE_LEADING];
1160 * スキャン方式ヒントのカッコ内をパースする
1163 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1166 const char *keyword = hint->base.keyword;
1169 * スキャン方式のヒントでリレーション名が読み取れない場合はヒント無効
1171 if ((str = parse_quote_value(str, &hint->relname, "relation name", true))
1178 * インデックスリストを受け付けるヒントであれば、インデックス参照をパース
1181 if (strcmp(keyword, HINT_INDEXSCAN) == 0 ||
1182 #if PG_VERSION_NUM >= 90200
1183 strcmp(keyword, HINT_INDEXONLYSCAN) == 0 ||
1185 strcmp(keyword, HINT_BITMAPSCAN) == 0)
1187 while (*str != ')' && *str != '\0')
1191 str = parse_quote_value(str, &indexname, "index name", true);
1195 hint->indexnames = lappend(hint->indexnames, indexname);
1201 * ヒントごとに決まっている許容スキャン方式をビットマスクとして設定
1203 if (strcasecmp(keyword, HINT_SEQSCAN) == 0)
1204 hint->enforce_mask = ENABLE_SEQSCAN;
1205 else if (strcasecmp(keyword, HINT_INDEXSCAN) == 0)
1206 hint->enforce_mask = ENABLE_INDEXSCAN;
1207 else if (strcasecmp(keyword, HINT_BITMAPSCAN) == 0)
1208 hint->enforce_mask = ENABLE_BITMAPSCAN;
1209 else if (strcasecmp(keyword, HINT_TIDSCAN) == 0)
1210 hint->enforce_mask = ENABLE_TIDSCAN;
1211 else if (strcasecmp(keyword, HINT_NOSEQSCAN) == 0)
1212 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1213 else if (strcasecmp(keyword, HINT_NOINDEXSCAN) == 0)
1214 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1215 else if (strcasecmp(keyword, HINT_NOBITMAPSCAN) == 0)
1216 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1217 else if (strcasecmp(keyword, HINT_NOTIDSCAN) == 0)
1218 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1219 #if PG_VERSION_NUM >= 90200
1220 else if (strcasecmp(keyword, HINT_INDEXONLYSCAN) == 0)
1221 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1222 else if (strcasecmp(keyword, HINT_NOINDEXONLYSCAN) == 0)
1223 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1227 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1235 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1239 const char *keyword = hint->base.keyword;
1243 hint->relnames = palloc(sizeof(char *));
1245 while ((str = parse_quote_value(str, &relname, "relation name", true))
1249 hint->relnames = repalloc(hint->relnames, sizeof(char *) * hint->nrels);
1250 hint->relnames[hint->nrels - 1] = relname;
1260 /* Join 対象のテーブルは最低でも2つ指定する必要がある */
1261 if (hint->nrels < 2)
1264 ("%s hint requires at least two relations.",
1265 hint->base.keyword));
1266 hint->base.state = HINT_STATE_ERROR;
1270 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1272 if (strcasecmp(keyword, HINT_NESTLOOP) == 0)
1273 hint->enforce_mask = ENABLE_NESTLOOP;
1274 else if (strcasecmp(keyword, HINT_MERGEJOIN) == 0)
1275 hint->enforce_mask = ENABLE_MERGEJOIN;
1276 else if (strcasecmp(keyword, HINT_HASHJOIN) == 0)
1277 hint->enforce_mask = ENABLE_HASHJOIN;
1278 else if (strcasecmp(keyword, HINT_NONESTLOOP) == 0)
1279 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1280 else if (strcasecmp(keyword, HINT_NOMERGEJOIN) == 0)
1281 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1282 else if (strcasecmp(keyword, HINT_NOHASHJOIN) == 0)
1283 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1286 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1294 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1303 if ((str = parse_quote_value(str, &relname, "relation name", true))
1307 hint->relations = lappend(hint->relations, relname);
1312 /* テーブル指定が2つ未満の場合は、Leading ヒントはエラーとする */
1313 if (list_length(hint->relations) < 2)
1315 parse_ereport(hint->base.hint_str,
1316 ("%s hint requires at least two relations.",
1318 hint->base.state = HINT_STATE_ERROR;
1325 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1327 if ((str = parse_quote_value(str, &hint->name, "parameter name", true))
1329 (str = parse_quote_value(str, &hint->value, "parameter value", false))
1337 * set GUC parameter functions
1341 set_config_option_wrapper(const char *name, const char *value,
1342 GucContext context, GucSource source,
1343 GucAction action, bool changeVal, int elevel)
1346 MemoryContext ccxt = CurrentMemoryContext;
1350 #if PG_VERSION_NUM >= 90200
1351 result = set_config_option(name, value, context, source,
1352 action, changeVal, 0);
1354 result = set_config_option(name, value, context, source,
1362 /* Save error info */
1363 MemoryContextSwitchTo(ccxt);
1364 errdata = CopyErrorData();
1367 ereport(elevel, (errcode(errdata->sqlerrcode),
1368 errmsg("%s", errdata->message),
1369 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1370 errdata->hint ? errhint("%s", errdata->hint) : 0));
1371 FreeErrorData(errdata);
1379 set_config_options(SetHint **options, int noptions, GucContext context)
1384 save_nestlevel = NewGUCNestLevel();
1386 for (i = 0; i < noptions; i++)
1388 SetHint *hint = options[i];
1391 if (!hint_state_enabled(hint))
1394 result = set_config_option_wrapper(hint->name, hint->value, context,
1395 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1396 pg_hint_plan_parse_messages);
1398 hint->base.state = HINT_STATE_USED;
1400 hint->base.state = HINT_STATE_ERROR;
1403 return save_nestlevel;
1406 #define SET_CONFIG_OPTION(name, type_bits) \
1407 set_config_option_wrapper((name), \
1408 (mask & (type_bits)) ? "true" : "false", \
1409 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1412 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1416 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1417 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1418 #if PG_VERSION_NUM >= 90200
1419 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1422 mask = enforce_mask;
1424 mask = enforce_mask & current_hint->init_scan_mask;
1426 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1427 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1428 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1429 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1430 #if PG_VERSION_NUM >= 90200
1431 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1436 set_join_config_options(unsigned char enforce_mask, GucContext context)
1440 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1441 enforce_mask == ENABLE_HASHJOIN)
1442 mask = enforce_mask;
1444 mask = enforce_mask & current_hint->init_join_mask;
1446 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1447 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1448 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1452 * pg_hint_plan hook functions
1456 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1457 ParamListInfo params, bool isTopLevel,
1458 DestReceiver *dest, char *completionTag)
1462 if (!pg_hint_plan_enable)
1464 if (prev_ProcessUtility)
1465 (*prev_ProcessUtility) (parsetree, queryString, params,
1466 isTopLevel, dest, completionTag);
1468 standard_ProcessUtility(parsetree, queryString, params,
1469 isTopLevel, dest, completionTag);
1475 if (IsA(node, ExplainStmt))
1478 * EXPLAIN対象のクエリのパースツリーを取得する
1483 stmt = (ExplainStmt *) node;
1485 Assert(IsA(stmt->query, Query));
1486 query = (Query *) stmt->query;
1488 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1489 node = query->utilityStmt;
1493 * EXECUTEコマンドならば、PREPARE時に指定されたクエリ文字列を取得し、ヒント
1496 if (IsA(node, ExecuteStmt))
1500 stmt = (ExecuteStmt *) node;
1501 stmt_name = stmt->name;
1508 if (prev_ProcessUtility)
1509 (*prev_ProcessUtility) (parsetree, queryString, params,
1510 isTopLevel, dest, completionTag);
1512 standard_ProcessUtility(parsetree, queryString, params,
1513 isTopLevel, dest, completionTag);
1527 if (prev_ProcessUtility)
1528 (*prev_ProcessUtility) (parsetree, queryString, params,
1529 isTopLevel, dest, completionTag);
1531 standard_ProcessUtility(parsetree, queryString, params,
1532 isTopLevel, dest, completionTag);
1536 * ヒント用スタック構造にヒントをプッシュする。なお、List構造体でヒント用スタッ
1537 * ク構造を実装していて、リストの先頭がスタックの一番上に該当する。
1540 push_hint(HintState *hstate)
1542 /* 新しいヒントをスタックに積む。 */
1543 HintStateStack = lcons(hstate, HintStateStack);
1546 * 先ほどスタックに積んだヒントを現在のヒントとしてcurrent_hintに格納する。
1548 current_hint = hstate;
1552 * ヒント用スタック構造から不要になったヒントをポップする。取り出されたヒントは
1558 /* ヒントのスタックが空の場合はエラーを返す */
1559 if(HintStateStack == NIL)
1560 elog(ERROR, "hint stack is empty");
1563 * ヒントのスタックから一番上のものを取り出して解放する。 current_hintは
1564 * 常に最上段ヒントを指す(スタックが空の場合はNULL)。
1566 HintStateStack = list_delete_first(HintStateStack);
1567 HintStateDelete(current_hint);
1568 if(HintStateStack == NIL)
1569 current_hint = NULL;
1571 current_hint = (HintState *) lfirst(list_head(HintStateStack));
1574 static PlannedStmt *
1575 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1578 PlannedStmt *result;
1582 * pg_hint_planが無効である場合は通常のparser処理をおこなう。
1583 * 他のフック関数で実行されるhint処理をスキップするために、current_hint 変数
1586 if (!pg_hint_plan_enable)
1588 current_hint = NULL;
1591 return (*prev_planner) (parse, cursorOptions, boundParams);
1593 return standard_planner(parse, cursorOptions, boundParams);
1597 hstate = parse_head_comment(parse);
1600 * hintが指定されない、または空のhintを指定された場合は通常のparser処理をお
1602 * 他のフック関数で実行されるhint処理をスキップするために、current_hint 変数
1607 current_hint = NULL;
1610 return (*prev_planner) (parse, cursorOptions, boundParams);
1612 return standard_planner(parse, cursorOptions, boundParams);
1615 /* 現在のヒントをスタックに積む。 */
1618 /* Set hint で指定されたGUCパラメータを設定する */
1619 save_nestlevel = set_config_options(current_hint->set_hints,
1620 current_hint->num_hints[HINT_TYPE_SET],
1621 current_hint->context);
1624 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
1625 if (enable_indexscan)
1626 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
1627 if (enable_bitmapscan)
1628 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
1630 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
1631 #if PG_VERSION_NUM >= 90200
1632 if (enable_indexonlyscan)
1633 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
1635 if (enable_nestloop)
1636 current_hint->init_join_mask |= ENABLE_NESTLOOP;
1637 if (enable_mergejoin)
1638 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
1639 if (enable_hashjoin)
1640 current_hint->init_join_mask |= ENABLE_HASHJOIN;
1643 * プラン作成中にエラーとなった場合、GUCパラメータと current_hintを
1644 * pg_hint_plan_planner 関数の実行前の状態に戻す。
1649 result = (*prev_planner) (parse, cursorOptions, boundParams);
1651 result = standard_planner(parse, cursorOptions, boundParams);
1656 * プランナ起動前の状態に戻すため、GUCパラメータを復元し、ヒント情報を
1659 AtEOXact_GUC(true, save_nestlevel);
1666 * Print hint if debugging.
1668 if (pg_hint_plan_debug_print)
1669 HintStateDump(current_hint);
1672 * プランナ起動前の状態に戻すため、GUCパラメータを復元し、ヒント情報を一つ
1675 AtEOXact_GUC(true, save_nestlevel);
1682 * aliasnameと一致するSCANヒントを探す
1684 static ScanMethodHint *
1685 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
1691 * RELOPT_BASEREL でなければ、scan method ヒントが適用しない。
1692 * 子テーブルの場合はRELOPT_OTHER_MEMBER_RELとなるが、サポート対象外とする。
1693 * また、通常のリレーション以外は、スキャン方式を選択できない。
1695 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
1698 rte = root->simple_rte_array[rel->relid];
1700 /* 外部表はスキャン方式が選択できない。 */
1701 if (rte->relkind == RELKIND_FOREIGN_TABLE)
1705 * スキャン方式のヒントのリストから、検索対象のリレーションと名称が一致する
1708 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1710 ScanMethodHint *hint = current_hint->scan_hints[i];
1712 /* すでに無効となっているヒントは検索対象にしない。 */
1713 if (!hint_state_enabled(hint))
1716 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
1724 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel)
1731 * We delete all the IndexOptInfo list and prevent you from being usable by
1734 if (hint->enforce_mask == ENABLE_SEQSCAN ||
1735 hint->enforce_mask == ENABLE_TIDSCAN)
1737 list_free_deep(rel->indexlist);
1738 rel->indexlist = NIL;
1739 hint->base.state = HINT_STATE_USED;
1745 * When a list of indexes is not specified, we just use all indexes.
1747 if (hint->indexnames == NIL)
1751 * Leaving only an specified index, we delete it from a IndexOptInfo list
1755 for (cell = list_head(rel->indexlist); cell; cell = next)
1757 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
1758 char *indexname = get_rel_name(info->indexoid);
1760 bool use_index = false;
1764 foreach(l, hint->indexnames)
1766 if (RelnameCmp(&indexname, &lfirst(l)) == 0)
1774 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
1783 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
1784 bool inhparent, RelOptInfo *rel)
1786 ScanMethodHint *hint;
1788 if (prev_get_relation_info)
1789 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
1791 /* 有効なヒントが指定されなかった場合は処理をスキップする。 */
1797 /* store does relids of parent table. */
1798 current_hint->parent_relid = rel->relid;
1800 else if (current_hint->parent_relid != 0)
1803 * We use the same GUC parameter if this table is the child table of a
1804 * table called pg_hint_plan_get_relation_info just before that.
1808 /* append_rel_list contains all append rels; ignore others */
1809 foreach(l, root->append_rel_list)
1811 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1813 /* This rel is child table. */
1814 if (appinfo->parent_relid == current_hint->parent_relid &&
1815 appinfo->child_relid == rel->relid)
1817 if (current_hint->parent_hint)
1818 delete_indexes(current_hint->parent_hint, rel);
1824 /* This rel is not inherit table. */
1825 current_hint->parent_relid = 0;
1826 current_hint->parent_hint = NULL;
1829 /* scan hint が指定されない場合は、GUCパラメータをリセットする。 */
1830 if ((hint = find_scan_hint(root, rel)) == NULL)
1832 set_scan_config_options(current_hint->init_scan_mask,
1833 current_hint->context);
1836 set_scan_config_options(hint->enforce_mask, current_hint->context);
1837 hint->base.state = HINT_STATE_USED;
1839 current_hint->parent_hint = hint;
1841 delete_indexes(hint, rel);
1845 * aliasnameがクエリ中に指定した別名と一致する場合は、そのインデックスを返し、一
1847 * aliasnameがクエリ中に複数回指定された場合は、-1を返す。
1850 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
1856 for (i = 1; i < root->simple_rel_array_size; i++)
1860 if (root->simple_rel_array[i] == NULL)
1863 Assert(i == root->simple_rel_array[i]->relid);
1865 if (RelnameCmp(&aliasname,
1866 &root->simple_rte_array[i]->eref->aliasname) != 0)
1869 foreach(l, initial_rels)
1871 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
1873 if (rel->reloptkind == RELOPT_BASEREL)
1875 if (rel->relid != i)
1880 Assert(rel->reloptkind == RELOPT_JOINREL);
1882 if (!bms_is_member(i, rel->relids))
1889 ("Relation name \"%s\" is ambiguous.",
1904 * relidビットマスクと一致するヒントを探す
1906 static JoinMethodHint *
1907 find_join_hint(Relids joinrelids)
1912 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
1914 foreach(l, join_hint)
1916 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
1918 if (bms_equal(joinrelids, hint->joinrelids))
1926 * 結合方式のヒントを使用しやすい構造に変換する。
1929 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
1930 List *initial_rels, JoinMethodHint **join_method_hints)
1939 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
1941 JoinMethodHint *hint = hstate->join_hints[i];
1944 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
1947 bms_free(hint->joinrelids);
1948 hint->joinrelids = NULL;
1950 for (j = 0; j < hint->nrels; j++)
1952 char *relname = hint->relnames[j];
1954 relid = find_relid_aliasname(root, relname, initial_rels,
1955 hint->base.hint_str);
1958 hint->base.state = HINT_STATE_ERROR;
1963 if (bms_is_member(relid, hint->joinrelids))
1965 parse_ereport(hint->base.hint_str,
1966 ("Relation name \"%s\" is duplicated.", relname));
1967 hint->base.state = HINT_STATE_ERROR;
1971 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
1974 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
1977 hstate->join_hint_level[hint->nrels] =
1978 lappend(hstate->join_hint_level[hint->nrels], hint);
1982 * 有効なLeading ヒントが指定されている場合は、結合順にあわせて join method
1983 * hint のフォーマットに変換する。
1985 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
1988 lhint = hstate->leading_hint;
1989 if (!hint_state_enabled(lhint))
1992 /* Leading hint は、全ての join 方式が有効な hint として登録する */
1995 foreach(l, lhint->relations)
1997 char *relname = (char *)lfirst(l);
1998 JoinMethodHint *hint;
2001 find_relid_aliasname(root, relname, initial_rels,
2006 bms_free(joinrelids);
2013 if (bms_is_member(relid, joinrelids))
2015 parse_ereport(lhint->base.hint_str,
2016 ("Relation name \"%s\" is duplicated.", relname));
2017 lhint->base.state = HINT_STATE_ERROR;
2018 bms_free(joinrelids);
2022 joinrelids = bms_add_member(joinrelids, relid);
2028 hint = find_join_hint(joinrelids);
2032 * Here relnames is not set, since Relids bitmap is sufficient to
2033 * control paths of this query afterwards.
2035 hint = (JoinMethodHint *) JoinMethodHintCreate(lhint->base.hint_str,
2037 hint->base.state = HINT_STATE_USED;
2038 hint->nrels = njoinrels;
2039 hint->enforce_mask = ENABLE_ALL_JOIN;
2040 hint->joinrelids = bms_copy(joinrelids);
2043 join_method_hints[njoinrels] = hint;
2045 if (njoinrels >= nbaserel)
2049 bms_free(joinrelids);
2054 for (i = 2; i <= njoinrels; i++)
2056 /* Leading で指定した組み合わせ以外の join hint を削除する */
2057 list_free(hstate->join_hint_level[i]);
2059 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
2062 if (hint_state_enabled(lhint))
2063 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2065 lhint->base.state = HINT_STATE_USED;
2070 * set_plain_rel_pathlist
2071 * Build access paths for a plain relation (no subquery, no inheritance)
2073 * This function was copied and edited from set_plain_rel_pathlist() in
2074 * src/backend/optimizer/path/allpaths.c
2077 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2079 /* Consider sequential scan */
2080 #if PG_VERSION_NUM >= 90200
2081 add_path(rel, create_seqscan_path(root, rel, NULL));
2083 add_path(rel, create_seqscan_path(root, rel));
2086 /* Consider index scans */
2087 create_index_paths(root, rel);
2089 /* Consider TID scans */
2090 create_tidscan_paths(root, rel);
2092 /* Now find the cheapest of the paths for this rel */
2097 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
2102 foreach(l, initial_rels)
2104 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2106 ScanMethodHint *hint;
2109 * スキャン方式が選択できるリレーションのみ、スキャンパスを再生成する。
2111 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2114 rte = root->simple_rte_array[rel->relid];
2116 /* 外部表はスキャン方式が選択できない。 */
2117 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2121 * scan method hint が指定されていなければ、初期値のGUCパラメータでscan
2124 if ((hint = find_scan_hint(root, rel)) == NULL)
2125 set_scan_config_options(hstate->init_scan_mask,
2129 set_scan_config_options(hint->enforce_mask, hstate->context);
2130 hint->base.state = HINT_STATE_USED;
2133 list_free_deep(rel->pathlist);
2134 rel->pathlist = NIL;
2137 /* It's an "append relation", process accordingly */
2138 set_append_rel_pathlist(root, rel, rel->relid, rte);
2142 set_plain_rel_pathlist(root, rel, rte);
2147 * Restore the GUC variables we set above.
2149 set_scan_config_options(hstate->init_scan_mask, hstate->context);
2153 * make_join_rel() をラップする関数
2155 * ヒントにしたがって、enabele_* パラメータを変更した上で、make_join_rel()を
2159 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
2162 JoinMethodHint *hint;
2166 joinrelids = bms_union(rel1->relids, rel2->relids);
2167 hint = find_join_hint(joinrelids);
2168 bms_free(joinrelids);
2171 return pg_hint_plan_make_join_rel(root, rel1, rel2);
2173 save_nestlevel = NewGUCNestLevel();
2175 set_join_config_options(hint->enforce_mask, current_hint->context);
2177 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2178 hint->base.state = HINT_STATE_USED;
2181 * Restore the GUC variables we set above.
2183 AtEOXact_GUC(true, save_nestlevel);
2189 get_num_baserels(List *initial_rels)
2194 foreach(l, initial_rels)
2196 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2198 if (rel->reloptkind == RELOPT_BASEREL)
2200 else if (rel->reloptkind ==RELOPT_JOINREL)
2201 nbaserel+= bms_num_members(rel->relids);
2204 /* other values not expected here */
2205 elog(ERROR, "Unrecognized reloptkind type: %d", rel->reloptkind);
2213 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
2216 JoinMethodHint **join_method_hints;
2222 * pg_hint_planが無効、または有効なヒントが1つも指定されなかった場合は、標準
2227 if (prev_join_search)
2228 return (*prev_join_search) (root, levels_needed, initial_rels);
2229 else if (enable_geqo && levels_needed >= geqo_threshold)
2230 return geqo(root, levels_needed, initial_rels);
2232 return standard_join_search(root, levels_needed, initial_rels);
2235 /* We apply scan method hint rebuild scan path. */
2236 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
2239 * GEQOを使用する条件を満たした場合は、GEQOを用いた結合方式の検索を行う。
2240 * このとき、スキャン方式のヒントとSetヒントのみが有効になり、結合方式や結合
2241 * 順序はヒント句は無効になりGEQOのアルゴリズムで決定される。
2243 if (enable_geqo && levels_needed >= geqo_threshold)
2244 return geqo(root, levels_needed, initial_rels);
2246 nbaserel = get_num_baserels(initial_rels);
2247 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
2248 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
2250 transform_join_hints(current_hint, root, nbaserel, initial_rels,
2253 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
2255 for (i = 2; i <= nbaserel; i++)
2257 list_free(current_hint->join_hint_level[i]);
2259 /* free Leading hint only */
2260 if (join_method_hints[i] != NULL &&
2261 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
2262 JoinMethodHintDelete(join_method_hints[i]);
2264 pfree(current_hint->join_hint_level);
2265 pfree(join_method_hints);
2267 if (current_hint->num_hints[HINT_TYPE_LEADING] > 0 &&
2268 hint_state_enabled(current_hint->leading_hint))
2269 set_join_config_options(current_hint->init_join_mask,
2270 current_hint->context);
2277 * Build access paths for a base relation
2279 * This function was copied and edited from set_rel_pathlist() in
2280 * src/backend/optimizer/path/allpaths.c
2283 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
2284 Index rti, RangeTblEntry *rte)
2286 #if PG_VERSION_NUM >= 90200
2287 if (IS_DUMMY_REL(rel))
2289 /* We already proved the relation empty, so nothing more to do */
2296 /* It's an "append relation", process accordingly */
2297 set_append_rel_pathlist(root, rel, rti, rte);
2301 if (rel->rtekind == RTE_RELATION)
2303 if (rte->relkind == RELKIND_RELATION)
2305 /* Plain relation */
2306 set_plain_rel_pathlist(root, rel, rte);
2309 elog(ERROR, "Unexpected relkind: %c", rte->relkind);
2312 elog(ERROR, "Unexpected rtekind: %d", (int) rel->rtekind);
2316 #define standard_join_search pg_hint_plan_standard_join_search
2317 #define join_search_one_level pg_hint_plan_join_search_one_level
2318 #define make_join_rel make_join_rel_wrapper
2321 #undef make_join_rel
2322 #define make_join_rel pg_hint_plan_make_join_rel
2323 #define add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype, sjinfo, restrictlist) \
2325 ScanMethodHint *hint = NULL; \
2326 if ((hint = find_scan_hint((root), (innerrel))) != NULL) \
2328 set_scan_config_options(hint->enforce_mask, current_hint->context); \
2329 hint->base.state = HINT_STATE_USED; \
2331 add_paths_to_joinrel((root), (joinrel), (outerrel), (innerrel), (jointype), (sjinfo), (restrictlist)); \
2333 set_scan_config_options(current_hint->init_scan_mask, current_hint->context); \
2335 #include "make_join_rel.c"