1 /*-------------------------------------------------------------------------
4 * do instructions or hints to the planner using C-style block comments
7 * Copyright (c) 2012, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
9 *-------------------------------------------------------------------------
12 #include "commands/prepare.h"
13 #include "mb/pg_wchar.h"
14 #include "miscadmin.h"
15 #include "nodes/nodeFuncs.h"
16 #include "optimizer/clauses.h"
17 #include "optimizer/cost.h"
18 #include "optimizer/geqo.h"
19 #include "optimizer/joininfo.h"
20 #include "optimizer/pathnode.h"
21 #include "optimizer/paths.h"
22 #include "optimizer/plancat.h"
23 #include "optimizer/planner.h"
24 #include "optimizer/prep.h"
25 #include "optimizer/restrictinfo.h"
26 #include "parser/scansup.h"
27 #include "tcop/utility.h"
28 #include "utils/lsyscache.h"
29 #include "utils/memutils.h"
30 #if PG_VERSION_NUM >= 90200
31 #include "catalog/pg_class.h"
34 #ifdef PG_MODULE_MAGIC
38 #if PG_VERSION_NUM < 90100
39 #error unsupported PostgreSQL version
42 #define BLOCK_COMMENT_START "/*"
43 #define BLOCK_COMMENT_END "*/"
44 #define HINT_COMMENT_KEYWORD "+"
45 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
46 #define HINT_END BLOCK_COMMENT_END
49 #define HINT_SEQSCAN "SeqScan"
50 #define HINT_INDEXSCAN "IndexScan"
51 #define HINT_BITMAPSCAN "BitmapScan"
52 #define HINT_TIDSCAN "TidScan"
53 #define HINT_NOSEQSCAN "NoSeqScan"
54 #define HINT_NOINDEXSCAN "NoIndexScan"
55 #define HINT_NOBITMAPSCAN "NoBitmapScan"
56 #define HINT_NOTIDSCAN "NoTidScan"
57 #if PG_VERSION_NUM >= 90200
58 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
59 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
61 #define HINT_NESTLOOP "NestLoop"
62 #define HINT_MERGEJOIN "MergeJoin"
63 #define HINT_HASHJOIN "HashJoin"
64 #define HINT_NONESTLOOP "NoNestLoop"
65 #define HINT_NOMERGEJOIN "NoMergeJoin"
66 #define HINT_NOHASHJOIN "NoHashJoin"
67 #define HINT_LEADING "Leading"
68 #define HINT_SET "Set"
70 #define HINT_ARRAY_DEFAULT_INITSIZE 8
72 #define parse_ereport(str, detail) \
73 ereport(pg_hint_plan_parse_messages, \
74 (errmsg("hint syntax error at or near \"%s\"", (str)), \
77 #define skip_space(str) \
78 while (isspace(*str)) \
83 ENABLE_SEQSCAN = 0x01,
84 ENABLE_INDEXSCAN = 0x02,
85 ENABLE_BITMAPSCAN = 0x04,
86 ENABLE_TIDSCAN = 0x08,
87 #if PG_VERSION_NUM >= 90200
88 ENABLE_INDEXONLYSCAN = 0x10
94 ENABLE_NESTLOOP = 0x01,
95 ENABLE_MERGEJOIN = 0x02,
96 ENABLE_HASHJOIN = 0x04
99 #if PG_VERSION_NUM >= 90200
100 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
101 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
102 ENABLE_INDEXONLYSCAN)
104 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
105 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN)
107 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
108 #define DISABLE_ALL_SCAN 0
109 #define DISABLE_ALL_JOIN 0
111 typedef struct Hint Hint;
112 typedef struct HintState HintState;
114 typedef Hint *(*HintCreateFunction) (const char *hint_str,
115 const char *keyword);
116 typedef void (*HintDeleteFunction) (Hint *hint);
117 typedef void (*HintDumpFunction) (Hint *hint, StringInfo buf);
118 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
119 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
120 Query *parse, const char *str);
123 #define NUM_HINT_TYPE 4
124 typedef enum HintType
126 HINT_TYPE_SCAN_METHOD,
127 HINT_TYPE_JOIN_METHOD,
132 static const char *HintTypeName[] = {
140 typedef enum HintStatus
142 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
143 HINT_STATE_USED, /* hint is used */
144 HINT_STATE_DUPLICATION, /* specified hint duplication */
145 HINT_STATE_ERROR /* execute error (parse error does not include
149 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
150 (hint)->base.state == HINT_STATE_USED)
152 /* common data for all hints. */
155 const char *hint_str; /* must not do pfree */
156 const char *keyword; /* must not do pfree */
159 HintDeleteFunction delete_func;
160 HintDumpFunction dump_func;
161 HintCmpFunction cmp_func;
162 HintParseFunction parser_func;
165 /* scan method hints */
166 typedef struct ScanMethodHint
171 unsigned char enforce_mask;
174 /* join method hints */
175 typedef struct JoinMethodHint
180 unsigned char enforce_mask;
184 /* join order hints */
185 typedef struct LeadingHint
188 List *relations; /* relation names specified in Leading hint */
191 /* change a run-time parameter hints */
192 typedef struct SetHint
195 char *name; /* name of variable */
200 * Describes a context of hint processing.
204 char *hint_str; /* original hint string */
207 int nall_hints; /* # of valid all hints */
208 int max_all_hints; /* # of slots for all hints */
209 Hint **all_hints; /* parsed all hints */
211 /* # of each hints */
212 int num_hints[NUM_HINT_TYPE];
214 /* for scan method hints */
215 ScanMethodHint **scan_hints; /* parsed scan hints */
216 int init_scan_mask; /* initial value scan parameter */
217 Index parent_relid; /* inherit parent table relid */
218 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
220 /* for join method hints */
221 JoinMethodHint **join_hints; /* parsed join hints */
222 int init_join_mask; /* initial value join parameter */
223 List **join_hint_level;
225 /* for Leading hint */
226 LeadingHint *leading_hint; /* parsed last specified Leading hint */
229 SetHint **set_hints; /* parsed Set hints */
230 GucContext context; /* which GUC parameters can we set? */
234 * Describes a hint parser module which is bound with particular hint keyword.
236 typedef struct HintParser
239 HintCreateFunction create_func;
242 /* Module callbacks */
246 static void push_hint(HintState *hstate);
247 static void pop_hint(void);
249 static void pg_hint_plan_ProcessUtility(Node *parsetree,
250 const char *queryString,
251 ParamListInfo params, bool isTopLevel,
253 char *completionTag);
254 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
255 ParamListInfo boundParams);
256 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
257 Oid relationObjectId,
258 bool inhparent, RelOptInfo *rel);
259 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
263 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword);
264 static void ScanMethodHintDelete(ScanMethodHint *hint);
265 static void ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf);
266 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
267 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
268 Query *parse, const char *str);
269 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword);
270 static void JoinMethodHintDelete(JoinMethodHint *hint);
271 static void JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf);
272 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
273 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
274 Query *parse, const char *str);
275 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword);
276 static void LeadingHintDelete(LeadingHint *hint);
277 static void LeadingHintDump(LeadingHint *hint, StringInfo buf);
278 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
279 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
280 Query *parse, const char *str);
281 static Hint *SetHintCreate(const char *hint_str, const char *keyword);
282 static void SetHintDelete(SetHint *hint);
283 static void SetHintDump(SetHint *hint, StringInfo buf);
284 static int SetHintCmp(const SetHint *a, const SetHint *b);
285 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
288 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
291 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
292 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
293 ListCell *other_rels);
294 static void make_rels_by_clauseless_joins(PlannerInfo *root,
296 ListCell *other_rels);
297 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
298 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
299 Index rti, RangeTblEntry *rte);
300 #if PG_VERSION_NUM >= 90200
301 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
302 List *live_childrels,
303 List *all_child_pathkeys);
305 static List *accumulate_append_subpath(List *subpaths, Path *path);
306 #if PG_VERSION_NUM < 90200
307 static void set_dummy_rel_pathlist(RelOptInfo *rel);
309 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
313 static bool pg_hint_plan_enable_hint = true;
314 static bool pg_hint_plan_debug_print = false;
315 static int pg_hint_plan_parse_messages = INFO;
317 static const struct config_enum_entry parse_messages_level_options[] = {
318 {"debug", DEBUG2, true},
319 {"debug5", DEBUG5, false},
320 {"debug4", DEBUG4, false},
321 {"debug3", DEBUG3, false},
322 {"debug2", DEBUG2, false},
323 {"debug1", DEBUG1, false},
325 {"info", INFO, false},
326 {"notice", NOTICE, false},
327 {"warning", WARNING, false},
328 {"error", ERROR, false},
330 * {"fatal", FATAL, true},
331 * {"panic", PANIC, true},
336 /* Saved hook values in case of unload */
337 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
338 static planner_hook_type prev_planner = NULL;
339 static get_relation_info_hook_type prev_get_relation_info = NULL;
340 static join_search_hook_type prev_join_search = NULL;
342 /* Hold reference to currently active hint */
343 static HintState *current_hint = NULL;
346 * List of hint contexts. We treat the head of the list as the Top of the
347 * context stack, so current_hint always points the first element of this list.
349 static List *HintStateStack = NIL;
352 * Holds statement name during executing EXECUTE command. NULL for other
355 static char *stmt_name = NULL;
357 static const HintParser parsers[] = {
358 {HINT_SEQSCAN, ScanMethodHintCreate},
359 {HINT_INDEXSCAN, ScanMethodHintCreate},
360 {HINT_BITMAPSCAN, ScanMethodHintCreate},
361 {HINT_TIDSCAN, ScanMethodHintCreate},
362 {HINT_NOSEQSCAN, ScanMethodHintCreate},
363 {HINT_NOINDEXSCAN, ScanMethodHintCreate},
364 {HINT_NOBITMAPSCAN, ScanMethodHintCreate},
365 {HINT_NOTIDSCAN, ScanMethodHintCreate},
366 #if PG_VERSION_NUM >= 90200
367 {HINT_INDEXONLYSCAN, ScanMethodHintCreate},
368 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate},
370 {HINT_NESTLOOP, JoinMethodHintCreate},
371 {HINT_MERGEJOIN, JoinMethodHintCreate},
372 {HINT_HASHJOIN, JoinMethodHintCreate},
373 {HINT_NONESTLOOP, JoinMethodHintCreate},
374 {HINT_NOMERGEJOIN, JoinMethodHintCreate},
375 {HINT_NOHASHJOIN, JoinMethodHintCreate},
376 {HINT_LEADING, LeadingHintCreate},
377 {HINT_SET, SetHintCreate},
382 * Module load callbacks
387 /* Define custom GUC variables. */
388 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
389 "Force planner to use plans specified in the hint comment preceding to the query.",
391 &pg_hint_plan_enable_hint,
399 DefineCustomBoolVariable("pg_hint_plan.debug_print",
400 "Logs results of hint parsing.",
402 &pg_hint_plan_debug_print,
410 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
411 "Message level of parse errors.",
413 &pg_hint_plan_parse_messages,
415 parse_messages_level_options,
423 prev_ProcessUtility = ProcessUtility_hook;
424 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
425 prev_planner = planner_hook;
426 planner_hook = pg_hint_plan_planner;
427 prev_get_relation_info = get_relation_info_hook;
428 get_relation_info_hook = pg_hint_plan_get_relation_info;
429 prev_join_search = join_search_hook;
430 join_search_hook = pg_hint_plan_join_search;
434 * Module unload callback
440 /* Uninstall hooks. */
441 ProcessUtility_hook = prev_ProcessUtility;
442 planner_hook = prev_planner;
443 get_relation_info_hook = prev_get_relation_info;
444 join_search_hook = prev_join_search;
448 * create and delete functions the hint object
452 ScanMethodHintCreate(const char *hint_str, const char *keyword)
454 ScanMethodHint *hint;
456 hint = palloc(sizeof(ScanMethodHint));
457 hint->base.hint_str = hint_str;
458 hint->base.keyword = keyword;
459 hint->base.type = HINT_TYPE_SCAN_METHOD;
460 hint->base.state = HINT_STATE_NOTUSED;
461 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
462 hint->base.dump_func = (HintDumpFunction) ScanMethodHintDump;
463 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
464 hint->base.parser_func = (HintParseFunction) ScanMethodHintParse;
465 hint->relname = NULL;
466 hint->indexnames = NIL;
467 hint->enforce_mask = 0;
469 return (Hint *) hint;
473 ScanMethodHintDelete(ScanMethodHint *hint)
479 pfree(hint->relname);
480 list_free_deep(hint->indexnames);
485 JoinMethodHintCreate(const char *hint_str, const char *keyword)
487 JoinMethodHint *hint;
489 hint = palloc(sizeof(JoinMethodHint));
490 hint->base.hint_str = hint_str;
491 hint->base.keyword = keyword;
492 hint->base.type = HINT_TYPE_JOIN_METHOD;
493 hint->base.state = HINT_STATE_NOTUSED;
494 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
495 hint->base.dump_func = (HintDumpFunction) JoinMethodHintDump;
496 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
497 hint->base.parser_func = (HintParseFunction) JoinMethodHintParse;
499 hint->relnames = NULL;
500 hint->enforce_mask = 0;
501 hint->joinrelids = NULL;
503 return (Hint *) hint;
507 JoinMethodHintDelete(JoinMethodHint *hint)
516 for (i = 0; i < hint->nrels; i++)
517 pfree(hint->relnames[i]);
518 pfree(hint->relnames);
520 bms_free(hint->joinrelids);
525 LeadingHintCreate(const char *hint_str, const char *keyword)
529 hint = palloc(sizeof(LeadingHint));
530 hint->base.hint_str = hint_str;
531 hint->base.keyword = keyword;
532 hint->base.type = HINT_TYPE_LEADING;
533 hint->base.state = HINT_STATE_NOTUSED;
534 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
535 hint->base.dump_func = (HintDumpFunction) LeadingHintDump;
536 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
537 hint->base.parser_func = (HintParseFunction) LeadingHintParse;
538 hint->relations = NIL;
540 return (Hint *) hint;
544 LeadingHintDelete(LeadingHint *hint)
549 list_free_deep(hint->relations);
554 SetHintCreate(const char *hint_str, const char *keyword)
558 hint = palloc(sizeof(SetHint));
559 hint->base.hint_str = hint_str;
560 hint->base.keyword = keyword;
561 hint->base.type = HINT_TYPE_SET;
562 hint->base.state = HINT_STATE_NOTUSED;
563 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
564 hint->base.dump_func = (HintDumpFunction) SetHintDump;
565 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
566 hint->base.parser_func = (HintParseFunction) SetHintParse;
570 return (Hint *) hint;
574 SetHintDelete(SetHint *hint)
587 HintStateCreate(void)
591 hstate = palloc(sizeof(HintState));
592 hstate->hint_str = NULL;
593 hstate->nall_hints = 0;
594 hstate->max_all_hints = 0;
595 hstate->all_hints = NULL;
596 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
597 hstate->scan_hints = NULL;
598 hstate->init_scan_mask = 0;
599 hstate->parent_relid = 0;
600 hstate->parent_hint = NULL;
601 hstate->join_hints = NULL;
602 hstate->init_join_mask = 0;
603 hstate->join_hint_level = NULL;
604 hstate->leading_hint = NULL;
605 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
606 hstate->set_hints = NULL;
612 HintStateDelete(HintState *hstate)
619 if (hstate->hint_str)
620 pfree(hstate->hint_str);
622 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
623 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
624 if (hstate->all_hints)
625 pfree(hstate->all_hints);
633 dump_quote_value(StringInfo buf, const char *value)
635 bool need_quote = false;
638 for (str = value; *str != '\0'; str++)
640 if (isspace(*str) || *str == ')' || *str == '"')
643 appendStringInfoCharMacro(buf, '"');
648 for (str = value; *str != '\0'; str++)
651 appendStringInfoCharMacro(buf, '"');
653 appendStringInfoCharMacro(buf, *str);
657 appendStringInfoCharMacro(buf, '"');
661 ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf)
665 appendStringInfo(buf, "%s(", hint->base.keyword);
666 dump_quote_value(buf, hint->relname);
667 foreach(l, hint->indexnames)
669 appendStringInfoCharMacro(buf, ' ');
670 dump_quote_value(buf, (char *) lfirst(l));
672 appendStringInfoString(buf, ")\n");
676 JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf)
680 appendStringInfo(buf, "%s(", hint->base.keyword);
681 dump_quote_value(buf, hint->relnames[0]);
682 for (i = 1; i < hint->nrels; i++)
684 appendStringInfoCharMacro(buf, ' ');
685 dump_quote_value(buf, hint->relnames[i]);
687 appendStringInfoString(buf, ")\n");
692 LeadingHintDump(LeadingHint *hint, StringInfo buf)
697 appendStringInfo(buf, "%s(", HINT_LEADING);
699 foreach(l, hint->relations)
704 appendStringInfoCharMacro(buf, ' ');
706 dump_quote_value(buf, (char *) lfirst(l));
709 appendStringInfoString(buf, ")\n");
713 SetHintDump(SetHint *hint, StringInfo buf)
715 appendStringInfo(buf, "%s(", HINT_SET);
716 dump_quote_value(buf, hint->name);
717 appendStringInfoCharMacro(buf, ' ');
718 dump_quote_value(buf, hint->value);
719 appendStringInfo(buf, ")\n");
723 all_hint_dump(HintState *hstate, StringInfo buf, const char *title,
728 appendStringInfo(buf, "%s:\n", title);
729 for (i = 0; i < hstate->nall_hints; i++)
731 if (hstate->all_hints[i]->state != state)
734 hstate->all_hints[i]->dump_func(hstate->all_hints[i], buf);
739 HintStateDump(HintState *hstate)
745 elog(LOG, "pg_hint_plan:\nno hint");
749 initStringInfo(&buf);
751 appendStringInfoString(&buf, "pg_hint_plan:\n");
752 all_hint_dump(hstate, &buf, "used hint", HINT_STATE_USED);
753 all_hint_dump(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
754 all_hint_dump(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
755 all_hint_dump(hstate, &buf, "error hint", HINT_STATE_ERROR);
757 elog(LOG, "%s", buf.data);
767 RelnameCmp(const void *a, const void *b)
769 const char *relnamea = *((const char **) a);
770 const char *relnameb = *((const char **) b);
772 return strcmp(relnamea, relnameb);
776 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
778 return RelnameCmp(&a->relname, &b->relname);
782 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
786 if (a->nrels != b->nrels)
787 return a->nrels - b->nrels;
789 for (i = 0; i < a->nrels; i++)
792 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
800 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
806 SetHintCmp(const SetHint *a, const SetHint *b)
808 return strcmp(a->name, b->name);
812 HintCmp(const void *a, const void *b)
814 const Hint *hinta = *((const Hint **) a);
815 const Hint *hintb = *((const Hint **) b);
817 if (hinta->type != hintb->type)
818 return hinta->type - hintb->type;
820 return hinta->cmp_func(hinta, hintb);
824 * Returns byte offset of hint b from hint a. If hint a was specified before
825 * b, positive value is returned.
828 HintCmpWithPos(const void *a, const void *b)
830 const Hint *hinta = *((const Hint **) a);
831 const Hint *hintb = *((const Hint **) b);
834 result = HintCmp(a, b);
836 result = hinta->hint_str - hintb->hint_str;
845 parse_keyword(const char *str, StringInfo buf)
849 while (!isspace(*str) && *str != '(' && *str != '\0')
850 appendStringInfoCharMacro(buf, *str++);
856 skip_opened_parenthesis(const char *str)
862 parse_ereport(str, ("Opening parenthesis is necessary."));
872 skip_closed_parenthesis(const char *str)
878 parse_ereport(str, ("Closing parenthesis is necessary."));
888 * Parse a token from str, and store malloc'd copy into word. A token can be
889 * quoted with '"'. Return value is pointer to unparsed portion of original
890 * string, or NULL if an error occurred.
892 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
895 parse_quote_value(const char *str, char **word, bool truncate)
900 /* Skip leading spaces. */
903 initStringInfo(&buf);
916 /* Double quotation must be closed. */
920 parse_ereport(str, ("Unterminated quoted string."));
925 * Skip escaped double quotation.
927 * We don't allow slash-asterisk and asterisk-slash (delimiters of
928 * block comments) to be an object name, so users must specify
929 * alias for such object names.
931 * Those special names can be allowed if we care escaped slashes
932 * and asterisks, but we don't.
941 else if (isspace(*str) || *str == ')' || *str == '"' || *str == '\0')
944 appendStringInfoCharMacro(&buf, *str++);
949 parse_ereport(str, ("Zero-length delimited string."));
956 /* Truncate name if it's too long */
958 truncate_identifier(buf.data, strlen(buf.data), true);
966 parse_hints(HintState *hstate, Query *parse, const char *str)
971 initStringInfo(&buf);
974 const HintParser *parser;
976 /* in error message, we output the comment including the keyword. */
979 /* parse only the keyword of the hint. */
980 resetStringInfo(&buf);
981 str = parse_keyword(str, &buf);
983 for (parser = parsers; parser->keyword != NULL; parser++)
985 char *keyword = parser->keyword;
988 if (strcasecmp(buf.data, keyword) != 0)
991 hint = parser->create_func(head, keyword);
993 /* parser of each hint does parse in a parenthesis. */
994 if ((str = skip_opened_parenthesis(str)) == NULL ||
995 (str = hint->parser_func(hint, hstate, parse, str)) == NULL ||
996 (str = skip_closed_parenthesis(str)) == NULL)
998 hint->delete_func(hint);
1004 * Add hint information into all_hints array. If we don't have
1005 * enough space, double the array.
1007 if (hstate->nall_hints == 0)
1009 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1010 hstate->all_hints = (Hint **)
1011 palloc(sizeof(Hint *) * hstate->max_all_hints);
1013 else if (hstate->nall_hints == hstate->max_all_hints)
1015 hstate->max_all_hints *= 2;
1016 hstate->all_hints = (Hint **)
1017 repalloc(hstate->all_hints,
1018 sizeof(Hint *) * hstate->max_all_hints);
1021 hstate->all_hints[hstate->nall_hints] = hint;
1022 hstate->nall_hints++;
1029 if (parser->keyword == NULL)
1032 ("Unrecognized hint keyword \"%s\".", buf.data));
1042 * Do basic parsing of the query head comment.
1045 parse_head_comment(Query *parse)
1054 /* get client-supplied query string. */
1057 PreparedStatement *entry;
1059 entry = FetchPreparedStatement(stmt_name, true);
1060 p = entry->plansource->query_string;
1063 p = debug_query_string;
1068 /* extract query head comment. */
1069 len = strlen(HINT_START);
1071 if (strncmp(p, HINT_START, len))
1078 /* find hint end keyword. */
1079 if ((tail = strstr(p, HINT_END)) == NULL)
1081 parse_ereport(head, ("Unterminated block comment."));
1085 /* We don't support nested block comments. */
1086 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1088 parse_ereport(head, ("Nested block comments are not supported."));
1092 /* Make a copy of hint. */
1094 head = palloc(len + 1);
1095 memcpy(head, p, len);
1099 hstate = HintStateCreate();
1100 hstate->hint_str = head;
1102 /* parse each hint. */
1103 parse_hints(hstate, parse, p);
1105 /* When nothing specified a hint, we free HintState and returns NULL. */
1106 if (hstate->nall_hints == 0)
1108 HintStateDelete(hstate);
1112 /* Sort hints in order of original position. */
1113 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1117 * If we have hints which are specified for an object, mark preceding one
1118 * as 'duplicated' to ignore it in planner phase.
1120 for (i = 0; i < hstate->nall_hints; i++)
1122 Hint *cur_hint = hstate->all_hints[i];
1125 /* Count up hints per hint-type. */
1126 hstate->num_hints[cur_hint->type]++;
1128 /* If we don't have next, nothing to compare. */
1129 if (i + 1 >= hstate->nall_hints)
1131 next_hint = hstate->all_hints[i + 1];
1134 * We need to pass address of hint pointers, because HintCmp has
1135 * been designed to be used with qsort.
1137 if (HintCmp(&cur_hint, &next_hint) == 0)
1139 parse_ereport(cur_hint->hint_str,
1140 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1141 cur_hint->state = HINT_STATE_DUPLICATION;
1146 * Make sure that per-type array pointers point proper position in the
1147 * array which consists of all hints.
1149 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1150 hstate->join_hints = (JoinMethodHint **) hstate->all_hints +
1151 hstate->num_hints[HINT_TYPE_SCAN_METHOD];
1152 hstate->leading_hint = (LeadingHint *) hstate->all_hints[
1153 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1154 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1155 hstate->num_hints[HINT_TYPE_LEADING] - 1];
1156 hstate->set_hints = (SetHint **) hstate->all_hints +
1157 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1158 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1159 hstate->num_hints[HINT_TYPE_LEADING];
1165 * Parse inside of parentheses of scan-method hints.
1168 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1171 const char *keyword = hint->base.keyword;
1173 /* Given hint is invalid if relation name can't be parsed. */
1174 if ((str = parse_quote_value(str, &hint->relname, true))
1180 /* Parse index name(s) if given hint accepts. */
1181 if (strcmp(keyword, HINT_INDEXSCAN) == 0 ||
1182 #if PG_VERSION_NUM >= 90200
1183 strcmp(keyword, HINT_INDEXONLYSCAN) == 0 ||
1185 strcmp(keyword, HINT_BITMAPSCAN) == 0)
1187 while (*str != ')' && *str != '\0')
1191 str = parse_quote_value(str, &indexname, true);
1195 hint->indexnames = lappend(hint->indexnames, indexname);
1200 /* Set a bit for specified hint. */
1201 if (strcasecmp(keyword, HINT_SEQSCAN) == 0)
1202 hint->enforce_mask = ENABLE_SEQSCAN;
1203 else if (strcasecmp(keyword, HINT_INDEXSCAN) == 0)
1204 hint->enforce_mask = ENABLE_INDEXSCAN;
1205 else if (strcasecmp(keyword, HINT_BITMAPSCAN) == 0)
1206 hint->enforce_mask = ENABLE_BITMAPSCAN;
1207 else if (strcasecmp(keyword, HINT_TIDSCAN) == 0)
1208 hint->enforce_mask = ENABLE_TIDSCAN;
1209 else if (strcasecmp(keyword, HINT_NOSEQSCAN) == 0)
1210 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1211 else if (strcasecmp(keyword, HINT_NOINDEXSCAN) == 0)
1212 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1213 else if (strcasecmp(keyword, HINT_NOBITMAPSCAN) == 0)
1214 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1215 else if (strcasecmp(keyword, HINT_NOTIDSCAN) == 0)
1216 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1217 #if PG_VERSION_NUM >= 90200
1218 else if (strcasecmp(keyword, HINT_INDEXONLYSCAN) == 0)
1219 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1220 else if (strcasecmp(keyword, HINT_NOINDEXONLYSCAN) == 0)
1221 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1225 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1233 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1237 const char *keyword = hint->base.keyword;
1241 hint->relnames = palloc(sizeof(char *));
1243 while ((str = parse_quote_value(str, &relname, true))
1247 hint->relnames = repalloc(hint->relnames, sizeof(char *) * hint->nrels);
1248 hint->relnames[hint->nrels - 1] = relname;
1258 /* A join hint requires at least two relations to be specified. */
1259 if (hint->nrels < 2)
1262 ("%s hint requires at least two relations.",
1263 hint->base.keyword));
1264 hint->base.state = HINT_STATE_ERROR;
1267 /* Sort hints in alphabetical order of relation names. */
1268 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1270 if (strcasecmp(keyword, HINT_NESTLOOP) == 0)
1271 hint->enforce_mask = ENABLE_NESTLOOP;
1272 else if (strcasecmp(keyword, HINT_MERGEJOIN) == 0)
1273 hint->enforce_mask = ENABLE_MERGEJOIN;
1274 else if (strcasecmp(keyword, HINT_HASHJOIN) == 0)
1275 hint->enforce_mask = ENABLE_HASHJOIN;
1276 else if (strcasecmp(keyword, HINT_NONESTLOOP) == 0)
1277 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1278 else if (strcasecmp(keyword, HINT_NOMERGEJOIN) == 0)
1279 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1280 else if (strcasecmp(keyword, HINT_NOHASHJOIN) == 0)
1281 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1284 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1292 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1301 if ((str = parse_quote_value(str, &relname, true))
1305 hint->relations = lappend(hint->relations, relname);
1310 /* A Leading hint requires at least two relations to be specified. */
1311 if (list_length(hint->relations) < 2)
1313 parse_ereport(hint->base.hint_str,
1314 ("%s hint requires at least two relations.",
1316 hint->base.state = HINT_STATE_ERROR;
1323 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1325 if ((str = parse_quote_value(str, &hint->name, true))
1327 (str = parse_quote_value(str, &hint->value, false))
1335 * set GUC parameter functions
1339 set_config_option_wrapper(const char *name, const char *value,
1340 GucContext context, GucSource source,
1341 GucAction action, bool changeVal, int elevel)
1344 MemoryContext ccxt = CurrentMemoryContext;
1348 #if PG_VERSION_NUM >= 90200
1349 result = set_config_option(name, value, context, source,
1350 action, changeVal, 0);
1352 result = set_config_option(name, value, context, source,
1360 /* Save error info */
1361 MemoryContextSwitchTo(ccxt);
1362 errdata = CopyErrorData();
1365 ereport(elevel, (errcode(errdata->sqlerrcode),
1366 errmsg("%s", errdata->message),
1367 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1368 errdata->hint ? errhint("%s", errdata->hint) : 0));
1369 FreeErrorData(errdata);
1377 set_config_options(SetHint **options, int noptions, GucContext context)
1382 save_nestlevel = NewGUCNestLevel();
1384 for (i = 0; i < noptions; i++)
1386 SetHint *hint = options[i];
1389 if (!hint_state_enabled(hint))
1392 result = set_config_option_wrapper(hint->name, hint->value, context,
1393 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1394 pg_hint_plan_parse_messages);
1396 hint->base.state = HINT_STATE_USED;
1398 hint->base.state = HINT_STATE_ERROR;
1401 return save_nestlevel;
1404 #define SET_CONFIG_OPTION(name, type_bits) \
1405 set_config_option_wrapper((name), \
1406 (mask & (type_bits)) ? "true" : "false", \
1407 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1410 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1414 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1415 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1416 #if PG_VERSION_NUM >= 90200
1417 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1420 mask = enforce_mask;
1422 mask = enforce_mask & current_hint->init_scan_mask;
1424 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1425 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1426 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1427 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1428 #if PG_VERSION_NUM >= 90200
1429 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1434 set_join_config_options(unsigned char enforce_mask, GucContext context)
1438 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1439 enforce_mask == ENABLE_HASHJOIN)
1440 mask = enforce_mask;
1442 mask = enforce_mask & current_hint->init_join_mask;
1444 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1445 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1446 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1450 * pg_hint_plan hook functions
1454 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1455 ParamListInfo params, bool isTopLevel,
1456 DestReceiver *dest, char *completionTag)
1460 if (!pg_hint_plan_enable_hint)
1462 if (prev_ProcessUtility)
1463 (*prev_ProcessUtility) (parsetree, queryString, params,
1464 isTopLevel, dest, completionTag);
1466 standard_ProcessUtility(parsetree, queryString, params,
1467 isTopLevel, dest, completionTag);
1473 if (IsA(node, ExplainStmt))
1476 * Draw out parse tree of actual query from Query struct of EXPLAIN
1482 stmt = (ExplainStmt *) node;
1484 Assert(IsA(stmt->query, Query));
1485 query = (Query *) stmt->query;
1487 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1488 node = query->utilityStmt;
1492 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
1493 * specified to preceding PREPARE command to use it as source of hints.
1495 if (IsA(node, ExecuteStmt))
1499 stmt = (ExecuteStmt *) node;
1500 stmt_name = stmt->name;
1502 #if PG_VERSION_NUM >= 90200
1504 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
1507 if (IsA(node, CreateTableAsStmt))
1509 CreateTableAsStmt *stmt;
1512 stmt = (CreateTableAsStmt *) node;
1513 Assert(IsA(stmt->query, Query));
1514 query = (Query *) stmt->query;
1516 if (query->commandType == CMD_UTILITY &&
1517 IsA(query->utilityStmt, ExecuteStmt))
1519 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
1520 stmt_name = estmt->name;
1528 if (prev_ProcessUtility)
1529 (*prev_ProcessUtility) (parsetree, queryString, params,
1530 isTopLevel, dest, completionTag);
1532 standard_ProcessUtility(parsetree, queryString, params,
1533 isTopLevel, dest, completionTag);
1547 if (prev_ProcessUtility)
1548 (*prev_ProcessUtility) (parsetree, queryString, params,
1549 isTopLevel, dest, completionTag);
1551 standard_ProcessUtility(parsetree, queryString, params,
1552 isTopLevel, dest, completionTag);
1556 * Push a hint into hint stack which is implemented with List struct. Head of
1557 * list is top of stack.
1560 push_hint(HintState *hstate)
1562 /* Prepend new hint to the list means pushing to stack. */
1563 HintStateStack = lcons(hstate, HintStateStack);
1565 /* Pushed hint is the one which should be used hereafter. */
1566 current_hint = hstate;
1569 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
1573 /* Hint stack must not be empty. */
1574 if(HintStateStack == NIL)
1575 elog(ERROR, "hint stack is empty");
1578 * Take a hint at the head from the list, and free it. Switch current_hint
1579 * to point new head (NULL if the list is empty).
1581 HintStateStack = list_delete_first(HintStateStack);
1582 HintStateDelete(current_hint);
1583 if(HintStateStack == NIL)
1584 current_hint = NULL;
1586 current_hint = (HintState *) lfirst(list_head(HintStateStack));
1589 static PlannedStmt *
1590 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1593 PlannedStmt *result;
1597 * Use standard planner if pg_hint_plan is disabled. Other hook functions
1598 * try to change plan with current_hint if any, so set it to NULL.
1600 if (!pg_hint_plan_enable_hint)
1602 current_hint = NULL;
1605 return (*prev_planner) (parse, cursorOptions, boundParams);
1607 return standard_planner(parse, cursorOptions, boundParams);
1610 /* Create hint struct from parse tree. */
1611 hstate = parse_head_comment(parse);
1614 * Use standard planner if the statement has not valid hint. Other hook
1615 * functions try to change plan with current_hint if any, so set it to
1620 current_hint = NULL;
1623 return (*prev_planner) (parse, cursorOptions, boundParams);
1625 return standard_planner(parse, cursorOptions, boundParams);
1629 * Push new hint struct to the hint stack to disable previous hint context.
1633 /* Set GUC parameters which are specified with Set hint. */
1634 save_nestlevel = set_config_options(current_hint->set_hints,
1635 current_hint->num_hints[HINT_TYPE_SET],
1636 current_hint->context);
1639 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
1640 if (enable_indexscan)
1641 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
1642 if (enable_bitmapscan)
1643 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
1645 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
1646 #if PG_VERSION_NUM >= 90200
1647 if (enable_indexonlyscan)
1648 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
1650 if (enable_nestloop)
1651 current_hint->init_join_mask |= ENABLE_NESTLOOP;
1652 if (enable_mergejoin)
1653 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
1654 if (enable_hashjoin)
1655 current_hint->init_join_mask |= ENABLE_HASHJOIN;
1658 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
1659 * state when this planner started when error occurred in planner.
1664 result = (*prev_planner) (parse, cursorOptions, boundParams);
1666 result = standard_planner(parse, cursorOptions, boundParams);
1671 * Rollback changes of GUC parameters, and pop current hint context
1672 * from hint stack to rewind the state.
1674 AtEOXact_GUC(true, save_nestlevel);
1680 /* Print hint in debug mode. */
1681 if (pg_hint_plan_debug_print)
1682 HintStateDump(current_hint);
1685 * Rollback changes of GUC parameters, and pop current hint context from
1686 * hint stack to rewind the state.
1688 AtEOXact_GUC(true, save_nestlevel);
1695 * Return scan method hint which matches given aliasname.
1697 static ScanMethodHint *
1698 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
1704 * We can't apply scan method hint if the relation is:
1705 * - not a base relation
1706 * - not an ordinary relation (such as join and subquery)
1708 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
1711 rte = root->simple_rte_array[rel->relid];
1713 /* We can't force scan method of foreign tables */
1714 if (rte->relkind == RELKIND_FOREIGN_TABLE)
1717 /* Find scan method hint, which matches given names, from the list. */
1718 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1720 ScanMethodHint *hint = current_hint->scan_hints[i];
1722 /* We ignore disabled hints. */
1723 if (!hint_state_enabled(hint))
1726 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
1734 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel)
1741 * We delete all the IndexOptInfo list and prevent you from being usable by
1744 if (hint->enforce_mask == ENABLE_SEQSCAN ||
1745 hint->enforce_mask == ENABLE_TIDSCAN)
1747 list_free_deep(rel->indexlist);
1748 rel->indexlist = NIL;
1749 hint->base.state = HINT_STATE_USED;
1755 * When a list of indexes is not specified, we just use all indexes.
1757 if (hint->indexnames == NIL)
1761 * Leaving only an specified index, we delete it from a IndexOptInfo list
1765 for (cell = list_head(rel->indexlist); cell; cell = next)
1767 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
1768 char *indexname = get_rel_name(info->indexoid);
1770 bool use_index = false;
1774 foreach(l, hint->indexnames)
1776 if (RelnameCmp(&indexname, &lfirst(l)) == 0)
1784 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
1793 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
1794 bool inhparent, RelOptInfo *rel)
1796 ScanMethodHint *hint;
1798 if (prev_get_relation_info)
1799 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
1801 /* Do nothing if we don't have valid hint in this context. */
1807 /* store does relids of parent table. */
1808 current_hint->parent_relid = rel->relid;
1810 else if (current_hint->parent_relid != 0)
1813 * We use the same GUC parameter if this table is the child table of a
1814 * table called pg_hint_plan_get_relation_info just before that.
1818 /* append_rel_list contains all append rels; ignore others */
1819 foreach(l, root->append_rel_list)
1821 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1823 /* This rel is child table. */
1824 if (appinfo->parent_relid == current_hint->parent_relid &&
1825 appinfo->child_relid == rel->relid)
1827 if (current_hint->parent_hint)
1828 delete_indexes(current_hint->parent_hint, rel);
1834 /* This rel is not inherit table. */
1835 current_hint->parent_relid = 0;
1836 current_hint->parent_hint = NULL;
1840 * If scan method hint was given, reset GUC parameters which control
1841 * planner behavior about choosing scan methods.
1843 if ((hint = find_scan_hint(root, rel)) == NULL)
1845 set_scan_config_options(current_hint->init_scan_mask,
1846 current_hint->context);
1849 set_scan_config_options(hint->enforce_mask, current_hint->context);
1850 hint->base.state = HINT_STATE_USED;
1852 current_hint->parent_hint = hint;
1854 delete_indexes(hint, rel);
1858 * Return index of relation which matches given aliasname, or 0 if not found.
1859 * If same aliasname was used multiple times in a query, return -1.
1862 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
1868 for (i = 1; i < root->simple_rel_array_size; i++)
1872 if (root->simple_rel_array[i] == NULL)
1875 Assert(i == root->simple_rel_array[i]->relid);
1877 if (RelnameCmp(&aliasname,
1878 &root->simple_rte_array[i]->eref->aliasname) != 0)
1881 foreach(l, initial_rels)
1883 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
1885 if (rel->reloptkind == RELOPT_BASEREL)
1887 if (rel->relid != i)
1892 Assert(rel->reloptkind == RELOPT_JOINREL);
1894 if (!bms_is_member(i, rel->relids))
1901 ("Relation name \"%s\" is ambiguous.",
1916 * Return join hint which matches given joinrelids.
1918 static JoinMethodHint *
1919 find_join_hint(Relids joinrelids)
1924 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
1926 foreach(l, join_hint)
1928 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
1930 if (bms_equal(joinrelids, hint->joinrelids))
1938 * Transform join method hint into handy form.
1940 * - create bitmap of relids from alias names, to make it easier to check
1941 * whether a join path matches a join method hint.
1942 * - add join method hints which are necessary to enforce join order
1943 * specified by Leading hint
1946 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
1947 List *initial_rels, JoinMethodHint **join_method_hints)
1957 * Create bitmap of relids from alias names for each join method hint.
1958 * Bitmaps are more handy than strings in join searching.
1960 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
1962 JoinMethodHint *hint = hstate->join_hints[i];
1965 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
1968 bms_free(hint->joinrelids);
1969 hint->joinrelids = NULL;
1971 for (j = 0; j < hint->nrels; j++)
1973 char *relname = hint->relnames[j];
1975 relid = find_relid_aliasname(root, relname, initial_rels,
1976 hint->base.hint_str);
1979 hint->base.state = HINT_STATE_ERROR;
1984 if (bms_is_member(relid, hint->joinrelids))
1986 parse_ereport(hint->base.hint_str,
1987 ("Relation name \"%s\" is duplicated.", relname));
1988 hint->base.state = HINT_STATE_ERROR;
1992 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
1995 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
1998 hstate->join_hint_level[hint->nrels] =
1999 lappend(hstate->join_hint_level[hint->nrels], hint);
2002 /* Do nothing if no Leading hint was supplied. */
2003 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2006 /* Do nothing if Leading hint is invalid. */
2007 lhint = hstate->leading_hint;
2008 if (!hint_state_enabled(lhint))
2012 * We need join method hints which fit specified join order in every join
2013 * level. For example, Leading(A B C) virtually requires following join
2014 * method hints, if no join method hint supplied:
2016 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
2017 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
2019 * If we already have join method hint which fits specified join order in
2020 * that join level, we leave it as-is and don't add new hints.
2024 foreach(l, lhint->relations)
2026 char *relname = (char *)lfirst(l);
2027 JoinMethodHint *hint;
2030 * Find relid of the relation which has given name. If we have the
2031 * name given in Leading hint multiple times in the join, nothing to
2034 relid = find_relid_aliasname(root, relname, initial_rels,
2038 bms_free(joinrelids);
2044 /* Found relid must not be in joinrelids. */
2045 if (bms_is_member(relid, joinrelids))
2047 parse_ereport(lhint->base.hint_str,
2048 ("Relation name \"%s\" is duplicated.", relname));
2049 lhint->base.state = HINT_STATE_ERROR;
2050 bms_free(joinrelids);
2054 /* Create bitmap of relids for current join level. */
2055 joinrelids = bms_add_member(joinrelids, relid);
2058 /* We never have join method hint for single relation. */
2063 * If we don't have join method hint, create new one for the
2064 * join combination with all join methods are enabled.
2066 hint = find_join_hint(joinrelids);
2070 * Here relnames is not set, since Relids bitmap is sufficient to
2071 * control paths of this query afterward.
2073 hint = (JoinMethodHint *) JoinMethodHintCreate(lhint->base.hint_str,
2075 hint->base.state = HINT_STATE_USED;
2076 hint->nrels = njoinrels;
2077 hint->enforce_mask = ENABLE_ALL_JOIN;
2078 hint->joinrelids = bms_copy(joinrelids);
2081 join_method_hints[njoinrels] = hint;
2083 if (njoinrels >= nbaserel)
2087 bms_free(joinrelids);
2093 * Delete all join hints which have different combination from Leading
2096 for (i = 2; i <= njoinrels; i++)
2098 list_free(hstate->join_hint_level[i]);
2100 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
2103 if (hint_state_enabled(lhint))
2104 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2106 lhint->base.state = HINT_STATE_USED;
2111 * set_plain_rel_pathlist
2112 * Build access paths for a plain relation (no subquery, no inheritance)
2114 * This function was copied and edited from set_plain_rel_pathlist() in
2115 * src/backend/optimizer/path/allpaths.c
2118 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2120 /* Consider sequential scan */
2121 #if PG_VERSION_NUM >= 90200
2122 add_path(rel, create_seqscan_path(root, rel, NULL));
2124 add_path(rel, create_seqscan_path(root, rel));
2127 /* Consider index scans */
2128 create_index_paths(root, rel);
2130 /* Consider TID scans */
2131 create_tidscan_paths(root, rel);
2133 /* Now find the cheapest of the paths for this rel */
2138 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
2143 foreach(l, initial_rels)
2145 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2147 ScanMethodHint *hint;
2149 /* Skip relations which we can't choose scan method. */
2150 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2153 rte = root->simple_rte_array[rel->relid];
2155 /* We can't force scan method of foreign tables */
2156 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2160 * Create scan paths with GUC parameters which are at the beginning of
2161 * planner if scan method hint is not specified, otherwise use
2162 * specified hints and mark the hint as used.
2164 if ((hint = find_scan_hint(root, rel)) == NULL)
2165 set_scan_config_options(hstate->init_scan_mask,
2169 set_scan_config_options(hint->enforce_mask, hstate->context);
2170 hint->base.state = HINT_STATE_USED;
2173 list_free_deep(rel->pathlist);
2174 rel->pathlist = NIL;
2177 /* It's an "append relation", process accordingly */
2178 set_append_rel_pathlist(root, rel, rel->relid, rte);
2182 set_plain_rel_pathlist(root, rel, rte);
2187 * Restore the GUC variables we set above.
2189 set_scan_config_options(hstate->init_scan_mask, hstate->context);
2193 * wrapper of make_join_rel()
2195 * call make_join_rel() after changing enable_* parameters according to given
2199 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
2202 JoinMethodHint *hint;
2206 joinrelids = bms_union(rel1->relids, rel2->relids);
2207 hint = find_join_hint(joinrelids);
2208 bms_free(joinrelids);
2211 return pg_hint_plan_make_join_rel(root, rel1, rel2);
2213 save_nestlevel = NewGUCNestLevel();
2215 set_join_config_options(hint->enforce_mask, current_hint->context);
2217 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2218 hint->base.state = HINT_STATE_USED;
2221 * Restore the GUC variables we set above.
2223 AtEOXact_GUC(true, save_nestlevel);
2229 get_num_baserels(List *initial_rels)
2234 foreach(l, initial_rels)
2236 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2238 if (rel->reloptkind == RELOPT_BASEREL)
2240 else if (rel->reloptkind ==RELOPT_JOINREL)
2241 nbaserel+= bms_num_members(rel->relids);
2244 /* other values not expected here */
2245 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
2253 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
2256 JoinMethodHint **join_method_hints;
2262 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
2263 * valid hint is supplied.
2267 if (prev_join_search)
2268 return (*prev_join_search) (root, levels_needed, initial_rels);
2269 else if (enable_geqo && levels_needed >= geqo_threshold)
2270 return geqo(root, levels_needed, initial_rels);
2272 return standard_join_search(root, levels_needed, initial_rels);
2275 /* We apply scan method hint rebuild scan path. */
2276 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
2279 * In the case using GEQO, only scan method hints and Set hints have
2280 * effect. Join method and join order is not controllable by hints.
2282 if (enable_geqo && levels_needed >= geqo_threshold)
2283 return geqo(root, levels_needed, initial_rels);
2285 nbaserel = get_num_baserels(initial_rels);
2286 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
2287 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
2289 transform_join_hints(current_hint, root, nbaserel, initial_rels,
2292 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
2294 for (i = 2; i <= nbaserel; i++)
2296 list_free(current_hint->join_hint_level[i]);
2298 /* free Leading hint only */
2299 if (join_method_hints[i] != NULL &&
2300 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
2301 JoinMethodHintDelete(join_method_hints[i]);
2303 pfree(current_hint->join_hint_level);
2304 pfree(join_method_hints);
2306 if (current_hint->num_hints[HINT_TYPE_LEADING] > 0 &&
2307 hint_state_enabled(current_hint->leading_hint))
2308 set_join_config_options(current_hint->init_join_mask,
2309 current_hint->context);
2316 * Build access paths for a base relation
2318 * This function was copied and edited from set_rel_pathlist() in
2319 * src/backend/optimizer/path/allpaths.c
2322 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
2323 Index rti, RangeTblEntry *rte)
2325 #if PG_VERSION_NUM >= 90200
2326 if (IS_DUMMY_REL(rel))
2328 /* We already proved the relation empty, so nothing more to do */
2335 /* It's an "append relation", process accordingly */
2336 set_append_rel_pathlist(root, rel, rti, rte);
2340 if (rel->rtekind == RTE_RELATION)
2342 if (rte->relkind == RELKIND_RELATION)
2344 /* Plain relation */
2345 set_plain_rel_pathlist(root, rel, rte);
2348 elog(ERROR, "unexpected relkind: %c", rte->relkind);
2351 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
2355 #define standard_join_search pg_hint_plan_standard_join_search
2356 #define join_search_one_level pg_hint_plan_join_search_one_level
2357 #define make_join_rel make_join_rel_wrapper
2360 #undef make_join_rel
2361 #define make_join_rel pg_hint_plan_make_join_rel
2362 #define add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype, sjinfo, restrictlist) \
2364 ScanMethodHint *hint = NULL; \
2365 if ((hint = find_scan_hint((root), (innerrel))) != NULL) \
2367 set_scan_config_options(hint->enforce_mask, current_hint->context); \
2368 hint->base.state = HINT_STATE_USED; \
2370 add_paths_to_joinrel((root), (joinrel), (outerrel), (innerrel), (jointype), (sjinfo), (restrictlist)); \
2372 set_scan_config_options(current_hint->init_scan_mask, current_hint->context); \
2374 #include "make_join_rel.c"