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 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 parse_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.parse_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.parse_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.parse_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.parse_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_parenthesis(const char *str, char parenthesis)
882 if (*str != parenthesis)
884 if (parenthesis == '(')
885 hint_ereport(str, ("Opening parenthesis is necessary."));
886 else if (parenthesis == ')')
887 hint_ereport(str, ("Closing parenthesis is necessary."));
898 * Parse a token from str, and store malloc'd copy into word. A token can be
899 * quoted with '"'. Return value is pointer to unparsed portion of original
900 * string, or NULL if an error occurred.
902 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
905 parse_quote_value(const char *str, char **word, bool truncate)
910 /* Skip leading spaces. */
913 initStringInfo(&buf);
926 /* Double quotation must be closed. */
930 hint_ereport(str, ("Unterminated quoted string."));
935 * Skip escaped double quotation.
937 * We don't allow slash-asterisk and asterisk-slash (delimiters of
938 * block comments) to be an object name, so users must specify
939 * alias for such object names.
941 * Those special names can be allowed if we care escaped slashes
942 * and asterisks, but we don't.
951 else if (isspace(*str) || *str == ')' || *str == '"' || *str == '\0')
954 appendStringInfoCharMacro(&buf, *str++);
959 hint_ereport(str, ("Zero-length delimited string."));
966 /* Truncate name if it's too long */
968 truncate_identifier(buf.data, strlen(buf.data), true);
976 parse_parentheses(const char *str, List **name_list, HintType type)
979 bool truncate = true;
981 if ((str = skip_parenthesis(str, '(')) == NULL)
986 /* Store words in parentheses into name_list. */
987 while(*str != ')' && *str != '\0')
989 if ((str = parse_quote_value(str, &name, truncate)) == NULL)
991 list_free(*name_list);
995 *name_list = lappend(*name_list, name);
998 if (type == HINT_TYPE_SET)
1004 if ((str = skip_parenthesis(str, ')')) == NULL)
1010 parse_hints(HintState *hstate, Query *parse, const char *str)
1015 initStringInfo(&buf);
1016 while (*str != '\0')
1018 const HintParser *parser;
1020 /* in error message, we output the comment including the keyword. */
1021 head = (char *) str;
1023 /* parse only the keyword of the hint. */
1024 resetStringInfo(&buf);
1025 str = parse_keyword(str, &buf);
1027 for (parser = parsers; parser->keyword != NULL; parser++)
1029 char *keyword = parser->keyword;
1032 if (strcasecmp(buf.data, keyword) != 0)
1035 hint = parser->create_func(head, keyword);
1037 /* parser of each hint does parse in a parenthesis. */
1038 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1040 hint->delete_func(hint);
1046 * Add hint information into all_hints array. If we don't have
1047 * enough space, double the array.
1049 if (hstate->nall_hints == 0)
1051 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1052 hstate->all_hints = (Hint **)
1053 palloc(sizeof(Hint *) * hstate->max_all_hints);
1055 else if (hstate->nall_hints == hstate->max_all_hints)
1057 hstate->max_all_hints *= 2;
1058 hstate->all_hints = (Hint **)
1059 repalloc(hstate->all_hints,
1060 sizeof(Hint *) * hstate->max_all_hints);
1063 hstate->all_hints[hstate->nall_hints] = hint;
1064 hstate->nall_hints++;
1071 if (parser->keyword == NULL)
1074 ("Unrecognized hint keyword \"%s\".", buf.data));
1084 * Do basic parsing of the query head comment.
1087 parse_head_comment(Query *parse)
1096 /* get client-supplied query string. */
1099 PreparedStatement *entry;
1101 entry = FetchPreparedStatement(stmt_name, true);
1102 p = entry->plansource->query_string;
1105 p = debug_query_string;
1110 /* extract query head comment. */
1111 len = strlen(HINT_START);
1113 if (strncmp(p, HINT_START, len))
1120 /* find hint end keyword. */
1121 if ((tail = strstr(p, HINT_END)) == NULL)
1123 hint_ereport(head, ("Unterminated block comment."));
1127 /* We don't support nested block comments. */
1128 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1130 hint_ereport(head, ("Nested block comments are not supported."));
1134 /* Make a copy of hint. */
1136 head = palloc(len + 1);
1137 memcpy(head, p, len);
1141 hstate = HintStateCreate();
1142 hstate->hint_str = head;
1144 /* parse each hint. */
1145 parse_hints(hstate, parse, p);
1147 /* When nothing specified a hint, we free HintState and returns NULL. */
1148 if (hstate->nall_hints == 0)
1150 HintStateDelete(hstate);
1154 /* Sort hints in order of original position. */
1155 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1158 /* Count number of hints per hint-type. */
1159 for (i = 0; i < hstate->nall_hints; i++)
1161 Hint *cur_hint = hstate->all_hints[i];
1162 hstate->num_hints[cur_hint->type]++;
1166 * If an object (or a set of objects) has multiple hints of same hint-type,
1167 * only the last hint is valid and others are igonred in planning.
1168 * Hints except the last are marked as 'duplicated' to remember the order.
1170 for (i = 0; i < hstate->nall_hints - 1; i++)
1172 Hint *cur_hint = hstate->all_hints[i];
1173 Hint *next_hint = hstate->all_hints[i + 1];
1176 * Note that we need to pass addresses of hint pointers, because
1177 * HintCmp is designed to sort array of Hint* by qsort.
1179 if (HintCmp(&cur_hint, &next_hint) == 0)
1181 hint_ereport(cur_hint->hint_str,
1182 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1183 cur_hint->state = HINT_STATE_DUPLICATION;
1188 * Make sure that per-type array pointers point proper position in the
1189 * array which consists of all hints.
1191 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1192 hstate->join_hints = (JoinMethodHint **) hstate->all_hints +
1193 hstate->num_hints[HINT_TYPE_SCAN_METHOD];
1194 hstate->leading_hint = (LeadingHint *) hstate->all_hints[
1195 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1196 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1197 hstate->num_hints[HINT_TYPE_LEADING] - 1];
1198 hstate->set_hints = (SetHint **) hstate->all_hints +
1199 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1200 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1201 hstate->num_hints[HINT_TYPE_LEADING];
1207 * Parse inside of parentheses of scan-method hints.
1210 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1213 const char *keyword = hint->base.keyword;
1214 List *name_list = NIL;
1217 if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1220 /* Parse relation name and index name(s) if given hint accepts. */
1221 length = list_length(name_list);
1224 hint->relname = linitial(name_list);
1225 hint->indexnames = list_delete_first(name_list);
1227 /* check whether the hint accepts index name(s). */
1228 if (strcmp(keyword, HINT_INDEXSCAN) != 0 &&
1229 #if PG_VERSION_NUM >= 90200
1230 strcmp(keyword, HINT_INDEXONLYSCAN) != 0 &&
1232 strcmp(keyword, HINT_BITMAPSCAN) != 0 &&
1236 ("%s hint accepts only one relation.",
1237 hint->base.keyword));
1238 hint->base.state = HINT_STATE_ERROR;
1245 ("%s hint requires a relation.",
1246 hint->base.keyword));
1247 hint->base.state = HINT_STATE_ERROR;
1251 /* Set a bit for specified hint. */
1252 if (strcmp(keyword, HINT_SEQSCAN) == 0)
1253 hint->enforce_mask = ENABLE_SEQSCAN;
1254 else if (strcmp(keyword, HINT_INDEXSCAN) == 0)
1255 hint->enforce_mask = ENABLE_INDEXSCAN;
1256 else if (strcmp(keyword, HINT_BITMAPSCAN) == 0)
1257 hint->enforce_mask = ENABLE_BITMAPSCAN;
1258 else if (strcmp(keyword, HINT_TIDSCAN) == 0)
1259 hint->enforce_mask = ENABLE_TIDSCAN;
1260 else if (strcmp(keyword, HINT_NOSEQSCAN) == 0)
1261 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1262 else if (strcmp(keyword, HINT_NOINDEXSCAN) == 0)
1263 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1264 else if (strcmp(keyword, HINT_NOBITMAPSCAN) == 0)
1265 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1266 else if (strcmp(keyword, HINT_NOTIDSCAN) == 0)
1267 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1268 #if PG_VERSION_NUM >= 90200
1269 else if (strcmp(keyword, HINT_INDEXONLYSCAN) == 0)
1270 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1271 else if (strcmp(keyword, HINT_NOINDEXONLYSCAN) == 0)
1272 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1276 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1284 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1287 const char *keyword = hint->base.keyword;
1288 List *name_list = NIL;
1290 if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1293 hint->nrels = list_length(name_list);
1295 if (hint->nrels > 0)
1301 * Transform relation names from list to array to sort them with qsort
1304 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1305 foreach (l, name_list)
1307 hint->relnames[i] = lfirst(l);
1312 list_free(name_list);
1314 /* A join hint requires at least two relations */
1315 if (hint->nrels < 2)
1318 ("%s hint requires at least two relations.",
1319 hint->base.keyword));
1320 hint->base.state = HINT_STATE_ERROR;
1324 /* Sort hints in alphabetical order of relation names. */
1325 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1327 if (strcmp(keyword, HINT_NESTLOOP) == 0)
1328 hint->enforce_mask = ENABLE_NESTLOOP;
1329 else if (strcmp(keyword, HINT_MERGEJOIN) == 0)
1330 hint->enforce_mask = ENABLE_MERGEJOIN;
1331 else if (strcmp(keyword, HINT_HASHJOIN) == 0)
1332 hint->enforce_mask = ENABLE_HASHJOIN;
1333 else if (strcmp(keyword, HINT_NONESTLOOP) == 0)
1334 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1335 else if (strcmp(keyword, HINT_NOMERGEJOIN) == 0)
1336 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1337 else if (strcmp(keyword, HINT_NOHASHJOIN) == 0)
1338 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1341 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1349 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1352 List *name_list = NIL;
1354 if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1357 hint->relations = name_list;
1359 /* A Leading hint requires at least two relations */
1360 if (list_length(hint->relations) < 2)
1362 hint_ereport(hint->base.hint_str,
1363 ("%s hint requires at least two relations.",
1365 hint->base.state = HINT_STATE_ERROR;
1372 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1374 List *name_list = NIL;
1376 if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1379 hint->words = name_list;
1381 /* We need both name and value to set GUC parameter. */
1382 if (list_length(name_list) == 2)
1384 hint->name = linitial(name_list);
1385 hint->value = lsecond(name_list);
1389 hint_ereport(hint->base.hint_str,
1390 ("%s hint requires name and value of GUC parameter.",
1392 hint->base.state = HINT_STATE_ERROR;
1399 * set GUC parameter functions
1403 set_config_option_wrapper(const char *name, const char *value,
1404 GucContext context, GucSource source,
1405 GucAction action, bool changeVal, int elevel)
1408 MemoryContext ccxt = CurrentMemoryContext;
1412 #if PG_VERSION_NUM >= 90200
1413 result = set_config_option(name, value, context, source,
1414 action, changeVal, 0);
1416 result = set_config_option(name, value, context, source,
1424 /* Save error info */
1425 MemoryContextSwitchTo(ccxt);
1426 errdata = CopyErrorData();
1429 ereport(elevel, (errcode(errdata->sqlerrcode),
1430 errmsg("%s", errdata->message),
1431 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1432 errdata->hint ? errhint("%s", errdata->hint) : 0));
1433 FreeErrorData(errdata);
1441 set_config_options(SetHint **options, int noptions, GucContext context)
1446 save_nestlevel = NewGUCNestLevel();
1448 for (i = 0; i < noptions; i++)
1450 SetHint *hint = options[i];
1453 if (!hint_state_enabled(hint))
1456 result = set_config_option_wrapper(hint->name, hint->value, context,
1457 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1458 pg_hint_plan_parse_messages);
1460 hint->base.state = HINT_STATE_USED;
1462 hint->base.state = HINT_STATE_ERROR;
1465 return save_nestlevel;
1468 #define SET_CONFIG_OPTION(name, type_bits) \
1469 set_config_option_wrapper((name), \
1470 (mask & (type_bits)) ? "true" : "false", \
1471 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1474 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1478 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1479 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1480 #if PG_VERSION_NUM >= 90200
1481 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1484 mask = enforce_mask;
1486 mask = enforce_mask & current_hint->init_scan_mask;
1488 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1489 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1490 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1491 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1492 #if PG_VERSION_NUM >= 90200
1493 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1498 set_join_config_options(unsigned char enforce_mask, GucContext context)
1502 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1503 enforce_mask == ENABLE_HASHJOIN)
1504 mask = enforce_mask;
1506 mask = enforce_mask & current_hint->init_join_mask;
1508 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1509 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1510 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1514 * pg_hint_plan hook functions
1518 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1519 ParamListInfo params, bool isTopLevel,
1520 DestReceiver *dest, char *completionTag)
1524 if (!pg_hint_plan_enable_hint)
1526 if (prev_ProcessUtility)
1527 (*prev_ProcessUtility) (parsetree, queryString, params,
1528 isTopLevel, dest, completionTag);
1530 standard_ProcessUtility(parsetree, queryString, params,
1531 isTopLevel, dest, completionTag);
1537 if (IsA(node, ExplainStmt))
1540 * Draw out parse tree of actual query from Query struct of EXPLAIN
1546 stmt = (ExplainStmt *) node;
1548 Assert(IsA(stmt->query, Query));
1549 query = (Query *) stmt->query;
1551 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1552 node = query->utilityStmt;
1556 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
1557 * specified to preceding PREPARE command to use it as source of hints.
1559 if (IsA(node, ExecuteStmt))
1563 stmt = (ExecuteStmt *) node;
1564 stmt_name = stmt->name;
1566 #if PG_VERSION_NUM >= 90200
1568 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
1571 if (IsA(node, CreateTableAsStmt))
1573 CreateTableAsStmt *stmt;
1576 stmt = (CreateTableAsStmt *) node;
1577 Assert(IsA(stmt->query, Query));
1578 query = (Query *) stmt->query;
1580 if (query->commandType == CMD_UTILITY &&
1581 IsA(query->utilityStmt, ExecuteStmt))
1583 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
1584 stmt_name = estmt->name;
1592 if (prev_ProcessUtility)
1593 (*prev_ProcessUtility) (parsetree, queryString, params,
1594 isTopLevel, dest, completionTag);
1596 standard_ProcessUtility(parsetree, queryString, params,
1597 isTopLevel, dest, completionTag);
1611 if (prev_ProcessUtility)
1612 (*prev_ProcessUtility) (parsetree, queryString, params,
1613 isTopLevel, dest, completionTag);
1615 standard_ProcessUtility(parsetree, queryString, params,
1616 isTopLevel, dest, completionTag);
1620 * Push a hint into hint stack which is implemented with List struct. Head of
1621 * list is top of stack.
1624 push_hint(HintState *hstate)
1626 /* Prepend new hint to the list means pushing to stack. */
1627 HintStateStack = lcons(hstate, HintStateStack);
1629 /* Pushed hint is the one which should be used hereafter. */
1630 current_hint = hstate;
1633 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
1637 /* Hint stack must not be empty. */
1638 if(HintStateStack == NIL)
1639 elog(ERROR, "hint stack is empty");
1642 * Take a hint at the head from the list, and free it. Switch current_hint
1643 * to point new head (NULL if the list is empty).
1645 HintStateStack = list_delete_first(HintStateStack);
1646 HintStateDelete(current_hint);
1647 if(HintStateStack == NIL)
1648 current_hint = NULL;
1650 current_hint = (HintState *) lfirst(list_head(HintStateStack));
1653 static PlannedStmt *
1654 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1657 PlannedStmt *result;
1661 * Use standard planner if pg_hint_plan is disabled. Other hook functions
1662 * try to change plan with current_hint if any, so set it to NULL.
1664 if (!pg_hint_plan_enable_hint)
1666 current_hint = NULL;
1669 return (*prev_planner) (parse, cursorOptions, boundParams);
1671 return standard_planner(parse, cursorOptions, boundParams);
1674 /* Create hint struct from parse tree. */
1675 hstate = parse_head_comment(parse);
1678 * Use standard planner if the statement has not valid hint. Other hook
1679 * functions try to change plan with current_hint if any, so set it to
1684 current_hint = NULL;
1687 return (*prev_planner) (parse, cursorOptions, boundParams);
1689 return standard_planner(parse, cursorOptions, boundParams);
1693 * Push new hint struct to the hint stack to disable previous hint context.
1697 /* Set GUC parameters which are specified with Set hint. */
1698 save_nestlevel = set_config_options(current_hint->set_hints,
1699 current_hint->num_hints[HINT_TYPE_SET],
1700 current_hint->context);
1703 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
1704 if (enable_indexscan)
1705 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
1706 if (enable_bitmapscan)
1707 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
1709 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
1710 #if PG_VERSION_NUM >= 90200
1711 if (enable_indexonlyscan)
1712 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
1714 if (enable_nestloop)
1715 current_hint->init_join_mask |= ENABLE_NESTLOOP;
1716 if (enable_mergejoin)
1717 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
1718 if (enable_hashjoin)
1719 current_hint->init_join_mask |= ENABLE_HASHJOIN;
1722 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
1723 * state when this planner started when error occurred in planner.
1728 result = (*prev_planner) (parse, cursorOptions, boundParams);
1730 result = standard_planner(parse, cursorOptions, boundParams);
1735 * Rollback changes of GUC parameters, and pop current hint context
1736 * from hint stack to rewind the state.
1738 AtEOXact_GUC(true, save_nestlevel);
1744 /* Print hint in debug mode. */
1745 if (pg_hint_plan_debug_print)
1746 HintStateDump(current_hint);
1749 * Rollback changes of GUC parameters, and pop current hint context from
1750 * hint stack to rewind the state.
1752 AtEOXact_GUC(true, save_nestlevel);
1759 * Return scan method hint which matches given aliasname.
1761 static ScanMethodHint *
1762 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
1768 * We can't apply scan method hint if the relation is:
1769 * - not a base relation
1770 * - not an ordinary relation (such as join and subquery)
1772 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
1775 rte = root->simple_rte_array[rel->relid];
1777 /* We can't force scan method of foreign tables */
1778 if (rte->relkind == RELKIND_FOREIGN_TABLE)
1781 /* Find scan method hint, which matches given names, from the list. */
1782 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1784 ScanMethodHint *hint = current_hint->scan_hints[i];
1786 /* We ignore disabled hints. */
1787 if (!hint_state_enabled(hint))
1790 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
1798 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel)
1805 * We delete all the IndexOptInfo list and prevent you from being usable by
1808 if (hint->enforce_mask == ENABLE_SEQSCAN ||
1809 hint->enforce_mask == ENABLE_TIDSCAN)
1811 list_free_deep(rel->indexlist);
1812 rel->indexlist = NIL;
1813 hint->base.state = HINT_STATE_USED;
1819 * When a list of indexes is not specified, we just use all indexes.
1821 if (hint->indexnames == NIL)
1825 * Leaving only an specified index, we delete it from a IndexOptInfo list
1829 for (cell = list_head(rel->indexlist); cell; cell = next)
1831 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
1832 char *indexname = get_rel_name(info->indexoid);
1834 bool use_index = false;
1838 foreach(l, hint->indexnames)
1840 if (RelnameCmp(&indexname, &lfirst(l)) == 0)
1848 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
1857 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
1858 bool inhparent, RelOptInfo *rel)
1860 ScanMethodHint *hint;
1862 if (prev_get_relation_info)
1863 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
1865 /* Do nothing if we don't have valid hint in this context. */
1871 /* store does relids of parent table. */
1872 current_hint->parent_relid = rel->relid;
1874 else if (current_hint->parent_relid != 0)
1877 * We use the same GUC parameter if this table is the child table of a
1878 * table called pg_hint_plan_get_relation_info just before that.
1882 /* append_rel_list contains all append rels; ignore others */
1883 foreach(l, root->append_rel_list)
1885 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1887 /* This rel is child table. */
1888 if (appinfo->parent_relid == current_hint->parent_relid &&
1889 appinfo->child_relid == rel->relid)
1891 if (current_hint->parent_hint)
1892 delete_indexes(current_hint->parent_hint, rel);
1898 /* This rel is not inherit table. */
1899 current_hint->parent_relid = 0;
1900 current_hint->parent_hint = NULL;
1904 * If scan method hint was given, reset GUC parameters which control
1905 * planner behavior about choosing scan methods.
1907 if ((hint = find_scan_hint(root, rel)) == NULL)
1909 set_scan_config_options(current_hint->init_scan_mask,
1910 current_hint->context);
1913 set_scan_config_options(hint->enforce_mask, current_hint->context);
1914 hint->base.state = HINT_STATE_USED;
1916 current_hint->parent_hint = hint;
1918 delete_indexes(hint, rel);
1922 * Return index of relation which matches given aliasname, or 0 if not found.
1923 * If same aliasname was used multiple times in a query, return -1.
1926 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
1932 for (i = 1; i < root->simple_rel_array_size; i++)
1936 if (root->simple_rel_array[i] == NULL)
1939 Assert(i == root->simple_rel_array[i]->relid);
1941 if (RelnameCmp(&aliasname,
1942 &root->simple_rte_array[i]->eref->aliasname) != 0)
1945 foreach(l, initial_rels)
1947 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
1949 if (rel->reloptkind == RELOPT_BASEREL)
1951 if (rel->relid != i)
1956 Assert(rel->reloptkind == RELOPT_JOINREL);
1958 if (!bms_is_member(i, rel->relids))
1965 ("Relation name \"%s\" is ambiguous.",
1980 * Return join hint which matches given joinrelids.
1982 static JoinMethodHint *
1983 find_join_hint(Relids joinrelids)
1988 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
1990 foreach(l, join_hint)
1992 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
1994 if (bms_equal(joinrelids, hint->joinrelids))
2002 * Transform join method hint into handy form.
2004 * - create bitmap of relids from alias names, to make it easier to check
2005 * whether a join path matches a join method hint.
2006 * - add join method hints which are necessary to enforce join order
2007 * specified by Leading hint
2010 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2011 List *initial_rels, JoinMethodHint **join_method_hints)
2021 * Create bitmap of relids from alias names for each join method hint.
2022 * Bitmaps are more handy than strings in join searching.
2024 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2026 JoinMethodHint *hint = hstate->join_hints[i];
2029 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
2032 bms_free(hint->joinrelids);
2033 hint->joinrelids = NULL;
2035 for (j = 0; j < hint->nrels; j++)
2037 char *relname = hint->relnames[j];
2039 relid = find_relid_aliasname(root, relname, initial_rels,
2040 hint->base.hint_str);
2043 hint->base.state = HINT_STATE_ERROR;
2048 if (bms_is_member(relid, hint->joinrelids))
2050 hint_ereport(hint->base.hint_str,
2051 ("Relation name \"%s\" is duplicated.", relname));
2052 hint->base.state = HINT_STATE_ERROR;
2056 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
2059 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
2062 hstate->join_hint_level[hint->nrels] =
2063 lappend(hstate->join_hint_level[hint->nrels], hint);
2066 /* Do nothing if no Leading hint was supplied. */
2067 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2070 /* Do nothing if Leading hint is invalid. */
2071 lhint = hstate->leading_hint;
2072 if (!hint_state_enabled(lhint))
2076 * We need join method hints which fit specified join order in every join
2077 * level. For example, Leading(A B C) virtually requires following join
2078 * method hints, if no join method hint supplied:
2080 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
2081 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
2083 * If we already have join method hint which fits specified join order in
2084 * that join level, we leave it as-is and don't add new hints.
2088 foreach(l, lhint->relations)
2090 char *relname = (char *)lfirst(l);
2091 JoinMethodHint *hint;
2094 * Find relid of the relation which has given name. If we have the
2095 * name given in Leading hint multiple times in the join, nothing to
2098 relid = find_relid_aliasname(root, relname, initial_rels,
2102 bms_free(joinrelids);
2108 /* Found relid must not be in joinrelids. */
2109 if (bms_is_member(relid, joinrelids))
2111 hint_ereport(lhint->base.hint_str,
2112 ("Relation name \"%s\" is duplicated.", relname));
2113 lhint->base.state = HINT_STATE_ERROR;
2114 bms_free(joinrelids);
2118 /* Create bitmap of relids for current join level. */
2119 joinrelids = bms_add_member(joinrelids, relid);
2122 /* We never have join method hint for single relation. */
2127 * If we don't have join method hint, create new one for the
2128 * join combination with all join methods are enabled.
2130 hint = find_join_hint(joinrelids);
2134 * Here relnames is not set, since Relids bitmap is sufficient to
2135 * control paths of this query afterward.
2137 hint = (JoinMethodHint *) JoinMethodHintCreate(lhint->base.hint_str,
2139 hint->base.state = HINT_STATE_USED;
2140 hint->nrels = njoinrels;
2141 hint->enforce_mask = ENABLE_ALL_JOIN;
2142 hint->joinrelids = bms_copy(joinrelids);
2145 join_method_hints[njoinrels] = hint;
2147 if (njoinrels >= nbaserel)
2151 bms_free(joinrelids);
2157 * Delete all join hints which have different combination from Leading
2160 for (i = 2; i <= njoinrels; i++)
2162 list_free(hstate->join_hint_level[i]);
2164 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
2167 if (hint_state_enabled(lhint))
2168 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2170 lhint->base.state = HINT_STATE_USED;
2175 * set_plain_rel_pathlist
2176 * Build access paths for a plain relation (no subquery, no inheritance)
2178 * This function was copied and edited from set_plain_rel_pathlist() in
2179 * src/backend/optimizer/path/allpaths.c
2182 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2184 /* Consider sequential scan */
2185 #if PG_VERSION_NUM >= 90200
2186 add_path(rel, create_seqscan_path(root, rel, NULL));
2188 add_path(rel, create_seqscan_path(root, rel));
2191 /* Consider index scans */
2192 create_index_paths(root, rel);
2194 /* Consider TID scans */
2195 create_tidscan_paths(root, rel);
2197 /* Now find the cheapest of the paths for this rel */
2202 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
2207 foreach(l, initial_rels)
2209 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2211 ScanMethodHint *hint;
2213 /* Skip relations which we can't choose scan method. */
2214 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2217 rte = root->simple_rte_array[rel->relid];
2219 /* We can't force scan method of foreign tables */
2220 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2224 * Create scan paths with GUC parameters which are at the beginning of
2225 * planner if scan method hint is not specified, otherwise use
2226 * specified hints and mark the hint as used.
2228 if ((hint = find_scan_hint(root, rel)) == NULL)
2229 set_scan_config_options(hstate->init_scan_mask,
2233 set_scan_config_options(hint->enforce_mask, hstate->context);
2234 hint->base.state = HINT_STATE_USED;
2237 list_free_deep(rel->pathlist);
2238 rel->pathlist = NIL;
2241 /* It's an "append relation", process accordingly */
2242 set_append_rel_pathlist(root, rel, rel->relid, rte);
2246 set_plain_rel_pathlist(root, rel, rte);
2251 * Restore the GUC variables we set above.
2253 set_scan_config_options(hstate->init_scan_mask, hstate->context);
2257 * wrapper of make_join_rel()
2259 * call make_join_rel() after changing enable_* parameters according to given
2263 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
2266 JoinMethodHint *hint;
2270 joinrelids = bms_union(rel1->relids, rel2->relids);
2271 hint = find_join_hint(joinrelids);
2272 bms_free(joinrelids);
2275 return pg_hint_plan_make_join_rel(root, rel1, rel2);
2277 save_nestlevel = NewGUCNestLevel();
2279 set_join_config_options(hint->enforce_mask, current_hint->context);
2281 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2282 hint->base.state = HINT_STATE_USED;
2285 * Restore the GUC variables we set above.
2287 AtEOXact_GUC(true, save_nestlevel);
2293 get_num_baserels(List *initial_rels)
2298 foreach(l, initial_rels)
2300 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2302 if (rel->reloptkind == RELOPT_BASEREL)
2304 else if (rel->reloptkind ==RELOPT_JOINREL)
2305 nbaserel+= bms_num_members(rel->relids);
2308 /* other values not expected here */
2309 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
2317 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
2320 JoinMethodHint **join_method_hints;
2326 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
2327 * valid hint is supplied.
2331 if (prev_join_search)
2332 return (*prev_join_search) (root, levels_needed, initial_rels);
2333 else if (enable_geqo && levels_needed >= geqo_threshold)
2334 return geqo(root, levels_needed, initial_rels);
2336 return standard_join_search(root, levels_needed, initial_rels);
2339 /* We apply scan method hint rebuild scan path. */
2340 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
2343 * In the case using GEQO, only scan method hints and Set hints have
2344 * effect. Join method and join order is not controllable by hints.
2346 if (enable_geqo && levels_needed >= geqo_threshold)
2347 return geqo(root, levels_needed, initial_rels);
2349 nbaserel = get_num_baserels(initial_rels);
2350 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
2351 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
2353 transform_join_hints(current_hint, root, nbaserel, initial_rels,
2356 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
2358 for (i = 2; i <= nbaserel; i++)
2360 list_free(current_hint->join_hint_level[i]);
2362 /* free Leading hint only */
2363 if (join_method_hints[i] != NULL &&
2364 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
2365 JoinMethodHintDelete(join_method_hints[i]);
2367 pfree(current_hint->join_hint_level);
2368 pfree(join_method_hints);
2370 if (current_hint->num_hints[HINT_TYPE_LEADING] > 0 &&
2371 hint_state_enabled(current_hint->leading_hint))
2372 set_join_config_options(current_hint->init_join_mask,
2373 current_hint->context);
2380 * Build access paths for a base relation
2382 * This function was copied and edited from set_rel_pathlist() in
2383 * src/backend/optimizer/path/allpaths.c
2386 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
2387 Index rti, RangeTblEntry *rte)
2389 #if PG_VERSION_NUM >= 90200
2390 if (IS_DUMMY_REL(rel))
2392 /* We already proved the relation empty, so nothing more to do */
2399 /* It's an "append relation", process accordingly */
2400 set_append_rel_pathlist(root, rel, rti, rte);
2404 if (rel->rtekind == RTE_RELATION)
2406 if (rte->relkind == RELKIND_RELATION)
2408 /* Plain relation */
2409 set_plain_rel_pathlist(root, rel, rte);
2412 elog(ERROR, "unexpected relkind: %c", rte->relkind);
2415 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
2419 #define standard_join_search pg_hint_plan_standard_join_search
2420 #define join_search_one_level pg_hint_plan_join_search_one_level
2421 #define make_join_rel make_join_rel_wrapper
2424 #undef make_join_rel
2425 #define make_join_rel pg_hint_plan_make_join_rel
2426 #define add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype, sjinfo, restrictlist) \
2428 ScanMethodHint *hint = NULL; \
2429 if ((hint = find_scan_hint((root), (innerrel))) != NULL) \
2431 set_scan_config_options(hint->enforce_mask, current_hint->context); \
2432 hint->base.state = HINT_STATE_USED; \
2434 add_paths_to_joinrel((root), (joinrel), (outerrel), (innerrel), (jointype), (sjinfo), (restrictlist)); \
2436 set_scan_config_options(current_hint->init_scan_mask, current_hint->context); \
2438 #include "make_join_rel.c"