1 /*-------------------------------------------------------------------------
4 * do instructions or hints to the planner using C-style block comments
7 * Copyright (c) 2012, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
9 *-------------------------------------------------------------------------
12 #include "commands/prepare.h"
13 #include "mb/pg_wchar.h"
14 #include "miscadmin.h"
15 #include "nodes/nodeFuncs.h"
16 #include "optimizer/clauses.h"
17 #include "optimizer/cost.h"
18 #include "optimizer/geqo.h"
19 #include "optimizer/joininfo.h"
20 #include "optimizer/pathnode.h"
21 #include "optimizer/paths.h"
22 #include "optimizer/plancat.h"
23 #include "optimizer/planner.h"
24 #include "optimizer/prep.h"
25 #include "optimizer/restrictinfo.h"
26 #include "parser/scansup.h"
27 #include "tcop/utility.h"
28 #include "utils/lsyscache.h"
29 #include "utils/memutils.h"
30 #if PG_VERSION_NUM >= 90200
31 #include "catalog/pg_class.h"
34 #ifdef PG_MODULE_MAGIC
38 #if PG_VERSION_NUM < 90100
39 #error unsupported PostgreSQL version
42 #define BLOCK_COMMENT_START "/*"
43 #define BLOCK_COMMENT_END "*/"
44 #define HINT_COMMENT_KEYWORD "+"
45 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
46 #define HINT_END BLOCK_COMMENT_END
49 #define HINT_SEQSCAN "SeqScan"
50 #define HINT_INDEXSCAN "IndexScan"
51 #define HINT_BITMAPSCAN "BitmapScan"
52 #define HINT_TIDSCAN "TidScan"
53 #define HINT_NOSEQSCAN "NoSeqScan"
54 #define HINT_NOINDEXSCAN "NoIndexScan"
55 #define HINT_NOBITMAPSCAN "NoBitmapScan"
56 #define HINT_NOTIDSCAN "NoTidScan"
57 #if PG_VERSION_NUM >= 90200
58 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
59 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
61 #define HINT_NESTLOOP "NestLoop"
62 #define HINT_MERGEJOIN "MergeJoin"
63 #define HINT_HASHJOIN "HashJoin"
64 #define HINT_NONESTLOOP "NoNestLoop"
65 #define HINT_NOMERGEJOIN "NoMergeJoin"
66 #define HINT_NOHASHJOIN "NoHashJoin"
67 #define HINT_LEADING "Leading"
68 #define HINT_SET "Set"
70 #define HINT_ARRAY_DEFAULT_INITSIZE 8
72 #define hint_ereport(str, detail) \
73 ereport(pg_hint_plan_parse_messages, \
74 (errmsg("hint syntax error at or near \"%s\"", (str)), \
77 #define skip_space(str) \
78 while (isspace(*str)) \
83 ENABLE_SEQSCAN = 0x01,
84 ENABLE_INDEXSCAN = 0x02,
85 ENABLE_BITMAPSCAN = 0x04,
86 ENABLE_TIDSCAN = 0x08,
87 #if PG_VERSION_NUM >= 90200
88 ENABLE_INDEXONLYSCAN = 0x10
94 ENABLE_NESTLOOP = 0x01,
95 ENABLE_MERGEJOIN = 0x02,
96 ENABLE_HASHJOIN = 0x04
99 #if PG_VERSION_NUM >= 90200
100 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
101 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
102 ENABLE_INDEXONLYSCAN)
104 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
105 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN)
107 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
108 #define DISABLE_ALL_SCAN 0
109 #define DISABLE_ALL_JOIN 0
111 /* hint keyword of enum type*/
112 typedef enum HintKeyword
114 HINT_KEYWORD_SEQSCAN,
115 HINT_KEYWORD_INDEXSCAN,
116 HINT_KEYWORD_BITMAPSCAN,
117 HINT_KEYWORD_TIDSCAN,
118 HINT_KEYWORD_NOSEQSCAN,
119 HINT_KEYWORD_NOINDEXSCAN,
120 HINT_KEYWORD_NOBITMAPSCAN,
121 HINT_KEYWORD_NOTIDSCAN,
122 #if PG_VERSION_NUM >= 90200
123 HINT_KEYWORD_INDEXONLYSCAN,
124 HINT_KEYWORD_NOINDEXONLYSCAN,
126 HINT_KEYWORD_NESTLOOP,
127 HINT_KEYWORD_MERGEJOIN,
128 HINT_KEYWORD_HASHJOIN,
129 HINT_KEYWORD_NONESTLOOP,
130 HINT_KEYWORD_NOMERGEJOIN,
131 HINT_KEYWORD_NOHASHJOIN,
132 HINT_KEYWORD_LEADING,
134 HINT_KEYWORD_UNRECOGNIZED
137 typedef struct Hint Hint;
138 typedef struct HintState HintState;
140 typedef Hint *(*HintCreateFunction) (const char *hint_str,
142 HintKeyword hint_keyword);
143 typedef void (*HintDeleteFunction) (Hint *hint);
144 typedef void (*HintDumpFunction) (Hint *hint, StringInfo buf);
145 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
146 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
147 Query *parse, const char *str);
150 #define NUM_HINT_TYPE 4
151 typedef enum HintType
153 HINT_TYPE_SCAN_METHOD,
154 HINT_TYPE_JOIN_METHOD,
159 static const char *HintTypeName[] = {
167 typedef enum HintStatus
169 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
170 HINT_STATE_USED, /* hint is used */
171 HINT_STATE_DUPLICATION, /* specified hint duplication */
172 HINT_STATE_ERROR /* execute error (parse error does not include
176 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
177 (hint)->base.state == HINT_STATE_USED)
179 /* common data for all hints. */
182 const char *hint_str; /* must not do pfree */
183 const char *keyword; /* must not do pfree */
184 HintKeyword hint_keyword;
187 HintDeleteFunction delete_func;
188 HintDumpFunction dump_func;
189 HintCmpFunction cmp_func;
190 HintParseFunction parse_func;
193 /* scan method hints */
194 typedef struct ScanMethodHint
199 unsigned char enforce_mask;
202 /* join method hints */
203 typedef struct JoinMethodHint
208 unsigned char enforce_mask;
212 /* join order hints */
213 typedef struct LeadingHint
216 List *relations; /* relation names specified in Leading hint */
219 /* change a run-time parameter hints */
220 typedef struct SetHint
223 char *name; /* name of variable */
229 * Describes a context of hint processing.
233 char *hint_str; /* original hint string */
236 int nall_hints; /* # of valid all hints */
237 int max_all_hints; /* # of slots for all hints */
238 Hint **all_hints; /* parsed all hints */
240 /* # of each hints */
241 int num_hints[NUM_HINT_TYPE];
243 /* for scan method hints */
244 ScanMethodHint **scan_hints; /* parsed scan hints */
245 int init_scan_mask; /* initial value scan parameter */
246 Index parent_relid; /* inherit parent table relid */
247 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
249 /* for join method hints */
250 JoinMethodHint **join_hints; /* parsed join hints */
251 int init_join_mask; /* initial value join parameter */
252 List **join_hint_level;
254 /* for Leading hint */
255 LeadingHint *leading_hint; /* parsed last specified Leading hint */
258 SetHint **set_hints; /* parsed Set hints */
259 GucContext context; /* which GUC parameters can we set? */
263 * Describes a hint parser module which is bound with particular hint keyword.
265 typedef struct HintParser
268 HintCreateFunction create_func;
269 HintKeyword hint_keyword;
272 /* Module callbacks */
276 static void push_hint(HintState *hstate);
277 static void pop_hint(void);
279 static void pg_hint_plan_ProcessUtility(Node *parsetree,
280 const char *queryString,
281 ParamListInfo params, bool isTopLevel,
283 char *completionTag);
284 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
285 ParamListInfo boundParams);
286 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
287 Oid relationObjectId,
288 bool inhparent, RelOptInfo *rel);
289 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
293 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
294 HintKeyword hint_keyword);
295 static void ScanMethodHintDelete(ScanMethodHint *hint);
296 static void ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf);
297 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
298 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
299 Query *parse, const char *str);
300 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
301 HintKeyword hint_keyword);
302 static void JoinMethodHintDelete(JoinMethodHint *hint);
303 static void JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf);
304 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
305 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
306 Query *parse, const char *str);
307 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
308 HintKeyword hint_keyword);
309 static void LeadingHintDelete(LeadingHint *hint);
310 static void LeadingHintDump(LeadingHint *hint, StringInfo buf);
311 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
312 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
313 Query *parse, const char *str);
314 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
315 HintKeyword hint_keyword);
316 static void SetHintDelete(SetHint *hint);
317 static void SetHintDump(SetHint *hint, StringInfo buf);
318 static int SetHintCmp(const SetHint *a, const SetHint *b);
319 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
322 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
325 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
326 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
327 ListCell *other_rels);
328 static void make_rels_by_clauseless_joins(PlannerInfo *root,
330 ListCell *other_rels);
331 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
332 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
333 Index rti, RangeTblEntry *rte);
334 #if PG_VERSION_NUM >= 90200
335 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
336 List *live_childrels,
337 List *all_child_pathkeys);
339 static List *accumulate_append_subpath(List *subpaths, Path *path);
340 #if PG_VERSION_NUM < 90200
341 static void set_dummy_rel_pathlist(RelOptInfo *rel);
343 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
347 static bool pg_hint_plan_enable_hint = true;
348 static bool pg_hint_plan_debug_print = false;
349 static int pg_hint_plan_parse_messages = INFO;
351 static const struct config_enum_entry parse_messages_level_options[] = {
352 {"debug", DEBUG2, true},
353 {"debug5", DEBUG5, false},
354 {"debug4", DEBUG4, false},
355 {"debug3", DEBUG3, false},
356 {"debug2", DEBUG2, false},
357 {"debug1", DEBUG1, false},
359 {"info", INFO, false},
360 {"notice", NOTICE, false},
361 {"warning", WARNING, false},
362 {"error", ERROR, false},
364 * {"fatal", FATAL, true},
365 * {"panic", PANIC, true},
370 /* Saved hook values in case of unload */
371 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
372 static planner_hook_type prev_planner = NULL;
373 static get_relation_info_hook_type prev_get_relation_info = NULL;
374 static join_search_hook_type prev_join_search = NULL;
376 /* Hold reference to currently active hint */
377 static HintState *current_hint = NULL;
380 * List of hint contexts. We treat the head of the list as the Top of the
381 * context stack, so current_hint always points the first element of this list.
383 static List *HintStateStack = NIL;
386 * Holds statement name during executing EXECUTE command. NULL for other
389 static char *stmt_name = NULL;
391 static const HintParser parsers[] = {
392 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
393 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
394 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
395 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
396 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
397 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
398 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
399 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
400 #if PG_VERSION_NUM >= 90200
401 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
402 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
404 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
405 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
406 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
407 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
408 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
409 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
410 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
411 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
412 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
416 * Module load callbacks
421 /* Define custom GUC variables. */
422 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
423 "Force planner to use plans specified in the hint comment preceding to the query.",
425 &pg_hint_plan_enable_hint,
433 DefineCustomBoolVariable("pg_hint_plan.debug_print",
434 "Logs results of hint parsing.",
436 &pg_hint_plan_debug_print,
444 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
445 "Message level of parse errors.",
447 &pg_hint_plan_parse_messages,
449 parse_messages_level_options,
457 prev_ProcessUtility = ProcessUtility_hook;
458 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
459 prev_planner = planner_hook;
460 planner_hook = pg_hint_plan_planner;
461 prev_get_relation_info = get_relation_info_hook;
462 get_relation_info_hook = pg_hint_plan_get_relation_info;
463 prev_join_search = join_search_hook;
464 join_search_hook = pg_hint_plan_join_search;
468 * Module unload callback
474 /* Uninstall hooks. */
475 ProcessUtility_hook = prev_ProcessUtility;
476 planner_hook = prev_planner;
477 get_relation_info_hook = prev_get_relation_info;
478 join_search_hook = prev_join_search;
482 * create and delete functions the hint object
486 ScanMethodHintCreate(const char *hint_str, const char *keyword,
487 HintKeyword hint_keyword)
489 ScanMethodHint *hint;
491 hint = palloc(sizeof(ScanMethodHint));
492 hint->base.hint_str = hint_str;
493 hint->base.keyword = keyword;
494 hint->base.hint_keyword = hint_keyword;
495 hint->base.type = HINT_TYPE_SCAN_METHOD;
496 hint->base.state = HINT_STATE_NOTUSED;
497 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
498 hint->base.dump_func = (HintDumpFunction) ScanMethodHintDump;
499 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
500 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
501 hint->relname = NULL;
502 hint->indexnames = NIL;
503 hint->enforce_mask = 0;
505 return (Hint *) hint;
509 ScanMethodHintDelete(ScanMethodHint *hint)
515 pfree(hint->relname);
516 list_free_deep(hint->indexnames);
521 JoinMethodHintCreate(const char *hint_str, const char *keyword,
522 HintKeyword hint_keyword)
524 JoinMethodHint *hint;
526 hint = palloc(sizeof(JoinMethodHint));
527 hint->base.hint_str = hint_str;
528 hint->base.keyword = keyword;
529 hint->base.hint_keyword = hint_keyword;
530 hint->base.type = HINT_TYPE_JOIN_METHOD;
531 hint->base.state = HINT_STATE_NOTUSED;
532 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
533 hint->base.dump_func = (HintDumpFunction) JoinMethodHintDump;
534 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
535 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
537 hint->relnames = NULL;
538 hint->enforce_mask = 0;
539 hint->joinrelids = NULL;
541 return (Hint *) hint;
545 JoinMethodHintDelete(JoinMethodHint *hint)
554 for (i = 0; i < hint->nrels; i++)
555 pfree(hint->relnames[i]);
556 pfree(hint->relnames);
558 bms_free(hint->joinrelids);
563 LeadingHintCreate(const char *hint_str, const char *keyword,
564 HintKeyword hint_keyword)
568 hint = palloc(sizeof(LeadingHint));
569 hint->base.hint_str = hint_str;
570 hint->base.keyword = keyword;
571 hint->base.hint_keyword = hint_keyword;
572 hint->base.type = HINT_TYPE_LEADING;
573 hint->base.state = HINT_STATE_NOTUSED;
574 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
575 hint->base.dump_func = (HintDumpFunction) LeadingHintDump;
576 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
577 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
578 hint->relations = NIL;
580 return (Hint *) hint;
584 LeadingHintDelete(LeadingHint *hint)
589 list_free_deep(hint->relations);
594 SetHintCreate(const char *hint_str, const char *keyword,
595 HintKeyword hint_keyword)
599 hint = palloc(sizeof(SetHint));
600 hint->base.hint_str = hint_str;
601 hint->base.keyword = keyword;
602 hint->base.hint_keyword = hint_keyword;
603 hint->base.type = HINT_TYPE_SET;
604 hint->base.state = HINT_STATE_NOTUSED;
605 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
606 hint->base.dump_func = (HintDumpFunction) SetHintDump;
607 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
608 hint->base.parse_func = (HintParseFunction) SetHintParse;
613 return (Hint *) hint;
617 SetHintDelete(SetHint *hint)
627 list_free(hint->words);
632 HintStateCreate(void)
636 hstate = palloc(sizeof(HintState));
637 hstate->hint_str = NULL;
638 hstate->nall_hints = 0;
639 hstate->max_all_hints = 0;
640 hstate->all_hints = NULL;
641 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
642 hstate->scan_hints = NULL;
643 hstate->init_scan_mask = 0;
644 hstate->parent_relid = 0;
645 hstate->parent_hint = NULL;
646 hstate->join_hints = NULL;
647 hstate->init_join_mask = 0;
648 hstate->join_hint_level = NULL;
649 hstate->leading_hint = NULL;
650 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
651 hstate->set_hints = NULL;
657 HintStateDelete(HintState *hstate)
664 if (hstate->hint_str)
665 pfree(hstate->hint_str);
667 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
668 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
669 if (hstate->all_hints)
670 pfree(hstate->all_hints);
678 dump_quote_value(StringInfo buf, const char *value)
680 bool need_quote = false;
683 for (str = value; *str != '\0'; str++)
685 if (isspace(*str) || *str == ')' || *str == '"')
688 appendStringInfoCharMacro(buf, '"');
693 for (str = value; *str != '\0'; str++)
696 appendStringInfoCharMacro(buf, '"');
698 appendStringInfoCharMacro(buf, *str);
702 appendStringInfoCharMacro(buf, '"');
706 ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf)
710 appendStringInfo(buf, "%s(", hint->base.keyword);
711 if (hint->relname != NULL)
713 dump_quote_value(buf, hint->relname);
714 foreach(l, hint->indexnames)
716 appendStringInfoCharMacro(buf, ' ');
717 dump_quote_value(buf, (char *) lfirst(l));
720 appendStringInfoString(buf, ")\n");
724 JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf)
728 appendStringInfo(buf, "%s(", hint->base.keyword);
729 if (hint->relnames != NULL)
731 dump_quote_value(buf, hint->relnames[0]);
732 for (i = 1; i < hint->nrels; i++)
734 appendStringInfoCharMacro(buf, ' ');
735 dump_quote_value(buf, hint->relnames[i]);
738 appendStringInfoString(buf, ")\n");
743 LeadingHintDump(LeadingHint *hint, StringInfo buf)
748 appendStringInfo(buf, "%s(", HINT_LEADING);
750 foreach(l, hint->relations)
755 appendStringInfoCharMacro(buf, ' ');
757 dump_quote_value(buf, (char *) lfirst(l));
760 appendStringInfoString(buf, ")\n");
764 SetHintDump(SetHint *hint, StringInfo buf)
766 bool is_first = true;
769 appendStringInfo(buf, "%s(", HINT_SET);
770 foreach(l, hint->words)
775 appendStringInfoCharMacro(buf, ' ');
777 dump_quote_value(buf, (char *) lfirst(l));
779 appendStringInfo(buf, ")\n");
783 all_hint_dump(HintState *hstate, StringInfo buf, const char *title,
788 appendStringInfo(buf, "%s:\n", title);
789 for (i = 0; i < hstate->nall_hints; i++)
791 if (hstate->all_hints[i]->state != state)
794 hstate->all_hints[i]->dump_func(hstate->all_hints[i], buf);
799 HintStateDump(HintState *hstate)
805 elog(LOG, "pg_hint_plan:\nno hint");
809 initStringInfo(&buf);
811 appendStringInfoString(&buf, "pg_hint_plan:\n");
812 all_hint_dump(hstate, &buf, "used hint", HINT_STATE_USED);
813 all_hint_dump(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
814 all_hint_dump(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
815 all_hint_dump(hstate, &buf, "error hint", HINT_STATE_ERROR);
817 elog(LOG, "%s", buf.data);
827 RelnameCmp(const void *a, const void *b)
829 const char *relnamea = *((const char **) a);
830 const char *relnameb = *((const char **) b);
832 return strcmp(relnamea, relnameb);
836 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
838 return RelnameCmp(&a->relname, &b->relname);
842 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
846 if (a->nrels != b->nrels)
847 return a->nrels - b->nrels;
849 for (i = 0; i < a->nrels; i++)
852 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
860 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
866 SetHintCmp(const SetHint *a, const SetHint *b)
868 return strcmp(a->name, b->name);
872 HintCmp(const void *a, const void *b)
874 const Hint *hinta = *((const Hint **) a);
875 const Hint *hintb = *((const Hint **) b);
877 if (hinta->type != hintb->type)
878 return hinta->type - hintb->type;
879 if (hinta->state == HINT_STATE_ERROR)
881 if (hintb->state == HINT_STATE_ERROR)
883 return hinta->cmp_func(hinta, hintb);
887 * Returns byte offset of hint b from hint a. If hint a was specified before
888 * b, positive value is returned.
891 HintCmpWithPos(const void *a, const void *b)
893 const Hint *hinta = *((const Hint **) a);
894 const Hint *hintb = *((const Hint **) b);
897 result = HintCmp(a, b);
899 result = hinta->hint_str - hintb->hint_str;
908 parse_keyword(const char *str, StringInfo buf)
912 while (!isspace(*str) && *str != '(' && *str != '\0')
913 appendStringInfoCharMacro(buf, *str++);
919 skip_parenthesis(const char *str, char parenthesis)
923 if (*str != parenthesis)
925 if (parenthesis == '(')
926 hint_ereport(str, ("Opening parenthesis is necessary."));
927 else if (parenthesis == ')')
928 hint_ereport(str, ("Closing parenthesis is necessary."));
939 * Parse a token from str, and store malloc'd copy into word. A token can be
940 * quoted with '"'. Return value is pointer to unparsed portion of original
941 * string, or NULL if an error occurred.
943 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
946 parse_quote_value(const char *str, char **word, bool truncate)
951 /* Skip leading spaces. */
954 initStringInfo(&buf);
967 /* Double quotation must be closed. */
971 hint_ereport(str, ("Unterminated quoted string."));
976 * Skip escaped double quotation.
978 * We don't allow slash-asterisk and asterisk-slash (delimiters of
979 * block comments) to be an object name, so users must specify
980 * alias for such object names.
982 * Those special names can be allowed if we care escaped slashes
983 * and asterisks, but we don't.
992 else if (isspace(*str) || *str == ')' || *str == '"' || *str == '\0')
995 appendStringInfoCharMacro(&buf, *str++);
1000 hint_ereport(str, ("Zero-length delimited string."));
1007 /* Truncate name if it's too long */
1009 truncate_identifier(buf.data, strlen(buf.data), true);
1017 parse_parentheses(const char *str, List **name_list, HintType type)
1020 bool truncate = true;
1022 if ((str = skip_parenthesis(str, '(')) == NULL)
1027 /* Store words in parentheses into name_list. */
1028 while(*str != ')' && *str != '\0')
1030 if ((str = parse_quote_value(str, &name, truncate)) == NULL)
1032 list_free(*name_list);
1036 *name_list = lappend(*name_list, name);
1039 if (type == HINT_TYPE_SET)
1045 if ((str = skip_parenthesis(str, ')')) == NULL)
1051 parse_hints(HintState *hstate, Query *parse, const char *str)
1056 initStringInfo(&buf);
1057 while (*str != '\0')
1059 const HintParser *parser;
1061 /* in error message, we output the comment including the keyword. */
1062 head = (char *) str;
1064 /* parse only the keyword of the hint. */
1065 resetStringInfo(&buf);
1066 str = parse_keyword(str, &buf);
1068 for (parser = parsers; parser->keyword != NULL; parser++)
1070 char *keyword = parser->keyword;
1073 if (strcasecmp(buf.data, keyword) != 0)
1076 hint = parser->create_func(head, keyword, parser->hint_keyword);
1078 /* parser of each hint does parse in a parenthesis. */
1079 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1081 hint->delete_func(hint);
1087 * Add hint information into all_hints array. If we don't have
1088 * enough space, double the array.
1090 if (hstate->nall_hints == 0)
1092 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1093 hstate->all_hints = (Hint **)
1094 palloc(sizeof(Hint *) * hstate->max_all_hints);
1096 else if (hstate->nall_hints == hstate->max_all_hints)
1098 hstate->max_all_hints *= 2;
1099 hstate->all_hints = (Hint **)
1100 repalloc(hstate->all_hints,
1101 sizeof(Hint *) * hstate->max_all_hints);
1104 hstate->all_hints[hstate->nall_hints] = hint;
1105 hstate->nall_hints++;
1112 if (parser->keyword == NULL)
1115 ("Unrecognized hint keyword \"%s\".", buf.data));
1125 * Do basic parsing of the query head comment.
1128 parse_head_comment(Query *parse)
1137 /* get client-supplied query string. */
1140 PreparedStatement *entry;
1142 entry = FetchPreparedStatement(stmt_name, true);
1143 p = entry->plansource->query_string;
1146 p = debug_query_string;
1151 /* extract query head comment. */
1152 len = strlen(HINT_START);
1154 if (strncmp(p, HINT_START, len))
1161 /* find hint end keyword. */
1162 if ((tail = strstr(p, HINT_END)) == NULL)
1164 hint_ereport(head, ("Unterminated block comment."));
1168 /* We don't support nested block comments. */
1169 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1171 hint_ereport(head, ("Nested block comments are not supported."));
1175 /* Make a copy of hint. */
1177 head = palloc(len + 1);
1178 memcpy(head, p, len);
1182 hstate = HintStateCreate();
1183 hstate->hint_str = head;
1185 /* parse each hint. */
1186 parse_hints(hstate, parse, p);
1188 /* When nothing specified a hint, we free HintState and returns NULL. */
1189 if (hstate->nall_hints == 0)
1191 HintStateDelete(hstate);
1195 /* Sort hints in order of original position. */
1196 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1199 /* Count number of hints per hint-type. */
1200 for (i = 0; i < hstate->nall_hints; i++)
1202 Hint *cur_hint = hstate->all_hints[i];
1203 hstate->num_hints[cur_hint->type]++;
1207 * If an object (or a set of objects) has multiple hints of same hint-type,
1208 * only the last hint is valid and others are igonred in planning.
1209 * Hints except the last are marked as 'duplicated' to remember the order.
1211 for (i = 0; i < hstate->nall_hints - 1; i++)
1213 Hint *cur_hint = hstate->all_hints[i];
1214 Hint *next_hint = hstate->all_hints[i + 1];
1217 * Note that we need to pass addresses of hint pointers, because
1218 * HintCmp is designed to sort array of Hint* by qsort.
1220 if (HintCmp(&cur_hint, &next_hint) == 0)
1222 hint_ereport(cur_hint->hint_str,
1223 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1224 cur_hint->state = HINT_STATE_DUPLICATION;
1229 * Make sure that per-type array pointers point proper position in the
1230 * array which consists of all hints.
1232 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1233 hstate->join_hints = (JoinMethodHint **) hstate->all_hints +
1234 hstate->num_hints[HINT_TYPE_SCAN_METHOD];
1235 hstate->leading_hint = (LeadingHint *) hstate->all_hints[
1236 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1237 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1238 hstate->num_hints[HINT_TYPE_LEADING] - 1];
1239 hstate->set_hints = (SetHint **) hstate->all_hints +
1240 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1241 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1242 hstate->num_hints[HINT_TYPE_LEADING];
1248 * Parse inside of parentheses of scan-method hints.
1251 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1254 const char *keyword = hint->base.keyword;
1255 HintKeyword hint_keyword = hint->base.hint_keyword;
1256 List *name_list = NIL;
1259 if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1262 /* Parse relation name and index name(s) if given hint accepts. */
1263 length = list_length(name_list);
1266 hint->relname = linitial(name_list);
1267 hint->indexnames = list_delete_first(name_list);
1269 /* check whether the hint accepts index name(s). */
1270 if (hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1271 #if PG_VERSION_NUM >= 90200
1272 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1274 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1278 ("%s hint accepts only one relation.",
1279 hint->base.keyword));
1280 hint->base.state = HINT_STATE_ERROR;
1287 ("%s hint requires a relation.",
1288 hint->base.keyword));
1289 hint->base.state = HINT_STATE_ERROR;
1293 /* Set a bit for specified hint. */
1294 switch (hint_keyword)
1296 case HINT_KEYWORD_SEQSCAN:
1297 hint->enforce_mask = ENABLE_SEQSCAN;
1299 case HINT_KEYWORD_INDEXSCAN:
1300 hint->enforce_mask = ENABLE_INDEXSCAN;
1302 case HINT_KEYWORD_BITMAPSCAN:
1303 hint->enforce_mask = ENABLE_BITMAPSCAN;
1305 case HINT_KEYWORD_TIDSCAN:
1306 hint->enforce_mask = ENABLE_TIDSCAN;
1308 case HINT_KEYWORD_NOSEQSCAN:
1309 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1311 case HINT_KEYWORD_NOINDEXSCAN:
1312 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1314 case HINT_KEYWORD_NOBITMAPSCAN:
1315 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1317 case HINT_KEYWORD_NOTIDSCAN:
1318 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1320 #if PG_VERSION_NUM >= 90200
1321 case HINT_KEYWORD_INDEXONLYSCAN:
1322 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1324 case HINT_KEYWORD_NOINDEXONLYSCAN:
1325 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1329 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1338 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1341 const char *keyword = hint->base.keyword;
1342 HintKeyword hint_keyword = hint->base.hint_keyword;
1343 List *name_list = NIL;
1345 if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1348 hint->nrels = list_length(name_list);
1350 if (hint->nrels > 0)
1356 * Transform relation names from list to array to sort them with qsort
1359 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1360 foreach (l, name_list)
1362 hint->relnames[i] = lfirst(l);
1367 list_free(name_list);
1369 /* A join hint requires at least two relations */
1370 if (hint->nrels < 2)
1373 ("%s hint requires at least two relations.",
1374 hint->base.keyword));
1375 hint->base.state = HINT_STATE_ERROR;
1379 /* Sort hints in alphabetical order of relation names. */
1380 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1382 switch (hint_keyword)
1384 case HINT_KEYWORD_NESTLOOP:
1385 hint->enforce_mask = ENABLE_NESTLOOP;
1387 case HINT_KEYWORD_MERGEJOIN:
1388 hint->enforce_mask = ENABLE_MERGEJOIN;
1390 case HINT_KEYWORD_HASHJOIN:
1391 hint->enforce_mask = ENABLE_HASHJOIN;
1393 case HINT_KEYWORD_NONESTLOOP:
1394 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1396 case HINT_KEYWORD_NOMERGEJOIN:
1397 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1399 case HINT_KEYWORD_NOHASHJOIN:
1400 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1403 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1412 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1415 List *name_list = NIL;
1417 if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1420 hint->relations = name_list;
1422 /* A Leading hint requires at least two relations */
1423 if (list_length(hint->relations) < 2)
1425 hint_ereport(hint->base.hint_str,
1426 ("%s hint requires at least two relations.",
1428 hint->base.state = HINT_STATE_ERROR;
1435 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1437 List *name_list = NIL;
1439 if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1442 hint->words = name_list;
1444 /* We need both name and value to set GUC parameter. */
1445 if (list_length(name_list) == 2)
1447 hint->name = linitial(name_list);
1448 hint->value = lsecond(name_list);
1452 hint_ereport(hint->base.hint_str,
1453 ("%s hint requires name and value of GUC parameter.",
1455 hint->base.state = HINT_STATE_ERROR;
1462 * set GUC parameter functions
1466 set_config_option_wrapper(const char *name, const char *value,
1467 GucContext context, GucSource source,
1468 GucAction action, bool changeVal, int elevel)
1471 MemoryContext ccxt = CurrentMemoryContext;
1475 #if PG_VERSION_NUM >= 90200
1476 result = set_config_option(name, value, context, source,
1477 action, changeVal, 0);
1479 result = set_config_option(name, value, context, source,
1487 /* Save error info */
1488 MemoryContextSwitchTo(ccxt);
1489 errdata = CopyErrorData();
1492 ereport(elevel, (errcode(errdata->sqlerrcode),
1493 errmsg("%s", errdata->message),
1494 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1495 errdata->hint ? errhint("%s", errdata->hint) : 0));
1496 FreeErrorData(errdata);
1504 set_config_options(SetHint **options, int noptions, GucContext context)
1509 save_nestlevel = NewGUCNestLevel();
1511 for (i = 0; i < noptions; i++)
1513 SetHint *hint = options[i];
1516 if (!hint_state_enabled(hint))
1519 result = set_config_option_wrapper(hint->name, hint->value, context,
1520 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1521 pg_hint_plan_parse_messages);
1523 hint->base.state = HINT_STATE_USED;
1525 hint->base.state = HINT_STATE_ERROR;
1528 return save_nestlevel;
1531 #define SET_CONFIG_OPTION(name, type_bits) \
1532 set_config_option_wrapper((name), \
1533 (mask & (type_bits)) ? "true" : "false", \
1534 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1537 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1541 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1542 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1543 #if PG_VERSION_NUM >= 90200
1544 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1547 mask = enforce_mask;
1549 mask = enforce_mask & current_hint->init_scan_mask;
1551 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1552 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1553 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1554 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1555 #if PG_VERSION_NUM >= 90200
1556 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1561 set_join_config_options(unsigned char enforce_mask, GucContext context)
1565 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1566 enforce_mask == ENABLE_HASHJOIN)
1567 mask = enforce_mask;
1569 mask = enforce_mask & current_hint->init_join_mask;
1571 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1572 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1573 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1577 * pg_hint_plan hook functions
1581 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1582 ParamListInfo params, bool isTopLevel,
1583 DestReceiver *dest, char *completionTag)
1587 if (!pg_hint_plan_enable_hint)
1589 if (prev_ProcessUtility)
1590 (*prev_ProcessUtility) (parsetree, queryString, params,
1591 isTopLevel, dest, completionTag);
1593 standard_ProcessUtility(parsetree, queryString, params,
1594 isTopLevel, dest, completionTag);
1600 if (IsA(node, ExplainStmt))
1603 * Draw out parse tree of actual query from Query struct of EXPLAIN
1609 stmt = (ExplainStmt *) node;
1611 Assert(IsA(stmt->query, Query));
1612 query = (Query *) stmt->query;
1614 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1615 node = query->utilityStmt;
1619 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
1620 * specified to preceding PREPARE command to use it as source of hints.
1622 if (IsA(node, ExecuteStmt))
1626 stmt = (ExecuteStmt *) node;
1627 stmt_name = stmt->name;
1629 #if PG_VERSION_NUM >= 90200
1631 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
1634 if (IsA(node, CreateTableAsStmt))
1636 CreateTableAsStmt *stmt;
1639 stmt = (CreateTableAsStmt *) node;
1640 Assert(IsA(stmt->query, Query));
1641 query = (Query *) stmt->query;
1643 if (query->commandType == CMD_UTILITY &&
1644 IsA(query->utilityStmt, ExecuteStmt))
1646 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
1647 stmt_name = estmt->name;
1655 if (prev_ProcessUtility)
1656 (*prev_ProcessUtility) (parsetree, queryString, params,
1657 isTopLevel, dest, completionTag);
1659 standard_ProcessUtility(parsetree, queryString, params,
1660 isTopLevel, dest, completionTag);
1674 if (prev_ProcessUtility)
1675 (*prev_ProcessUtility) (parsetree, queryString, params,
1676 isTopLevel, dest, completionTag);
1678 standard_ProcessUtility(parsetree, queryString, params,
1679 isTopLevel, dest, completionTag);
1683 * Push a hint into hint stack which is implemented with List struct. Head of
1684 * list is top of stack.
1687 push_hint(HintState *hstate)
1689 /* Prepend new hint to the list means pushing to stack. */
1690 HintStateStack = lcons(hstate, HintStateStack);
1692 /* Pushed hint is the one which should be used hereafter. */
1693 current_hint = hstate;
1696 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
1700 /* Hint stack must not be empty. */
1701 if(HintStateStack == NIL)
1702 elog(ERROR, "hint stack is empty");
1705 * Take a hint at the head from the list, and free it. Switch current_hint
1706 * to point new head (NULL if the list is empty).
1708 HintStateStack = list_delete_first(HintStateStack);
1709 HintStateDelete(current_hint);
1710 if(HintStateStack == NIL)
1711 current_hint = NULL;
1713 current_hint = (HintState *) lfirst(list_head(HintStateStack));
1716 static PlannedStmt *
1717 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1720 PlannedStmt *result;
1724 * Use standard planner if pg_hint_plan is disabled. Other hook functions
1725 * try to change plan with current_hint if any, so set it to NULL.
1727 if (!pg_hint_plan_enable_hint)
1729 current_hint = NULL;
1732 return (*prev_planner) (parse, cursorOptions, boundParams);
1734 return standard_planner(parse, cursorOptions, boundParams);
1737 /* Create hint struct from parse tree. */
1738 hstate = parse_head_comment(parse);
1741 * Use standard planner if the statement has not valid hint. Other hook
1742 * functions try to change plan with current_hint if any, so set it to
1747 current_hint = NULL;
1750 return (*prev_planner) (parse, cursorOptions, boundParams);
1752 return standard_planner(parse, cursorOptions, boundParams);
1756 * Push new hint struct to the hint stack to disable previous hint context.
1760 /* Set GUC parameters which are specified with Set hint. */
1761 save_nestlevel = set_config_options(current_hint->set_hints,
1762 current_hint->num_hints[HINT_TYPE_SET],
1763 current_hint->context);
1766 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
1767 if (enable_indexscan)
1768 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
1769 if (enable_bitmapscan)
1770 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
1772 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
1773 #if PG_VERSION_NUM >= 90200
1774 if (enable_indexonlyscan)
1775 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
1777 if (enable_nestloop)
1778 current_hint->init_join_mask |= ENABLE_NESTLOOP;
1779 if (enable_mergejoin)
1780 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
1781 if (enable_hashjoin)
1782 current_hint->init_join_mask |= ENABLE_HASHJOIN;
1785 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
1786 * state when this planner started when error occurred in planner.
1791 result = (*prev_planner) (parse, cursorOptions, boundParams);
1793 result = standard_planner(parse, cursorOptions, boundParams);
1798 * Rollback changes of GUC parameters, and pop current hint context
1799 * from hint stack to rewind the state.
1801 AtEOXact_GUC(true, save_nestlevel);
1807 /* Print hint in debug mode. */
1808 if (pg_hint_plan_debug_print)
1809 HintStateDump(current_hint);
1812 * Rollback changes of GUC parameters, and pop current hint context from
1813 * hint stack to rewind the state.
1815 AtEOXact_GUC(true, save_nestlevel);
1822 * Return scan method hint which matches given aliasname.
1824 static ScanMethodHint *
1825 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
1831 * We can't apply scan method hint if the relation is:
1832 * - not a base relation
1833 * - not an ordinary relation (such as join and subquery)
1835 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
1838 rte = root->simple_rte_array[rel->relid];
1840 /* We can't force scan method of foreign tables */
1841 if (rte->relkind == RELKIND_FOREIGN_TABLE)
1844 /* Find scan method hint, which matches given names, from the list. */
1845 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1847 ScanMethodHint *hint = current_hint->scan_hints[i];
1849 /* We ignore disabled hints. */
1850 if (!hint_state_enabled(hint))
1853 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
1861 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel)
1869 * We delete all the IndexOptInfo list and prevent you from being usable by
1872 if (hint->enforce_mask == ENABLE_SEQSCAN ||
1873 hint->enforce_mask == ENABLE_TIDSCAN)
1875 list_free_deep(rel->indexlist);
1876 rel->indexlist = NIL;
1877 hint->base.state = HINT_STATE_USED;
1883 * When a list of indexes is not specified, we just use all indexes.
1885 if (hint->indexnames == NIL)
1889 * Leaving only an specified index, we delete it from a IndexOptInfo list
1893 if (pg_hint_plan_debug_print)
1894 initStringInfo(&buf);
1896 for (cell = list_head(rel->indexlist); cell; cell = next)
1898 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
1899 char *indexname = get_rel_name(info->indexoid);
1901 bool use_index = false;
1905 foreach(l, hint->indexnames)
1907 if (RelnameCmp(&indexname, &lfirst(l)) == 0)
1910 if (pg_hint_plan_debug_print)
1912 appendStringInfoCharMacro(&buf, ' ');
1913 dump_quote_value(&buf, indexname);
1921 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
1928 if (pg_hint_plan_debug_print)
1930 ereport(LOG, (errmsg("\"%s\":%s", hint->relname, buf.data)));
1936 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
1937 bool inhparent, RelOptInfo *rel)
1939 ScanMethodHint *hint;
1941 if (prev_get_relation_info)
1942 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
1944 /* Do nothing if we don't have valid hint in this context. */
1950 /* store does relids of parent table. */
1951 current_hint->parent_relid = rel->relid;
1953 else if (current_hint->parent_relid != 0)
1956 * We use the same GUC parameter if this table is the child table of a
1957 * table called pg_hint_plan_get_relation_info just before that.
1961 /* append_rel_list contains all append rels; ignore others */
1962 foreach(l, root->append_rel_list)
1964 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1966 /* This rel is child table. */
1967 if (appinfo->parent_relid == current_hint->parent_relid &&
1968 appinfo->child_relid == rel->relid)
1970 if (current_hint->parent_hint)
1971 delete_indexes(current_hint->parent_hint, rel);
1977 /* This rel is not inherit table. */
1978 current_hint->parent_relid = 0;
1979 current_hint->parent_hint = NULL;
1983 * If scan method hint was given, reset GUC parameters which control
1984 * planner behavior about choosing scan methods.
1986 if ((hint = find_scan_hint(root, rel)) == NULL)
1988 set_scan_config_options(current_hint->init_scan_mask,
1989 current_hint->context);
1992 set_scan_config_options(hint->enforce_mask, current_hint->context);
1993 hint->base.state = HINT_STATE_USED;
1995 current_hint->parent_hint = hint;
1997 delete_indexes(hint, rel);
2001 * Return index of relation which matches given aliasname, or 0 if not found.
2002 * If same aliasname was used multiple times in a query, return -1.
2005 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
2011 for (i = 1; i < root->simple_rel_array_size; i++)
2015 if (root->simple_rel_array[i] == NULL)
2018 Assert(i == root->simple_rel_array[i]->relid);
2020 if (RelnameCmp(&aliasname,
2021 &root->simple_rte_array[i]->eref->aliasname) != 0)
2024 foreach(l, initial_rels)
2026 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2028 if (rel->reloptkind == RELOPT_BASEREL)
2030 if (rel->relid != i)
2035 Assert(rel->reloptkind == RELOPT_JOINREL);
2037 if (!bms_is_member(i, rel->relids))
2044 ("Relation name \"%s\" is ambiguous.",
2059 * Return join hint which matches given joinrelids.
2061 static JoinMethodHint *
2062 find_join_hint(Relids joinrelids)
2067 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
2069 foreach(l, join_hint)
2071 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
2073 if (bms_equal(joinrelids, hint->joinrelids))
2081 * Transform join method hint into handy form.
2083 * - create bitmap of relids from alias names, to make it easier to check
2084 * whether a join path matches a join method hint.
2085 * - add join method hints which are necessary to enforce join order
2086 * specified by Leading hint
2089 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2090 List *initial_rels, JoinMethodHint **join_method_hints)
2100 * Create bitmap of relids from alias names for each join method hint.
2101 * Bitmaps are more handy than strings in join searching.
2103 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2105 JoinMethodHint *hint = hstate->join_hints[i];
2108 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
2111 bms_free(hint->joinrelids);
2112 hint->joinrelids = NULL;
2114 for (j = 0; j < hint->nrels; j++)
2116 char *relname = hint->relnames[j];
2118 relid = find_relid_aliasname(root, relname, initial_rels,
2119 hint->base.hint_str);
2122 hint->base.state = HINT_STATE_ERROR;
2127 if (bms_is_member(relid, hint->joinrelids))
2129 hint_ereport(hint->base.hint_str,
2130 ("Relation name \"%s\" is duplicated.", relname));
2131 hint->base.state = HINT_STATE_ERROR;
2135 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
2138 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
2141 hstate->join_hint_level[hint->nrels] =
2142 lappend(hstate->join_hint_level[hint->nrels], hint);
2145 /* Do nothing if no Leading hint was supplied. */
2146 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2149 /* Do nothing if Leading hint is invalid. */
2150 lhint = hstate->leading_hint;
2151 if (!hint_state_enabled(lhint))
2155 * We need join method hints which fit specified join order in every join
2156 * level. For example, Leading(A B C) virtually requires following join
2157 * method hints, if no join method hint supplied:
2159 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
2160 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
2162 * If we already have join method hint which fits specified join order in
2163 * that join level, we leave it as-is and don't add new hints.
2167 foreach(l, lhint->relations)
2169 char *relname = (char *)lfirst(l);
2170 JoinMethodHint *hint;
2173 * Find relid of the relation which has given name. If we have the
2174 * name given in Leading hint multiple times in the join, nothing to
2177 relid = find_relid_aliasname(root, relname, initial_rels,
2181 bms_free(joinrelids);
2187 /* Found relid must not be in joinrelids. */
2188 if (bms_is_member(relid, joinrelids))
2190 hint_ereport(lhint->base.hint_str,
2191 ("Relation name \"%s\" is duplicated.", relname));
2192 lhint->base.state = HINT_STATE_ERROR;
2193 bms_free(joinrelids);
2197 /* Create bitmap of relids for current join level. */
2198 joinrelids = bms_add_member(joinrelids, relid);
2201 /* We never have join method hint for single relation. */
2206 * If we don't have join method hint, create new one for the
2207 * join combination with all join methods are enabled.
2209 hint = find_join_hint(joinrelids);
2213 * Here relnames is not set, since Relids bitmap is sufficient to
2214 * control paths of this query afterward.
2216 hint = (JoinMethodHint *) JoinMethodHintCreate(lhint->base.hint_str,
2218 HINT_KEYWORD_LEADING);
2219 hint->base.state = HINT_STATE_USED;
2220 hint->nrels = njoinrels;
2221 hint->enforce_mask = ENABLE_ALL_JOIN;
2222 hint->joinrelids = bms_copy(joinrelids);
2225 join_method_hints[njoinrels] = hint;
2227 if (njoinrels >= nbaserel)
2231 bms_free(joinrelids);
2237 * Delete all join hints which have different combination from Leading
2240 for (i = 2; i <= njoinrels; i++)
2242 list_free(hstate->join_hint_level[i]);
2244 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
2247 if (hint_state_enabled(lhint))
2248 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2250 lhint->base.state = HINT_STATE_USED;
2255 * set_plain_rel_pathlist
2256 * Build access paths for a plain relation (no subquery, no inheritance)
2258 * This function was copied and edited from set_plain_rel_pathlist() in
2259 * src/backend/optimizer/path/allpaths.c
2262 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2264 /* Consider sequential scan */
2265 #if PG_VERSION_NUM >= 90200
2266 add_path(rel, create_seqscan_path(root, rel, NULL));
2268 add_path(rel, create_seqscan_path(root, rel));
2271 /* Consider index scans */
2272 create_index_paths(root, rel);
2274 /* Consider TID scans */
2275 create_tidscan_paths(root, rel);
2277 /* Now find the cheapest of the paths for this rel */
2282 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
2287 foreach(l, initial_rels)
2289 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2291 ScanMethodHint *hint;
2293 /* Skip relations which we can't choose scan method. */
2294 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2297 rte = root->simple_rte_array[rel->relid];
2299 /* We can't force scan method of foreign tables */
2300 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2304 * Create scan paths with GUC parameters which are at the beginning of
2305 * planner if scan method hint is not specified, otherwise use
2306 * specified hints and mark the hint as used.
2308 if ((hint = find_scan_hint(root, rel)) == NULL)
2309 set_scan_config_options(hstate->init_scan_mask,
2313 set_scan_config_options(hint->enforce_mask, hstate->context);
2314 hint->base.state = HINT_STATE_USED;
2317 list_free_deep(rel->pathlist);
2318 rel->pathlist = NIL;
2321 /* It's an "append relation", process accordingly */
2322 set_append_rel_pathlist(root, rel, rel->relid, rte);
2326 set_plain_rel_pathlist(root, rel, rte);
2331 * Restore the GUC variables we set above.
2333 set_scan_config_options(hstate->init_scan_mask, hstate->context);
2337 * wrapper of make_join_rel()
2339 * call make_join_rel() after changing enable_* parameters according to given
2343 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
2346 JoinMethodHint *hint;
2350 joinrelids = bms_union(rel1->relids, rel2->relids);
2351 hint = find_join_hint(joinrelids);
2352 bms_free(joinrelids);
2355 return pg_hint_plan_make_join_rel(root, rel1, rel2);
2357 save_nestlevel = NewGUCNestLevel();
2359 set_join_config_options(hint->enforce_mask, current_hint->context);
2361 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2362 hint->base.state = HINT_STATE_USED;
2365 * Restore the GUC variables we set above.
2367 AtEOXact_GUC(true, save_nestlevel);
2373 get_num_baserels(List *initial_rels)
2378 foreach(l, initial_rels)
2380 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2382 if (rel->reloptkind == RELOPT_BASEREL)
2384 else if (rel->reloptkind ==RELOPT_JOINREL)
2385 nbaserel+= bms_num_members(rel->relids);
2388 /* other values not expected here */
2389 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
2397 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
2400 JoinMethodHint **join_method_hints;
2406 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
2407 * valid hint is supplied.
2411 if (prev_join_search)
2412 return (*prev_join_search) (root, levels_needed, initial_rels);
2413 else if (enable_geqo && levels_needed >= geqo_threshold)
2414 return geqo(root, levels_needed, initial_rels);
2416 return standard_join_search(root, levels_needed, initial_rels);
2419 /* We apply scan method hint rebuild scan path. */
2420 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
2423 * In the case using GEQO, only scan method hints and Set hints have
2424 * effect. Join method and join order is not controllable by hints.
2426 if (enable_geqo && levels_needed >= geqo_threshold)
2427 return geqo(root, levels_needed, initial_rels);
2429 nbaserel = get_num_baserels(initial_rels);
2430 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
2431 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
2433 transform_join_hints(current_hint, root, nbaserel, initial_rels,
2436 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
2438 for (i = 2; i <= nbaserel; i++)
2440 list_free(current_hint->join_hint_level[i]);
2442 /* free Leading hint only */
2443 if (join_method_hints[i] != NULL &&
2444 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
2445 JoinMethodHintDelete(join_method_hints[i]);
2447 pfree(current_hint->join_hint_level);
2448 pfree(join_method_hints);
2450 if (current_hint->num_hints[HINT_TYPE_LEADING] > 0 &&
2451 hint_state_enabled(current_hint->leading_hint))
2452 set_join_config_options(current_hint->init_join_mask,
2453 current_hint->context);
2460 * Build access paths for a base relation
2462 * This function was copied and edited from set_rel_pathlist() in
2463 * src/backend/optimizer/path/allpaths.c
2466 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
2467 Index rti, RangeTblEntry *rte)
2469 #if PG_VERSION_NUM >= 90200
2470 if (IS_DUMMY_REL(rel))
2472 /* We already proved the relation empty, so nothing more to do */
2479 /* It's an "append relation", process accordingly */
2480 set_append_rel_pathlist(root, rel, rti, rte);
2484 if (rel->rtekind == RTE_RELATION)
2486 if (rte->relkind == RELKIND_RELATION)
2488 /* Plain relation */
2489 set_plain_rel_pathlist(root, rel, rte);
2492 elog(ERROR, "unexpected relkind: %c", rte->relkind);
2495 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
2499 #define standard_join_search pg_hint_plan_standard_join_search
2500 #define join_search_one_level pg_hint_plan_join_search_one_level
2501 #define make_join_rel make_join_rel_wrapper
2504 #undef make_join_rel
2505 #define make_join_rel pg_hint_plan_make_join_rel
2506 #define add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype, sjinfo, restrictlist) \
2508 ScanMethodHint *hint = NULL; \
2509 if ((hint = find_scan_hint((root), (innerrel))) != NULL) \
2511 set_scan_config_options(hint->enforce_mask, current_hint->context); \
2512 hint->base.state = HINT_STATE_USED; \
2514 add_paths_to_joinrel((root), (joinrel), (outerrel), (innerrel), (jointype), (sjinfo), (restrictlist)); \
2516 set_scan_config_options(current_hint->init_scan_mask, current_hint->context); \
2518 #include "make_join_rel.c"