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 */
201 * Describes a context of hint processing.
205 char *hint_str; /* original hint string */
208 int nall_hints; /* # of valid all hints */
209 int max_all_hints; /* # of slots for all hints */
210 Hint **all_hints; /* parsed all hints */
212 /* # of each hints */
213 int num_hints[NUM_HINT_TYPE];
215 /* for scan method hints */
216 ScanMethodHint **scan_hints; /* parsed scan hints */
217 int init_scan_mask; /* initial value scan parameter */
218 Index parent_relid; /* inherit parent table relid */
219 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
221 /* for join method hints */
222 JoinMethodHint **join_hints; /* parsed join hints */
223 int init_join_mask; /* initial value join parameter */
224 List **join_hint_level;
226 /* for Leading hint */
227 LeadingHint *leading_hint; /* parsed last specified Leading hint */
230 SetHint **set_hints; /* parsed Set hints */
231 GucContext context; /* which GUC parameters can we set? */
235 * Describes a hint parser module which is bound with particular hint keyword.
237 typedef struct HintParser
240 HintCreateFunction create_func;
243 /* Module callbacks */
247 static void push_hint(HintState *hstate);
248 static void pop_hint(void);
250 static void pg_hint_plan_ProcessUtility(Node *parsetree,
251 const char *queryString,
252 ParamListInfo params, bool isTopLevel,
254 char *completionTag);
255 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
256 ParamListInfo boundParams);
257 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
258 Oid relationObjectId,
259 bool inhparent, RelOptInfo *rel);
260 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
264 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword);
265 static void ScanMethodHintDelete(ScanMethodHint *hint);
266 static void ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf);
267 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
268 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
269 Query *parse, const char *str);
270 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword);
271 static void JoinMethodHintDelete(JoinMethodHint *hint);
272 static void JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf);
273 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
274 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
275 Query *parse, const char *str);
276 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword);
277 static void LeadingHintDelete(LeadingHint *hint);
278 static void LeadingHintDump(LeadingHint *hint, StringInfo buf);
279 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
280 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
281 Query *parse, const char *str);
282 static Hint *SetHintCreate(const char *hint_str, const char *keyword);
283 static void SetHintDelete(SetHint *hint);
284 static void SetHintDump(SetHint *hint, StringInfo buf);
285 static int SetHintCmp(const SetHint *a, const SetHint *b);
286 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
289 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
292 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
293 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
294 ListCell *other_rels);
295 static void make_rels_by_clauseless_joins(PlannerInfo *root,
297 ListCell *other_rels);
298 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
299 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
300 Index rti, RangeTblEntry *rte);
301 #if PG_VERSION_NUM >= 90200
302 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
303 List *live_childrels,
304 List *all_child_pathkeys);
306 static List *accumulate_append_subpath(List *subpaths, Path *path);
307 #if PG_VERSION_NUM < 90200
308 static void set_dummy_rel_pathlist(RelOptInfo *rel);
310 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
314 static bool pg_hint_plan_enable_hint = true;
315 static bool pg_hint_plan_debug_print = false;
316 static int pg_hint_plan_parse_messages = INFO;
318 static const struct config_enum_entry parse_messages_level_options[] = {
319 {"debug", DEBUG2, true},
320 {"debug5", DEBUG5, false},
321 {"debug4", DEBUG4, false},
322 {"debug3", DEBUG3, false},
323 {"debug2", DEBUG2, false},
324 {"debug1", DEBUG1, false},
326 {"info", INFO, false},
327 {"notice", NOTICE, false},
328 {"warning", WARNING, false},
329 {"error", ERROR, false},
331 * {"fatal", FATAL, true},
332 * {"panic", PANIC, true},
337 /* Saved hook values in case of unload */
338 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
339 static planner_hook_type prev_planner = NULL;
340 static get_relation_info_hook_type prev_get_relation_info = NULL;
341 static join_search_hook_type prev_join_search = NULL;
343 /* Hold reference to currently active hint */
344 static HintState *current_hint = NULL;
347 * List of hint contexts. We treat the head of the list as the Top of the
348 * context stack, so current_hint always points the first element of this list.
350 static List *HintStateStack = NIL;
353 * Holds statement name during executing EXECUTE command. NULL for other
356 static char *stmt_name = NULL;
358 static const HintParser parsers[] = {
359 {HINT_SEQSCAN, ScanMethodHintCreate},
360 {HINT_INDEXSCAN, ScanMethodHintCreate},
361 {HINT_BITMAPSCAN, ScanMethodHintCreate},
362 {HINT_TIDSCAN, ScanMethodHintCreate},
363 {HINT_NOSEQSCAN, ScanMethodHintCreate},
364 {HINT_NOINDEXSCAN, ScanMethodHintCreate},
365 {HINT_NOBITMAPSCAN, ScanMethodHintCreate},
366 {HINT_NOTIDSCAN, ScanMethodHintCreate},
367 #if PG_VERSION_NUM >= 90200
368 {HINT_INDEXONLYSCAN, ScanMethodHintCreate},
369 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate},
371 {HINT_NESTLOOP, JoinMethodHintCreate},
372 {HINT_MERGEJOIN, JoinMethodHintCreate},
373 {HINT_HASHJOIN, JoinMethodHintCreate},
374 {HINT_NONESTLOOP, JoinMethodHintCreate},
375 {HINT_NOMERGEJOIN, JoinMethodHintCreate},
376 {HINT_NOHASHJOIN, JoinMethodHintCreate},
377 {HINT_LEADING, LeadingHintCreate},
378 {HINT_SET, SetHintCreate},
383 * Module load callbacks
388 /* Define custom GUC variables. */
389 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
390 "Force planner to use plans specified in the hint comment preceding to the query.",
392 &pg_hint_plan_enable_hint,
400 DefineCustomBoolVariable("pg_hint_plan.debug_print",
401 "Logs results of hint parsing.",
403 &pg_hint_plan_debug_print,
411 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
412 "Message level of parse errors.",
414 &pg_hint_plan_parse_messages,
416 parse_messages_level_options,
424 prev_ProcessUtility = ProcessUtility_hook;
425 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
426 prev_planner = planner_hook;
427 planner_hook = pg_hint_plan_planner;
428 prev_get_relation_info = get_relation_info_hook;
429 get_relation_info_hook = pg_hint_plan_get_relation_info;
430 prev_join_search = join_search_hook;
431 join_search_hook = pg_hint_plan_join_search;
435 * Module unload callback
441 /* Uninstall hooks. */
442 ProcessUtility_hook = prev_ProcessUtility;
443 planner_hook = prev_planner;
444 get_relation_info_hook = prev_get_relation_info;
445 join_search_hook = prev_join_search;
449 * create and delete functions the hint object
453 ScanMethodHintCreate(const char *hint_str, const char *keyword)
455 ScanMethodHint *hint;
457 hint = palloc(sizeof(ScanMethodHint));
458 hint->base.hint_str = hint_str;
459 hint->base.keyword = keyword;
460 hint->base.type = HINT_TYPE_SCAN_METHOD;
461 hint->base.state = HINT_STATE_NOTUSED;
462 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
463 hint->base.dump_func = (HintDumpFunction) ScanMethodHintDump;
464 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
465 hint->base.parser_func = (HintParseFunction) ScanMethodHintParse;
466 hint->relname = NULL;
467 hint->indexnames = NIL;
468 hint->enforce_mask = 0;
470 return (Hint *) hint;
474 ScanMethodHintDelete(ScanMethodHint *hint)
480 pfree(hint->relname);
481 list_free_deep(hint->indexnames);
486 JoinMethodHintCreate(const char *hint_str, const char *keyword)
488 JoinMethodHint *hint;
490 hint = palloc(sizeof(JoinMethodHint));
491 hint->base.hint_str = hint_str;
492 hint->base.keyword = keyword;
493 hint->base.type = HINT_TYPE_JOIN_METHOD;
494 hint->base.state = HINT_STATE_NOTUSED;
495 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
496 hint->base.dump_func = (HintDumpFunction) JoinMethodHintDump;
497 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
498 hint->base.parser_func = (HintParseFunction) JoinMethodHintParse;
500 hint->relnames = NULL;
501 hint->enforce_mask = 0;
502 hint->joinrelids = NULL;
504 return (Hint *) hint;
508 JoinMethodHintDelete(JoinMethodHint *hint)
517 for (i = 0; i < hint->nrels; i++)
518 pfree(hint->relnames[i]);
519 pfree(hint->relnames);
521 bms_free(hint->joinrelids);
526 LeadingHintCreate(const char *hint_str, const char *keyword)
530 hint = palloc(sizeof(LeadingHint));
531 hint->base.hint_str = hint_str;
532 hint->base.keyword = keyword;
533 hint->base.type = HINT_TYPE_LEADING;
534 hint->base.state = HINT_STATE_NOTUSED;
535 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
536 hint->base.dump_func = (HintDumpFunction) LeadingHintDump;
537 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
538 hint->base.parser_func = (HintParseFunction) LeadingHintParse;
539 hint->relations = NIL;
541 return (Hint *) hint;
545 LeadingHintDelete(LeadingHint *hint)
550 list_free_deep(hint->relations);
555 SetHintCreate(const char *hint_str, const char *keyword)
559 hint = palloc(sizeof(SetHint));
560 hint->base.hint_str = hint_str;
561 hint->base.keyword = keyword;
562 hint->base.type = HINT_TYPE_SET;
563 hint->base.state = HINT_STATE_NOTUSED;
564 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
565 hint->base.dump_func = (HintDumpFunction) SetHintDump;
566 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
567 hint->base.parser_func = (HintParseFunction) SetHintParse;
572 return (Hint *) hint;
576 SetHintDelete(SetHint *hint)
586 list_free(hint->words);
591 HintStateCreate(void)
595 hstate = palloc(sizeof(HintState));
596 hstate->hint_str = NULL;
597 hstate->nall_hints = 0;
598 hstate->max_all_hints = 0;
599 hstate->all_hints = NULL;
600 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
601 hstate->scan_hints = NULL;
602 hstate->init_scan_mask = 0;
603 hstate->parent_relid = 0;
604 hstate->parent_hint = NULL;
605 hstate->join_hints = NULL;
606 hstate->init_join_mask = 0;
607 hstate->join_hint_level = NULL;
608 hstate->leading_hint = NULL;
609 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
610 hstate->set_hints = NULL;
616 HintStateDelete(HintState *hstate)
623 if (hstate->hint_str)
624 pfree(hstate->hint_str);
626 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
627 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
628 if (hstate->all_hints)
629 pfree(hstate->all_hints);
637 dump_quote_value(StringInfo buf, const char *value)
639 bool need_quote = false;
642 for (str = value; *str != '\0'; str++)
644 if (isspace(*str) || *str == ')' || *str == '"')
647 appendStringInfoCharMacro(buf, '"');
652 for (str = value; *str != '\0'; str++)
655 appendStringInfoCharMacro(buf, '"');
657 appendStringInfoCharMacro(buf, *str);
661 appendStringInfoCharMacro(buf, '"');
665 ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf)
669 appendStringInfo(buf, "%s(", hint->base.keyword);
670 if (hint->relname != NULL)
672 dump_quote_value(buf, hint->relname);
673 foreach(l, hint->indexnames)
675 appendStringInfoCharMacro(buf, ' ');
676 dump_quote_value(buf, (char *) lfirst(l));
679 appendStringInfoString(buf, ")\n");
683 JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf)
687 appendStringInfo(buf, "%s(", hint->base.keyword);
688 if (hint->relnames != NULL)
690 dump_quote_value(buf, hint->relnames[0]);
691 for (i = 1; i < hint->nrels; i++)
693 appendStringInfoCharMacro(buf, ' ');
694 dump_quote_value(buf, hint->relnames[i]);
697 appendStringInfoString(buf, ")\n");
702 LeadingHintDump(LeadingHint *hint, StringInfo buf)
707 appendStringInfo(buf, "%s(", HINT_LEADING);
709 foreach(l, hint->relations)
714 appendStringInfoCharMacro(buf, ' ');
716 dump_quote_value(buf, (char *) lfirst(l));
719 appendStringInfoString(buf, ")\n");
723 SetHintDump(SetHint *hint, StringInfo buf)
725 bool is_first = true;
728 appendStringInfo(buf, "%s(", HINT_SET);
729 foreach(l, hint->words)
734 appendStringInfoCharMacro(buf, ' ');
736 dump_quote_value(buf, (char *) lfirst(l));
738 appendStringInfo(buf, ")\n");
742 all_hint_dump(HintState *hstate, StringInfo buf, const char *title,
747 appendStringInfo(buf, "%s:\n", title);
748 for (i = 0; i < hstate->nall_hints; i++)
750 if (hstate->all_hints[i]->state != state)
753 hstate->all_hints[i]->dump_func(hstate->all_hints[i], buf);
758 HintStateDump(HintState *hstate)
764 elog(LOG, "pg_hint_plan:\nno hint");
768 initStringInfo(&buf);
770 appendStringInfoString(&buf, "pg_hint_plan:\n");
771 all_hint_dump(hstate, &buf, "used hint", HINT_STATE_USED);
772 all_hint_dump(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
773 all_hint_dump(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
774 all_hint_dump(hstate, &buf, "error hint", HINT_STATE_ERROR);
776 elog(LOG, "%s", buf.data);
786 RelnameCmp(const void *a, const void *b)
788 const char *relnamea = *((const char **) a);
789 const char *relnameb = *((const char **) b);
791 return strcmp(relnamea, relnameb);
795 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
797 return RelnameCmp(&a->relname, &b->relname);
801 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
805 if (a->nrels != b->nrels)
806 return a->nrels - b->nrels;
808 for (i = 0; i < a->nrels; i++)
811 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
819 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
825 SetHintCmp(const SetHint *a, const SetHint *b)
827 return strcmp(a->name, b->name);
831 HintCmp(const void *a, const void *b)
833 const Hint *hinta = *((const Hint **) a);
834 const Hint *hintb = *((const Hint **) b);
836 if (hinta->type != hintb->type)
837 return hinta->type - hintb->type;
838 if (hinta->state == HINT_STATE_ERROR)
840 if (hintb->state == HINT_STATE_ERROR)
842 return hinta->cmp_func(hinta, hintb);
846 * Returns byte offset of hint b from hint a. If hint a was specified before
847 * b, positive value is returned.
850 HintCmpWithPos(const void *a, const void *b)
852 const Hint *hinta = *((const Hint **) a);
853 const Hint *hintb = *((const Hint **) b);
856 result = HintCmp(a, b);
858 result = hinta->hint_str - hintb->hint_str;
867 parse_keyword(const char *str, StringInfo buf)
871 while (!isspace(*str) && *str != '(' && *str != '\0')
872 appendStringInfoCharMacro(buf, *str++);
878 skip_opened_parenthesis(const char *str)
884 parse_ereport(str, ("Opening parenthesis is necessary."));
894 skip_closed_parenthesis(const char *str)
900 parse_ereport(str, ("Closing parenthesis is necessary."));
910 * Parse a token from str, and store malloc'd copy into word. A token can be
911 * quoted with '"'. Return value is pointer to unparsed portion of original
912 * string, or NULL if an error occurred.
914 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
917 parse_quote_value(const char *str, char **word, bool truncate)
922 /* Skip leading spaces. */
925 initStringInfo(&buf);
938 /* Double quotation must be closed. */
942 parse_ereport(str, ("Unterminated quoted string."));
947 * Skip escaped double quotation.
949 * We don't allow slash-asterisk and asterisk-slash (delimiters of
950 * block comments) to be an object name, so users must specify
951 * alias for such object names.
953 * Those special names can be allowed if we care escaped slashes
954 * and asterisks, but we don't.
963 else if (isspace(*str) || *str == ')' || *str == '"' || *str == '\0')
966 appendStringInfoCharMacro(&buf, *str++);
971 parse_ereport(str, ("Zero-length delimited string."));
978 /* Truncate name if it's too long */
980 truncate_identifier(buf.data, strlen(buf.data), true);
988 parse_parentheses(const char *str, List **name_list, HintType type)
991 bool truncate = true;
993 if ((str = skip_opened_parenthesis(str)) == NULL)
998 /* Store words in a parenthesis in a list. */
999 while(*str != ')' && *str != '\0')
1001 if ((str = parse_quote_value(str, &name, truncate)) == NULL)
1003 list_free(*name_list);
1007 *name_list = lappend(*name_list, name);
1010 if (type == HINT_TYPE_SET)
1016 if ((str = skip_closed_parenthesis(str)) == NULL)
1022 parse_hints(HintState *hstate, Query *parse, const char *str)
1027 initStringInfo(&buf);
1028 while (*str != '\0')
1030 const HintParser *parser;
1032 /* in error message, we output the comment including the keyword. */
1033 head = (char *) str;
1035 /* parse only the keyword of the hint. */
1036 resetStringInfo(&buf);
1037 str = parse_keyword(str, &buf);
1039 for (parser = parsers; parser->keyword != NULL; parser++)
1041 char *keyword = parser->keyword;
1044 if (strcasecmp(buf.data, keyword) != 0)
1047 hint = parser->create_func(head, keyword);
1049 /* parser of each hint does parse in a parenthesis. */
1050 if ((str = hint->parser_func(hint, hstate, parse, str)) == NULL)
1052 hint->delete_func(hint);
1058 * Add hint information into all_hints array. If we don't have
1059 * enough space, double the array.
1061 if (hstate->nall_hints == 0)
1063 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1064 hstate->all_hints = (Hint **)
1065 palloc(sizeof(Hint *) * hstate->max_all_hints);
1067 else if (hstate->nall_hints == hstate->max_all_hints)
1069 hstate->max_all_hints *= 2;
1070 hstate->all_hints = (Hint **)
1071 repalloc(hstate->all_hints,
1072 sizeof(Hint *) * hstate->max_all_hints);
1075 hstate->all_hints[hstate->nall_hints] = hint;
1076 hstate->nall_hints++;
1083 if (parser->keyword == NULL)
1086 ("Unrecognized hint keyword \"%s\".", buf.data));
1096 * Do basic parsing of the query head comment.
1099 parse_head_comment(Query *parse)
1108 /* get client-supplied query string. */
1111 PreparedStatement *entry;
1113 entry = FetchPreparedStatement(stmt_name, true);
1114 p = entry->plansource->query_string;
1117 p = debug_query_string;
1122 /* extract query head comment. */
1123 len = strlen(HINT_START);
1125 if (strncmp(p, HINT_START, len))
1132 /* find hint end keyword. */
1133 if ((tail = strstr(p, HINT_END)) == NULL)
1135 parse_ereport(head, ("Unterminated block comment."));
1139 /* We don't support nested block comments. */
1140 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1142 parse_ereport(head, ("Nested block comments are not supported."));
1146 /* Make a copy of hint. */
1148 head = palloc(len + 1);
1149 memcpy(head, p, len);
1153 hstate = HintStateCreate();
1154 hstate->hint_str = head;
1156 /* parse each hint. */
1157 parse_hints(hstate, parse, p);
1159 /* When nothing specified a hint, we free HintState and returns NULL. */
1160 if (hstate->nall_hints == 0)
1162 HintStateDelete(hstate);
1166 /* Sort hints in order of original position. */
1167 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1170 /* Count up hints per hint-type. */
1171 for (i = 0; i < hstate->nall_hints; i++)
1173 Hint *cur_hint = hstate->all_hints[i];
1174 hstate->num_hints[cur_hint->type]++;
1178 * If we have hints which are specified for an object, mark preceding one
1179 * as 'duplicated' to ignore it in planner phase.
1180 * We need to pass address of hint pointers, because HintCmp has
1181 * been designed to be used with qsort.
1183 for (i = 0; i < hstate->nall_hints - 1; i++)
1185 Hint *cur_hint = hstate->all_hints[i];
1186 Hint *next_hint = hstate->all_hints[i + 1];
1188 if (HintCmp(&cur_hint, &next_hint) == 0)
1190 parse_ereport(cur_hint->hint_str,
1191 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1192 cur_hint->state = HINT_STATE_DUPLICATION;
1197 * Make sure that per-type array pointers point proper position in the
1198 * array which consists of all hints.
1200 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1201 hstate->join_hints = (JoinMethodHint **) hstate->all_hints +
1202 hstate->num_hints[HINT_TYPE_SCAN_METHOD];
1203 hstate->leading_hint = (LeadingHint *) hstate->all_hints[
1204 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1205 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1206 hstate->num_hints[HINT_TYPE_LEADING] - 1];
1207 hstate->set_hints = (SetHint **) hstate->all_hints +
1208 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1209 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1210 hstate->num_hints[HINT_TYPE_LEADING];
1216 * Parse inside of parentheses of scan-method hints.
1219 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1222 const char *keyword = hint->base.keyword;
1223 List *name_list = NIL;
1226 if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1229 /* Parse relation name and index name(s) if given hint accepts. */
1230 length = list_length(name_list);
1233 hint->relname = linitial(name_list);
1234 hint->indexnames = list_delete_first(name_list);
1236 /* check the kerword to need the only relation. */
1237 if (strcmp(keyword, HINT_INDEXSCAN) != 0 &&
1238 #if PG_VERSION_NUM >= 90200
1239 strcmp(keyword, HINT_INDEXONLYSCAN) != 0 &&
1241 strcmp(keyword, HINT_BITMAPSCAN) != 0 &&
1245 ("%s hint requires only one relation.",
1246 hint->base.keyword));
1247 hint->base.state = HINT_STATE_ERROR;
1254 ("%s hint requires a relation.",
1255 hint->base.keyword));
1256 hint->base.state = HINT_STATE_ERROR;
1260 /* Set a bit for specified hint. */
1261 if (strcasecmp(keyword, HINT_SEQSCAN) == 0)
1262 hint->enforce_mask = ENABLE_SEQSCAN;
1263 else if (strcasecmp(keyword, HINT_INDEXSCAN) == 0)
1264 hint->enforce_mask = ENABLE_INDEXSCAN;
1265 else if (strcasecmp(keyword, HINT_BITMAPSCAN) == 0)
1266 hint->enforce_mask = ENABLE_BITMAPSCAN;
1267 else if (strcasecmp(keyword, HINT_TIDSCAN) == 0)
1268 hint->enforce_mask = ENABLE_TIDSCAN;
1269 else if (strcasecmp(keyword, HINT_NOSEQSCAN) == 0)
1270 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1271 else if (strcasecmp(keyword, HINT_NOINDEXSCAN) == 0)
1272 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1273 else if (strcasecmp(keyword, HINT_NOBITMAPSCAN) == 0)
1274 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1275 else if (strcasecmp(keyword, HINT_NOTIDSCAN) == 0)
1276 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1277 #if PG_VERSION_NUM >= 90200
1278 else if (strcasecmp(keyword, HINT_INDEXONLYSCAN) == 0)
1279 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1280 else if (strcasecmp(keyword, HINT_NOINDEXONLYSCAN) == 0)
1281 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1285 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1293 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1296 const char *keyword = hint->base.keyword;
1297 List *name_list = NIL;
1299 if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1302 hint->nrels = list_length(name_list);
1304 if (hint->nrels > 0)
1309 /* save the data on the list in array of join hint struct. */
1310 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1311 foreach (l, name_list)
1313 hint->relnames[i] = lfirst(l);
1318 list_free(name_list);
1320 /* A join hint requires at least two relations to be specified. */
1321 if (hint->nrels < 2)
1324 ("%s hint requires at least two relations.",
1325 hint->base.keyword));
1326 hint->base.state = HINT_STATE_ERROR;
1330 /* Sort hints in alphabetical order of relation names. */
1331 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1333 if (strcasecmp(keyword, HINT_NESTLOOP) == 0)
1334 hint->enforce_mask = ENABLE_NESTLOOP;
1335 else if (strcasecmp(keyword, HINT_MERGEJOIN) == 0)
1336 hint->enforce_mask = ENABLE_MERGEJOIN;
1337 else if (strcasecmp(keyword, HINT_HASHJOIN) == 0)
1338 hint->enforce_mask = ENABLE_HASHJOIN;
1339 else if (strcasecmp(keyword, HINT_NONESTLOOP) == 0)
1340 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1341 else if (strcasecmp(keyword, HINT_NOMERGEJOIN) == 0)
1342 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1343 else if (strcasecmp(keyword, HINT_NOHASHJOIN) == 0)
1344 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1347 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1355 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1358 List *name_list = NIL;
1360 if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1363 hint->relations = name_list;
1365 /* A Leading hint requires at least two relations to be specified. */
1366 if (list_length(hint->relations) < 2)
1368 parse_ereport(hint->base.hint_str,
1369 ("%s hint requires at least two relations.",
1371 hint->base.state = HINT_STATE_ERROR;
1378 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1380 List *name_list = NIL;
1382 if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1385 hint->words = name_list;
1387 /* need only parameter's name and parameter's value to set GUC parameter. */
1388 if (list_length(name_list) == 2)
1390 hint->name = linitial(name_list);
1391 hint->value = lsecond(name_list);
1395 parse_ereport(hint->base.hint_str,
1396 ("%s hint requires two relations.",
1398 hint->base.state = HINT_STATE_ERROR;
1405 * set GUC parameter functions
1409 set_config_option_wrapper(const char *name, const char *value,
1410 GucContext context, GucSource source,
1411 GucAction action, bool changeVal, int elevel)
1414 MemoryContext ccxt = CurrentMemoryContext;
1418 #if PG_VERSION_NUM >= 90200
1419 result = set_config_option(name, value, context, source,
1420 action, changeVal, 0);
1422 result = set_config_option(name, value, context, source,
1430 /* Save error info */
1431 MemoryContextSwitchTo(ccxt);
1432 errdata = CopyErrorData();
1435 ereport(elevel, (errcode(errdata->sqlerrcode),
1436 errmsg("%s", errdata->message),
1437 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1438 errdata->hint ? errhint("%s", errdata->hint) : 0));
1439 FreeErrorData(errdata);
1447 set_config_options(SetHint **options, int noptions, GucContext context)
1452 save_nestlevel = NewGUCNestLevel();
1454 for (i = 0; i < noptions; i++)
1456 SetHint *hint = options[i];
1459 if (!hint_state_enabled(hint))
1462 result = set_config_option_wrapper(hint->name, hint->value, context,
1463 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1464 pg_hint_plan_parse_messages);
1466 hint->base.state = HINT_STATE_USED;
1468 hint->base.state = HINT_STATE_ERROR;
1471 return save_nestlevel;
1474 #define SET_CONFIG_OPTION(name, type_bits) \
1475 set_config_option_wrapper((name), \
1476 (mask & (type_bits)) ? "true" : "false", \
1477 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1480 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1484 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1485 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1486 #if PG_VERSION_NUM >= 90200
1487 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1490 mask = enforce_mask;
1492 mask = enforce_mask & current_hint->init_scan_mask;
1494 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1495 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1496 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1497 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1498 #if PG_VERSION_NUM >= 90200
1499 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1504 set_join_config_options(unsigned char enforce_mask, GucContext context)
1508 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1509 enforce_mask == ENABLE_HASHJOIN)
1510 mask = enforce_mask;
1512 mask = enforce_mask & current_hint->init_join_mask;
1514 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1515 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1516 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1520 * pg_hint_plan hook functions
1524 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1525 ParamListInfo params, bool isTopLevel,
1526 DestReceiver *dest, char *completionTag)
1530 if (!pg_hint_plan_enable_hint)
1532 if (prev_ProcessUtility)
1533 (*prev_ProcessUtility) (parsetree, queryString, params,
1534 isTopLevel, dest, completionTag);
1536 standard_ProcessUtility(parsetree, queryString, params,
1537 isTopLevel, dest, completionTag);
1543 if (IsA(node, ExplainStmt))
1546 * Draw out parse tree of actual query from Query struct of EXPLAIN
1552 stmt = (ExplainStmt *) node;
1554 Assert(IsA(stmt->query, Query));
1555 query = (Query *) stmt->query;
1557 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1558 node = query->utilityStmt;
1562 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
1563 * specified to preceding PREPARE command to use it as source of hints.
1565 if (IsA(node, ExecuteStmt))
1569 stmt = (ExecuteStmt *) node;
1570 stmt_name = stmt->name;
1572 #if PG_VERSION_NUM >= 90200
1574 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
1577 if (IsA(node, CreateTableAsStmt))
1579 CreateTableAsStmt *stmt;
1582 stmt = (CreateTableAsStmt *) node;
1583 Assert(IsA(stmt->query, Query));
1584 query = (Query *) stmt->query;
1586 if (query->commandType == CMD_UTILITY &&
1587 IsA(query->utilityStmt, ExecuteStmt))
1589 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
1590 stmt_name = estmt->name;
1598 if (prev_ProcessUtility)
1599 (*prev_ProcessUtility) (parsetree, queryString, params,
1600 isTopLevel, dest, completionTag);
1602 standard_ProcessUtility(parsetree, queryString, params,
1603 isTopLevel, dest, completionTag);
1617 if (prev_ProcessUtility)
1618 (*prev_ProcessUtility) (parsetree, queryString, params,
1619 isTopLevel, dest, completionTag);
1621 standard_ProcessUtility(parsetree, queryString, params,
1622 isTopLevel, dest, completionTag);
1626 * Push a hint into hint stack which is implemented with List struct. Head of
1627 * list is top of stack.
1630 push_hint(HintState *hstate)
1632 /* Prepend new hint to the list means pushing to stack. */
1633 HintStateStack = lcons(hstate, HintStateStack);
1635 /* Pushed hint is the one which should be used hereafter. */
1636 current_hint = hstate;
1639 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
1643 /* Hint stack must not be empty. */
1644 if(HintStateStack == NIL)
1645 elog(ERROR, "hint stack is empty");
1648 * Take a hint at the head from the list, and free it. Switch current_hint
1649 * to point new head (NULL if the list is empty).
1651 HintStateStack = list_delete_first(HintStateStack);
1652 HintStateDelete(current_hint);
1653 if(HintStateStack == NIL)
1654 current_hint = NULL;
1656 current_hint = (HintState *) lfirst(list_head(HintStateStack));
1659 static PlannedStmt *
1660 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1663 PlannedStmt *result;
1667 * Use standard planner if pg_hint_plan is disabled. Other hook functions
1668 * try to change plan with current_hint if any, so set it to NULL.
1670 if (!pg_hint_plan_enable_hint)
1672 current_hint = NULL;
1675 return (*prev_planner) (parse, cursorOptions, boundParams);
1677 return standard_planner(parse, cursorOptions, boundParams);
1680 /* Create hint struct from parse tree. */
1681 hstate = parse_head_comment(parse);
1684 * Use standard planner if the statement has not valid hint. Other hook
1685 * functions try to change plan with current_hint if any, so set it to
1690 current_hint = NULL;
1693 return (*prev_planner) (parse, cursorOptions, boundParams);
1695 return standard_planner(parse, cursorOptions, boundParams);
1699 * Push new hint struct to the hint stack to disable previous hint context.
1703 /* Set GUC parameters which are specified with Set hint. */
1704 save_nestlevel = set_config_options(current_hint->set_hints,
1705 current_hint->num_hints[HINT_TYPE_SET],
1706 current_hint->context);
1709 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
1710 if (enable_indexscan)
1711 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
1712 if (enable_bitmapscan)
1713 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
1715 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
1716 #if PG_VERSION_NUM >= 90200
1717 if (enable_indexonlyscan)
1718 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
1720 if (enable_nestloop)
1721 current_hint->init_join_mask |= ENABLE_NESTLOOP;
1722 if (enable_mergejoin)
1723 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
1724 if (enable_hashjoin)
1725 current_hint->init_join_mask |= ENABLE_HASHJOIN;
1728 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
1729 * state when this planner started when error occurred in planner.
1734 result = (*prev_planner) (parse, cursorOptions, boundParams);
1736 result = standard_planner(parse, cursorOptions, boundParams);
1741 * Rollback changes of GUC parameters, and pop current hint context
1742 * from hint stack to rewind the state.
1744 AtEOXact_GUC(true, save_nestlevel);
1750 /* Print hint in debug mode. */
1751 if (pg_hint_plan_debug_print)
1752 HintStateDump(current_hint);
1755 * Rollback changes of GUC parameters, and pop current hint context from
1756 * hint stack to rewind the state.
1758 AtEOXact_GUC(true, save_nestlevel);
1765 * Return scan method hint which matches given aliasname.
1767 static ScanMethodHint *
1768 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
1774 * We can't apply scan method hint if the relation is:
1775 * - not a base relation
1776 * - not an ordinary relation (such as join and subquery)
1778 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
1781 rte = root->simple_rte_array[rel->relid];
1783 /* We can't force scan method of foreign tables */
1784 if (rte->relkind == RELKIND_FOREIGN_TABLE)
1787 /* Find scan method hint, which matches given names, from the list. */
1788 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1790 ScanMethodHint *hint = current_hint->scan_hints[i];
1792 /* We ignore disabled hints. */
1793 if (!hint_state_enabled(hint))
1796 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
1804 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel)
1811 * We delete all the IndexOptInfo list and prevent you from being usable by
1814 if (hint->enforce_mask == ENABLE_SEQSCAN ||
1815 hint->enforce_mask == ENABLE_TIDSCAN)
1817 list_free_deep(rel->indexlist);
1818 rel->indexlist = NIL;
1819 hint->base.state = HINT_STATE_USED;
1825 * When a list of indexes is not specified, we just use all indexes.
1827 if (hint->indexnames == NIL)
1831 * Leaving only an specified index, we delete it from a IndexOptInfo list
1835 for (cell = list_head(rel->indexlist); cell; cell = next)
1837 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
1838 char *indexname = get_rel_name(info->indexoid);
1840 bool use_index = false;
1844 foreach(l, hint->indexnames)
1846 if (RelnameCmp(&indexname, &lfirst(l)) == 0)
1854 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
1863 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
1864 bool inhparent, RelOptInfo *rel)
1866 ScanMethodHint *hint;
1868 if (prev_get_relation_info)
1869 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
1871 /* Do nothing if we don't have valid hint in this context. */
1877 /* store does relids of parent table. */
1878 current_hint->parent_relid = rel->relid;
1880 else if (current_hint->parent_relid != 0)
1883 * We use the same GUC parameter if this table is the child table of a
1884 * table called pg_hint_plan_get_relation_info just before that.
1888 /* append_rel_list contains all append rels; ignore others */
1889 foreach(l, root->append_rel_list)
1891 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1893 /* This rel is child table. */
1894 if (appinfo->parent_relid == current_hint->parent_relid &&
1895 appinfo->child_relid == rel->relid)
1897 if (current_hint->parent_hint)
1898 delete_indexes(current_hint->parent_hint, rel);
1904 /* This rel is not inherit table. */
1905 current_hint->parent_relid = 0;
1906 current_hint->parent_hint = NULL;
1910 * If scan method hint was given, reset GUC parameters which control
1911 * planner behavior about choosing scan methods.
1913 if ((hint = find_scan_hint(root, rel)) == NULL)
1915 set_scan_config_options(current_hint->init_scan_mask,
1916 current_hint->context);
1919 set_scan_config_options(hint->enforce_mask, current_hint->context);
1920 hint->base.state = HINT_STATE_USED;
1922 current_hint->parent_hint = hint;
1924 delete_indexes(hint, rel);
1928 * Return index of relation which matches given aliasname, or 0 if not found.
1929 * If same aliasname was used multiple times in a query, return -1.
1932 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
1938 for (i = 1; i < root->simple_rel_array_size; i++)
1942 if (root->simple_rel_array[i] == NULL)
1945 Assert(i == root->simple_rel_array[i]->relid);
1947 if (RelnameCmp(&aliasname,
1948 &root->simple_rte_array[i]->eref->aliasname) != 0)
1951 foreach(l, initial_rels)
1953 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
1955 if (rel->reloptkind == RELOPT_BASEREL)
1957 if (rel->relid != i)
1962 Assert(rel->reloptkind == RELOPT_JOINREL);
1964 if (!bms_is_member(i, rel->relids))
1971 ("Relation name \"%s\" is ambiguous.",
1986 * Return join hint which matches given joinrelids.
1988 static JoinMethodHint *
1989 find_join_hint(Relids joinrelids)
1994 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
1996 foreach(l, join_hint)
1998 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
2000 if (bms_equal(joinrelids, hint->joinrelids))
2008 * Transform join method hint into handy form.
2010 * - create bitmap of relids from alias names, to make it easier to check
2011 * whether a join path matches a join method hint.
2012 * - add join method hints which are necessary to enforce join order
2013 * specified by Leading hint
2016 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2017 List *initial_rels, JoinMethodHint **join_method_hints)
2027 * Create bitmap of relids from alias names for each join method hint.
2028 * Bitmaps are more handy than strings in join searching.
2030 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2032 JoinMethodHint *hint = hstate->join_hints[i];
2035 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
2038 bms_free(hint->joinrelids);
2039 hint->joinrelids = NULL;
2041 for (j = 0; j < hint->nrels; j++)
2043 char *relname = hint->relnames[j];
2045 relid = find_relid_aliasname(root, relname, initial_rels,
2046 hint->base.hint_str);
2049 hint->base.state = HINT_STATE_ERROR;
2054 if (bms_is_member(relid, hint->joinrelids))
2056 parse_ereport(hint->base.hint_str,
2057 ("Relation name \"%s\" is duplicated.", relname));
2058 hint->base.state = HINT_STATE_ERROR;
2062 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
2065 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
2068 hstate->join_hint_level[hint->nrels] =
2069 lappend(hstate->join_hint_level[hint->nrels], hint);
2072 /* Do nothing if no Leading hint was supplied. */
2073 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2076 /* Do nothing if Leading hint is invalid. */
2077 lhint = hstate->leading_hint;
2078 if (!hint_state_enabled(lhint))
2082 * We need join method hints which fit specified join order in every join
2083 * level. For example, Leading(A B C) virtually requires following join
2084 * method hints, if no join method hint supplied:
2086 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
2087 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
2089 * If we already have join method hint which fits specified join order in
2090 * that join level, we leave it as-is and don't add new hints.
2094 foreach(l, lhint->relations)
2096 char *relname = (char *)lfirst(l);
2097 JoinMethodHint *hint;
2100 * Find relid of the relation which has given name. If we have the
2101 * name given in Leading hint multiple times in the join, nothing to
2104 relid = find_relid_aliasname(root, relname, initial_rels,
2108 bms_free(joinrelids);
2114 /* Found relid must not be in joinrelids. */
2115 if (bms_is_member(relid, joinrelids))
2117 parse_ereport(lhint->base.hint_str,
2118 ("Relation name \"%s\" is duplicated.", relname));
2119 lhint->base.state = HINT_STATE_ERROR;
2120 bms_free(joinrelids);
2124 /* Create bitmap of relids for current join level. */
2125 joinrelids = bms_add_member(joinrelids, relid);
2128 /* We never have join method hint for single relation. */
2133 * If we don't have join method hint, create new one for the
2134 * join combination with all join methods are enabled.
2136 hint = find_join_hint(joinrelids);
2140 * Here relnames is not set, since Relids bitmap is sufficient to
2141 * control paths of this query afterward.
2143 hint = (JoinMethodHint *) JoinMethodHintCreate(lhint->base.hint_str,
2145 hint->base.state = HINT_STATE_USED;
2146 hint->nrels = njoinrels;
2147 hint->enforce_mask = ENABLE_ALL_JOIN;
2148 hint->joinrelids = bms_copy(joinrelids);
2151 join_method_hints[njoinrels] = hint;
2153 if (njoinrels >= nbaserel)
2157 bms_free(joinrelids);
2163 * Delete all join hints which have different combination from Leading
2166 for (i = 2; i <= njoinrels; i++)
2168 list_free(hstate->join_hint_level[i]);
2170 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
2173 if (hint_state_enabled(lhint))
2174 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2176 lhint->base.state = HINT_STATE_USED;
2181 * set_plain_rel_pathlist
2182 * Build access paths for a plain relation (no subquery, no inheritance)
2184 * This function was copied and edited from set_plain_rel_pathlist() in
2185 * src/backend/optimizer/path/allpaths.c
2188 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2190 /* Consider sequential scan */
2191 #if PG_VERSION_NUM >= 90200
2192 add_path(rel, create_seqscan_path(root, rel, NULL));
2194 add_path(rel, create_seqscan_path(root, rel));
2197 /* Consider index scans */
2198 create_index_paths(root, rel);
2200 /* Consider TID scans */
2201 create_tidscan_paths(root, rel);
2203 /* Now find the cheapest of the paths for this rel */
2208 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
2213 foreach(l, initial_rels)
2215 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2217 ScanMethodHint *hint;
2219 /* Skip relations which we can't choose scan method. */
2220 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2223 rte = root->simple_rte_array[rel->relid];
2225 /* We can't force scan method of foreign tables */
2226 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2230 * Create scan paths with GUC parameters which are at the beginning of
2231 * planner if scan method hint is not specified, otherwise use
2232 * specified hints and mark the hint as used.
2234 if ((hint = find_scan_hint(root, rel)) == NULL)
2235 set_scan_config_options(hstate->init_scan_mask,
2239 set_scan_config_options(hint->enforce_mask, hstate->context);
2240 hint->base.state = HINT_STATE_USED;
2243 list_free_deep(rel->pathlist);
2244 rel->pathlist = NIL;
2247 /* It's an "append relation", process accordingly */
2248 set_append_rel_pathlist(root, rel, rel->relid, rte);
2252 set_plain_rel_pathlist(root, rel, rte);
2257 * Restore the GUC variables we set above.
2259 set_scan_config_options(hstate->init_scan_mask, hstate->context);
2263 * wrapper of make_join_rel()
2265 * call make_join_rel() after changing enable_* parameters according to given
2269 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
2272 JoinMethodHint *hint;
2276 joinrelids = bms_union(rel1->relids, rel2->relids);
2277 hint = find_join_hint(joinrelids);
2278 bms_free(joinrelids);
2281 return pg_hint_plan_make_join_rel(root, rel1, rel2);
2283 save_nestlevel = NewGUCNestLevel();
2285 set_join_config_options(hint->enforce_mask, current_hint->context);
2287 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2288 hint->base.state = HINT_STATE_USED;
2291 * Restore the GUC variables we set above.
2293 AtEOXact_GUC(true, save_nestlevel);
2299 get_num_baserels(List *initial_rels)
2304 foreach(l, initial_rels)
2306 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2308 if (rel->reloptkind == RELOPT_BASEREL)
2310 else if (rel->reloptkind ==RELOPT_JOINREL)
2311 nbaserel+= bms_num_members(rel->relids);
2314 /* other values not expected here */
2315 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
2323 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
2326 JoinMethodHint **join_method_hints;
2332 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
2333 * valid hint is supplied.
2337 if (prev_join_search)
2338 return (*prev_join_search) (root, levels_needed, initial_rels);
2339 else if (enable_geqo && levels_needed >= geqo_threshold)
2340 return geqo(root, levels_needed, initial_rels);
2342 return standard_join_search(root, levels_needed, initial_rels);
2345 /* We apply scan method hint rebuild scan path. */
2346 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
2349 * In the case using GEQO, only scan method hints and Set hints have
2350 * effect. Join method and join order is not controllable by hints.
2352 if (enable_geqo && levels_needed >= geqo_threshold)
2353 return geqo(root, levels_needed, initial_rels);
2355 nbaserel = get_num_baserels(initial_rels);
2356 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
2357 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
2359 transform_join_hints(current_hint, root, nbaserel, initial_rels,
2362 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
2364 for (i = 2; i <= nbaserel; i++)
2366 list_free(current_hint->join_hint_level[i]);
2368 /* free Leading hint only */
2369 if (join_method_hints[i] != NULL &&
2370 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
2371 JoinMethodHintDelete(join_method_hints[i]);
2373 pfree(current_hint->join_hint_level);
2374 pfree(join_method_hints);
2376 if (current_hint->num_hints[HINT_TYPE_LEADING] > 0 &&
2377 hint_state_enabled(current_hint->leading_hint))
2378 set_join_config_options(current_hint->init_join_mask,
2379 current_hint->context);
2386 * Build access paths for a base relation
2388 * This function was copied and edited from set_rel_pathlist() in
2389 * src/backend/optimizer/path/allpaths.c
2392 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
2393 Index rti, RangeTblEntry *rte)
2395 #if PG_VERSION_NUM >= 90200
2396 if (IS_DUMMY_REL(rel))
2398 /* We already proved the relation empty, so nothing more to do */
2405 /* It's an "append relation", process accordingly */
2406 set_append_rel_pathlist(root, rel, rti, rte);
2410 if (rel->rtekind == RTE_RELATION)
2412 if (rte->relkind == RELKIND_RELATION)
2414 /* Plain relation */
2415 set_plain_rel_pathlist(root, rel, rte);
2418 elog(ERROR, "unexpected relkind: %c", rte->relkind);
2421 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
2425 #define standard_join_search pg_hint_plan_standard_join_search
2426 #define join_search_one_level pg_hint_plan_join_search_one_level
2427 #define make_join_rel make_join_rel_wrapper
2430 #undef make_join_rel
2431 #define make_join_rel pg_hint_plan_make_join_rel
2432 #define add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype, sjinfo, restrictlist) \
2434 ScanMethodHint *hint = NULL; \
2435 if ((hint = find_scan_hint((root), (innerrel))) != NULL) \
2437 set_scan_config_options(hint->enforce_mask, current_hint->context); \
2438 hint->base.state = HINT_STATE_USED; \
2440 add_paths_to_joinrel((root), (joinrel), (outerrel), (innerrel), (jointype), (sjinfo), (restrictlist)); \
2442 set_scan_config_options(current_hint->init_scan_mask, current_hint->context); \
2444 #include "make_join_rel.c"