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, char *value_type, bool truncate)
900 /* Skip leading spaces. */
903 initStringInfo(&buf);
916 /* Double quotation must be closed. */
920 parse_ereport(str, ("Unterminated quoted %s.", value_type));
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++);
951 type = pstrdup(value_type);
952 type[0] = toupper(type[0]);
953 parse_ereport(str, ("%s is necessary.", type));
961 /* Truncate name if it's too long */
963 truncate_identifier(buf.data, strlen(buf.data), true);
971 parse_hints(HintState *hstate, Query *parse, const char *str)
976 initStringInfo(&buf);
979 const HintParser *parser;
981 /* in error message, we output the comment including the keyword. */
984 /* parse only the keyword of the hint. */
985 resetStringInfo(&buf);
986 str = parse_keyword(str, &buf);
988 for (parser = parsers; parser->keyword != NULL; parser++)
990 char *keyword = parser->keyword;
993 if (strcasecmp(buf.data, keyword) != 0)
996 hint = parser->create_func(head, keyword);
998 /* parser of each hint does parse in a parenthesis. */
999 if ((str = skip_opened_parenthesis(str)) == NULL ||
1000 (str = hint->parser_func(hint, hstate, parse, str)) == NULL ||
1001 (str = skip_closed_parenthesis(str)) == NULL)
1003 hint->delete_func(hint);
1009 * Add hint information into all_hints array. If we don't have
1010 * enough space, double the array.
1012 if (hstate->nall_hints == 0)
1014 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1015 hstate->all_hints = (Hint **)
1016 palloc(sizeof(Hint *) * hstate->max_all_hints);
1018 else if (hstate->nall_hints == hstate->max_all_hints)
1020 hstate->max_all_hints *= 2;
1021 hstate->all_hints = (Hint **)
1022 repalloc(hstate->all_hints,
1023 sizeof(Hint *) * hstate->max_all_hints);
1026 hstate->all_hints[hstate->nall_hints] = hint;
1027 hstate->nall_hints++;
1034 if (parser->keyword == NULL)
1037 ("Unrecognized hint keyword \"%s\".", buf.data));
1047 * Do basic parsing of the query head comment.
1050 parse_head_comment(Query *parse)
1059 /* get client-supplied query string. */
1062 PreparedStatement *entry;
1064 entry = FetchPreparedStatement(stmt_name, true);
1065 p = entry->plansource->query_string;
1068 p = debug_query_string;
1073 /* extract query head comment. */
1074 len = strlen(HINT_START);
1076 if (strncmp(p, HINT_START, len))
1083 /* find hint end keyword. */
1084 if ((tail = strstr(p, HINT_END)) == NULL)
1086 parse_ereport(head, ("Unterminated block comment."));
1090 /* We don't support nested block comments. */
1091 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1093 parse_ereport(head, ("Nested block comments are not supported."));
1097 /* Make a copy of hint. */
1099 head = palloc(len + 1);
1100 memcpy(head, p, len);
1104 hstate = HintStateCreate();
1105 hstate->hint_str = head;
1107 /* parse each hint. */
1108 parse_hints(hstate, parse, p);
1110 /* When nothing specified a hint, we free HintState and returns NULL. */
1111 if (hstate->nall_hints == 0)
1113 HintStateDelete(hstate);
1117 /* Sort hints in order of original position. */
1118 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1122 * If we have hints which are specified for an object, mark preceding one
1123 * as 'duplicated' to ignore it in planner phase.
1125 for (i = 0; i < hstate->nall_hints; i++)
1127 Hint *cur_hint = hstate->all_hints[i];
1130 /* Count up hints per hint-type. */
1131 hstate->num_hints[cur_hint->type]++;
1133 /* If we don't have next, nothing to compare. */
1134 if (i + 1 >= hstate->nall_hints)
1136 next_hint = hstate->all_hints[i + 1];
1139 * We need to pass address of hint pointers, because HintCmp has
1140 * been designed to be used with qsort.
1142 if (HintCmp(&cur_hint, &next_hint) == 0)
1144 parse_ereport(cur_hint->hint_str,
1145 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1146 cur_hint->state = HINT_STATE_DUPLICATION;
1151 * Make sure that per-type array pointers point proper position in the
1152 * array which consists of all hints.
1154 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1155 hstate->join_hints = (JoinMethodHint **) hstate->all_hints +
1156 hstate->num_hints[HINT_TYPE_SCAN_METHOD];
1157 hstate->leading_hint = (LeadingHint *) hstate->all_hints[
1158 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1159 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1160 hstate->num_hints[HINT_TYPE_LEADING] - 1];
1161 hstate->set_hints = (SetHint **) hstate->all_hints +
1162 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1163 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1164 hstate->num_hints[HINT_TYPE_LEADING];
1170 * Parse inside of parentheses of scan-method hints.
1173 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1176 const char *keyword = hint->base.keyword;
1178 /* Given hint is invalid if relation name can't be parsed. */
1179 if ((str = parse_quote_value(str, &hint->relname, "relation name", true))
1185 /* Parse index name(s) if given hint accepts. */
1186 if (strcmp(keyword, HINT_INDEXSCAN) == 0 ||
1187 #if PG_VERSION_NUM >= 90200
1188 strcmp(keyword, HINT_INDEXONLYSCAN) == 0 ||
1190 strcmp(keyword, HINT_BITMAPSCAN) == 0)
1192 while (*str != ')' && *str != '\0')
1196 str = parse_quote_value(str, &indexname, "index name", true);
1200 hint->indexnames = lappend(hint->indexnames, indexname);
1205 /* Set a bit for specified hint. */
1206 if (strcasecmp(keyword, HINT_SEQSCAN) == 0)
1207 hint->enforce_mask = ENABLE_SEQSCAN;
1208 else if (strcasecmp(keyword, HINT_INDEXSCAN) == 0)
1209 hint->enforce_mask = ENABLE_INDEXSCAN;
1210 else if (strcasecmp(keyword, HINT_BITMAPSCAN) == 0)
1211 hint->enforce_mask = ENABLE_BITMAPSCAN;
1212 else if (strcasecmp(keyword, HINT_TIDSCAN) == 0)
1213 hint->enforce_mask = ENABLE_TIDSCAN;
1214 else if (strcasecmp(keyword, HINT_NOSEQSCAN) == 0)
1215 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1216 else if (strcasecmp(keyword, HINT_NOINDEXSCAN) == 0)
1217 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1218 else if (strcasecmp(keyword, HINT_NOBITMAPSCAN) == 0)
1219 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1220 else if (strcasecmp(keyword, HINT_NOTIDSCAN) == 0)
1221 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1222 #if PG_VERSION_NUM >= 90200
1223 else if (strcasecmp(keyword, HINT_INDEXONLYSCAN) == 0)
1224 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1225 else if (strcasecmp(keyword, HINT_NOINDEXONLYSCAN) == 0)
1226 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1230 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1238 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1242 const char *keyword = hint->base.keyword;
1246 hint->relnames = palloc(sizeof(char *));
1248 while ((str = parse_quote_value(str, &relname, "relation name", true))
1252 hint->relnames = repalloc(hint->relnames, sizeof(char *) * hint->nrels);
1253 hint->relnames[hint->nrels - 1] = relname;
1263 /* A join hint requires at least two relations to be specified. */
1264 if (hint->nrels < 2)
1267 ("%s hint requires at least two relations.",
1268 hint->base.keyword));
1269 hint->base.state = HINT_STATE_ERROR;
1272 /* Sort hints in alphabetical order of relation names. */
1273 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1275 if (strcasecmp(keyword, HINT_NESTLOOP) == 0)
1276 hint->enforce_mask = ENABLE_NESTLOOP;
1277 else if (strcasecmp(keyword, HINT_MERGEJOIN) == 0)
1278 hint->enforce_mask = ENABLE_MERGEJOIN;
1279 else if (strcasecmp(keyword, HINT_HASHJOIN) == 0)
1280 hint->enforce_mask = ENABLE_HASHJOIN;
1281 else if (strcasecmp(keyword, HINT_NONESTLOOP) == 0)
1282 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1283 else if (strcasecmp(keyword, HINT_NOMERGEJOIN) == 0)
1284 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1285 else if (strcasecmp(keyword, HINT_NOHASHJOIN) == 0)
1286 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1289 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1297 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1306 if ((str = parse_quote_value(str, &relname, "relation name", true))
1310 hint->relations = lappend(hint->relations, relname);
1315 /* A Leading hint requires at least two relations to be specified. */
1316 if (list_length(hint->relations) < 2)
1318 parse_ereport(hint->base.hint_str,
1319 ("%s hint requires at least two relations.",
1321 hint->base.state = HINT_STATE_ERROR;
1328 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1330 if ((str = parse_quote_value(str, &hint->name, "parameter name", true))
1332 (str = parse_quote_value(str, &hint->value, "parameter value", false))
1340 * set GUC parameter functions
1344 set_config_option_wrapper(const char *name, const char *value,
1345 GucContext context, GucSource source,
1346 GucAction action, bool changeVal, int elevel)
1349 MemoryContext ccxt = CurrentMemoryContext;
1353 #if PG_VERSION_NUM >= 90200
1354 result = set_config_option(name, value, context, source,
1355 action, changeVal, 0);
1357 result = set_config_option(name, value, context, source,
1365 /* Save error info */
1366 MemoryContextSwitchTo(ccxt);
1367 errdata = CopyErrorData();
1370 ereport(elevel, (errcode(errdata->sqlerrcode),
1371 errmsg("%s", errdata->message),
1372 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1373 errdata->hint ? errhint("%s", errdata->hint) : 0));
1374 FreeErrorData(errdata);
1382 set_config_options(SetHint **options, int noptions, GucContext context)
1387 save_nestlevel = NewGUCNestLevel();
1389 for (i = 0; i < noptions; i++)
1391 SetHint *hint = options[i];
1394 if (!hint_state_enabled(hint))
1397 result = set_config_option_wrapper(hint->name, hint->value, context,
1398 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1399 pg_hint_plan_parse_messages);
1401 hint->base.state = HINT_STATE_USED;
1403 hint->base.state = HINT_STATE_ERROR;
1406 return save_nestlevel;
1409 #define SET_CONFIG_OPTION(name, type_bits) \
1410 set_config_option_wrapper((name), \
1411 (mask & (type_bits)) ? "true" : "false", \
1412 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1415 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1419 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1420 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1421 #if PG_VERSION_NUM >= 90200
1422 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1425 mask = enforce_mask;
1427 mask = enforce_mask & current_hint->init_scan_mask;
1429 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1430 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1431 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1432 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1433 #if PG_VERSION_NUM >= 90200
1434 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1439 set_join_config_options(unsigned char enforce_mask, GucContext context)
1443 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1444 enforce_mask == ENABLE_HASHJOIN)
1445 mask = enforce_mask;
1447 mask = enforce_mask & current_hint->init_join_mask;
1449 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1450 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1451 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1455 * pg_hint_plan hook functions
1459 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1460 ParamListInfo params, bool isTopLevel,
1461 DestReceiver *dest, char *completionTag)
1465 if (!pg_hint_plan_enable_hint)
1467 if (prev_ProcessUtility)
1468 (*prev_ProcessUtility) (parsetree, queryString, params,
1469 isTopLevel, dest, completionTag);
1471 standard_ProcessUtility(parsetree, queryString, params,
1472 isTopLevel, dest, completionTag);
1478 if (IsA(node, ExplainStmt))
1481 * Draw out parse tree of actual query from Query struct of EXPLAIN
1487 stmt = (ExplainStmt *) node;
1489 Assert(IsA(stmt->query, Query));
1490 query = (Query *) stmt->query;
1492 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1493 node = query->utilityStmt;
1497 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
1498 * specified to preceding PREPARE command to use it as source of hints.
1500 if (IsA(node, ExecuteStmt))
1504 stmt = (ExecuteStmt *) node;
1505 stmt_name = stmt->name;
1507 #if PG_VERSION_NUM >= 90200
1509 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
1512 if (IsA(node, CreateTableAsStmt))
1514 CreateTableAsStmt *stmt;
1517 stmt = (CreateTableAsStmt *) node;
1518 Assert(IsA(stmt->query, Query));
1519 query = (Query *) stmt->query;
1521 if (query->commandType == CMD_UTILITY &&
1522 IsA(query->utilityStmt, ExecuteStmt))
1524 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
1525 stmt_name = estmt->name;
1533 if (prev_ProcessUtility)
1534 (*prev_ProcessUtility) (parsetree, queryString, params,
1535 isTopLevel, dest, completionTag);
1537 standard_ProcessUtility(parsetree, queryString, params,
1538 isTopLevel, dest, completionTag);
1552 if (prev_ProcessUtility)
1553 (*prev_ProcessUtility) (parsetree, queryString, params,
1554 isTopLevel, dest, completionTag);
1556 standard_ProcessUtility(parsetree, queryString, params,
1557 isTopLevel, dest, completionTag);
1561 * Push a hint into hint stack which is implemented with List struct. Head of
1562 * list is top of stack.
1565 push_hint(HintState *hstate)
1567 /* Prepend new hint to the list means pushing to stack. */
1568 HintStateStack = lcons(hstate, HintStateStack);
1570 /* Pushed hint is the one which should be used hereafter. */
1571 current_hint = hstate;
1574 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
1578 /* Hint stack must not be empty. */
1579 if(HintStateStack == NIL)
1580 elog(ERROR, "hint stack is empty");
1583 * Take a hint at the head from the list, and free it. Switch current_hint
1584 * to point new head (NULL if the list is empty).
1586 HintStateStack = list_delete_first(HintStateStack);
1587 HintStateDelete(current_hint);
1588 if(HintStateStack == NIL)
1589 current_hint = NULL;
1591 current_hint = (HintState *) lfirst(list_head(HintStateStack));
1594 static PlannedStmt *
1595 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1598 PlannedStmt *result;
1602 * Use standard planner if pg_hint_plan is disabled. Other hook functions
1603 * try to change plan with current_hint if any, so set it to NULL.
1605 if (!pg_hint_plan_enable_hint)
1607 current_hint = NULL;
1610 return (*prev_planner) (parse, cursorOptions, boundParams);
1612 return standard_planner(parse, cursorOptions, boundParams);
1615 /* Create hint struct from parse tree. */
1616 hstate = parse_head_comment(parse);
1619 * Use standard planner if the statement has not valid hint. Other hook
1620 * functions try to change plan with current_hint if any, so set it to
1625 current_hint = NULL;
1628 return (*prev_planner) (parse, cursorOptions, boundParams);
1630 return standard_planner(parse, cursorOptions, boundParams);
1634 * Push new hint struct to the hint stack to disable previous hint context.
1638 /* Set GUC parameters which are specified with Set hint. */
1639 save_nestlevel = set_config_options(current_hint->set_hints,
1640 current_hint->num_hints[HINT_TYPE_SET],
1641 current_hint->context);
1644 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
1645 if (enable_indexscan)
1646 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
1647 if (enable_bitmapscan)
1648 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
1650 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
1651 #if PG_VERSION_NUM >= 90200
1652 if (enable_indexonlyscan)
1653 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
1655 if (enable_nestloop)
1656 current_hint->init_join_mask |= ENABLE_NESTLOOP;
1657 if (enable_mergejoin)
1658 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
1659 if (enable_hashjoin)
1660 current_hint->init_join_mask |= ENABLE_HASHJOIN;
1663 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
1664 * state when this planner started when error occurred in planner.
1669 result = (*prev_planner) (parse, cursorOptions, boundParams);
1671 result = standard_planner(parse, cursorOptions, boundParams);
1676 * Rollback changes of GUC parameters, and pop current hint context
1677 * from hint stack to rewind the state.
1679 AtEOXact_GUC(true, save_nestlevel);
1685 /* Print hint in debug mode. */
1686 if (pg_hint_plan_debug_print)
1687 HintStateDump(current_hint);
1690 * Rollback changes of GUC parameters, and pop current hint context from
1691 * hint stack to rewind the state.
1693 AtEOXact_GUC(true, save_nestlevel);
1700 * Return scan method hint which matches given aliasname.
1702 static ScanMethodHint *
1703 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
1709 * We can't apply scan method hint if the relation is:
1710 * - not a base relation
1711 * - not an ordinary relation (such as join and subquery)
1713 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
1716 rte = root->simple_rte_array[rel->relid];
1718 /* We can't force scan method of foreign tables */
1719 if (rte->relkind == RELKIND_FOREIGN_TABLE)
1722 /* Find scan method hint, which matches given names, from the list. */
1723 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1725 ScanMethodHint *hint = current_hint->scan_hints[i];
1727 /* We ignore disabled hints. */
1728 if (!hint_state_enabled(hint))
1731 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
1739 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel)
1746 * We delete all the IndexOptInfo list and prevent you from being usable by
1749 if (hint->enforce_mask == ENABLE_SEQSCAN ||
1750 hint->enforce_mask == ENABLE_TIDSCAN)
1752 list_free_deep(rel->indexlist);
1753 rel->indexlist = NIL;
1754 hint->base.state = HINT_STATE_USED;
1760 * When a list of indexes is not specified, we just use all indexes.
1762 if (hint->indexnames == NIL)
1766 * Leaving only an specified index, we delete it from a IndexOptInfo list
1770 for (cell = list_head(rel->indexlist); cell; cell = next)
1772 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
1773 char *indexname = get_rel_name(info->indexoid);
1775 bool use_index = false;
1779 foreach(l, hint->indexnames)
1781 if (RelnameCmp(&indexname, &lfirst(l)) == 0)
1789 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
1798 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
1799 bool inhparent, RelOptInfo *rel)
1801 ScanMethodHint *hint;
1803 if (prev_get_relation_info)
1804 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
1806 /* Do nothing if we don't have valid hint in this context. */
1812 /* store does relids of parent table. */
1813 current_hint->parent_relid = rel->relid;
1815 else if (current_hint->parent_relid != 0)
1818 * We use the same GUC parameter if this table is the child table of a
1819 * table called pg_hint_plan_get_relation_info just before that.
1823 /* append_rel_list contains all append rels; ignore others */
1824 foreach(l, root->append_rel_list)
1826 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1828 /* This rel is child table. */
1829 if (appinfo->parent_relid == current_hint->parent_relid &&
1830 appinfo->child_relid == rel->relid)
1832 if (current_hint->parent_hint)
1833 delete_indexes(current_hint->parent_hint, rel);
1839 /* This rel is not inherit table. */
1840 current_hint->parent_relid = 0;
1841 current_hint->parent_hint = NULL;
1845 * If scan method hint was given, reset GUC parameters which control
1846 * planner behavior about choosing scan methods.
1848 if ((hint = find_scan_hint(root, rel)) == NULL)
1850 set_scan_config_options(current_hint->init_scan_mask,
1851 current_hint->context);
1854 set_scan_config_options(hint->enforce_mask, current_hint->context);
1855 hint->base.state = HINT_STATE_USED;
1857 current_hint->parent_hint = hint;
1859 delete_indexes(hint, rel);
1863 * Return index of relation which matches given aliasname, or 0 if not found.
1864 * If same aliasname was used multiple times in a query, return -1.
1867 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
1873 for (i = 1; i < root->simple_rel_array_size; i++)
1877 if (root->simple_rel_array[i] == NULL)
1880 Assert(i == root->simple_rel_array[i]->relid);
1882 if (RelnameCmp(&aliasname,
1883 &root->simple_rte_array[i]->eref->aliasname) != 0)
1886 foreach(l, initial_rels)
1888 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
1890 if (rel->reloptkind == RELOPT_BASEREL)
1892 if (rel->relid != i)
1897 Assert(rel->reloptkind == RELOPT_JOINREL);
1899 if (!bms_is_member(i, rel->relids))
1906 ("Relation name \"%s\" is ambiguous.",
1921 * Return join hint which matches given joinrelids.
1923 static JoinMethodHint *
1924 find_join_hint(Relids joinrelids)
1929 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
1931 foreach(l, join_hint)
1933 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
1935 if (bms_equal(joinrelids, hint->joinrelids))
1943 * Transform join method hint into handy form.
1945 * - create bitmap of relids from alias names, to make it easier to check
1946 * whether a join path matches a join method hint.
1947 * - add join method hints which are necessary to enforce join order
1948 * specified by Leading hint
1951 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
1952 List *initial_rels, JoinMethodHint **join_method_hints)
1962 * Create bitmap of relids from alias names for each join method hint.
1963 * Bitmaps are more handy than strings in join searching.
1965 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
1967 JoinMethodHint *hint = hstate->join_hints[i];
1970 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
1973 bms_free(hint->joinrelids);
1974 hint->joinrelids = NULL;
1976 for (j = 0; j < hint->nrels; j++)
1978 char *relname = hint->relnames[j];
1980 relid = find_relid_aliasname(root, relname, initial_rels,
1981 hint->base.hint_str);
1984 hint->base.state = HINT_STATE_ERROR;
1989 if (bms_is_member(relid, hint->joinrelids))
1991 parse_ereport(hint->base.hint_str,
1992 ("Relation name \"%s\" is duplicated.", relname));
1993 hint->base.state = HINT_STATE_ERROR;
1997 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
2000 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
2003 hstate->join_hint_level[hint->nrels] =
2004 lappend(hstate->join_hint_level[hint->nrels], hint);
2007 /* Do nothing if no Leading hint was supplied. */
2008 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2011 /* Do nothing if Leading hint is invalid. */
2012 lhint = hstate->leading_hint;
2013 if (!hint_state_enabled(lhint))
2017 * We need join method hints which fit specified join order in every join
2018 * level. For example, Leading(A B C) virtually requires following join
2019 * method hints, if no join method hint supplied:
2021 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
2022 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
2024 * If we already have join method hint which fits specified join order in
2025 * that join level, we leave it as-is and don't add new hints.
2029 foreach(l, lhint->relations)
2031 char *relname = (char *)lfirst(l);
2032 JoinMethodHint *hint;
2035 * Find relid of the relation which has given name. If we have the
2036 * name given in Leading hint multiple times in the join, nothing to
2039 relid = find_relid_aliasname(root, relname, initial_rels,
2043 bms_free(joinrelids);
2049 /* Found relid must not be in joinrelids. */
2050 if (bms_is_member(relid, joinrelids))
2052 parse_ereport(lhint->base.hint_str,
2053 ("Relation name \"%s\" is duplicated.", relname));
2054 lhint->base.state = HINT_STATE_ERROR;
2055 bms_free(joinrelids);
2059 /* Create bitmap of relids for current join level. */
2060 joinrelids = bms_add_member(joinrelids, relid);
2063 /* We never have join method hint for single relation. */
2068 * If we don't have join method hint, create new one for the
2069 * join combination with all join methods are enabled.
2071 hint = find_join_hint(joinrelids);
2075 * Here relnames is not set, since Relids bitmap is sufficient to
2076 * control paths of this query afterward.
2078 hint = (JoinMethodHint *) JoinMethodHintCreate(lhint->base.hint_str,
2080 hint->base.state = HINT_STATE_USED;
2081 hint->nrels = njoinrels;
2082 hint->enforce_mask = ENABLE_ALL_JOIN;
2083 hint->joinrelids = bms_copy(joinrelids);
2086 join_method_hints[njoinrels] = hint;
2088 if (njoinrels >= nbaserel)
2092 bms_free(joinrelids);
2098 * Delete all join hints which have different combination from Leading
2101 for (i = 2; i <= njoinrels; i++)
2103 list_free(hstate->join_hint_level[i]);
2105 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
2108 if (hint_state_enabled(lhint))
2109 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2111 lhint->base.state = HINT_STATE_USED;
2116 * set_plain_rel_pathlist
2117 * Build access paths for a plain relation (no subquery, no inheritance)
2119 * This function was copied and edited from set_plain_rel_pathlist() in
2120 * src/backend/optimizer/path/allpaths.c
2123 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2125 /* Consider sequential scan */
2126 #if PG_VERSION_NUM >= 90200
2127 add_path(rel, create_seqscan_path(root, rel, NULL));
2129 add_path(rel, create_seqscan_path(root, rel));
2132 /* Consider index scans */
2133 create_index_paths(root, rel);
2135 /* Consider TID scans */
2136 create_tidscan_paths(root, rel);
2138 /* Now find the cheapest of the paths for this rel */
2143 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
2148 foreach(l, initial_rels)
2150 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2152 ScanMethodHint *hint;
2154 /* Skip relations which we can't choose scan method. */
2155 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2158 rte = root->simple_rte_array[rel->relid];
2160 /* We can't force scan method of foreign tables */
2161 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2165 * Create scan paths with GUC parameters which are at the beginning of
2166 * planner if scan method hint is not specified, otherwise use
2167 * specified hints and mark the hint as used.
2169 if ((hint = find_scan_hint(root, rel)) == NULL)
2170 set_scan_config_options(hstate->init_scan_mask,
2174 set_scan_config_options(hint->enforce_mask, hstate->context);
2175 hint->base.state = HINT_STATE_USED;
2178 list_free_deep(rel->pathlist);
2179 rel->pathlist = NIL;
2182 /* It's an "append relation", process accordingly */
2183 set_append_rel_pathlist(root, rel, rel->relid, rte);
2187 set_plain_rel_pathlist(root, rel, rte);
2192 * Restore the GUC variables we set above.
2194 set_scan_config_options(hstate->init_scan_mask, hstate->context);
2198 * wrapper of make_join_rel()
2200 * call make_join_rel() after changing enable_* parameters according to given
2204 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
2207 JoinMethodHint *hint;
2211 joinrelids = bms_union(rel1->relids, rel2->relids);
2212 hint = find_join_hint(joinrelids);
2213 bms_free(joinrelids);
2216 return pg_hint_plan_make_join_rel(root, rel1, rel2);
2218 save_nestlevel = NewGUCNestLevel();
2220 set_join_config_options(hint->enforce_mask, current_hint->context);
2222 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2223 hint->base.state = HINT_STATE_USED;
2226 * Restore the GUC variables we set above.
2228 AtEOXact_GUC(true, save_nestlevel);
2234 get_num_baserels(List *initial_rels)
2239 foreach(l, initial_rels)
2241 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2243 if (rel->reloptkind == RELOPT_BASEREL)
2245 else if (rel->reloptkind ==RELOPT_JOINREL)
2246 nbaserel+= bms_num_members(rel->relids);
2249 /* other values not expected here */
2250 elog(ERROR, "Unrecognized reloptkind type: %d", rel->reloptkind);
2258 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
2261 JoinMethodHint **join_method_hints;
2267 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
2268 * valid hint is supplied.
2272 if (prev_join_search)
2273 return (*prev_join_search) (root, levels_needed, initial_rels);
2274 else if (enable_geqo && levels_needed >= geqo_threshold)
2275 return geqo(root, levels_needed, initial_rels);
2277 return standard_join_search(root, levels_needed, initial_rels);
2280 /* We apply scan method hint rebuild scan path. */
2281 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
2284 * In the case using GEQO, only scan method hints and Set hints have
2285 * effect. Join method and join order is not controllable by hints.
2287 if (enable_geqo && levels_needed >= geqo_threshold)
2288 return geqo(root, levels_needed, initial_rels);
2290 nbaserel = get_num_baserels(initial_rels);
2291 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
2292 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
2294 transform_join_hints(current_hint, root, nbaserel, initial_rels,
2297 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
2299 for (i = 2; i <= nbaserel; i++)
2301 list_free(current_hint->join_hint_level[i]);
2303 /* free Leading hint only */
2304 if (join_method_hints[i] != NULL &&
2305 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
2306 JoinMethodHintDelete(join_method_hints[i]);
2308 pfree(current_hint->join_hint_level);
2309 pfree(join_method_hints);
2311 if (current_hint->num_hints[HINT_TYPE_LEADING] > 0 &&
2312 hint_state_enabled(current_hint->leading_hint))
2313 set_join_config_options(current_hint->init_join_mask,
2314 current_hint->context);
2321 * Build access paths for a base relation
2323 * This function was copied and edited from set_rel_pathlist() in
2324 * src/backend/optimizer/path/allpaths.c
2327 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
2328 Index rti, RangeTblEntry *rte)
2330 #if PG_VERSION_NUM >= 90200
2331 if (IS_DUMMY_REL(rel))
2333 /* We already proved the relation empty, so nothing more to do */
2340 /* It's an "append relation", process accordingly */
2341 set_append_rel_pathlist(root, rel, rti, rte);
2345 if (rel->rtekind == RTE_RELATION)
2347 if (rte->relkind == RELKIND_RELATION)
2349 /* Plain relation */
2350 set_plain_rel_pathlist(root, rel, rte);
2353 elog(ERROR, "Unexpected relkind: %c", rte->relkind);
2356 elog(ERROR, "Unexpected rtekind: %d", (int) rel->rtekind);
2360 #define standard_join_search pg_hint_plan_standard_join_search
2361 #define join_search_one_level pg_hint_plan_join_search_one_level
2362 #define make_join_rel make_join_rel_wrapper
2365 #undef make_join_rel
2366 #define make_join_rel pg_hint_plan_make_join_rel
2367 #define add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype, sjinfo, restrictlist) \
2369 ScanMethodHint *hint = NULL; \
2370 if ((hint = find_scan_hint((root), (innerrel))) != NULL) \
2372 set_scan_config_options(hint->enforce_mask, current_hint->context); \
2373 hint->base.state = HINT_STATE_USED; \
2375 add_paths_to_joinrel((root), (joinrel), (outerrel), (innerrel), (jointype), (sjinfo), (restrictlist)); \
2377 set_scan_config_options(current_hint->init_scan_mask, current_hint->context); \
2379 #include "make_join_rel.c"