1 /*-------------------------------------------------------------------------
4 * do instructions or hints to the planner using C-style block comments
7 * Copyright (c) 2012-2013, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
9 *-------------------------------------------------------------------------
12 #include "catalog/pg_collation.h"
13 #include "catalog/pg_index.h"
14 #include "commands/prepare.h"
15 #include "mb/pg_wchar.h"
16 #include "miscadmin.h"
17 #include "nodes/nodeFuncs.h"
18 #include "optimizer/clauses.h"
19 #include "optimizer/cost.h"
20 #include "optimizer/geqo.h"
21 #include "optimizer/joininfo.h"
22 #include "optimizer/pathnode.h"
23 #include "optimizer/paths.h"
24 #include "optimizer/plancat.h"
25 #include "optimizer/planner.h"
26 #include "optimizer/prep.h"
27 #include "optimizer/restrictinfo.h"
28 #include "parser/scansup.h"
29 #include "tcop/utility.h"
30 #include "utils/builtins.h"
31 #include "utils/lsyscache.h"
32 #include "utils/memutils.h"
33 #include "utils/rel.h"
34 #include "utils/syscache.h"
35 #if PG_VERSION_NUM >= 90200
36 #include "catalog/pg_class.h"
39 #include "executor/spi.h"
40 #include "catalog/pg_type.h"
42 #ifdef PG_MODULE_MAGIC
46 #if PG_VERSION_NUM < 90100
47 #error unsupported PostgreSQL version
50 #define BLOCK_COMMENT_START "/*"
51 #define BLOCK_COMMENT_END "*/"
52 #define HINT_COMMENT_KEYWORD "+"
53 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
54 #define HINT_END BLOCK_COMMENT_END
57 #define HINT_SEQSCAN "SeqScan"
58 #define HINT_INDEXSCAN "IndexScan"
59 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
60 #define HINT_BITMAPSCAN "BitmapScan"
61 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
62 #define HINT_TIDSCAN "TidScan"
63 #define HINT_NOSEQSCAN "NoSeqScan"
64 #define HINT_NOINDEXSCAN "NoIndexScan"
65 #define HINT_NOBITMAPSCAN "NoBitmapScan"
66 #define HINT_NOTIDSCAN "NoTidScan"
67 #if PG_VERSION_NUM >= 90200
68 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
69 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
70 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
72 #define HINT_NESTLOOP "NestLoop"
73 #define HINT_MERGEJOIN "MergeJoin"
74 #define HINT_HASHJOIN "HashJoin"
75 #define HINT_NONESTLOOP "NoNestLoop"
76 #define HINT_NOMERGEJOIN "NoMergeJoin"
77 #define HINT_NOHASHJOIN "NoHashJoin"
78 #define HINT_LEADING "Leading"
79 #define HINT_SET "Set"
81 #define HINT_ARRAY_DEFAULT_INITSIZE 8
83 #define hint_ereport(str, detail) \
84 ereport(pg_hint_plan_parse_messages, \
85 (errmsg("hint syntax error at or near \"%s\"", (str)), \
88 #define skip_space(str) \
89 while (isspace(*str)) \
94 ENABLE_SEQSCAN = 0x01,
95 ENABLE_INDEXSCAN = 0x02,
96 ENABLE_BITMAPSCAN = 0x04,
97 ENABLE_TIDSCAN = 0x08,
98 #if PG_VERSION_NUM >= 90200
99 ENABLE_INDEXONLYSCAN = 0x10
105 ENABLE_NESTLOOP = 0x01,
106 ENABLE_MERGEJOIN = 0x02,
107 ENABLE_HASHJOIN = 0x04
110 #if PG_VERSION_NUM >= 90200
111 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
112 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
113 ENABLE_INDEXONLYSCAN)
115 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
116 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN)
118 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
119 #define DISABLE_ALL_SCAN 0
120 #define DISABLE_ALL_JOIN 0
122 /* hint keyword of enum type*/
123 typedef enum HintKeyword
125 HINT_KEYWORD_SEQSCAN,
126 HINT_KEYWORD_INDEXSCAN,
127 HINT_KEYWORD_INDEXSCANREGEXP,
128 HINT_KEYWORD_BITMAPSCAN,
129 HINT_KEYWORD_BITMAPSCANREGEXP,
130 HINT_KEYWORD_TIDSCAN,
131 HINT_KEYWORD_NOSEQSCAN,
132 HINT_KEYWORD_NOINDEXSCAN,
133 HINT_KEYWORD_NOBITMAPSCAN,
134 HINT_KEYWORD_NOTIDSCAN,
135 #if PG_VERSION_NUM >= 90200
136 HINT_KEYWORD_INDEXONLYSCAN,
137 HINT_KEYWORD_INDEXONLYSCANREGEXP,
138 HINT_KEYWORD_NOINDEXONLYSCAN,
140 HINT_KEYWORD_NESTLOOP,
141 HINT_KEYWORD_MERGEJOIN,
142 HINT_KEYWORD_HASHJOIN,
143 HINT_KEYWORD_NONESTLOOP,
144 HINT_KEYWORD_NOMERGEJOIN,
145 HINT_KEYWORD_NOHASHJOIN,
146 HINT_KEYWORD_LEADING,
148 HINT_KEYWORD_UNRECOGNIZED
151 typedef struct Hint Hint;
152 typedef struct HintState HintState;
154 typedef Hint *(*HintCreateFunction) (const char *hint_str,
156 HintKeyword hint_keyword);
157 typedef void (*HintDeleteFunction) (Hint *hint);
158 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf);
159 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
160 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
161 Query *parse, const char *str);
164 #define NUM_HINT_TYPE 4
165 typedef enum HintType
167 HINT_TYPE_SCAN_METHOD,
168 HINT_TYPE_JOIN_METHOD,
173 static const char *HintTypeName[] = {
181 typedef enum HintStatus
183 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
184 HINT_STATE_USED, /* hint is used */
185 HINT_STATE_DUPLICATION, /* specified hint duplication */
186 HINT_STATE_ERROR /* execute error (parse error does not include
190 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
191 (hint)->base.state == HINT_STATE_USED)
193 /* common data for all hints. */
196 const char *hint_str; /* must not do pfree */
197 const char *keyword; /* must not do pfree */
198 HintKeyword hint_keyword;
201 HintDeleteFunction delete_func;
202 HintDescFunction desc_func;
203 HintCmpFunction cmp_func;
204 HintParseFunction parse_func;
207 /* scan method hints */
208 typedef struct ScanMethodHint
214 unsigned char enforce_mask;
217 typedef struct ParentIndexInfo
222 char *expression_str;
229 /* join method hints */
230 typedef struct JoinMethodHint
236 unsigned char enforce_mask;
238 Relids inner_joinrelids;
241 /* join order hints */
242 typedef struct OuterInnerRels
245 List *outer_inner_pair;
248 typedef struct LeadingHint
251 List *relations; /* relation names specified in Leading hint */
252 OuterInnerRels *outer_inner;
255 /* change a run-time parameter hints */
256 typedef struct SetHint
259 char *name; /* name of variable */
265 * Describes a context of hint processing.
269 char *hint_str; /* original hint string */
272 int nall_hints; /* # of valid all hints */
273 int max_all_hints; /* # of slots for all hints */
274 Hint **all_hints; /* parsed all hints */
276 /* # of each hints */
277 int num_hints[NUM_HINT_TYPE];
279 /* for scan method hints */
280 ScanMethodHint **scan_hints; /* parsed scan hints */
281 int init_scan_mask; /* initial value scan parameter */
282 Index parent_relid; /* inherit parent table relid */
283 Oid parent_rel_oid; /* inherit parent table relid */
284 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
285 List *parent_index_infos; /* infomation of inherit parent table's
288 /* for join method hints */
289 JoinMethodHint **join_hints; /* parsed join hints */
290 int init_join_mask; /* initial value join parameter */
291 List **join_hint_level;
293 /* for Leading hint */
294 LeadingHint **leading_hint; /* parsed Leading hints */
297 SetHint **set_hints; /* parsed Set hints */
298 GucContext context; /* which GUC parameters can we set? */
302 * Describes a hint parser module which is bound with particular hint keyword.
304 typedef struct HintParser
307 HintCreateFunction create_func;
308 HintKeyword hint_keyword;
311 /* Module callbacks */
315 static void push_hint(HintState *hstate);
316 static void pop_hint(void);
318 static void pg_hint_plan_ProcessUtility(Node *parsetree,
319 const char *queryString,
320 ParamListInfo params, bool isTopLevel,
322 char *completionTag);
323 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
324 ParamListInfo boundParams);
325 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
326 Oid relationObjectId,
327 bool inhparent, RelOptInfo *rel);
328 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
332 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
333 HintKeyword hint_keyword);
334 static void ScanMethodHintDelete(ScanMethodHint *hint);
335 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf);
336 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
337 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
338 Query *parse, const char *str);
339 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
340 HintKeyword hint_keyword);
341 static void JoinMethodHintDelete(JoinMethodHint *hint);
342 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf);
343 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
344 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
345 Query *parse, const char *str);
346 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
347 HintKeyword hint_keyword);
348 static void LeadingHintDelete(LeadingHint *hint);
349 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf);
350 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
351 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
352 Query *parse, const char *str);
353 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
354 HintKeyword hint_keyword);
355 static void SetHintDelete(SetHint *hint);
356 static void SetHintDesc(SetHint *hint, StringInfo buf);
357 static int SetHintCmp(const SetHint *a, const SetHint *b);
358 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
361 static void quote_value(StringInfo buf, const char *value);
363 static const char *parse_quoted_value(const char *str, char **word,
366 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
369 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
370 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
371 ListCell *other_rels);
372 static void make_rels_by_clauseless_joins(PlannerInfo *root,
374 ListCell *other_rels);
375 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
376 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
377 Index rti, RangeTblEntry *rte);
378 #if PG_VERSION_NUM >= 90200
379 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
380 List *live_childrels,
381 List *all_child_pathkeys);
383 static List *accumulate_append_subpath(List *subpaths, Path *path);
384 #if PG_VERSION_NUM < 90200
385 static void set_dummy_rel_pathlist(RelOptInfo *rel);
387 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
391 static bool pg_hint_plan_enable_hint = true;
392 static bool pg_hint_plan_debug_print = false;
393 static int pg_hint_plan_parse_messages = INFO;
395 static const struct config_enum_entry parse_messages_level_options[] = {
396 {"debug", DEBUG2, true},
397 {"debug5", DEBUG5, false},
398 {"debug4", DEBUG4, false},
399 {"debug3", DEBUG3, false},
400 {"debug2", DEBUG2, false},
401 {"debug1", DEBUG1, false},
403 {"info", INFO, false},
404 {"notice", NOTICE, false},
405 {"warning", WARNING, false},
406 {"error", ERROR, false},
408 * {"fatal", FATAL, true},
409 * {"panic", PANIC, true},
414 /* Saved hook values in case of unload */
415 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
416 static planner_hook_type prev_planner = NULL;
417 static get_relation_info_hook_type prev_get_relation_info = NULL;
418 static join_search_hook_type prev_join_search = NULL;
420 /* Hold reference to currently active hint */
421 static HintState *current_hint = NULL;
424 * List of hint contexts. We treat the head of the list as the Top of the
425 * context stack, so current_hint always points the first element of this list.
427 static List *HintStateStack = NIL;
430 * Holds statement name during executing EXECUTE command. NULL for other
433 static char *stmt_name = NULL;
435 static const HintParser parsers[] = {
436 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
437 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
438 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
439 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
440 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
441 HINT_KEYWORD_BITMAPSCANREGEXP},
442 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
443 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
444 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
445 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
446 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
447 #if PG_VERSION_NUM >= 90200
448 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
449 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
450 HINT_KEYWORD_INDEXONLYSCANREGEXP},
451 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
453 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
454 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
455 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
456 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
457 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
458 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
459 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
460 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
461 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
465 static const char *search_query =
467 " FROM hint_plan.hints "
468 " WHERE norm_query_string = $1 "
469 " AND ( application_name = $2 "
470 " OR application_name = '' ) "
471 " ORDER BY application_name DESC";
474 * Module load callbacks
479 /* Define custom GUC variables. */
480 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
481 "Force planner to use plans specified in the hint comment preceding to the query.",
483 &pg_hint_plan_enable_hint,
491 DefineCustomBoolVariable("pg_hint_plan.debug_print",
492 "Logs results of hint parsing.",
494 &pg_hint_plan_debug_print,
502 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
503 "Message level of parse errors.",
505 &pg_hint_plan_parse_messages,
507 parse_messages_level_options,
515 prev_ProcessUtility = ProcessUtility_hook;
516 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
517 prev_planner = planner_hook;
518 planner_hook = pg_hint_plan_planner;
519 prev_get_relation_info = get_relation_info_hook;
520 get_relation_info_hook = pg_hint_plan_get_relation_info;
521 prev_join_search = join_search_hook;
522 join_search_hook = pg_hint_plan_join_search;
526 * Module unload callback
532 /* Uninstall hooks. */
533 ProcessUtility_hook = prev_ProcessUtility;
534 planner_hook = prev_planner;
535 get_relation_info_hook = prev_get_relation_info;
536 join_search_hook = prev_join_search;
540 * create and delete functions the hint object
544 ScanMethodHintCreate(const char *hint_str, const char *keyword,
545 HintKeyword hint_keyword)
547 ScanMethodHint *hint;
549 hint = palloc(sizeof(ScanMethodHint));
550 hint->base.hint_str = hint_str;
551 hint->base.keyword = keyword;
552 hint->base.hint_keyword = hint_keyword;
553 hint->base.type = HINT_TYPE_SCAN_METHOD;
554 hint->base.state = HINT_STATE_NOTUSED;
555 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
556 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
557 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
558 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
559 hint->relname = NULL;
560 hint->indexnames = NIL;
561 hint->regexp = false;
562 hint->enforce_mask = 0;
564 return (Hint *) hint;
568 ScanMethodHintDelete(ScanMethodHint *hint)
574 pfree(hint->relname);
575 list_free_deep(hint->indexnames);
580 JoinMethodHintCreate(const char *hint_str, const char *keyword,
581 HintKeyword hint_keyword)
583 JoinMethodHint *hint;
585 hint = palloc(sizeof(JoinMethodHint));
586 hint->base.hint_str = hint_str;
587 hint->base.keyword = keyword;
588 hint->base.hint_keyword = hint_keyword;
589 hint->base.type = HINT_TYPE_JOIN_METHOD;
590 hint->base.state = HINT_STATE_NOTUSED;
591 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
592 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
593 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
594 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
596 hint->inner_nrels = 0;
597 hint->relnames = NULL;
598 hint->enforce_mask = 0;
599 hint->joinrelids = NULL;
600 hint->inner_joinrelids = NULL;
602 return (Hint *) hint;
606 JoinMethodHintDelete(JoinMethodHint *hint)
615 for (i = 0; i < hint->nrels; i++)
616 pfree(hint->relnames[i]);
617 pfree(hint->relnames);
620 bms_free(hint->joinrelids);
621 bms_free(hint->inner_joinrelids);
626 LeadingHintCreate(const char *hint_str, const char *keyword,
627 HintKeyword hint_keyword)
631 hint = palloc(sizeof(LeadingHint));
632 hint->base.hint_str = hint_str;
633 hint->base.keyword = keyword;
634 hint->base.hint_keyword = hint_keyword;
635 hint->base.type = HINT_TYPE_LEADING;
636 hint->base.state = HINT_STATE_NOTUSED;
637 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
638 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
639 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
640 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
641 hint->relations = NIL;
642 hint->outer_inner = NULL;
644 return (Hint *) hint;
648 LeadingHintDelete(LeadingHint *hint)
653 list_free_deep(hint->relations);
654 if (hint->outer_inner)
655 pfree(hint->outer_inner);
660 SetHintCreate(const char *hint_str, const char *keyword,
661 HintKeyword hint_keyword)
665 hint = palloc(sizeof(SetHint));
666 hint->base.hint_str = hint_str;
667 hint->base.keyword = keyword;
668 hint->base.hint_keyword = hint_keyword;
669 hint->base.type = HINT_TYPE_SET;
670 hint->base.state = HINT_STATE_NOTUSED;
671 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
672 hint->base.desc_func = (HintDescFunction) SetHintDesc;
673 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
674 hint->base.parse_func = (HintParseFunction) SetHintParse;
679 return (Hint *) hint;
683 SetHintDelete(SetHint *hint)
693 list_free(hint->words);
698 HintStateCreate(void)
702 hstate = palloc(sizeof(HintState));
703 hstate->hint_str = NULL;
704 hstate->nall_hints = 0;
705 hstate->max_all_hints = 0;
706 hstate->all_hints = NULL;
707 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
708 hstate->scan_hints = NULL;
709 hstate->init_scan_mask = 0;
710 hstate->parent_relid = 0;
711 hstate->parent_rel_oid = InvalidOid;
712 hstate->parent_hint = NULL;
713 hstate->parent_index_infos = NIL;
714 hstate->join_hints = NULL;
715 hstate->init_join_mask = 0;
716 hstate->join_hint_level = NULL;
717 hstate->leading_hint = NULL;
718 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
719 hstate->set_hints = NULL;
725 HintStateDelete(HintState *hstate)
732 if (hstate->hint_str)
733 pfree(hstate->hint_str);
735 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
736 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
737 if (hstate->all_hints)
738 pfree(hstate->all_hints);
739 if (hstate->parent_index_infos)
740 list_free(hstate->parent_index_infos);
744 * Copy given value into buf, with quoting with '"' if necessary.
747 quote_value(StringInfo buf, const char *value)
749 bool need_quote = false;
752 for (str = value; *str != '\0'; str++)
754 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
757 appendStringInfoCharMacro(buf, '"');
762 for (str = value; *str != '\0'; str++)
765 appendStringInfoCharMacro(buf, '"');
767 appendStringInfoCharMacro(buf, *str);
771 appendStringInfoCharMacro(buf, '"');
775 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
779 appendStringInfo(buf, "%s(", hint->base.keyword);
780 if (hint->relname != NULL)
782 quote_value(buf, hint->relname);
783 foreach(l, hint->indexnames)
785 appendStringInfoCharMacro(buf, ' ');
786 quote_value(buf, (char *) lfirst(l));
789 appendStringInfoString(buf, ")\n");
793 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
797 appendStringInfo(buf, "%s(", hint->base.keyword);
798 if (hint->relnames != NULL)
800 quote_value(buf, hint->relnames[0]);
801 for (i = 1; i < hint->nrels; i++)
803 appendStringInfoCharMacro(buf, ' ');
804 quote_value(buf, hint->relnames[i]);
807 appendStringInfoString(buf, ")\n");
812 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
814 if (outer_inner->relation == NULL)
821 appendStringInfoCharMacro(buf, '(');
822 foreach(l, outer_inner->outer_inner_pair)
827 appendStringInfoCharMacro(buf, ' ');
829 OuterInnerDesc(lfirst(l), buf);
832 appendStringInfoCharMacro(buf, ')');
835 quote_value(buf, outer_inner->relation);
839 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
841 appendStringInfo(buf, "%s(", HINT_LEADING);
842 if (hint->outer_inner == NULL)
849 foreach(l, hint->relations)
854 appendStringInfoCharMacro(buf, ' ');
856 quote_value(buf, (char *) lfirst(l));
860 OuterInnerDesc(hint->outer_inner, buf);
862 appendStringInfoString(buf, ")\n");
866 SetHintDesc(SetHint *hint, StringInfo buf)
868 bool is_first = true;
871 appendStringInfo(buf, "%s(", HINT_SET);
872 foreach(l, hint->words)
877 appendStringInfoCharMacro(buf, ' ');
879 quote_value(buf, (char *) lfirst(l));
881 appendStringInfo(buf, ")\n");
885 * Append string which repserents all hints in a given state to buf, with
886 * preceding title with them.
889 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
894 appendStringInfo(buf, "%s:\n", title);
895 for (i = 0; i < hstate->nall_hints; i++)
897 if (hstate->all_hints[i]->state != state)
900 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf);
905 * Dump contents of given hstate to server log with log level LOG.
908 HintStateDump(HintState *hstate)
914 elog(LOG, "pg_hint_plan:\nno hint");
918 initStringInfo(&buf);
920 appendStringInfoString(&buf, "pg_hint_plan:\n");
921 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
922 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
923 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
924 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
926 elog(LOG, "%s", buf.data);
936 RelnameCmp(const void *a, const void *b)
938 const char *relnamea = *((const char **) a);
939 const char *relnameb = *((const char **) b);
941 return strcmp(relnamea, relnameb);
945 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
947 return RelnameCmp(&a->relname, &b->relname);
951 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
955 if (a->nrels != b->nrels)
956 return a->nrels - b->nrels;
958 for (i = 0; i < a->nrels; i++)
961 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
969 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
975 SetHintCmp(const SetHint *a, const SetHint *b)
977 return strcmp(a->name, b->name);
981 HintCmp(const void *a, const void *b)
983 const Hint *hinta = *((const Hint **) a);
984 const Hint *hintb = *((const Hint **) b);
986 if (hinta->type != hintb->type)
987 return hinta->type - hintb->type;
988 if (hinta->state == HINT_STATE_ERROR)
990 if (hintb->state == HINT_STATE_ERROR)
992 return hinta->cmp_func(hinta, hintb);
996 * Returns byte offset of hint b from hint a. If hint a was specified before
997 * b, positive value is returned.
1000 HintCmpWithPos(const void *a, const void *b)
1002 const Hint *hinta = *((const Hint **) a);
1003 const Hint *hintb = *((const Hint **) b);
1006 result = HintCmp(a, b);
1008 result = hinta->hint_str - hintb->hint_str;
1017 parse_keyword(const char *str, StringInfo buf)
1021 while (!isspace(*str) && *str != '(' && *str != '\0')
1022 appendStringInfoCharMacro(buf, *str++);
1028 skip_parenthesis(const char *str, char parenthesis)
1032 if (*str != parenthesis)
1034 if (parenthesis == '(')
1035 hint_ereport(str, ("Opening parenthesis is necessary."));
1036 else if (parenthesis == ')')
1037 hint_ereport(str, ("Closing parenthesis is necessary."));
1048 * Parse a token from str, and store malloc'd copy into word. A token can be
1049 * quoted with '"'. Return value is pointer to unparsed portion of original
1050 * string, or NULL if an error occurred.
1052 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1055 parse_quoted_value(const char *str, char **word, bool truncate)
1060 /* Skip leading spaces. */
1063 initStringInfo(&buf);
1076 /* Double quotation must be closed. */
1080 hint_ereport(str, ("Unterminated quoted string."));
1085 * Skip escaped double quotation.
1087 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1088 * block comments) to be an object name, so users must specify
1089 * alias for such object names.
1091 * Those special names can be allowed if we care escaped slashes
1092 * and asterisks, but we don't.
1101 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1105 appendStringInfoCharMacro(&buf, *str++);
1110 hint_ereport(str, ("Zero-length delimited string."));
1117 /* Truncate name if it's too long */
1119 truncate_identifier(buf.data, strlen(buf.data), true);
1126 static OuterInnerRels *
1127 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1129 OuterInnerRels *outer_inner;
1131 outer_inner = palloc(sizeof(OuterInnerRels));
1132 outer_inner->relation = name;
1133 outer_inner->outer_inner_pair = outer_inner_list;
1139 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1141 List *outer_inner_pair = NIL;
1143 if ((str = skip_parenthesis(str, '(')) == NULL)
1148 /* Store words in parentheses into outer_inner_list. */
1149 while(*str != ')' && *str != '\0')
1151 OuterInnerRels *outer_inner_rels;
1155 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1163 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1166 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1169 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1174 (str = skip_parenthesis(str, ')')) == NULL)
1176 list_free(outer_inner_pair);
1180 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1186 parse_parentheses_Leading(const char *str, List **name_list,
1187 OuterInnerRels **outer_inner)
1190 bool truncate = true;
1192 if ((str = skip_parenthesis(str, '(')) == NULL)
1198 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1203 /* Store words in parentheses into name_list. */
1204 while(*str != ')' && *str != '\0')
1206 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1208 list_free(*name_list);
1212 *name_list = lappend(*name_list, name);
1217 if ((str = skip_parenthesis(str, ')')) == NULL)
1223 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1226 bool truncate = true;
1228 if ((str = skip_parenthesis(str, '(')) == NULL)
1233 /* Store words in parentheses into name_list. */
1234 while(*str != ')' && *str != '\0')
1236 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1238 list_free(*name_list);
1242 *name_list = lappend(*name_list, name);
1245 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1246 #if PG_VERSION_NUM >= 90200
1247 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1249 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1250 keyword == HINT_KEYWORD_SET)
1256 if ((str = skip_parenthesis(str, ')')) == NULL)
1262 parse_hints(HintState *hstate, Query *parse, const char *str)
1267 initStringInfo(&buf);
1268 while (*str != '\0')
1270 const HintParser *parser;
1272 /* in error message, we output the comment including the keyword. */
1273 head = (char *) str;
1275 /* parse only the keyword of the hint. */
1276 resetStringInfo(&buf);
1277 str = parse_keyword(str, &buf);
1279 for (parser = parsers; parser->keyword != NULL; parser++)
1281 char *keyword = parser->keyword;
1284 if (strcasecmp(buf.data, keyword) != 0)
1287 hint = parser->create_func(head, keyword, parser->hint_keyword);
1289 /* parser of each hint does parse in a parenthesis. */
1290 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1292 hint->delete_func(hint);
1298 * Add hint information into all_hints array. If we don't have
1299 * enough space, double the array.
1301 if (hstate->nall_hints == 0)
1303 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1304 hstate->all_hints = (Hint **)
1305 palloc(sizeof(Hint *) * hstate->max_all_hints);
1307 else if (hstate->nall_hints == hstate->max_all_hints)
1309 hstate->max_all_hints *= 2;
1310 hstate->all_hints = (Hint **)
1311 repalloc(hstate->all_hints,
1312 sizeof(Hint *) * hstate->max_all_hints);
1315 hstate->all_hints[hstate->nall_hints] = hint;
1316 hstate->nall_hints++;
1323 if (parser->keyword == NULL)
1326 ("Unrecognized hint keyword \"%s\".", buf.data));
1340 const char *query_string,
1341 const char *app_name)
1343 static SPIPlanPtr plan = NULL;
1346 Oid argtypes[2] = { TEXTOID, TEXTOID };
1348 bool nulls[2] = { false, false };
1352 ret = SPI_connect();
1353 if (ret != SPI_OK_CONNECT)
1354 elog(ERROR, "pg_hint_plan: SPI_connect => %d", ret);
1359 p = SPI_prepare(query, 2, argtypes);
1361 elog(ERROR, "pg_hint_plan: SPI_prepare => %d", SPI_result);
1362 plan = SPI_saveplan(p);
1366 str = cstring_to_text(query_string);
1367 app = cstring_to_text(app_name);
1368 values[0] = PointerGetDatum(str);
1369 values[1] = PointerGetDatum(app);
1371 pg_hint_plan_enable_hint = false;
1372 ret = SPI_execute_plan(plan, values, nulls, true, 1);
1373 pg_hint_plan_enable_hint = true;
1374 if (ret != SPI_OK_SELECT)
1375 elog(ERROR, "pg_hint_plan: SPI_execute_plan => %d", ret);
1377 if (SPI_processed > 0)
1379 sprintf(buf, "%s", SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1));
1380 elog(LOG, "pg_hint_plan: SPI_execute_plan vals => %s", buf);
1383 elog(LOG, "pg_hint_plan: SPI_execute_plan rows => 0");
1387 return SPI_processed > 0;
1391 * Do basic parsing of the query head comment.
1394 parse_head_comment(Query *parse)
1397 const char *hint_head;
1404 /* get client-supplied query string. */
1407 PreparedStatement *entry;
1409 entry = FetchPreparedStatement(stmt_name, true);
1410 p = entry->plansource->query_string;
1413 p = debug_query_string;
1418 /* extract query head comment. */
1419 hint_head = strstr(p, HINT_START);
1420 if (hint_head == NULL)
1422 for (;p < hint_head; p++)
1425 * Allow these characters precedes hint comment:
1427 * - alphabets which are in ASCII range
1428 * - space, tabs and new-lines
1429 * - underscores, for identifier
1430 * - commas, for SELECT clause, EXPLAIN and PREPARE
1431 * - parentheses, for EXPLAIN and PREPARE
1433 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1434 * avoid behavior which depends on locale setting.
1436 if (!(*p >= '0' && *p <= '9') &&
1437 !(*p >= 'A' && *p <= 'Z') &&
1438 !(*p >= 'a' && *p <= 'z') &&
1442 *p != '(' && *p != ')')
1446 len = strlen(HINT_START);
1451 /* find hint end keyword. */
1452 if ((tail = strstr(p, HINT_END)) == NULL)
1454 hint_ereport(head, ("Unterminated block comment."));
1458 /* We don't support nested block comments. */
1459 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1461 hint_ereport(head, ("Nested block comments are not supported."));
1465 /* Make a copy of hint. */
1467 head = palloc(len + 1);
1468 memcpy(head, p, len);
1472 hstate = HintStateCreate();
1473 hstate->hint_str = head;
1475 /* parse each hint. */
1476 parse_hints(hstate, parse, p);
1478 /* When nothing specified a hint, we free HintState and returns NULL. */
1479 if (hstate->nall_hints == 0)
1481 HintStateDelete(hstate);
1485 /* Sort hints in order of original position. */
1486 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1489 /* Count number of hints per hint-type. */
1490 for (i = 0; i < hstate->nall_hints; i++)
1492 Hint *cur_hint = hstate->all_hints[i];
1493 hstate->num_hints[cur_hint->type]++;
1497 * If an object (or a set of objects) has multiple hints of same hint-type,
1498 * only the last hint is valid and others are igonred in planning.
1499 * Hints except the last are marked as 'duplicated' to remember the order.
1501 for (i = 0; i < hstate->nall_hints - 1; i++)
1503 Hint *cur_hint = hstate->all_hints[i];
1504 Hint *next_hint = hstate->all_hints[i + 1];
1507 * Leading hint is marked as 'duplicated' in transform_join_hints.
1509 if (cur_hint->type == HINT_TYPE_LEADING &&
1510 next_hint->type == HINT_TYPE_LEADING)
1514 * Note that we need to pass addresses of hint pointers, because
1515 * HintCmp is designed to sort array of Hint* by qsort.
1517 if (HintCmp(&cur_hint, &next_hint) == 0)
1519 hint_ereport(cur_hint->hint_str,
1520 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1521 cur_hint->state = HINT_STATE_DUPLICATION;
1526 * Make sure that per-type array pointers point proper position in the
1527 * array which consists of all hints.
1529 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1530 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1531 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1532 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1533 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1534 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1535 hstate->num_hints[HINT_TYPE_LEADING]);
1541 * Parse inside of parentheses of scan-method hints.
1544 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1547 const char *keyword = hint->base.keyword;
1548 HintKeyword hint_keyword = hint->base.hint_keyword;
1549 List *name_list = NIL;
1552 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1555 /* Parse relation name and index name(s) if given hint accepts. */
1556 length = list_length(name_list);
1559 hint->relname = linitial(name_list);
1560 hint->indexnames = list_delete_first(name_list);
1562 /* check whether the hint accepts index name(s). */
1564 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1565 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1566 #if PG_VERSION_NUM >= 90200
1567 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1568 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1570 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1571 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1574 ("%s hint accepts only one relation.",
1575 hint->base.keyword));
1576 hint->base.state = HINT_STATE_ERROR;
1583 ("%s hint requires a relation.",
1584 hint->base.keyword));
1585 hint->base.state = HINT_STATE_ERROR;
1589 /* Set a bit for specified hint. */
1590 switch (hint_keyword)
1592 case HINT_KEYWORD_SEQSCAN:
1593 hint->enforce_mask = ENABLE_SEQSCAN;
1595 case HINT_KEYWORD_INDEXSCAN:
1596 hint->enforce_mask = ENABLE_INDEXSCAN;
1598 case HINT_KEYWORD_INDEXSCANREGEXP:
1599 hint->enforce_mask = ENABLE_INDEXSCAN;
1600 hint->regexp = true;
1602 case HINT_KEYWORD_BITMAPSCAN:
1603 hint->enforce_mask = ENABLE_BITMAPSCAN;
1605 case HINT_KEYWORD_BITMAPSCANREGEXP:
1606 hint->enforce_mask = ENABLE_BITMAPSCAN;
1607 hint->regexp = true;
1609 case HINT_KEYWORD_TIDSCAN:
1610 hint->enforce_mask = ENABLE_TIDSCAN;
1612 case HINT_KEYWORD_NOSEQSCAN:
1613 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1615 case HINT_KEYWORD_NOINDEXSCAN:
1616 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1618 case HINT_KEYWORD_NOBITMAPSCAN:
1619 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1621 case HINT_KEYWORD_NOTIDSCAN:
1622 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1624 #if PG_VERSION_NUM >= 90200
1625 case HINT_KEYWORD_INDEXONLYSCAN:
1626 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1628 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1629 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1630 hint->regexp = true;
1632 case HINT_KEYWORD_NOINDEXONLYSCAN:
1633 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1637 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1646 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1649 const char *keyword = hint->base.keyword;
1650 HintKeyword hint_keyword = hint->base.hint_keyword;
1651 List *name_list = NIL;
1653 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1656 hint->nrels = list_length(name_list);
1658 if (hint->nrels > 0)
1664 * Transform relation names from list to array to sort them with qsort
1667 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1668 foreach (l, name_list)
1670 hint->relnames[i] = lfirst(l);
1675 list_free(name_list);
1677 /* A join hint requires at least two relations */
1678 if (hint->nrels < 2)
1681 ("%s hint requires at least two relations.",
1682 hint->base.keyword));
1683 hint->base.state = HINT_STATE_ERROR;
1687 /* Sort hints in alphabetical order of relation names. */
1688 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1690 switch (hint_keyword)
1692 case HINT_KEYWORD_NESTLOOP:
1693 hint->enforce_mask = ENABLE_NESTLOOP;
1695 case HINT_KEYWORD_MERGEJOIN:
1696 hint->enforce_mask = ENABLE_MERGEJOIN;
1698 case HINT_KEYWORD_HASHJOIN:
1699 hint->enforce_mask = ENABLE_HASHJOIN;
1701 case HINT_KEYWORD_NONESTLOOP:
1702 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1704 case HINT_KEYWORD_NOMERGEJOIN:
1705 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1707 case HINT_KEYWORD_NOHASHJOIN:
1708 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1711 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1720 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1723 if (outer_inner->outer_inner_pair == NIL)
1725 if (outer_inner->relation)
1731 if (list_length(outer_inner->outer_inner_pair) == 2)
1733 foreach(l, outer_inner->outer_inner_pair)
1735 if (!OuterInnerPairCheck(lfirst(l)))
1746 OuterInnerList(OuterInnerRels *outer_inner)
1748 List *outer_inner_list = NIL;
1750 OuterInnerRels *outer_inner_rels;
1752 foreach(l, outer_inner->outer_inner_pair)
1754 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
1756 if (outer_inner_rels->relation != NULL)
1757 outer_inner_list = lappend(outer_inner_list,
1758 outer_inner_rels->relation);
1760 outer_inner_list = list_concat(outer_inner_list,
1761 OuterInnerList(outer_inner_rels));
1763 return outer_inner_list;
1767 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1770 List *name_list = NIL;
1771 OuterInnerRels *outer_inner = NULL;
1773 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
1777 if (outer_inner != NULL)
1778 name_list = OuterInnerList(outer_inner);
1780 hint->relations = name_list;
1781 hint->outer_inner = outer_inner;
1783 /* A Leading hint requires at least two relations */
1784 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
1786 hint_ereport(hint->base.hint_str,
1787 ("%s hint requires at least two relations.",
1789 hint->base.state = HINT_STATE_ERROR;
1791 else if (hint->outer_inner != NULL &&
1792 !OuterInnerPairCheck(hint->outer_inner))
1794 hint_ereport(hint->base.hint_str,
1795 ("%s hint requires two sets of relations when parentheses nests.",
1797 hint->base.state = HINT_STATE_ERROR;
1804 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1806 List *name_list = NIL;
1808 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
1812 hint->words = name_list;
1814 /* We need both name and value to set GUC parameter. */
1815 if (list_length(name_list) == 2)
1817 hint->name = linitial(name_list);
1818 hint->value = lsecond(name_list);
1822 hint_ereport(hint->base.hint_str,
1823 ("%s hint requires name and value of GUC parameter.",
1825 hint->base.state = HINT_STATE_ERROR;
1832 * set GUC parameter functions
1836 set_config_option_wrapper(const char *name, const char *value,
1837 GucContext context, GucSource source,
1838 GucAction action, bool changeVal, int elevel)
1841 MemoryContext ccxt = CurrentMemoryContext;
1845 #if PG_VERSION_NUM >= 90200
1846 result = set_config_option(name, value, context, source,
1847 action, changeVal, 0);
1849 result = set_config_option(name, value, context, source,
1857 /* Save error info */
1858 MemoryContextSwitchTo(ccxt);
1859 errdata = CopyErrorData();
1862 ereport(elevel, (errcode(errdata->sqlerrcode),
1863 errmsg("%s", errdata->message),
1864 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1865 errdata->hint ? errhint("%s", errdata->hint) : 0));
1866 FreeErrorData(errdata);
1874 set_config_options(SetHint **options, int noptions, GucContext context)
1879 save_nestlevel = NewGUCNestLevel();
1881 for (i = 0; i < noptions; i++)
1883 SetHint *hint = options[i];
1886 if (!hint_state_enabled(hint))
1889 result = set_config_option_wrapper(hint->name, hint->value, context,
1890 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1891 pg_hint_plan_parse_messages);
1893 hint->base.state = HINT_STATE_USED;
1895 hint->base.state = HINT_STATE_ERROR;
1898 return save_nestlevel;
1901 #define SET_CONFIG_OPTION(name, type_bits) \
1902 set_config_option_wrapper((name), \
1903 (mask & (type_bits)) ? "true" : "false", \
1904 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1907 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1911 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1912 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1913 #if PG_VERSION_NUM >= 90200
1914 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1917 mask = enforce_mask;
1919 mask = enforce_mask & current_hint->init_scan_mask;
1921 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1922 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1923 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1924 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1925 #if PG_VERSION_NUM >= 90200
1926 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1931 set_join_config_options(unsigned char enforce_mask, GucContext context)
1935 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1936 enforce_mask == ENABLE_HASHJOIN)
1937 mask = enforce_mask;
1939 mask = enforce_mask & current_hint->init_join_mask;
1941 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1942 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1943 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1947 * pg_hint_plan hook functions
1951 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1952 ParamListInfo params, bool isTopLevel,
1953 DestReceiver *dest, char *completionTag)
1957 if (!pg_hint_plan_enable_hint)
1959 if (prev_ProcessUtility)
1960 (*prev_ProcessUtility) (parsetree, queryString, params,
1961 isTopLevel, dest, completionTag);
1963 standard_ProcessUtility(parsetree, queryString, params,
1964 isTopLevel, dest, completionTag);
1970 if (IsA(node, ExplainStmt))
1973 * Draw out parse tree of actual query from Query struct of EXPLAIN
1979 stmt = (ExplainStmt *) node;
1981 Assert(IsA(stmt->query, Query));
1982 query = (Query *) stmt->query;
1984 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1985 node = query->utilityStmt;
1989 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
1990 * specified to preceding PREPARE command to use it as source of hints.
1992 if (IsA(node, ExecuteStmt))
1996 stmt = (ExecuteStmt *) node;
1997 stmt_name = stmt->name;
1999 #if PG_VERSION_NUM >= 90200
2001 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2004 if (IsA(node, CreateTableAsStmt))
2006 CreateTableAsStmt *stmt;
2009 stmt = (CreateTableAsStmt *) node;
2010 Assert(IsA(stmt->query, Query));
2011 query = (Query *) stmt->query;
2013 if (query->commandType == CMD_UTILITY &&
2014 IsA(query->utilityStmt, ExecuteStmt))
2016 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2017 stmt_name = estmt->name;
2025 if (prev_ProcessUtility)
2026 (*prev_ProcessUtility) (parsetree, queryString, params,
2027 isTopLevel, dest, completionTag);
2029 standard_ProcessUtility(parsetree, queryString, params,
2030 isTopLevel, dest, completionTag);
2044 if (prev_ProcessUtility)
2045 (*prev_ProcessUtility) (parsetree, queryString, params,
2046 isTopLevel, dest, completionTag);
2048 standard_ProcessUtility(parsetree, queryString, params,
2049 isTopLevel, dest, completionTag);
2053 * Push a hint into hint stack which is implemented with List struct. Head of
2054 * list is top of stack.
2057 push_hint(HintState *hstate)
2059 /* Prepend new hint to the list means pushing to stack. */
2060 HintStateStack = lcons(hstate, HintStateStack);
2062 /* Pushed hint is the one which should be used hereafter. */
2063 current_hint = hstate;
2066 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2070 /* Hint stack must not be empty. */
2071 if(HintStateStack == NIL)
2072 elog(ERROR, "hint stack is empty");
2075 * Take a hint at the head from the list, and free it. Switch current_hint
2076 * to point new head (NULL if the list is empty).
2078 HintStateStack = list_delete_first(HintStateStack);
2079 HintStateDelete(current_hint);
2080 if(HintStateStack == NIL)
2081 current_hint = NULL;
2083 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2086 static PlannedStmt *
2087 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2090 PlannedStmt *result;
2094 * Use standard planner if pg_hint_plan is disabled. Other hook functions
2095 * try to change plan with current_hint if any, so set it to NULL.
2097 if (!pg_hint_plan_enable_hint)
2099 current_hint = NULL;
2102 return (*prev_planner) (parse, cursorOptions, boundParams);
2104 return standard_planner(parse, cursorOptions, boundParams);
2109 * TODO: replace "app1" with current application_name setting of the
2111 * XXX: use something instead of debug_query_string?
2113 search_hints(search_query, debug_query_string, "app1");
2115 /* Create hint struct from parse tree. */
2116 hstate = parse_head_comment(parse);
2119 * Use standard planner if the statement has not valid hint. Other hook
2120 * functions try to change plan with current_hint if any, so set it to
2125 current_hint = NULL;
2128 return (*prev_planner) (parse, cursorOptions, boundParams);
2130 return standard_planner(parse, cursorOptions, boundParams);
2134 * Push new hint struct to the hint stack to disable previous hint context.
2138 /* Set GUC parameters which are specified with Set hint. */
2139 save_nestlevel = set_config_options(current_hint->set_hints,
2140 current_hint->num_hints[HINT_TYPE_SET],
2141 current_hint->context);
2144 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2145 if (enable_indexscan)
2146 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2147 if (enable_bitmapscan)
2148 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2150 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2151 #if PG_VERSION_NUM >= 90200
2152 if (enable_indexonlyscan)
2153 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2155 if (enable_nestloop)
2156 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2157 if (enable_mergejoin)
2158 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2159 if (enable_hashjoin)
2160 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2163 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2164 * state when this planner started when error occurred in planner.
2169 result = (*prev_planner) (parse, cursorOptions, boundParams);
2171 result = standard_planner(parse, cursorOptions, boundParams);
2176 * Rollback changes of GUC parameters, and pop current hint context
2177 * from hint stack to rewind the state.
2179 AtEOXact_GUC(true, save_nestlevel);
2185 /* Print hint in debug mode. */
2186 if (pg_hint_plan_debug_print)
2187 HintStateDump(current_hint);
2190 * Rollback changes of GUC parameters, and pop current hint context from
2191 * hint stack to rewind the state.
2193 AtEOXact_GUC(true, save_nestlevel);
2200 * Return scan method hint which matches given aliasname.
2202 static ScanMethodHint *
2203 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2209 * We can't apply scan method hint if the relation is:
2210 * - not a base relation
2211 * - not an ordinary relation (such as join and subquery)
2213 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2216 rte = root->simple_rte_array[rel->relid];
2218 /* We can't force scan method of foreign tables */
2219 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2222 /* Find scan method hint, which matches given names, from the list. */
2223 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2225 ScanMethodHint *hint = current_hint->scan_hints[i];
2227 /* We ignore disabled hints. */
2228 if (!hint_state_enabled(hint))
2231 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2241 * Returns TRUE on match, FALSE on no match.
2243 * s1 --- the data to match against
2244 * s2 --- the pattern
2246 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2249 regexpeq(const char *s1, const char *s2)
2255 strcpy(name.data, s1);
2256 regexp = cstring_to_text(s2);
2258 result = DirectFunctionCall2Coll(nameregexeq,
2259 DEFAULT_COLLATION_OID,
2260 NameGetDatum(&name),
2261 PointerGetDatum(regexp));
2262 return DatumGetBool(result);
2266 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2274 * We delete all the IndexOptInfo list and prevent you from being usable by
2277 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2278 hint->enforce_mask == ENABLE_TIDSCAN)
2280 list_free_deep(rel->indexlist);
2281 rel->indexlist = NIL;
2282 hint->base.state = HINT_STATE_USED;
2288 * When a list of indexes is not specified, we just use all indexes.
2290 if (hint->indexnames == NIL)
2294 * Leaving only an specified index, we delete it from a IndexOptInfo list
2298 if (pg_hint_plan_debug_print)
2299 initStringInfo(&buf);
2301 for (cell = list_head(rel->indexlist); cell; cell = next)
2303 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2304 char *indexname = get_rel_name(info->indexoid);
2306 bool use_index = false;
2310 foreach(l, hint->indexnames)
2312 char *hintname = (char *) lfirst(l);
2316 result = regexpeq(indexname, hintname);
2318 result = RelnameCmp(&indexname, &hintname) == 0;
2323 if (pg_hint_plan_debug_print)
2325 appendStringInfoCharMacro(&buf, ' ');
2326 quote_value(&buf, indexname);
2334 * to make the index a candidate when definition of this index is
2335 * matched with the index's definition of current_hint.
2337 if (OidIsValid(relationObjectId) && !use_index)
2339 foreach(l, current_hint->parent_index_infos)
2343 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2345 /* check to match the parameter of unique */
2346 if (p_info->indisunique != info->unique)
2349 /* check to match the parameter of index's method */
2350 if (p_info->method != info->relam)
2353 /* to check to match the indexkey's configuration */
2354 if ((list_length(p_info->column_names)) !=
2358 /* check to match the indexkey's configuration */
2359 for (i = 0; i < info->ncolumns; i++)
2361 char *c_attname = NULL;
2362 char *p_attname = NULL;
2365 list_nth(p_info->column_names, i);
2367 /* both are expressions */
2368 if (info->indexkeys[i] == 0 && !p_attname)
2371 /* one's column is expression, the other is not */
2372 if (info->indexkeys[i] == 0 || !p_attname)
2375 c_attname = get_attname(relationObjectId,
2376 info->indexkeys[i]);
2378 if (strcmp(p_attname, c_attname) != 0)
2381 if (p_info->indcollation[i] != info->indexcollations[i])
2384 if (p_info->opclass[i] != info->opcintype[i])
2387 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2388 info->reverse_sort[i])
2391 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2392 info->nulls_first[i])
2397 if (i != info->ncolumns)
2400 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2401 (p_info->indpred_str && (info->indpred != NIL)))
2404 * Fetch the pg_index tuple by the Oid of the index
2406 ht_idx = SearchSysCache1(INDEXRELID,
2407 ObjectIdGetDatum(info->indexoid));
2409 /* check to match the expression's parameter of index */
2410 if (p_info->expression_str &&
2411 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2418 * to change the expression's parameter of child's
2421 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2422 Anum_pg_index_indexprs,
2425 result = DirectFunctionCall2(pg_get_expr,
2430 if (strcmp(p_info->expression_str,
2431 text_to_cstring(DatumGetTextP(result))) != 0)
2434 ReleaseSysCache(ht_idx);
2440 /* Check to match the predicate's paraameter of index */
2441 if (p_info->indpred_str &&
2442 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2449 * to change the predicate's parabeter of child's
2452 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2453 Anum_pg_index_indpred,
2456 result = DirectFunctionCall2(pg_get_expr,
2461 if (strcmp(p_info->indpred_str,
2462 text_to_cstring(DatumGetTextP(result))) != 0)
2465 ReleaseSysCache(ht_idx);
2472 ReleaseSysCache(ht_idx);
2474 else if (p_info->expression_str || (info->indexprs != NIL))
2476 else if (p_info->indpred_str || (info->indpred != NIL))
2481 /* to log the candidate of index */
2482 if (pg_hint_plan_debug_print)
2484 appendStringInfoCharMacro(&buf, ' ');
2485 quote_value(&buf, indexname);
2493 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2500 if (pg_hint_plan_debug_print)
2503 StringInfoData rel_buf;
2505 if (OidIsValid(relationObjectId))
2506 relname = get_rel_name(relationObjectId);
2508 relname = hint->relname;
2510 initStringInfo(&rel_buf);
2511 quote_value(&rel_buf, relname);
2514 (errmsg("available indexes for %s(%s):%s",
2519 pfree(rel_buf.data);
2524 * Return information of index definition.
2526 static ParentIndexInfo *
2527 get_parent_index_info(Oid indexoid, Oid relid)
2529 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
2530 Relation indexRelation;
2531 Form_pg_index index;
2535 indexRelation = index_open(indexoid, RowExclusiveLock);
2537 index = indexRelation->rd_index;
2539 p_info->indisunique = index->indisunique;
2540 p_info->method = indexRelation->rd_rel->relam;
2542 p_info->column_names = NIL;
2543 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2544 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2545 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
2547 for (i = 0; i < index->indnatts; i++)
2549 attname = get_attname(relid, index->indkey.values[i]);
2550 p_info->column_names = lappend(p_info->column_names, attname);
2552 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
2553 p_info->opclass[i] = indexRelation->rd_opcintype[i];
2554 p_info->indoption[i] = indexRelation->rd_indoption[i];
2558 * to check to match the expression's paraameter of index with child indexes
2560 p_info->expression_str = NULL;
2561 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
2567 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2568 Anum_pg_index_indexprs, &isnull);
2570 result = DirectFunctionCall2(pg_get_expr,
2572 ObjectIdGetDatum(relid));
2574 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
2578 * to check to match the predicate's paraameter of index with child indexes
2580 p_info->indpred_str = NULL;
2581 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
2587 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2588 Anum_pg_index_indpred, &isnull);
2590 result = DirectFunctionCall2(pg_get_expr,
2592 ObjectIdGetDatum(relid));
2594 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
2597 index_close(indexRelation, NoLock);
2603 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2604 bool inhparent, RelOptInfo *rel)
2606 ScanMethodHint *hint;
2608 if (prev_get_relation_info)
2609 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2611 /* Do nothing if we don't have valid hint in this context. */
2617 /* store does relids of parent table. */
2618 current_hint->parent_relid = rel->relid;
2619 current_hint->parent_rel_oid = relationObjectId;
2621 else if (current_hint->parent_relid != 0)
2624 * We use the same GUC parameter if this table is the child table of a
2625 * table called pg_hint_plan_get_relation_info just before that.
2629 /* append_rel_list contains all append rels; ignore others */
2630 foreach(l, root->append_rel_list)
2632 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2634 /* This rel is child table. */
2635 if (appinfo->parent_relid == current_hint->parent_relid &&
2636 appinfo->child_relid == rel->relid)
2638 if (current_hint->parent_hint)
2639 delete_indexes(current_hint->parent_hint, rel,
2646 /* This rel is not inherit table. */
2647 current_hint->parent_relid = 0;
2648 current_hint->parent_rel_oid = InvalidOid;
2649 current_hint->parent_hint = NULL;
2653 * If scan method hint was given, reset GUC parameters which control
2654 * planner behavior about choosing scan methods.
2656 if ((hint = find_scan_hint(root, rel)) == NULL)
2658 set_scan_config_options(current_hint->init_scan_mask,
2659 current_hint->context);
2662 set_scan_config_options(hint->enforce_mask, current_hint->context);
2663 hint->base.state = HINT_STATE_USED;
2671 current_hint->parent_hint = hint;
2673 relation = heap_open(relationObjectId, NoLock);
2674 indexoidlist = RelationGetIndexList(relation);
2676 foreach(l, indexoidlist)
2678 Oid indexoid = lfirst_oid(l);
2679 char *indexname = get_rel_name(indexoid);
2680 bool use_index = false;
2682 ParentIndexInfo *parent_index_info;
2684 foreach(lc, hint->indexnames)
2686 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
2695 parent_index_info = get_parent_index_info(indexoid,
2697 current_hint->parent_index_infos =
2698 lappend(current_hint->parent_index_infos, parent_index_info);
2700 heap_close(relation, NoLock);
2703 delete_indexes(hint, rel, InvalidOid);
2707 * Return index of relation which matches given aliasname, or 0 if not found.
2708 * If same aliasname was used multiple times in a query, return -1.
2711 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
2717 for (i = 1; i < root->simple_rel_array_size; i++)
2721 if (root->simple_rel_array[i] == NULL)
2724 Assert(i == root->simple_rel_array[i]->relid);
2726 if (RelnameCmp(&aliasname,
2727 &root->simple_rte_array[i]->eref->aliasname) != 0)
2730 foreach(l, initial_rels)
2732 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2734 if (rel->reloptkind == RELOPT_BASEREL)
2736 if (rel->relid != i)
2741 Assert(rel->reloptkind == RELOPT_JOINREL);
2743 if (!bms_is_member(i, rel->relids))
2750 ("Relation name \"%s\" is ambiguous.",
2765 * Return join hint which matches given joinrelids.
2767 static JoinMethodHint *
2768 find_join_hint(Relids joinrelids)
2773 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
2775 foreach(l, join_hint)
2777 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
2779 if (bms_equal(joinrelids, hint->joinrelids))
2787 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
2788 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
2790 OuterInnerRels *outer_rels;
2791 OuterInnerRels *inner_rels;
2792 Relids outer_relids;
2793 Relids inner_relids;
2795 JoinMethodHint *hint;
2797 if (outer_inner->relation != NULL)
2799 return bms_make_singleton(
2800 find_relid_aliasname(root, outer_inner->relation,
2802 leading_hint->base.hint_str));
2805 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
2806 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
2808 outer_relids = OuterInnerJoinCreate(outer_rels,
2814 inner_relids = OuterInnerJoinCreate(inner_rels,
2821 join_relids = bms_add_members(outer_relids, inner_relids);
2823 if (bms_num_members(join_relids) > nbaserel)
2827 * If we don't have join method hint, create new one for the
2828 * join combination with all join methods are enabled.
2830 hint = find_join_hint(join_relids);
2834 * Here relnames is not set, since Relids bitmap is sufficient to
2835 * control paths of this query afterward.
2837 hint = (JoinMethodHint *) JoinMethodHintCreate(
2838 leading_hint->base.hint_str,
2840 HINT_KEYWORD_LEADING);
2841 hint->base.state = HINT_STATE_USED;
2842 hint->nrels = bms_num_members(join_relids);
2843 hint->enforce_mask = ENABLE_ALL_JOIN;
2844 hint->joinrelids = bms_copy(join_relids);
2845 hint->inner_nrels = bms_num_members(inner_relids);
2846 hint->inner_joinrelids = bms_copy(inner_relids);
2848 hstate->join_hint_level[hint->nrels] =
2849 lappend(hstate->join_hint_level[hint->nrels], hint);
2853 hint->inner_nrels = bms_num_members(inner_relids);
2854 hint->inner_joinrelids = bms_copy(inner_relids);
2861 * Transform join method hint into handy form.
2863 * - create bitmap of relids from alias names, to make it easier to check
2864 * whether a join path matches a join method hint.
2865 * - add join method hints which are necessary to enforce join order
2866 * specified by Leading hint
2869 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2870 List *initial_rels, JoinMethodHint **join_method_hints)
2878 LeadingHint *lhint = NULL;
2881 * Create bitmap of relids from alias names for each join method hint.
2882 * Bitmaps are more handy than strings in join searching.
2884 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2886 JoinMethodHint *hint = hstate->join_hints[i];
2889 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
2892 bms_free(hint->joinrelids);
2893 hint->joinrelids = NULL;
2895 for (j = 0; j < hint->nrels; j++)
2897 relname = hint->relnames[j];
2899 relid = find_relid_aliasname(root, relname, initial_rels,
2900 hint->base.hint_str);
2903 hint->base.state = HINT_STATE_ERROR;
2908 if (bms_is_member(relid, hint->joinrelids))
2910 hint_ereport(hint->base.hint_str,
2911 ("Relation name \"%s\" is duplicated.", relname));
2912 hint->base.state = HINT_STATE_ERROR;
2916 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
2919 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
2922 hstate->join_hint_level[hint->nrels] =
2923 lappend(hstate->join_hint_level[hint->nrels], hint);
2926 /* Do nothing if no Leading hint was supplied. */
2927 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2931 * Decide to use Leading hint。
2933 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
2935 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
2938 if (leading_hint->base.state == HINT_STATE_ERROR)
2944 foreach(l, leading_hint->relations)
2946 relname = (char *)lfirst(l);;
2948 relid = find_relid_aliasname(root, relname, initial_rels,
2949 leading_hint->base.hint_str);
2951 leading_hint->base.state = HINT_STATE_ERROR;
2956 if (bms_is_member(relid, relids))
2958 hint_ereport(leading_hint->base.hint_str,
2959 ("Relation name \"%s\" is duplicated.", relname));
2960 leading_hint->base.state = HINT_STATE_ERROR;
2964 relids = bms_add_member(relids, relid);
2967 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
2972 hint_ereport(lhint->base.hint_str,
2973 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
2974 lhint->base.state = HINT_STATE_DUPLICATION;
2976 leading_hint->base.state = HINT_STATE_USED;
2977 lhint = leading_hint;
2980 /* check to exist Leading hint marked with 'used'. */
2985 * We need join method hints which fit specified join order in every join
2986 * level. For example, Leading(A B C) virtually requires following join
2987 * method hints, if no join method hint supplied:
2989 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
2990 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
2992 * If we already have join method hint which fits specified join order in
2993 * that join level, we leave it as-is and don't add new hints.
2997 if (lhint->outer_inner == NULL)
2999 foreach(l, lhint->relations)
3001 JoinMethodHint *hint;
3003 relname = (char *)lfirst(l);
3006 * Find relid of the relation which has given name. If we have the
3007 * name given in Leading hint multiple times in the join, nothing to
3010 relid = find_relid_aliasname(root, relname, initial_rels,
3013 /* Create bitmap of relids for current join level. */
3014 joinrelids = bms_add_member(joinrelids, relid);
3017 /* We never have join method hint for single relation. */
3022 * If we don't have join method hint, create new one for the
3023 * join combination with all join methods are enabled.
3025 hint = find_join_hint(joinrelids);
3029 * Here relnames is not set, since Relids bitmap is sufficient
3030 * to control paths of this query afterward.
3032 hint = (JoinMethodHint *) JoinMethodHintCreate(
3033 lhint->base.hint_str,
3035 HINT_KEYWORD_LEADING);
3036 hint->base.state = HINT_STATE_USED;
3037 hint->nrels = njoinrels;
3038 hint->enforce_mask = ENABLE_ALL_JOIN;
3039 hint->joinrelids = bms_copy(joinrelids);
3042 join_method_hints[njoinrels] = hint;
3044 if (njoinrels >= nbaserel)
3047 bms_free(joinrelids);
3053 * Delete all join hints which have different combination from Leading
3056 for (i = 2; i <= njoinrels; i++)
3058 list_free(hstate->join_hint_level[i]);
3060 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3065 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3072 njoinrels = bms_num_members(joinrelids);
3073 Assert(njoinrels >= 2);
3076 * Delete all join hints which have different combination from Leading
3079 for (i = 2;i <= njoinrels; i++)
3081 if (hstate->join_hint_level[i] != NIL)
3083 ListCell *prev = NULL;
3084 ListCell *next = NULL;
3085 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3088 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3092 if (hint->inner_nrels == 0 &&
3093 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3094 bms_equal(bms_union(hint->joinrelids, joinrelids),
3097 hstate->join_hint_level[i] =
3098 list_delete_cell(hstate->join_hint_level[i], l,
3107 bms_free(joinrelids);
3110 if (hint_state_enabled(lhint))
3112 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3119 * set_plain_rel_pathlist
3120 * Build access paths for a plain relation (no subquery, no inheritance)
3122 * This function was copied and edited from set_plain_rel_pathlist() in
3123 * src/backend/optimizer/path/allpaths.c
3126 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3128 /* Consider sequential scan */
3129 #if PG_VERSION_NUM >= 90200
3130 add_path(rel, create_seqscan_path(root, rel, NULL));
3132 add_path(rel, create_seqscan_path(root, rel));
3135 /* Consider index scans */
3136 create_index_paths(root, rel);
3138 /* Consider TID scans */
3139 create_tidscan_paths(root, rel);
3141 /* Now find the cheapest of the paths for this rel */
3146 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3151 foreach(l, initial_rels)
3153 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3155 ScanMethodHint *hint;
3157 /* Skip relations which we can't choose scan method. */
3158 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3161 rte = root->simple_rte_array[rel->relid];
3163 /* We can't force scan method of foreign tables */
3164 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3168 * Create scan paths with GUC parameters which are at the beginning of
3169 * planner if scan method hint is not specified, otherwise use
3170 * specified hints and mark the hint as used.
3172 if ((hint = find_scan_hint(root, rel)) == NULL)
3173 set_scan_config_options(hstate->init_scan_mask,
3177 set_scan_config_options(hint->enforce_mask, hstate->context);
3178 hint->base.state = HINT_STATE_USED;
3181 list_free_deep(rel->pathlist);
3182 rel->pathlist = NIL;
3185 /* It's an "append relation", process accordingly */
3186 set_append_rel_pathlist(root, rel, rel->relid, rte);
3190 set_plain_rel_pathlist(root, rel, rte);
3195 * Restore the GUC variables we set above.
3197 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3201 * wrapper of make_join_rel()
3203 * call make_join_rel() after changing enable_* parameters according to given
3207 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3210 JoinMethodHint *hint;
3214 joinrelids = bms_union(rel1->relids, rel2->relids);
3215 hint = find_join_hint(joinrelids);
3216 bms_free(joinrelids);
3219 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3221 if (hint->inner_nrels == 0)
3223 save_nestlevel = NewGUCNestLevel();
3225 set_join_config_options(hint->enforce_mask, current_hint->context);
3227 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3228 hint->base.state = HINT_STATE_USED;
3231 * Restore the GUC variables we set above.
3233 AtEOXact_GUC(true, save_nestlevel);
3236 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3245 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3246 RelOptInfo *joinrel,
3247 RelOptInfo *outerrel,
3248 RelOptInfo *innerrel,
3250 SpecialJoinInfo *sjinfo,
3253 ScanMethodHint *scan_hint = NULL;
3255 JoinMethodHint *join_hint;
3258 if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
3260 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3261 scan_hint->base.state = HINT_STATE_USED;
3264 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3265 join_hint = find_join_hint(joinrelids);
3266 bms_free(joinrelids);
3268 if (join_hint && join_hint->inner_nrels != 0)
3270 save_nestlevel = NewGUCNestLevel();
3272 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3275 set_join_config_options(join_hint->enforce_mask,
3276 current_hint->context);
3278 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3279 sjinfo, restrictlist);
3280 join_hint->base.state = HINT_STATE_USED;
3284 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3285 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3286 sjinfo, restrictlist);
3290 * Restore the GUC variables we set above.
3292 AtEOXact_GUC(true, save_nestlevel);
3295 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3296 sjinfo, restrictlist);
3298 if (scan_hint != NULL)
3299 set_scan_config_options(current_hint->init_scan_mask,
3300 current_hint->context);
3304 get_num_baserels(List *initial_rels)
3309 foreach(l, initial_rels)
3311 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3313 if (rel->reloptkind == RELOPT_BASEREL)
3315 else if (rel->reloptkind ==RELOPT_JOINREL)
3316 nbaserel+= bms_num_members(rel->relids);
3319 /* other values not expected here */
3320 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3328 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3331 JoinMethodHint **join_method_hints;
3335 bool leading_hint_enable;
3338 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3339 * valid hint is supplied.
3343 if (prev_join_search)
3344 return (*prev_join_search) (root, levels_needed, initial_rels);
3345 else if (enable_geqo && levels_needed >= geqo_threshold)
3346 return geqo(root, levels_needed, initial_rels);
3348 return standard_join_search(root, levels_needed, initial_rels);
3351 /* We apply scan method hint rebuild scan path. */
3352 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3355 * In the case using GEQO, only scan method hints and Set hints have
3356 * effect. Join method and join order is not controllable by hints.
3358 if (enable_geqo && levels_needed >= geqo_threshold)
3359 return geqo(root, levels_needed, initial_rels);
3361 nbaserel = get_num_baserels(initial_rels);
3362 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3363 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3365 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3366 initial_rels, join_method_hints);
3368 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3370 for (i = 2; i <= nbaserel; i++)
3372 list_free(current_hint->join_hint_level[i]);
3374 /* free Leading hint only */
3375 if (join_method_hints[i] != NULL &&
3376 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3377 JoinMethodHintDelete(join_method_hints[i]);
3379 pfree(current_hint->join_hint_level);
3380 pfree(join_method_hints);
3382 if (leading_hint_enable)
3383 set_join_config_options(current_hint->init_join_mask,
3384 current_hint->context);
3391 * Build access paths for a base relation
3393 * This function was copied and edited from set_rel_pathlist() in
3394 * src/backend/optimizer/path/allpaths.c
3397 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3398 Index rti, RangeTblEntry *rte)
3400 #if PG_VERSION_NUM >= 90200
3401 if (IS_DUMMY_REL(rel))
3403 /* We already proved the relation empty, so nothing more to do */
3410 /* It's an "append relation", process accordingly */
3411 set_append_rel_pathlist(root, rel, rti, rte);
3415 if (rel->rtekind == RTE_RELATION)
3417 if (rte->relkind == RELKIND_RELATION)
3419 /* Plain relation */
3420 set_plain_rel_pathlist(root, rel, rte);
3423 elog(ERROR, "unexpected relkind: %c", rte->relkind);
3426 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
3430 #define standard_join_search pg_hint_plan_standard_join_search
3431 #define join_search_one_level pg_hint_plan_join_search_one_level
3432 #define make_join_rel make_join_rel_wrapper
3435 #undef make_join_rel
3436 #define make_join_rel pg_hint_plan_make_join_rel
3437 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
3438 #include "make_join_rel.c"