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 * Module load callbacks
470 /* Define custom GUC variables. */
471 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
472 "Force planner to use plans specified in the hint comment preceding to the query.",
474 &pg_hint_plan_enable_hint,
482 DefineCustomBoolVariable("pg_hint_plan.debug_print",
483 "Logs results of hint parsing.",
485 &pg_hint_plan_debug_print,
493 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
494 "Message level of parse errors.",
496 &pg_hint_plan_parse_messages,
498 parse_messages_level_options,
506 prev_ProcessUtility = ProcessUtility_hook;
507 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
508 prev_planner = planner_hook;
509 planner_hook = pg_hint_plan_planner;
510 prev_get_relation_info = get_relation_info_hook;
511 get_relation_info_hook = pg_hint_plan_get_relation_info;
512 prev_join_search = join_search_hook;
513 join_search_hook = pg_hint_plan_join_search;
517 * Module unload callback
523 /* Uninstall hooks. */
524 ProcessUtility_hook = prev_ProcessUtility;
525 planner_hook = prev_planner;
526 get_relation_info_hook = prev_get_relation_info;
527 join_search_hook = prev_join_search;
531 * create and delete functions the hint object
535 ScanMethodHintCreate(const char *hint_str, const char *keyword,
536 HintKeyword hint_keyword)
538 ScanMethodHint *hint;
540 hint = palloc(sizeof(ScanMethodHint));
541 hint->base.hint_str = hint_str;
542 hint->base.keyword = keyword;
543 hint->base.hint_keyword = hint_keyword;
544 hint->base.type = HINT_TYPE_SCAN_METHOD;
545 hint->base.state = HINT_STATE_NOTUSED;
546 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
547 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
548 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
549 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
550 hint->relname = NULL;
551 hint->indexnames = NIL;
552 hint->regexp = false;
553 hint->enforce_mask = 0;
555 return (Hint *) hint;
559 ScanMethodHintDelete(ScanMethodHint *hint)
565 pfree(hint->relname);
566 list_free_deep(hint->indexnames);
571 JoinMethodHintCreate(const char *hint_str, const char *keyword,
572 HintKeyword hint_keyword)
574 JoinMethodHint *hint;
576 hint = palloc(sizeof(JoinMethodHint));
577 hint->base.hint_str = hint_str;
578 hint->base.keyword = keyword;
579 hint->base.hint_keyword = hint_keyword;
580 hint->base.type = HINT_TYPE_JOIN_METHOD;
581 hint->base.state = HINT_STATE_NOTUSED;
582 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
583 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
584 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
585 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
587 hint->inner_nrels = 0;
588 hint->relnames = NULL;
589 hint->enforce_mask = 0;
590 hint->joinrelids = NULL;
591 hint->inner_joinrelids = NULL;
593 return (Hint *) hint;
597 JoinMethodHintDelete(JoinMethodHint *hint)
606 for (i = 0; i < hint->nrels; i++)
607 pfree(hint->relnames[i]);
608 pfree(hint->relnames);
611 bms_free(hint->joinrelids);
612 bms_free(hint->inner_joinrelids);
617 LeadingHintCreate(const char *hint_str, const char *keyword,
618 HintKeyword hint_keyword)
622 hint = palloc(sizeof(LeadingHint));
623 hint->base.hint_str = hint_str;
624 hint->base.keyword = keyword;
625 hint->base.hint_keyword = hint_keyword;
626 hint->base.type = HINT_TYPE_LEADING;
627 hint->base.state = HINT_STATE_NOTUSED;
628 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
629 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
630 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
631 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
632 hint->relations = NIL;
633 hint->outer_inner = NULL;
635 return (Hint *) hint;
639 LeadingHintDelete(LeadingHint *hint)
644 list_free_deep(hint->relations);
645 if (hint->outer_inner)
646 pfree(hint->outer_inner);
651 SetHintCreate(const char *hint_str, const char *keyword,
652 HintKeyword hint_keyword)
656 hint = palloc(sizeof(SetHint));
657 hint->base.hint_str = hint_str;
658 hint->base.keyword = keyword;
659 hint->base.hint_keyword = hint_keyword;
660 hint->base.type = HINT_TYPE_SET;
661 hint->base.state = HINT_STATE_NOTUSED;
662 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
663 hint->base.desc_func = (HintDescFunction) SetHintDesc;
664 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
665 hint->base.parse_func = (HintParseFunction) SetHintParse;
670 return (Hint *) hint;
674 SetHintDelete(SetHint *hint)
684 list_free(hint->words);
689 HintStateCreate(void)
693 hstate = palloc(sizeof(HintState));
694 hstate->hint_str = NULL;
695 hstate->nall_hints = 0;
696 hstate->max_all_hints = 0;
697 hstate->all_hints = NULL;
698 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
699 hstate->scan_hints = NULL;
700 hstate->init_scan_mask = 0;
701 hstate->parent_relid = 0;
702 hstate->parent_rel_oid = InvalidOid;
703 hstate->parent_hint = NULL;
704 hstate->parent_index_infos = NIL;
705 hstate->join_hints = NULL;
706 hstate->init_join_mask = 0;
707 hstate->join_hint_level = NULL;
708 hstate->leading_hint = NULL;
709 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
710 hstate->set_hints = NULL;
716 HintStateDelete(HintState *hstate)
723 if (hstate->hint_str)
724 pfree(hstate->hint_str);
726 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
727 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
728 if (hstate->all_hints)
729 pfree(hstate->all_hints);
730 if (hstate->parent_index_infos)
731 list_free(hstate->parent_index_infos);
735 * Copy given value into buf, with quoting with '"' if necessary.
738 quote_value(StringInfo buf, const char *value)
740 bool need_quote = false;
743 for (str = value; *str != '\0'; str++)
745 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
748 appendStringInfoCharMacro(buf, '"');
753 for (str = value; *str != '\0'; str++)
756 appendStringInfoCharMacro(buf, '"');
758 appendStringInfoCharMacro(buf, *str);
762 appendStringInfoCharMacro(buf, '"');
766 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
770 appendStringInfo(buf, "%s(", hint->base.keyword);
771 if (hint->relname != NULL)
773 quote_value(buf, hint->relname);
774 foreach(l, hint->indexnames)
776 appendStringInfoCharMacro(buf, ' ');
777 quote_value(buf, (char *) lfirst(l));
780 appendStringInfoString(buf, ")\n");
784 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
788 appendStringInfo(buf, "%s(", hint->base.keyword);
789 if (hint->relnames != NULL)
791 quote_value(buf, hint->relnames[0]);
792 for (i = 1; i < hint->nrels; i++)
794 appendStringInfoCharMacro(buf, ' ');
795 quote_value(buf, hint->relnames[i]);
798 appendStringInfoString(buf, ")\n");
803 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
805 if (outer_inner->relation == NULL)
812 appendStringInfoCharMacro(buf, '(');
813 foreach(l, outer_inner->outer_inner_pair)
818 appendStringInfoCharMacro(buf, ' ');
820 OuterInnerDesc(lfirst(l), buf);
823 appendStringInfoCharMacro(buf, ')');
826 quote_value(buf, outer_inner->relation);
830 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
832 appendStringInfo(buf, "%s(", HINT_LEADING);
833 if (hint->outer_inner == NULL)
840 foreach(l, hint->relations)
845 appendStringInfoCharMacro(buf, ' ');
847 quote_value(buf, (char *) lfirst(l));
851 OuterInnerDesc(hint->outer_inner, buf);
853 appendStringInfoString(buf, ")\n");
857 SetHintDesc(SetHint *hint, StringInfo buf)
859 bool is_first = true;
862 appendStringInfo(buf, "%s(", HINT_SET);
863 foreach(l, hint->words)
868 appendStringInfoCharMacro(buf, ' ');
870 quote_value(buf, (char *) lfirst(l));
872 appendStringInfo(buf, ")\n");
876 * Append string which repserents all hints in a given state to buf, with
877 * preceding title with them.
880 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
885 appendStringInfo(buf, "%s:\n", title);
886 for (i = 0; i < hstate->nall_hints; i++)
888 if (hstate->all_hints[i]->state != state)
891 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf);
896 * Dump contents of given hstate to server log with log level LOG.
899 HintStateDump(HintState *hstate)
905 elog(LOG, "pg_hint_plan:\nno hint");
909 initStringInfo(&buf);
911 appendStringInfoString(&buf, "pg_hint_plan:\n");
912 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
913 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
914 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
915 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
917 elog(LOG, "%s", buf.data);
927 RelnameCmp(const void *a, const void *b)
929 const char *relnamea = *((const char **) a);
930 const char *relnameb = *((const char **) b);
932 return strcmp(relnamea, relnameb);
936 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
938 return RelnameCmp(&a->relname, &b->relname);
942 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
946 if (a->nrels != b->nrels)
947 return a->nrels - b->nrels;
949 for (i = 0; i < a->nrels; i++)
952 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
960 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
966 SetHintCmp(const SetHint *a, const SetHint *b)
968 return strcmp(a->name, b->name);
972 HintCmp(const void *a, const void *b)
974 const Hint *hinta = *((const Hint **) a);
975 const Hint *hintb = *((const Hint **) b);
977 if (hinta->type != hintb->type)
978 return hinta->type - hintb->type;
979 if (hinta->state == HINT_STATE_ERROR)
981 if (hintb->state == HINT_STATE_ERROR)
983 return hinta->cmp_func(hinta, hintb);
987 * Returns byte offset of hint b from hint a. If hint a was specified before
988 * b, positive value is returned.
991 HintCmpWithPos(const void *a, const void *b)
993 const Hint *hinta = *((const Hint **) a);
994 const Hint *hintb = *((const Hint **) b);
997 result = HintCmp(a, b);
999 result = hinta->hint_str - hintb->hint_str;
1008 parse_keyword(const char *str, StringInfo buf)
1012 while (!isspace(*str) && *str != '(' && *str != '\0')
1013 appendStringInfoCharMacro(buf, *str++);
1019 skip_parenthesis(const char *str, char parenthesis)
1023 if (*str != parenthesis)
1025 if (parenthesis == '(')
1026 hint_ereport(str, ("Opening parenthesis is necessary."));
1027 else if (parenthesis == ')')
1028 hint_ereport(str, ("Closing parenthesis is necessary."));
1039 * Parse a token from str, and store malloc'd copy into word. A token can be
1040 * quoted with '"'. Return value is pointer to unparsed portion of original
1041 * string, or NULL if an error occurred.
1043 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1046 parse_quoted_value(const char *str, char **word, bool truncate)
1051 /* Skip leading spaces. */
1054 initStringInfo(&buf);
1067 /* Double quotation must be closed. */
1071 hint_ereport(str, ("Unterminated quoted string."));
1076 * Skip escaped double quotation.
1078 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1079 * block comments) to be an object name, so users must specify
1080 * alias for such object names.
1082 * Those special names can be allowed if we care escaped slashes
1083 * and asterisks, but we don't.
1092 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1096 appendStringInfoCharMacro(&buf, *str++);
1101 hint_ereport(str, ("Zero-length delimited string."));
1108 /* Truncate name if it's too long */
1110 truncate_identifier(buf.data, strlen(buf.data), true);
1117 static OuterInnerRels *
1118 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1120 OuterInnerRels *outer_inner;
1122 outer_inner = palloc(sizeof(OuterInnerRels));
1123 outer_inner->relation = name;
1124 outer_inner->outer_inner_pair = outer_inner_list;
1130 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1132 List *outer_inner_pair = NIL;
1134 if ((str = skip_parenthesis(str, '(')) == NULL)
1139 /* Store words in parentheses into outer_inner_list. */
1140 while(*str != ')' && *str != '\0')
1142 OuterInnerRels *outer_inner_rels;
1146 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1154 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1157 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1160 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1165 (str = skip_parenthesis(str, ')')) == NULL)
1167 list_free(outer_inner_pair);
1171 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1177 parse_parentheses_Leading(const char *str, List **name_list,
1178 OuterInnerRels **outer_inner)
1181 bool truncate = true;
1183 if ((str = skip_parenthesis(str, '(')) == NULL)
1189 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1194 /* Store words in parentheses into name_list. */
1195 while(*str != ')' && *str != '\0')
1197 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1199 list_free(*name_list);
1203 *name_list = lappend(*name_list, name);
1208 if ((str = skip_parenthesis(str, ')')) == NULL)
1214 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1217 bool truncate = true;
1219 if ((str = skip_parenthesis(str, '(')) == NULL)
1224 /* Store words in parentheses into name_list. */
1225 while(*str != ')' && *str != '\0')
1227 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1229 list_free(*name_list);
1233 *name_list = lappend(*name_list, name);
1236 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1237 #if PG_VERSION_NUM >= 90200
1238 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1240 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1241 keyword == HINT_KEYWORD_SET)
1247 if ((str = skip_parenthesis(str, ')')) == NULL)
1253 parse_hints(HintState *hstate, Query *parse, const char *str)
1258 initStringInfo(&buf);
1259 while (*str != '\0')
1261 const HintParser *parser;
1263 /* in error message, we output the comment including the keyword. */
1264 head = (char *) str;
1266 /* parse only the keyword of the hint. */
1267 resetStringInfo(&buf);
1268 str = parse_keyword(str, &buf);
1270 for (parser = parsers; parser->keyword != NULL; parser++)
1272 char *keyword = parser->keyword;
1275 if (strcasecmp(buf.data, keyword) != 0)
1278 hint = parser->create_func(head, keyword, parser->hint_keyword);
1280 /* parser of each hint does parse in a parenthesis. */
1281 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1283 hint->delete_func(hint);
1289 * Add hint information into all_hints array. If we don't have
1290 * enough space, double the array.
1292 if (hstate->nall_hints == 0)
1294 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1295 hstate->all_hints = (Hint **)
1296 palloc(sizeof(Hint *) * hstate->max_all_hints);
1298 else if (hstate->nall_hints == hstate->max_all_hints)
1300 hstate->max_all_hints *= 2;
1301 hstate->all_hints = (Hint **)
1302 repalloc(hstate->all_hints,
1303 sizeof(Hint *) * hstate->max_all_hints);
1306 hstate->all_hints[hstate->nall_hints] = hint;
1307 hstate->nall_hints++;
1314 if (parser->keyword == NULL)
1317 ("Unrecognized hint keyword \"%s\".", buf.data));
1329 get_hints_from_table(const char *client_query, const char *client_application)
1331 const char *search_query =
1333 " FROM hint_plan.hints "
1334 " WHERE norm_query_string = $1 "
1335 " AND ( application_name = $2 "
1336 " OR application_name = '' ) "
1337 " ORDER BY application_name DESC";
1338 static SPIPlanPtr plan = NULL;
1341 Oid argtypes[2] = { TEXTOID, TEXTOID };
1343 bool nulls[2] = { false, false };
1347 ret = SPI_connect();
1348 if (ret != SPI_OK_CONNECT)
1349 elog(ERROR, "pg_hint_plan: SPI_connect => %d", ret);
1354 p = SPI_prepare(search_query, 2, argtypes);
1356 elog(ERROR, "pg_hint_plan: SPI_prepare => %d", SPI_result);
1357 plan = SPI_saveplan(p);
1361 qry = cstring_to_text(client_query);
1362 app = cstring_to_text(client_application);
1363 values[0] = PointerGetDatum(qry);
1364 values[1] = PointerGetDatum(app);
1366 pg_hint_plan_enable_hint = false;
1367 ret = SPI_execute_plan(plan, values, nulls, true, 1);
1368 pg_hint_plan_enable_hint = true;
1369 if (ret != SPI_OK_SELECT)
1370 elog(ERROR, "pg_hint_plan: SPI_execute_plan => %d", ret);
1372 if (SPI_processed > 0)
1377 hints = pstrdup(SPI_getvalue(SPI_tuptable->vals[0],
1378 SPI_tuptable->tupdesc, 1));
1379 len = strlen(hints);
1380 buf = SPI_palloc(len + 1);
1381 memcpy(buf, hints, len);
1392 * Get client-supplied query string.
1395 get_query_string(void)
1401 PreparedStatement *entry;
1403 entry = FetchPreparedStatement(stmt_name, true);
1404 p = entry->plansource->query_string;
1407 p = debug_query_string;
1413 * Get hints from the head block comment in client-supplied query string.
1416 get_hints_from_comment(const char *p)
1418 const char *hint_head;
1426 /* extract query head comment. */
1427 hint_head = strstr(p, HINT_START);
1428 if (hint_head == NULL)
1430 for (;p < hint_head; p++)
1433 * Allow these characters precedes hint comment:
1435 * - alphabets which are in ASCII range
1436 * - space, tabs and new-lines
1437 * - underscores, for identifier
1438 * - commas, for SELECT clause, EXPLAIN and PREPARE
1439 * - parentheses, for EXPLAIN and PREPARE
1441 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1442 * avoid behavior which depends on locale setting.
1444 if (!(*p >= '0' && *p <= '9') &&
1445 !(*p >= 'A' && *p <= 'Z') &&
1446 !(*p >= 'a' && *p <= 'z') &&
1450 *p != '(' && *p != ')')
1454 len = strlen(HINT_START);
1459 /* find hint end keyword. */
1460 if ((tail = strstr(p, HINT_END)) == NULL)
1462 hint_ereport(head, ("Unterminated block comment."));
1466 /* We don't support nested block comments. */
1467 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1469 hint_ereport(head, ("Nested block comments are not supported."));
1473 /* Make a copy of hint. */
1475 head = palloc(len + 1);
1476 memcpy(head, p, len);
1484 * Parse hints that got, create hint struct from parse tree and parse hints.
1487 create_hintstate(Query *parse, const char *hints)
1497 hstate = HintStateCreate();
1498 hstate->hint_str = (char *) hints;
1500 /* parse each hint. */
1501 parse_hints(hstate, parse, p);
1503 /* When nothing specified a hint, we free HintState and returns NULL. */
1504 if (hstate->nall_hints == 0)
1506 HintStateDelete(hstate);
1510 /* Sort hints in order of original position. */
1511 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1514 /* Count number of hints per hint-type. */
1515 for (i = 0; i < hstate->nall_hints; i++)
1517 Hint *cur_hint = hstate->all_hints[i];
1518 hstate->num_hints[cur_hint->type]++;
1522 * If an object (or a set of objects) has multiple hints of same hint-type,
1523 * only the last hint is valid and others are igonred in planning.
1524 * Hints except the last are marked as 'duplicated' to remember the order.
1526 for (i = 0; i < hstate->nall_hints - 1; i++)
1528 Hint *cur_hint = hstate->all_hints[i];
1529 Hint *next_hint = hstate->all_hints[i + 1];
1532 * Leading hint is marked as 'duplicated' in transform_join_hints.
1534 if (cur_hint->type == HINT_TYPE_LEADING &&
1535 next_hint->type == HINT_TYPE_LEADING)
1539 * Note that we need to pass addresses of hint pointers, because
1540 * HintCmp is designed to sort array of Hint* by qsort.
1542 if (HintCmp(&cur_hint, &next_hint) == 0)
1544 hint_ereport(cur_hint->hint_str,
1545 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1546 cur_hint->state = HINT_STATE_DUPLICATION;
1551 * Make sure that per-type array pointers point proper position in the
1552 * array which consists of all hints.
1554 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1555 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1556 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1557 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1558 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1559 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1560 hstate->num_hints[HINT_TYPE_LEADING]);
1566 * Parse inside of parentheses of scan-method hints.
1569 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1572 const char *keyword = hint->base.keyword;
1573 HintKeyword hint_keyword = hint->base.hint_keyword;
1574 List *name_list = NIL;
1577 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1580 /* Parse relation name and index name(s) if given hint accepts. */
1581 length = list_length(name_list);
1584 hint->relname = linitial(name_list);
1585 hint->indexnames = list_delete_first(name_list);
1587 /* check whether the hint accepts index name(s). */
1589 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1590 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1591 #if PG_VERSION_NUM >= 90200
1592 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1593 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1595 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1596 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1599 ("%s hint accepts only one relation.",
1600 hint->base.keyword));
1601 hint->base.state = HINT_STATE_ERROR;
1608 ("%s hint requires a relation.",
1609 hint->base.keyword));
1610 hint->base.state = HINT_STATE_ERROR;
1614 /* Set a bit for specified hint. */
1615 switch (hint_keyword)
1617 case HINT_KEYWORD_SEQSCAN:
1618 hint->enforce_mask = ENABLE_SEQSCAN;
1620 case HINT_KEYWORD_INDEXSCAN:
1621 hint->enforce_mask = ENABLE_INDEXSCAN;
1623 case HINT_KEYWORD_INDEXSCANREGEXP:
1624 hint->enforce_mask = ENABLE_INDEXSCAN;
1625 hint->regexp = true;
1627 case HINT_KEYWORD_BITMAPSCAN:
1628 hint->enforce_mask = ENABLE_BITMAPSCAN;
1630 case HINT_KEYWORD_BITMAPSCANREGEXP:
1631 hint->enforce_mask = ENABLE_BITMAPSCAN;
1632 hint->regexp = true;
1634 case HINT_KEYWORD_TIDSCAN:
1635 hint->enforce_mask = ENABLE_TIDSCAN;
1637 case HINT_KEYWORD_NOSEQSCAN:
1638 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1640 case HINT_KEYWORD_NOINDEXSCAN:
1641 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1643 case HINT_KEYWORD_NOBITMAPSCAN:
1644 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1646 case HINT_KEYWORD_NOTIDSCAN:
1647 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1649 #if PG_VERSION_NUM >= 90200
1650 case HINT_KEYWORD_INDEXONLYSCAN:
1651 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1653 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1654 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1655 hint->regexp = true;
1657 case HINT_KEYWORD_NOINDEXONLYSCAN:
1658 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1662 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1671 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1674 const char *keyword = hint->base.keyword;
1675 HintKeyword hint_keyword = hint->base.hint_keyword;
1676 List *name_list = NIL;
1678 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1681 hint->nrels = list_length(name_list);
1683 if (hint->nrels > 0)
1689 * Transform relation names from list to array to sort them with qsort
1692 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1693 foreach (l, name_list)
1695 hint->relnames[i] = lfirst(l);
1700 list_free(name_list);
1702 /* A join hint requires at least two relations */
1703 if (hint->nrels < 2)
1706 ("%s hint requires at least two relations.",
1707 hint->base.keyword));
1708 hint->base.state = HINT_STATE_ERROR;
1712 /* Sort hints in alphabetical order of relation names. */
1713 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1715 switch (hint_keyword)
1717 case HINT_KEYWORD_NESTLOOP:
1718 hint->enforce_mask = ENABLE_NESTLOOP;
1720 case HINT_KEYWORD_MERGEJOIN:
1721 hint->enforce_mask = ENABLE_MERGEJOIN;
1723 case HINT_KEYWORD_HASHJOIN:
1724 hint->enforce_mask = ENABLE_HASHJOIN;
1726 case HINT_KEYWORD_NONESTLOOP:
1727 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1729 case HINT_KEYWORD_NOMERGEJOIN:
1730 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1732 case HINT_KEYWORD_NOHASHJOIN:
1733 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1736 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1745 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1748 if (outer_inner->outer_inner_pair == NIL)
1750 if (outer_inner->relation)
1756 if (list_length(outer_inner->outer_inner_pair) == 2)
1758 foreach(l, outer_inner->outer_inner_pair)
1760 if (!OuterInnerPairCheck(lfirst(l)))
1771 OuterInnerList(OuterInnerRels *outer_inner)
1773 List *outer_inner_list = NIL;
1775 OuterInnerRels *outer_inner_rels;
1777 foreach(l, outer_inner->outer_inner_pair)
1779 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
1781 if (outer_inner_rels->relation != NULL)
1782 outer_inner_list = lappend(outer_inner_list,
1783 outer_inner_rels->relation);
1785 outer_inner_list = list_concat(outer_inner_list,
1786 OuterInnerList(outer_inner_rels));
1788 return outer_inner_list;
1792 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1795 List *name_list = NIL;
1796 OuterInnerRels *outer_inner = NULL;
1798 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
1802 if (outer_inner != NULL)
1803 name_list = OuterInnerList(outer_inner);
1805 hint->relations = name_list;
1806 hint->outer_inner = outer_inner;
1808 /* A Leading hint requires at least two relations */
1809 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
1811 hint_ereport(hint->base.hint_str,
1812 ("%s hint requires at least two relations.",
1814 hint->base.state = HINT_STATE_ERROR;
1816 else if (hint->outer_inner != NULL &&
1817 !OuterInnerPairCheck(hint->outer_inner))
1819 hint_ereport(hint->base.hint_str,
1820 ("%s hint requires two sets of relations when parentheses nests.",
1822 hint->base.state = HINT_STATE_ERROR;
1829 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1831 List *name_list = NIL;
1833 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
1837 hint->words = name_list;
1839 /* We need both name and value to set GUC parameter. */
1840 if (list_length(name_list) == 2)
1842 hint->name = linitial(name_list);
1843 hint->value = lsecond(name_list);
1847 hint_ereport(hint->base.hint_str,
1848 ("%s hint requires name and value of GUC parameter.",
1850 hint->base.state = HINT_STATE_ERROR;
1857 * set GUC parameter functions
1861 set_config_option_wrapper(const char *name, const char *value,
1862 GucContext context, GucSource source,
1863 GucAction action, bool changeVal, int elevel)
1866 MemoryContext ccxt = CurrentMemoryContext;
1870 #if PG_VERSION_NUM >= 90200
1871 result = set_config_option(name, value, context, source,
1872 action, changeVal, 0);
1874 result = set_config_option(name, value, context, source,
1882 /* Save error info */
1883 MemoryContextSwitchTo(ccxt);
1884 errdata = CopyErrorData();
1887 ereport(elevel, (errcode(errdata->sqlerrcode),
1888 errmsg("%s", errdata->message),
1889 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1890 errdata->hint ? errhint("%s", errdata->hint) : 0));
1891 FreeErrorData(errdata);
1899 set_config_options(SetHint **options, int noptions, GucContext context)
1904 save_nestlevel = NewGUCNestLevel();
1906 for (i = 0; i < noptions; i++)
1908 SetHint *hint = options[i];
1911 if (!hint_state_enabled(hint))
1914 result = set_config_option_wrapper(hint->name, hint->value, context,
1915 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1916 pg_hint_plan_parse_messages);
1918 hint->base.state = HINT_STATE_USED;
1920 hint->base.state = HINT_STATE_ERROR;
1923 return save_nestlevel;
1926 #define SET_CONFIG_OPTION(name, type_bits) \
1927 set_config_option_wrapper((name), \
1928 (mask & (type_bits)) ? "true" : "false", \
1929 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1932 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1936 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1937 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1938 #if PG_VERSION_NUM >= 90200
1939 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1942 mask = enforce_mask;
1944 mask = enforce_mask & current_hint->init_scan_mask;
1946 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1947 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1948 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1949 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1950 #if PG_VERSION_NUM >= 90200
1951 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1956 set_join_config_options(unsigned char enforce_mask, GucContext context)
1960 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1961 enforce_mask == ENABLE_HASHJOIN)
1962 mask = enforce_mask;
1964 mask = enforce_mask & current_hint->init_join_mask;
1966 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1967 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1968 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1972 * pg_hint_plan hook functions
1976 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1977 ParamListInfo params, bool isTopLevel,
1978 DestReceiver *dest, char *completionTag)
1982 if (!pg_hint_plan_enable_hint)
1984 if (prev_ProcessUtility)
1985 (*prev_ProcessUtility) (parsetree, queryString, params,
1986 isTopLevel, dest, completionTag);
1988 standard_ProcessUtility(parsetree, queryString, params,
1989 isTopLevel, dest, completionTag);
1995 if (IsA(node, ExplainStmt))
1998 * Draw out parse tree of actual query from Query struct of EXPLAIN
2004 stmt = (ExplainStmt *) node;
2006 Assert(IsA(stmt->query, Query));
2007 query = (Query *) stmt->query;
2009 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2010 node = query->utilityStmt;
2014 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2015 * specified to preceding PREPARE command to use it as source of hints.
2017 if (IsA(node, ExecuteStmt))
2021 stmt = (ExecuteStmt *) node;
2022 stmt_name = stmt->name;
2024 #if PG_VERSION_NUM >= 90200
2026 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2029 if (IsA(node, CreateTableAsStmt))
2031 CreateTableAsStmt *stmt;
2034 stmt = (CreateTableAsStmt *) node;
2035 Assert(IsA(stmt->query, Query));
2036 query = (Query *) stmt->query;
2038 if (query->commandType == CMD_UTILITY &&
2039 IsA(query->utilityStmt, ExecuteStmt))
2041 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2042 stmt_name = estmt->name;
2050 if (prev_ProcessUtility)
2051 (*prev_ProcessUtility) (parsetree, queryString, params,
2052 isTopLevel, dest, completionTag);
2054 standard_ProcessUtility(parsetree, queryString, params,
2055 isTopLevel, dest, completionTag);
2069 if (prev_ProcessUtility)
2070 (*prev_ProcessUtility) (parsetree, queryString, params,
2071 isTopLevel, dest, completionTag);
2073 standard_ProcessUtility(parsetree, queryString, params,
2074 isTopLevel, dest, completionTag);
2078 * Push a hint into hint stack which is implemented with List struct. Head of
2079 * list is top of stack.
2082 push_hint(HintState *hstate)
2084 /* Prepend new hint to the list means pushing to stack. */
2085 HintStateStack = lcons(hstate, HintStateStack);
2087 /* Pushed hint is the one which should be used hereafter. */
2088 current_hint = hstate;
2091 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2095 /* Hint stack must not be empty. */
2096 if(HintStateStack == NIL)
2097 elog(ERROR, "hint stack is empty");
2100 * Take a hint at the head from the list, and free it. Switch current_hint
2101 * to point new head (NULL if the list is empty).
2103 HintStateStack = list_delete_first(HintStateStack);
2104 HintStateDelete(current_hint);
2105 if(HintStateStack == NIL)
2106 current_hint = NULL;
2108 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2111 static PlannedStmt *
2112 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2117 PlannedStmt *result;
2121 * Use standard planner if pg_hint_plan is disabled. Other hook functions
2122 * try to change plan with current_hint if any, so set it to NULL.
2124 if (!pg_hint_plan_enable_hint)
2125 goto standard_planner_proc;
2127 /* Create hint struct from client-supplied query string. */
2128 query = get_query_string();
2131 * get_hints_from_table
2132 * TODO: replace "app1" with current application_name setting of the
2134 * XXX: use something instead of debug_query_string?
2136 hints = get_hints_from_table(query, application_name);
2138 "pg_hint_plan: get_hints_from_table [%s][%s]=>[%s]",
2139 query, application_name,
2140 hints ? hints : "(none)");
2142 hints = get_hints_from_comment(query);
2143 hstate = create_hintstate(parse, hints);
2146 * Use standard planner if the statement has not valid hint. Other hook
2147 * functions try to change plan with current_hint if any, so set it to
2151 goto standard_planner_proc;
2154 * Push new hint struct to the hint stack to disable previous hint context.
2158 /* Set GUC parameters which are specified with Set hint. */
2159 save_nestlevel = set_config_options(current_hint->set_hints,
2160 current_hint->num_hints[HINT_TYPE_SET],
2161 current_hint->context);
2164 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2165 if (enable_indexscan)
2166 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2167 if (enable_bitmapscan)
2168 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2170 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2171 #if PG_VERSION_NUM >= 90200
2172 if (enable_indexonlyscan)
2173 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2175 if (enable_nestloop)
2176 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2177 if (enable_mergejoin)
2178 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2179 if (enable_hashjoin)
2180 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2183 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2184 * state when this planner started when error occurred in planner.
2189 result = (*prev_planner) (parse, cursorOptions, boundParams);
2191 result = standard_planner(parse, cursorOptions, boundParams);
2196 * Rollback changes of GUC parameters, and pop current hint context
2197 * from hint stack to rewind the state.
2199 AtEOXact_GUC(true, save_nestlevel);
2205 /* Print hint in debug mode. */
2206 if (pg_hint_plan_debug_print)
2207 HintStateDump(current_hint);
2210 * Rollback changes of GUC parameters, and pop current hint context from
2211 * hint stack to rewind the state.
2213 AtEOXact_GUC(true, save_nestlevel);
2218 standard_planner_proc:
2219 current_hint = NULL;
2221 return (*prev_planner) (parse, cursorOptions, boundParams);
2223 return standard_planner(parse, cursorOptions, boundParams);
2227 * Return scan method hint which matches given aliasname.
2229 static ScanMethodHint *
2230 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2236 * We can't apply scan method hint if the relation is:
2237 * - not a base relation
2238 * - not an ordinary relation (such as join and subquery)
2240 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2243 rte = root->simple_rte_array[rel->relid];
2245 /* We can't force scan method of foreign tables */
2246 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2249 /* Find scan method hint, which matches given names, from the list. */
2250 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2252 ScanMethodHint *hint = current_hint->scan_hints[i];
2254 /* We ignore disabled hints. */
2255 if (!hint_state_enabled(hint))
2258 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2268 * Returns TRUE on match, FALSE on no match.
2270 * s1 --- the data to match against
2271 * s2 --- the pattern
2273 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2276 regexpeq(const char *s1, const char *s2)
2282 strcpy(name.data, s1);
2283 regexp = cstring_to_text(s2);
2285 result = DirectFunctionCall2Coll(nameregexeq,
2286 DEFAULT_COLLATION_OID,
2287 NameGetDatum(&name),
2288 PointerGetDatum(regexp));
2289 return DatumGetBool(result);
2293 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2301 * We delete all the IndexOptInfo list and prevent you from being usable by
2304 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2305 hint->enforce_mask == ENABLE_TIDSCAN)
2307 list_free_deep(rel->indexlist);
2308 rel->indexlist = NIL;
2309 hint->base.state = HINT_STATE_USED;
2315 * When a list of indexes is not specified, we just use all indexes.
2317 if (hint->indexnames == NIL)
2321 * Leaving only an specified index, we delete it from a IndexOptInfo list
2325 if (pg_hint_plan_debug_print)
2326 initStringInfo(&buf);
2328 for (cell = list_head(rel->indexlist); cell; cell = next)
2330 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2331 char *indexname = get_rel_name(info->indexoid);
2333 bool use_index = false;
2337 foreach(l, hint->indexnames)
2339 char *hintname = (char *) lfirst(l);
2343 result = regexpeq(indexname, hintname);
2345 result = RelnameCmp(&indexname, &hintname) == 0;
2350 if (pg_hint_plan_debug_print)
2352 appendStringInfoCharMacro(&buf, ' ');
2353 quote_value(&buf, indexname);
2361 * to make the index a candidate when definition of this index is
2362 * matched with the index's definition of current_hint.
2364 if (OidIsValid(relationObjectId) && !use_index)
2366 foreach(l, current_hint->parent_index_infos)
2370 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2372 /* check to match the parameter of unique */
2373 if (p_info->indisunique != info->unique)
2376 /* check to match the parameter of index's method */
2377 if (p_info->method != info->relam)
2380 /* to check to match the indexkey's configuration */
2381 if ((list_length(p_info->column_names)) !=
2385 /* check to match the indexkey's configuration */
2386 for (i = 0; i < info->ncolumns; i++)
2388 char *c_attname = NULL;
2389 char *p_attname = NULL;
2392 list_nth(p_info->column_names, i);
2394 /* both are expressions */
2395 if (info->indexkeys[i] == 0 && !p_attname)
2398 /* one's column is expression, the other is not */
2399 if (info->indexkeys[i] == 0 || !p_attname)
2402 c_attname = get_attname(relationObjectId,
2403 info->indexkeys[i]);
2405 if (strcmp(p_attname, c_attname) != 0)
2408 if (p_info->indcollation[i] != info->indexcollations[i])
2411 if (p_info->opclass[i] != info->opcintype[i])
2414 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2415 info->reverse_sort[i])
2418 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2419 info->nulls_first[i])
2424 if (i != info->ncolumns)
2427 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2428 (p_info->indpred_str && (info->indpred != NIL)))
2431 * Fetch the pg_index tuple by the Oid of the index
2433 ht_idx = SearchSysCache1(INDEXRELID,
2434 ObjectIdGetDatum(info->indexoid));
2436 /* check to match the expression's parameter of index */
2437 if (p_info->expression_str &&
2438 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2445 * to change the expression's parameter of child's
2448 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2449 Anum_pg_index_indexprs,
2452 result = DirectFunctionCall2(pg_get_expr,
2457 if (strcmp(p_info->expression_str,
2458 text_to_cstring(DatumGetTextP(result))) != 0)
2461 ReleaseSysCache(ht_idx);
2467 /* Check to match the predicate's paraameter of index */
2468 if (p_info->indpred_str &&
2469 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2476 * to change the predicate's parabeter of child's
2479 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2480 Anum_pg_index_indpred,
2483 result = DirectFunctionCall2(pg_get_expr,
2488 if (strcmp(p_info->indpred_str,
2489 text_to_cstring(DatumGetTextP(result))) != 0)
2492 ReleaseSysCache(ht_idx);
2499 ReleaseSysCache(ht_idx);
2501 else if (p_info->expression_str || (info->indexprs != NIL))
2503 else if (p_info->indpred_str || (info->indpred != NIL))
2508 /* to log the candidate of index */
2509 if (pg_hint_plan_debug_print)
2511 appendStringInfoCharMacro(&buf, ' ');
2512 quote_value(&buf, indexname);
2520 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2527 if (pg_hint_plan_debug_print)
2530 StringInfoData rel_buf;
2532 if (OidIsValid(relationObjectId))
2533 relname = get_rel_name(relationObjectId);
2535 relname = hint->relname;
2537 initStringInfo(&rel_buf);
2538 quote_value(&rel_buf, relname);
2541 (errmsg("available indexes for %s(%s):%s",
2546 pfree(rel_buf.data);
2551 * Return information of index definition.
2553 static ParentIndexInfo *
2554 get_parent_index_info(Oid indexoid, Oid relid)
2556 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
2557 Relation indexRelation;
2558 Form_pg_index index;
2562 indexRelation = index_open(indexoid, RowExclusiveLock);
2564 index = indexRelation->rd_index;
2566 p_info->indisunique = index->indisunique;
2567 p_info->method = indexRelation->rd_rel->relam;
2569 p_info->column_names = NIL;
2570 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2571 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2572 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
2574 for (i = 0; i < index->indnatts; i++)
2576 attname = get_attname(relid, index->indkey.values[i]);
2577 p_info->column_names = lappend(p_info->column_names, attname);
2579 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
2580 p_info->opclass[i] = indexRelation->rd_opcintype[i];
2581 p_info->indoption[i] = indexRelation->rd_indoption[i];
2585 * to check to match the expression's paraameter of index with child indexes
2587 p_info->expression_str = NULL;
2588 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
2594 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2595 Anum_pg_index_indexprs, &isnull);
2597 result = DirectFunctionCall2(pg_get_expr,
2599 ObjectIdGetDatum(relid));
2601 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
2605 * to check to match the predicate's paraameter of index with child indexes
2607 p_info->indpred_str = NULL;
2608 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
2614 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2615 Anum_pg_index_indpred, &isnull);
2617 result = DirectFunctionCall2(pg_get_expr,
2619 ObjectIdGetDatum(relid));
2621 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
2624 index_close(indexRelation, NoLock);
2630 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2631 bool inhparent, RelOptInfo *rel)
2633 ScanMethodHint *hint;
2635 if (prev_get_relation_info)
2636 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2638 /* Do nothing if we don't have valid hint in this context. */
2644 /* store does relids of parent table. */
2645 current_hint->parent_relid = rel->relid;
2646 current_hint->parent_rel_oid = relationObjectId;
2648 else if (current_hint->parent_relid != 0)
2651 * We use the same GUC parameter if this table is the child table of a
2652 * table called pg_hint_plan_get_relation_info just before that.
2656 /* append_rel_list contains all append rels; ignore others */
2657 foreach(l, root->append_rel_list)
2659 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2661 /* This rel is child table. */
2662 if (appinfo->parent_relid == current_hint->parent_relid &&
2663 appinfo->child_relid == rel->relid)
2665 if (current_hint->parent_hint)
2666 delete_indexes(current_hint->parent_hint, rel,
2673 /* This rel is not inherit table. */
2674 current_hint->parent_relid = 0;
2675 current_hint->parent_rel_oid = InvalidOid;
2676 current_hint->parent_hint = NULL;
2680 * If scan method hint was given, reset GUC parameters which control
2681 * planner behavior about choosing scan methods.
2683 if ((hint = find_scan_hint(root, rel)) == NULL)
2685 set_scan_config_options(current_hint->init_scan_mask,
2686 current_hint->context);
2689 set_scan_config_options(hint->enforce_mask, current_hint->context);
2690 hint->base.state = HINT_STATE_USED;
2698 current_hint->parent_hint = hint;
2700 relation = heap_open(relationObjectId, NoLock);
2701 indexoidlist = RelationGetIndexList(relation);
2703 foreach(l, indexoidlist)
2705 Oid indexoid = lfirst_oid(l);
2706 char *indexname = get_rel_name(indexoid);
2707 bool use_index = false;
2709 ParentIndexInfo *parent_index_info;
2711 foreach(lc, hint->indexnames)
2713 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
2722 parent_index_info = get_parent_index_info(indexoid,
2724 current_hint->parent_index_infos =
2725 lappend(current_hint->parent_index_infos, parent_index_info);
2727 heap_close(relation, NoLock);
2730 delete_indexes(hint, rel, InvalidOid);
2734 * Return index of relation which matches given aliasname, or 0 if not found.
2735 * If same aliasname was used multiple times in a query, return -1.
2738 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
2744 for (i = 1; i < root->simple_rel_array_size; i++)
2748 if (root->simple_rel_array[i] == NULL)
2751 Assert(i == root->simple_rel_array[i]->relid);
2753 if (RelnameCmp(&aliasname,
2754 &root->simple_rte_array[i]->eref->aliasname) != 0)
2757 foreach(l, initial_rels)
2759 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2761 if (rel->reloptkind == RELOPT_BASEREL)
2763 if (rel->relid != i)
2768 Assert(rel->reloptkind == RELOPT_JOINREL);
2770 if (!bms_is_member(i, rel->relids))
2777 ("Relation name \"%s\" is ambiguous.",
2792 * Return join hint which matches given joinrelids.
2794 static JoinMethodHint *
2795 find_join_hint(Relids joinrelids)
2800 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
2802 foreach(l, join_hint)
2804 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
2806 if (bms_equal(joinrelids, hint->joinrelids))
2814 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
2815 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
2817 OuterInnerRels *outer_rels;
2818 OuterInnerRels *inner_rels;
2819 Relids outer_relids;
2820 Relids inner_relids;
2822 JoinMethodHint *hint;
2824 if (outer_inner->relation != NULL)
2826 return bms_make_singleton(
2827 find_relid_aliasname(root, outer_inner->relation,
2829 leading_hint->base.hint_str));
2832 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
2833 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
2835 outer_relids = OuterInnerJoinCreate(outer_rels,
2841 inner_relids = OuterInnerJoinCreate(inner_rels,
2848 join_relids = bms_add_members(outer_relids, inner_relids);
2850 if (bms_num_members(join_relids) > nbaserel)
2854 * If we don't have join method hint, create new one for the
2855 * join combination with all join methods are enabled.
2857 hint = find_join_hint(join_relids);
2861 * Here relnames is not set, since Relids bitmap is sufficient to
2862 * control paths of this query afterward.
2864 hint = (JoinMethodHint *) JoinMethodHintCreate(
2865 leading_hint->base.hint_str,
2867 HINT_KEYWORD_LEADING);
2868 hint->base.state = HINT_STATE_USED;
2869 hint->nrels = bms_num_members(join_relids);
2870 hint->enforce_mask = ENABLE_ALL_JOIN;
2871 hint->joinrelids = bms_copy(join_relids);
2872 hint->inner_nrels = bms_num_members(inner_relids);
2873 hint->inner_joinrelids = bms_copy(inner_relids);
2875 hstate->join_hint_level[hint->nrels] =
2876 lappend(hstate->join_hint_level[hint->nrels], hint);
2880 hint->inner_nrels = bms_num_members(inner_relids);
2881 hint->inner_joinrelids = bms_copy(inner_relids);
2888 * Transform join method hint into handy form.
2890 * - create bitmap of relids from alias names, to make it easier to check
2891 * whether a join path matches a join method hint.
2892 * - add join method hints which are necessary to enforce join order
2893 * specified by Leading hint
2896 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2897 List *initial_rels, JoinMethodHint **join_method_hints)
2905 LeadingHint *lhint = NULL;
2908 * Create bitmap of relids from alias names for each join method hint.
2909 * Bitmaps are more handy than strings in join searching.
2911 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2913 JoinMethodHint *hint = hstate->join_hints[i];
2916 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
2919 bms_free(hint->joinrelids);
2920 hint->joinrelids = NULL;
2922 for (j = 0; j < hint->nrels; j++)
2924 relname = hint->relnames[j];
2926 relid = find_relid_aliasname(root, relname, initial_rels,
2927 hint->base.hint_str);
2930 hint->base.state = HINT_STATE_ERROR;
2935 if (bms_is_member(relid, hint->joinrelids))
2937 hint_ereport(hint->base.hint_str,
2938 ("Relation name \"%s\" is duplicated.", relname));
2939 hint->base.state = HINT_STATE_ERROR;
2943 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
2946 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
2949 hstate->join_hint_level[hint->nrels] =
2950 lappend(hstate->join_hint_level[hint->nrels], hint);
2953 /* Do nothing if no Leading hint was supplied. */
2954 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2958 * Decide to use Leading hint。
2960 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
2962 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
2965 if (leading_hint->base.state == HINT_STATE_ERROR)
2971 foreach(l, leading_hint->relations)
2973 relname = (char *)lfirst(l);;
2975 relid = find_relid_aliasname(root, relname, initial_rels,
2976 leading_hint->base.hint_str);
2978 leading_hint->base.state = HINT_STATE_ERROR;
2983 if (bms_is_member(relid, relids))
2985 hint_ereport(leading_hint->base.hint_str,
2986 ("Relation name \"%s\" is duplicated.", relname));
2987 leading_hint->base.state = HINT_STATE_ERROR;
2991 relids = bms_add_member(relids, relid);
2994 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
2999 hint_ereport(lhint->base.hint_str,
3000 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3001 lhint->base.state = HINT_STATE_DUPLICATION;
3003 leading_hint->base.state = HINT_STATE_USED;
3004 lhint = leading_hint;
3007 /* check to exist Leading hint marked with 'used'. */
3012 * We need join method hints which fit specified join order in every join
3013 * level. For example, Leading(A B C) virtually requires following join
3014 * method hints, if no join method hint supplied:
3016 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3017 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3019 * If we already have join method hint which fits specified join order in
3020 * that join level, we leave it as-is and don't add new hints.
3024 if (lhint->outer_inner == NULL)
3026 foreach(l, lhint->relations)
3028 JoinMethodHint *hint;
3030 relname = (char *)lfirst(l);
3033 * Find relid of the relation which has given name. If we have the
3034 * name given in Leading hint multiple times in the join, nothing to
3037 relid = find_relid_aliasname(root, relname, initial_rels,
3040 /* Create bitmap of relids for current join level. */
3041 joinrelids = bms_add_member(joinrelids, relid);
3044 /* We never have join method hint for single relation. */
3049 * If we don't have join method hint, create new one for the
3050 * join combination with all join methods are enabled.
3052 hint = find_join_hint(joinrelids);
3056 * Here relnames is not set, since Relids bitmap is sufficient
3057 * to control paths of this query afterward.
3059 hint = (JoinMethodHint *) JoinMethodHintCreate(
3060 lhint->base.hint_str,
3062 HINT_KEYWORD_LEADING);
3063 hint->base.state = HINT_STATE_USED;
3064 hint->nrels = njoinrels;
3065 hint->enforce_mask = ENABLE_ALL_JOIN;
3066 hint->joinrelids = bms_copy(joinrelids);
3069 join_method_hints[njoinrels] = hint;
3071 if (njoinrels >= nbaserel)
3074 bms_free(joinrelids);
3080 * Delete all join hints which have different combination from Leading
3083 for (i = 2; i <= njoinrels; i++)
3085 list_free(hstate->join_hint_level[i]);
3087 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3092 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3099 njoinrels = bms_num_members(joinrelids);
3100 Assert(njoinrels >= 2);
3103 * Delete all join hints which have different combination from Leading
3106 for (i = 2;i <= njoinrels; i++)
3108 if (hstate->join_hint_level[i] != NIL)
3110 ListCell *prev = NULL;
3111 ListCell *next = NULL;
3112 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3115 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3119 if (hint->inner_nrels == 0 &&
3120 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3121 bms_equal(bms_union(hint->joinrelids, joinrelids),
3124 hstate->join_hint_level[i] =
3125 list_delete_cell(hstate->join_hint_level[i], l,
3134 bms_free(joinrelids);
3137 if (hint_state_enabled(lhint))
3139 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3146 * set_plain_rel_pathlist
3147 * Build access paths for a plain relation (no subquery, no inheritance)
3149 * This function was copied and edited from set_plain_rel_pathlist() in
3150 * src/backend/optimizer/path/allpaths.c
3153 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3155 /* Consider sequential scan */
3156 #if PG_VERSION_NUM >= 90200
3157 add_path(rel, create_seqscan_path(root, rel, NULL));
3159 add_path(rel, create_seqscan_path(root, rel));
3162 /* Consider index scans */
3163 create_index_paths(root, rel);
3165 /* Consider TID scans */
3166 create_tidscan_paths(root, rel);
3168 /* Now find the cheapest of the paths for this rel */
3173 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3178 foreach(l, initial_rels)
3180 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3182 ScanMethodHint *hint;
3184 /* Skip relations which we can't choose scan method. */
3185 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3188 rte = root->simple_rte_array[rel->relid];
3190 /* We can't force scan method of foreign tables */
3191 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3195 * Create scan paths with GUC parameters which are at the beginning of
3196 * planner if scan method hint is not specified, otherwise use
3197 * specified hints and mark the hint as used.
3199 if ((hint = find_scan_hint(root, rel)) == NULL)
3200 set_scan_config_options(hstate->init_scan_mask,
3204 set_scan_config_options(hint->enforce_mask, hstate->context);
3205 hint->base.state = HINT_STATE_USED;
3208 list_free_deep(rel->pathlist);
3209 rel->pathlist = NIL;
3212 /* It's an "append relation", process accordingly */
3213 set_append_rel_pathlist(root, rel, rel->relid, rte);
3217 set_plain_rel_pathlist(root, rel, rte);
3222 * Restore the GUC variables we set above.
3224 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3228 * wrapper of make_join_rel()
3230 * call make_join_rel() after changing enable_* parameters according to given
3234 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3237 JoinMethodHint *hint;
3241 joinrelids = bms_union(rel1->relids, rel2->relids);
3242 hint = find_join_hint(joinrelids);
3243 bms_free(joinrelids);
3246 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3248 if (hint->inner_nrels == 0)
3250 save_nestlevel = NewGUCNestLevel();
3252 set_join_config_options(hint->enforce_mask, current_hint->context);
3254 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3255 hint->base.state = HINT_STATE_USED;
3258 * Restore the GUC variables we set above.
3260 AtEOXact_GUC(true, save_nestlevel);
3263 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3272 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3273 RelOptInfo *joinrel,
3274 RelOptInfo *outerrel,
3275 RelOptInfo *innerrel,
3277 SpecialJoinInfo *sjinfo,
3280 ScanMethodHint *scan_hint = NULL;
3282 JoinMethodHint *join_hint;
3285 if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
3287 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3288 scan_hint->base.state = HINT_STATE_USED;
3291 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3292 join_hint = find_join_hint(joinrelids);
3293 bms_free(joinrelids);
3295 if (join_hint && join_hint->inner_nrels != 0)
3297 save_nestlevel = NewGUCNestLevel();
3299 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3302 set_join_config_options(join_hint->enforce_mask,
3303 current_hint->context);
3305 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3306 sjinfo, restrictlist);
3307 join_hint->base.state = HINT_STATE_USED;
3311 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3312 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3313 sjinfo, restrictlist);
3317 * Restore the GUC variables we set above.
3319 AtEOXact_GUC(true, save_nestlevel);
3322 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3323 sjinfo, restrictlist);
3325 if (scan_hint != NULL)
3326 set_scan_config_options(current_hint->init_scan_mask,
3327 current_hint->context);
3331 get_num_baserels(List *initial_rels)
3336 foreach(l, initial_rels)
3338 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3340 if (rel->reloptkind == RELOPT_BASEREL)
3342 else if (rel->reloptkind ==RELOPT_JOINREL)
3343 nbaserel+= bms_num_members(rel->relids);
3346 /* other values not expected here */
3347 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3355 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3358 JoinMethodHint **join_method_hints;
3362 bool leading_hint_enable;
3365 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3366 * valid hint is supplied.
3370 if (prev_join_search)
3371 return (*prev_join_search) (root, levels_needed, initial_rels);
3372 else if (enable_geqo && levels_needed >= geqo_threshold)
3373 return geqo(root, levels_needed, initial_rels);
3375 return standard_join_search(root, levels_needed, initial_rels);
3378 /* We apply scan method hint rebuild scan path. */
3379 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3382 * In the case using GEQO, only scan method hints and Set hints have
3383 * effect. Join method and join order is not controllable by hints.
3385 if (enable_geqo && levels_needed >= geqo_threshold)
3386 return geqo(root, levels_needed, initial_rels);
3388 nbaserel = get_num_baserels(initial_rels);
3389 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3390 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3392 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3393 initial_rels, join_method_hints);
3395 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3397 for (i = 2; i <= nbaserel; i++)
3399 list_free(current_hint->join_hint_level[i]);
3401 /* free Leading hint only */
3402 if (join_method_hints[i] != NULL &&
3403 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3404 JoinMethodHintDelete(join_method_hints[i]);
3406 pfree(current_hint->join_hint_level);
3407 pfree(join_method_hints);
3409 if (leading_hint_enable)
3410 set_join_config_options(current_hint->init_join_mask,
3411 current_hint->context);
3418 * Build access paths for a base relation
3420 * This function was copied and edited from set_rel_pathlist() in
3421 * src/backend/optimizer/path/allpaths.c
3424 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3425 Index rti, RangeTblEntry *rte)
3427 #if PG_VERSION_NUM >= 90200
3428 if (IS_DUMMY_REL(rel))
3430 /* We already proved the relation empty, so nothing more to do */
3437 /* It's an "append relation", process accordingly */
3438 set_append_rel_pathlist(root, rel, rti, rte);
3442 if (rel->rtekind == RTE_RELATION)
3444 if (rte->relkind == RELKIND_RELATION)
3446 /* Plain relation */
3447 set_plain_rel_pathlist(root, rel, rte);
3450 elog(ERROR, "unexpected relkind: %c", rte->relkind);
3453 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
3457 #define standard_join_search pg_hint_plan_standard_join_search
3458 #define join_search_one_level pg_hint_plan_join_search_one_level
3459 #define make_join_rel make_join_rel_wrapper
3462 #undef make_join_rel
3463 #define make_join_rel pg_hint_plan_make_join_rel
3464 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
3465 #include "make_join_rel.c"