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"
43 #ifdef PG_MODULE_MAGIC
47 #if PG_VERSION_NUM < 90100
48 #error unsupported PostgreSQL version
51 #define BLOCK_COMMENT_START "/*"
52 #define BLOCK_COMMENT_END "*/"
53 #define HINT_COMMENT_KEYWORD "+"
54 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
55 #define HINT_END BLOCK_COMMENT_END
58 #define HINT_SEQSCAN "SeqScan"
59 #define HINT_INDEXSCAN "IndexScan"
60 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
61 #define HINT_BITMAPSCAN "BitmapScan"
62 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
63 #define HINT_TIDSCAN "TidScan"
64 #define HINT_NOSEQSCAN "NoSeqScan"
65 #define HINT_NOINDEXSCAN "NoIndexScan"
66 #define HINT_NOBITMAPSCAN "NoBitmapScan"
67 #define HINT_NOTIDSCAN "NoTidScan"
68 #if PG_VERSION_NUM >= 90200
69 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
70 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
71 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
73 #define HINT_NESTLOOP "NestLoop"
74 #define HINT_MERGEJOIN "MergeJoin"
75 #define HINT_HASHJOIN "HashJoin"
76 #define HINT_NONESTLOOP "NoNestLoop"
77 #define HINT_NOMERGEJOIN "NoMergeJoin"
78 #define HINT_NOHASHJOIN "NoHashJoin"
79 #define HINT_LEADING "Leading"
80 #define HINT_SET "Set"
82 #define HINT_ARRAY_DEFAULT_INITSIZE 8
84 #define hint_ereport(str, detail) \
85 ereport(pg_hint_plan_parse_messages, \
86 (errmsg("hint syntax error at or near \"%s\"", (str)), \
89 #define skip_space(str) \
90 while (isspace(*str)) \
95 ENABLE_SEQSCAN = 0x01,
96 ENABLE_INDEXSCAN = 0x02,
97 ENABLE_BITMAPSCAN = 0x04,
98 ENABLE_TIDSCAN = 0x08,
99 #if PG_VERSION_NUM >= 90200
100 ENABLE_INDEXONLYSCAN = 0x10
106 ENABLE_NESTLOOP = 0x01,
107 ENABLE_MERGEJOIN = 0x02,
108 ENABLE_HASHJOIN = 0x04
111 #if PG_VERSION_NUM >= 90200
112 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
113 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
114 ENABLE_INDEXONLYSCAN)
116 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
117 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN)
119 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
120 #define DISABLE_ALL_SCAN 0
121 #define DISABLE_ALL_JOIN 0
123 /* hint keyword of enum type*/
124 typedef enum HintKeyword
126 HINT_KEYWORD_SEQSCAN,
127 HINT_KEYWORD_INDEXSCAN,
128 HINT_KEYWORD_INDEXSCANREGEXP,
129 HINT_KEYWORD_BITMAPSCAN,
130 HINT_KEYWORD_BITMAPSCANREGEXP,
131 HINT_KEYWORD_TIDSCAN,
132 HINT_KEYWORD_NOSEQSCAN,
133 HINT_KEYWORD_NOINDEXSCAN,
134 HINT_KEYWORD_NOBITMAPSCAN,
135 HINT_KEYWORD_NOTIDSCAN,
136 #if PG_VERSION_NUM >= 90200
137 HINT_KEYWORD_INDEXONLYSCAN,
138 HINT_KEYWORD_INDEXONLYSCANREGEXP,
139 HINT_KEYWORD_NOINDEXONLYSCAN,
141 HINT_KEYWORD_NESTLOOP,
142 HINT_KEYWORD_MERGEJOIN,
143 HINT_KEYWORD_HASHJOIN,
144 HINT_KEYWORD_NONESTLOOP,
145 HINT_KEYWORD_NOMERGEJOIN,
146 HINT_KEYWORD_NOHASHJOIN,
147 HINT_KEYWORD_LEADING,
149 HINT_KEYWORD_UNRECOGNIZED
152 typedef struct Hint Hint;
153 typedef struct HintState HintState;
155 typedef Hint *(*HintCreateFunction) (const char *hint_str,
157 HintKeyword hint_keyword);
158 typedef void (*HintDeleteFunction) (Hint *hint);
159 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf);
160 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
161 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
162 Query *parse, const char *str);
165 #define NUM_HINT_TYPE 4
166 typedef enum HintType
168 HINT_TYPE_SCAN_METHOD,
169 HINT_TYPE_JOIN_METHOD,
174 static const char *HintTypeName[] = {
182 typedef enum HintStatus
184 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
185 HINT_STATE_USED, /* hint is used */
186 HINT_STATE_DUPLICATION, /* specified hint duplication */
187 HINT_STATE_ERROR /* execute error (parse error does not include
191 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
192 (hint)->base.state == HINT_STATE_USED)
194 /* common data for all hints. */
197 const char *hint_str; /* must not do pfree */
198 const char *keyword; /* must not do pfree */
199 HintKeyword hint_keyword;
202 HintDeleteFunction delete_func;
203 HintDescFunction desc_func;
204 HintCmpFunction cmp_func;
205 HintParseFunction parse_func;
208 /* scan method hints */
209 typedef struct ScanMethodHint
215 unsigned char enforce_mask;
218 typedef struct ParentIndexInfo
223 char *expression_str;
230 /* join method hints */
231 typedef struct JoinMethodHint
237 unsigned char enforce_mask;
239 Relids inner_joinrelids;
242 /* join order hints */
243 typedef struct OuterInnerRels
246 List *outer_inner_pair;
249 typedef struct LeadingHint
252 List *relations; /* relation names specified in Leading hint */
253 OuterInnerRels *outer_inner;
256 /* change a run-time parameter hints */
257 typedef struct SetHint
260 char *name; /* name of variable */
266 * Describes a context of hint processing.
270 char *hint_str; /* original hint string */
273 int nall_hints; /* # of valid all hints */
274 int max_all_hints; /* # of slots for all hints */
275 Hint **all_hints; /* parsed all hints */
277 /* # of each hints */
278 int num_hints[NUM_HINT_TYPE];
280 /* for scan method hints */
281 ScanMethodHint **scan_hints; /* parsed scan hints */
282 int init_scan_mask; /* initial value scan parameter */
283 Index parent_relid; /* inherit parent table relid */
284 Oid parent_rel_oid; /* inherit parent table relid */
285 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
286 List *parent_index_infos; /* infomation of inherit parent table's
289 /* for join method hints */
290 JoinMethodHint **join_hints; /* parsed join hints */
291 int init_join_mask; /* initial value join parameter */
292 List **join_hint_level;
294 /* for Leading hint */
295 LeadingHint **leading_hint; /* parsed Leading hints */
298 SetHint **set_hints; /* parsed Set hints */
299 GucContext context; /* which GUC parameters can we set? */
303 * Describes a hint parser module which is bound with particular hint keyword.
305 typedef struct HintParser
308 HintCreateFunction create_func;
309 HintKeyword hint_keyword;
312 /* Module callbacks */
316 static void push_hint(HintState *hstate);
317 static void pop_hint(void);
319 static void pg_hint_plan_ProcessUtility(Node *parsetree,
320 const char *queryString,
321 ParamListInfo params, bool isTopLevel,
323 char *completionTag);
324 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
325 ParamListInfo boundParams);
326 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
327 Oid relationObjectId,
328 bool inhparent, RelOptInfo *rel);
329 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
333 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
334 HintKeyword hint_keyword);
335 static void ScanMethodHintDelete(ScanMethodHint *hint);
336 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf);
337 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
338 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
339 Query *parse, const char *str);
340 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
341 HintKeyword hint_keyword);
342 static void JoinMethodHintDelete(JoinMethodHint *hint);
343 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf);
344 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
345 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
346 Query *parse, const char *str);
347 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
348 HintKeyword hint_keyword);
349 static void LeadingHintDelete(LeadingHint *hint);
350 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf);
351 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
352 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
353 Query *parse, const char *str);
354 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
355 HintKeyword hint_keyword);
356 static void SetHintDelete(SetHint *hint);
357 static void SetHintDesc(SetHint *hint, StringInfo buf);
358 static int SetHintCmp(const SetHint *a, const SetHint *b);
359 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
362 static void quote_value(StringInfo buf, const char *value);
364 static const char *parse_quoted_value(const char *str, char **word,
367 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
370 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
371 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
372 ListCell *other_rels);
373 static void make_rels_by_clauseless_joins(PlannerInfo *root,
375 ListCell *other_rels);
376 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
377 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
378 Index rti, RangeTblEntry *rte);
379 #if PG_VERSION_NUM >= 90200
380 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
381 List *live_childrels,
382 List *all_child_pathkeys);
384 static List *accumulate_append_subpath(List *subpaths, Path *path);
385 #if PG_VERSION_NUM < 90200
386 static void set_dummy_rel_pathlist(RelOptInfo *rel);
388 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
391 static void pg_hint_plan_plpgsql_func_setup(PLpgSQL_execstate *estate,
393 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
395 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
399 static bool pg_hint_plan_enable_hint = true;
400 static bool pg_hint_plan_debug_print = false;
401 static int pg_hint_plan_parse_messages = INFO;
403 static const struct config_enum_entry parse_messages_level_options[] = {
404 {"debug", DEBUG2, true},
405 {"debug5", DEBUG5, false},
406 {"debug4", DEBUG4, false},
407 {"debug3", DEBUG3, false},
408 {"debug2", DEBUG2, false},
409 {"debug1", DEBUG1, false},
411 {"info", INFO, false},
412 {"notice", NOTICE, false},
413 {"warning", WARNING, false},
414 {"error", ERROR, false},
416 * {"fatal", FATAL, true},
417 * {"panic", PANIC, true},
422 /* Saved hook values in case of unload */
423 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
424 static planner_hook_type prev_planner = NULL;
425 static get_relation_info_hook_type prev_get_relation_info = NULL;
426 static join_search_hook_type prev_join_search = NULL;
428 /* Hold reference to currently active hint */
429 static HintState *current_hint = NULL;
432 * List of hint contexts. We treat the head of the list as the Top of the
433 * context stack, so current_hint always points the first element of this list.
435 static List *HintStateStack = NIL;
438 * Holds statement name during executing EXECUTE command. NULL for other
441 static char *stmt_name = NULL;
443 static const HintParser parsers[] = {
444 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
445 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
446 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
447 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
448 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
449 HINT_KEYWORD_BITMAPSCANREGEXP},
450 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
451 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
452 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
453 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
454 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
455 #if PG_VERSION_NUM >= 90200
456 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
457 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
458 HINT_KEYWORD_INDEXONLYSCANREGEXP},
459 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
461 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
462 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
463 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
464 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
465 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
466 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
467 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
468 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
469 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
472 const char *hint_query_string = NULL;
473 PLpgSQL_plugin plugin_funcs = { };
475 * Module load callbacks
480 /* Define custom GUC variables. */
481 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
482 "Force planner to use plans specified in the hint comment preceding to the query.",
484 &pg_hint_plan_enable_hint,
492 DefineCustomBoolVariable("pg_hint_plan.debug_print",
493 "Logs results of hint parsing.",
495 &pg_hint_plan_debug_print,
503 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
504 "Message level of parse errors.",
506 &pg_hint_plan_parse_messages,
508 parse_messages_level_options,
516 prev_ProcessUtility = ProcessUtility_hook;
517 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
518 prev_planner = planner_hook;
519 planner_hook = pg_hint_plan_planner;
520 prev_get_relation_info = get_relation_info_hook;
521 get_relation_info_hook = pg_hint_plan_get_relation_info;
522 prev_join_search = join_search_hook;
523 join_search_hook = pg_hint_plan_join_search;
525 /* PL/pgSQL plugin hook */
526 PLpgSQL_plugin **var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
527 *var_ptr = &plugin_funcs;
528 (&plugin_funcs)->func_setup = (void *)pg_hint_plan_plpgsql_func_setup;
532 * Module unload callback
538 /* Uninstall hooks. */
539 ProcessUtility_hook = prev_ProcessUtility;
540 planner_hook = prev_planner;
541 get_relation_info_hook = prev_get_relation_info;
542 join_search_hook = prev_join_search;
546 * create and delete functions the hint object
550 ScanMethodHintCreate(const char *hint_str, const char *keyword,
551 HintKeyword hint_keyword)
553 ScanMethodHint *hint;
555 hint = palloc(sizeof(ScanMethodHint));
556 hint->base.hint_str = hint_str;
557 hint->base.keyword = keyword;
558 hint->base.hint_keyword = hint_keyword;
559 hint->base.type = HINT_TYPE_SCAN_METHOD;
560 hint->base.state = HINT_STATE_NOTUSED;
561 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
562 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
563 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
564 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
565 hint->relname = NULL;
566 hint->indexnames = NIL;
567 hint->regexp = false;
568 hint->enforce_mask = 0;
570 return (Hint *) hint;
574 ScanMethodHintDelete(ScanMethodHint *hint)
580 pfree(hint->relname);
581 list_free_deep(hint->indexnames);
586 JoinMethodHintCreate(const char *hint_str, const char *keyword,
587 HintKeyword hint_keyword)
589 JoinMethodHint *hint;
591 hint = palloc(sizeof(JoinMethodHint));
592 hint->base.hint_str = hint_str;
593 hint->base.keyword = keyword;
594 hint->base.hint_keyword = hint_keyword;
595 hint->base.type = HINT_TYPE_JOIN_METHOD;
596 hint->base.state = HINT_STATE_NOTUSED;
597 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
598 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
599 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
600 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
602 hint->inner_nrels = 0;
603 hint->relnames = NULL;
604 hint->enforce_mask = 0;
605 hint->joinrelids = NULL;
606 hint->inner_joinrelids = NULL;
608 return (Hint *) hint;
612 JoinMethodHintDelete(JoinMethodHint *hint)
621 for (i = 0; i < hint->nrels; i++)
622 pfree(hint->relnames[i]);
623 pfree(hint->relnames);
626 bms_free(hint->joinrelids);
627 bms_free(hint->inner_joinrelids);
632 LeadingHintCreate(const char *hint_str, const char *keyword,
633 HintKeyword hint_keyword)
637 hint = palloc(sizeof(LeadingHint));
638 hint->base.hint_str = hint_str;
639 hint->base.keyword = keyword;
640 hint->base.hint_keyword = hint_keyword;
641 hint->base.type = HINT_TYPE_LEADING;
642 hint->base.state = HINT_STATE_NOTUSED;
643 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
644 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
645 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
646 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
647 hint->relations = NIL;
648 hint->outer_inner = NULL;
650 return (Hint *) hint;
654 LeadingHintDelete(LeadingHint *hint)
659 list_free_deep(hint->relations);
660 if (hint->outer_inner)
661 pfree(hint->outer_inner);
666 SetHintCreate(const char *hint_str, const char *keyword,
667 HintKeyword hint_keyword)
671 hint = palloc(sizeof(SetHint));
672 hint->base.hint_str = hint_str;
673 hint->base.keyword = keyword;
674 hint->base.hint_keyword = hint_keyword;
675 hint->base.type = HINT_TYPE_SET;
676 hint->base.state = HINT_STATE_NOTUSED;
677 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
678 hint->base.desc_func = (HintDescFunction) SetHintDesc;
679 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
680 hint->base.parse_func = (HintParseFunction) SetHintParse;
685 return (Hint *) hint;
689 SetHintDelete(SetHint *hint)
699 list_free(hint->words);
704 HintStateCreate(void)
708 hstate = palloc(sizeof(HintState));
709 hstate->hint_str = NULL;
710 hstate->nall_hints = 0;
711 hstate->max_all_hints = 0;
712 hstate->all_hints = NULL;
713 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
714 hstate->scan_hints = NULL;
715 hstate->init_scan_mask = 0;
716 hstate->parent_relid = 0;
717 hstate->parent_rel_oid = InvalidOid;
718 hstate->parent_hint = NULL;
719 hstate->parent_index_infos = NIL;
720 hstate->join_hints = NULL;
721 hstate->init_join_mask = 0;
722 hstate->join_hint_level = NULL;
723 hstate->leading_hint = NULL;
724 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
725 hstate->set_hints = NULL;
731 HintStateDelete(HintState *hstate)
738 if (hstate->hint_str)
739 pfree(hstate->hint_str);
741 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
742 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
743 if (hstate->all_hints)
744 pfree(hstate->all_hints);
745 if (hstate->parent_index_infos)
746 list_free(hstate->parent_index_infos);
750 * Copy given value into buf, with quoting with '"' if necessary.
753 quote_value(StringInfo buf, const char *value)
755 bool need_quote = false;
758 for (str = value; *str != '\0'; str++)
760 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
763 appendStringInfoCharMacro(buf, '"');
768 for (str = value; *str != '\0'; str++)
771 appendStringInfoCharMacro(buf, '"');
773 appendStringInfoCharMacro(buf, *str);
777 appendStringInfoCharMacro(buf, '"');
781 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
785 appendStringInfo(buf, "%s(", hint->base.keyword);
786 if (hint->relname != NULL)
788 quote_value(buf, hint->relname);
789 foreach(l, hint->indexnames)
791 appendStringInfoCharMacro(buf, ' ');
792 quote_value(buf, (char *) lfirst(l));
795 appendStringInfoString(buf, ")\n");
799 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
803 appendStringInfo(buf, "%s(", hint->base.keyword);
804 if (hint->relnames != NULL)
806 quote_value(buf, hint->relnames[0]);
807 for (i = 1; i < hint->nrels; i++)
809 appendStringInfoCharMacro(buf, ' ');
810 quote_value(buf, hint->relnames[i]);
813 appendStringInfoString(buf, ")\n");
818 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
820 if (outer_inner->relation == NULL)
827 appendStringInfoCharMacro(buf, '(');
828 foreach(l, outer_inner->outer_inner_pair)
833 appendStringInfoCharMacro(buf, ' ');
835 OuterInnerDesc(lfirst(l), buf);
838 appendStringInfoCharMacro(buf, ')');
841 quote_value(buf, outer_inner->relation);
845 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
847 appendStringInfo(buf, "%s(", HINT_LEADING);
848 if (hint->outer_inner == NULL)
855 foreach(l, hint->relations)
860 appendStringInfoCharMacro(buf, ' ');
862 quote_value(buf, (char *) lfirst(l));
866 OuterInnerDesc(hint->outer_inner, buf);
868 appendStringInfoString(buf, ")\n");
872 SetHintDesc(SetHint *hint, StringInfo buf)
874 bool is_first = true;
877 appendStringInfo(buf, "%s(", HINT_SET);
878 foreach(l, hint->words)
883 appendStringInfoCharMacro(buf, ' ');
885 quote_value(buf, (char *) lfirst(l));
887 appendStringInfo(buf, ")\n");
891 * Append string which repserents all hints in a given state to buf, with
892 * preceding title with them.
895 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
900 appendStringInfo(buf, "%s:\n", title);
901 for (i = 0; i < hstate->nall_hints; i++)
903 if (hstate->all_hints[i]->state != state)
906 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf);
911 * Dump contents of given hstate to server log with log level LOG.
914 HintStateDump(HintState *hstate)
920 elog(LOG, "pg_hint_plan:\nno hint");
924 initStringInfo(&buf);
926 appendStringInfoString(&buf, "pg_hint_plan:\n");
927 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
928 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
929 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
930 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
932 elog(LOG, "%s", buf.data);
942 RelnameCmp(const void *a, const void *b)
944 const char *relnamea = *((const char **) a);
945 const char *relnameb = *((const char **) b);
947 return strcmp(relnamea, relnameb);
951 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
953 return RelnameCmp(&a->relname, &b->relname);
957 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
961 if (a->nrels != b->nrels)
962 return a->nrels - b->nrels;
964 for (i = 0; i < a->nrels; i++)
967 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
975 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
981 SetHintCmp(const SetHint *a, const SetHint *b)
983 return strcmp(a->name, b->name);
987 HintCmp(const void *a, const void *b)
989 const Hint *hinta = *((const Hint **) a);
990 const Hint *hintb = *((const Hint **) b);
992 if (hinta->type != hintb->type)
993 return hinta->type - hintb->type;
994 if (hinta->state == HINT_STATE_ERROR)
996 if (hintb->state == HINT_STATE_ERROR)
998 return hinta->cmp_func(hinta, hintb);
1002 * Returns byte offset of hint b from hint a. If hint a was specified before
1003 * b, positive value is returned.
1006 HintCmpWithPos(const void *a, const void *b)
1008 const Hint *hinta = *((const Hint **) a);
1009 const Hint *hintb = *((const Hint **) b);
1012 result = HintCmp(a, b);
1014 result = hinta->hint_str - hintb->hint_str;
1023 parse_keyword(const char *str, StringInfo buf)
1027 while (!isspace(*str) && *str != '(' && *str != '\0')
1028 appendStringInfoCharMacro(buf, *str++);
1034 skip_parenthesis(const char *str, char parenthesis)
1038 if (*str != parenthesis)
1040 if (parenthesis == '(')
1041 hint_ereport(str, ("Opening parenthesis is necessary."));
1042 else if (parenthesis == ')')
1043 hint_ereport(str, ("Closing parenthesis is necessary."));
1054 * Parse a token from str, and store malloc'd copy into word. A token can be
1055 * quoted with '"'. Return value is pointer to unparsed portion of original
1056 * string, or NULL if an error occurred.
1058 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1061 parse_quoted_value(const char *str, char **word, bool truncate)
1066 /* Skip leading spaces. */
1069 initStringInfo(&buf);
1082 /* Double quotation must be closed. */
1086 hint_ereport(str, ("Unterminated quoted string."));
1091 * Skip escaped double quotation.
1093 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1094 * block comments) to be an object name, so users must specify
1095 * alias for such object names.
1097 * Those special names can be allowed if we care escaped slashes
1098 * and asterisks, but we don't.
1107 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1111 appendStringInfoCharMacro(&buf, *str++);
1116 hint_ereport(str, ("Zero-length delimited string."));
1123 /* Truncate name if it's too long */
1125 truncate_identifier(buf.data, strlen(buf.data), true);
1132 static OuterInnerRels *
1133 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1135 OuterInnerRels *outer_inner;
1137 outer_inner = palloc(sizeof(OuterInnerRels));
1138 outer_inner->relation = name;
1139 outer_inner->outer_inner_pair = outer_inner_list;
1145 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1147 List *outer_inner_pair = NIL;
1149 if ((str = skip_parenthesis(str, '(')) == NULL)
1154 /* Store words in parentheses into outer_inner_list. */
1155 while(*str != ')' && *str != '\0')
1157 OuterInnerRels *outer_inner_rels;
1161 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1169 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1172 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1175 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1180 (str = skip_parenthesis(str, ')')) == NULL)
1182 list_free(outer_inner_pair);
1186 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1192 parse_parentheses_Leading(const char *str, List **name_list,
1193 OuterInnerRels **outer_inner)
1196 bool truncate = true;
1198 if ((str = skip_parenthesis(str, '(')) == NULL)
1204 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1209 /* Store words in parentheses into name_list. */
1210 while(*str != ')' && *str != '\0')
1212 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1214 list_free(*name_list);
1218 *name_list = lappend(*name_list, name);
1223 if ((str = skip_parenthesis(str, ')')) == NULL)
1229 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1232 bool truncate = true;
1234 if ((str = skip_parenthesis(str, '(')) == NULL)
1239 /* Store words in parentheses into name_list. */
1240 while(*str != ')' && *str != '\0')
1242 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1244 list_free(*name_list);
1248 *name_list = lappend(*name_list, name);
1251 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1252 #if PG_VERSION_NUM >= 90200
1253 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1255 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1256 keyword == HINT_KEYWORD_SET)
1262 if ((str = skip_parenthesis(str, ')')) == NULL)
1268 parse_hints(HintState *hstate, Query *parse, const char *str)
1273 initStringInfo(&buf);
1274 while (*str != '\0')
1276 const HintParser *parser;
1278 /* in error message, we output the comment including the keyword. */
1279 head = (char *) str;
1281 /* parse only the keyword of the hint. */
1282 resetStringInfo(&buf);
1283 str = parse_keyword(str, &buf);
1285 for (parser = parsers; parser->keyword != NULL; parser++)
1287 char *keyword = parser->keyword;
1290 if (strcasecmp(buf.data, keyword) != 0)
1293 hint = parser->create_func(head, keyword, parser->hint_keyword);
1295 /* parser of each hint does parse in a parenthesis. */
1296 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1298 hint->delete_func(hint);
1304 * Add hint information into all_hints array. If we don't have
1305 * enough space, double the array.
1307 if (hstate->nall_hints == 0)
1309 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1310 hstate->all_hints = (Hint **)
1311 palloc(sizeof(Hint *) * hstate->max_all_hints);
1313 else if (hstate->nall_hints == hstate->max_all_hints)
1315 hstate->max_all_hints *= 2;
1316 hstate->all_hints = (Hint **)
1317 repalloc(hstate->all_hints,
1318 sizeof(Hint *) * hstate->max_all_hints);
1321 hstate->all_hints[hstate->nall_hints] = hint;
1322 hstate->nall_hints++;
1329 if (parser->keyword == NULL)
1332 ("Unrecognized hint keyword \"%s\".", buf.data));
1343 * Get hints from table by client-supplied query string and application name.
1346 get_hints_from_table(const char *client_query, const char *client_application)
1348 const char *search_query =
1350 " FROM hint_plan.hints "
1351 " WHERE norm_query_string = $1 "
1352 " AND ( application_name = $2 "
1353 " OR application_name = '' ) "
1354 " ORDER BY application_name DESC";
1355 static SPIPlanPtr plan = NULL;
1358 Oid argtypes[2] = { TEXTOID, TEXTOID };
1360 bool nulls[2] = { false, false };
1364 ret = SPI_connect();
1365 if (ret != SPI_OK_CONNECT)
1366 elog(ERROR, "pg_hint_plan: SPI_connect => %d", ret);
1371 p = SPI_prepare(search_query, 2, argtypes);
1373 elog(ERROR, "pg_hint_plan: SPI_prepare => %d", SPI_result);
1374 plan = SPI_saveplan(p);
1378 qry = cstring_to_text(client_query);
1379 app = cstring_to_text(client_application);
1380 values[0] = PointerGetDatum(qry);
1381 values[1] = PointerGetDatum(app);
1383 pg_hint_plan_enable_hint = false;
1384 ret = SPI_execute_plan(plan, values, nulls, true, 1);
1385 pg_hint_plan_enable_hint = true;
1386 if (ret != SPI_OK_SELECT)
1387 elog(ERROR, "pg_hint_plan: SPI_execute_plan => %d", ret);
1389 if (SPI_processed > 0)
1393 hints = SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
1395 * SPI_connectで新しく作成されたメモリコンテキスト内で、pallocを
1396 * 使用してメモリを確保してもSPI_finishで解放されてしまう。
1397 * それを防ぐために、SPI_pallocを使って上位エクゼキュータコンテ
1398 * キスト内にメモリを確保し、そこにヒント用テーブルから取得した
1401 buf = SPI_palloc(strlen(hints) + 1);
1412 * Get client-supplied query string.
1415 get_query_string(void)
1421 PreparedStatement *entry;
1423 entry = FetchPreparedStatement(stmt_name, true);
1424 p = entry->plansource->query_string;
1426 else if (hint_query_string)
1427 p = hint_query_string;
1429 p = debug_query_string;
1435 * Get hints from the head block comment in client-supplied query string.
1438 get_hints_from_comment(const char *p)
1440 const char *hint_head;
1448 /* extract query head comment. */
1449 hint_head = strstr(p, HINT_START);
1450 if (hint_head == NULL)
1452 for (;p < hint_head; p++)
1455 * Allow these characters precedes hint comment:
1457 * - alphabets which are in ASCII range
1458 * - space, tabs and new-lines
1459 * - underscores, for identifier
1460 * - commas, for SELECT clause, EXPLAIN and PREPARE
1461 * - parentheses, for EXPLAIN and PREPARE
1463 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1464 * avoid behavior which depends on locale setting.
1466 if (!(*p >= '0' && *p <= '9') &&
1467 !(*p >= 'A' && *p <= 'Z') &&
1468 !(*p >= 'a' && *p <= 'z') &&
1472 *p != '(' && *p != ')')
1476 len = strlen(HINT_START);
1481 /* find hint end keyword. */
1482 if ((tail = strstr(p, HINT_END)) == NULL)
1484 hint_ereport(head, ("Unterminated block comment."));
1488 /* We don't support nested block comments. */
1489 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1491 hint_ereport(head, ("Nested block comments are not supported."));
1495 /* Make a copy of hint. */
1497 head = palloc(len + 1);
1498 memcpy(head, p, len);
1506 * Parse hints that got, create hint struct from parse tree and parse hints.
1509 create_hintstate(Query *parse, const char *hints)
1519 hstate = HintStateCreate();
1520 hstate->hint_str = (char *) hints;
1522 /* parse each hint. */
1523 parse_hints(hstate, parse, p);
1525 /* When nothing specified a hint, we free HintState and returns NULL. */
1526 if (hstate->nall_hints == 0)
1528 HintStateDelete(hstate);
1532 /* Sort hints in order of original position. */
1533 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1536 /* Count number of hints per hint-type. */
1537 for (i = 0; i < hstate->nall_hints; i++)
1539 Hint *cur_hint = hstate->all_hints[i];
1540 hstate->num_hints[cur_hint->type]++;
1544 * If an object (or a set of objects) has multiple hints of same hint-type,
1545 * only the last hint is valid and others are igonred in planning.
1546 * Hints except the last are marked as 'duplicated' to remember the order.
1548 for (i = 0; i < hstate->nall_hints - 1; i++)
1550 Hint *cur_hint = hstate->all_hints[i];
1551 Hint *next_hint = hstate->all_hints[i + 1];
1554 * Leading hint is marked as 'duplicated' in transform_join_hints.
1556 if (cur_hint->type == HINT_TYPE_LEADING &&
1557 next_hint->type == HINT_TYPE_LEADING)
1561 * Note that we need to pass addresses of hint pointers, because
1562 * HintCmp is designed to sort array of Hint* by qsort.
1564 if (HintCmp(&cur_hint, &next_hint) == 0)
1566 hint_ereport(cur_hint->hint_str,
1567 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1568 cur_hint->state = HINT_STATE_DUPLICATION;
1573 * Make sure that per-type array pointers point proper position in the
1574 * array which consists of all hints.
1576 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1577 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1578 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1579 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1580 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1581 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1582 hstate->num_hints[HINT_TYPE_LEADING]);
1588 * Parse inside of parentheses of scan-method hints.
1591 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1594 const char *keyword = hint->base.keyword;
1595 HintKeyword hint_keyword = hint->base.hint_keyword;
1596 List *name_list = NIL;
1599 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1602 /* Parse relation name and index name(s) if given hint accepts. */
1603 length = list_length(name_list);
1606 hint->relname = linitial(name_list);
1607 hint->indexnames = list_delete_first(name_list);
1609 /* check whether the hint accepts index name(s). */
1611 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1612 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1613 #if PG_VERSION_NUM >= 90200
1614 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1615 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1617 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1618 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1621 ("%s hint accepts only one relation.",
1622 hint->base.keyword));
1623 hint->base.state = HINT_STATE_ERROR;
1630 ("%s hint requires a relation.",
1631 hint->base.keyword));
1632 hint->base.state = HINT_STATE_ERROR;
1636 /* Set a bit for specified hint. */
1637 switch (hint_keyword)
1639 case HINT_KEYWORD_SEQSCAN:
1640 hint->enforce_mask = ENABLE_SEQSCAN;
1642 case HINT_KEYWORD_INDEXSCAN:
1643 hint->enforce_mask = ENABLE_INDEXSCAN;
1645 case HINT_KEYWORD_INDEXSCANREGEXP:
1646 hint->enforce_mask = ENABLE_INDEXSCAN;
1647 hint->regexp = true;
1649 case HINT_KEYWORD_BITMAPSCAN:
1650 hint->enforce_mask = ENABLE_BITMAPSCAN;
1652 case HINT_KEYWORD_BITMAPSCANREGEXP:
1653 hint->enforce_mask = ENABLE_BITMAPSCAN;
1654 hint->regexp = true;
1656 case HINT_KEYWORD_TIDSCAN:
1657 hint->enforce_mask = ENABLE_TIDSCAN;
1659 case HINT_KEYWORD_NOSEQSCAN:
1660 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1662 case HINT_KEYWORD_NOINDEXSCAN:
1663 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1665 case HINT_KEYWORD_NOBITMAPSCAN:
1666 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1668 case HINT_KEYWORD_NOTIDSCAN:
1669 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1671 #if PG_VERSION_NUM >= 90200
1672 case HINT_KEYWORD_INDEXONLYSCAN:
1673 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1675 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1676 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1677 hint->regexp = true;
1679 case HINT_KEYWORD_NOINDEXONLYSCAN:
1680 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1684 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1693 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1696 const char *keyword = hint->base.keyword;
1697 HintKeyword hint_keyword = hint->base.hint_keyword;
1698 List *name_list = NIL;
1700 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1703 hint->nrels = list_length(name_list);
1705 if (hint->nrels > 0)
1711 * Transform relation names from list to array to sort them with qsort
1714 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1715 foreach (l, name_list)
1717 hint->relnames[i] = lfirst(l);
1722 list_free(name_list);
1724 /* A join hint requires at least two relations */
1725 if (hint->nrels < 2)
1728 ("%s hint requires at least two relations.",
1729 hint->base.keyword));
1730 hint->base.state = HINT_STATE_ERROR;
1734 /* Sort hints in alphabetical order of relation names. */
1735 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1737 switch (hint_keyword)
1739 case HINT_KEYWORD_NESTLOOP:
1740 hint->enforce_mask = ENABLE_NESTLOOP;
1742 case HINT_KEYWORD_MERGEJOIN:
1743 hint->enforce_mask = ENABLE_MERGEJOIN;
1745 case HINT_KEYWORD_HASHJOIN:
1746 hint->enforce_mask = ENABLE_HASHJOIN;
1748 case HINT_KEYWORD_NONESTLOOP:
1749 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1751 case HINT_KEYWORD_NOMERGEJOIN:
1752 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1754 case HINT_KEYWORD_NOHASHJOIN:
1755 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1758 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1767 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1770 if (outer_inner->outer_inner_pair == NIL)
1772 if (outer_inner->relation)
1778 if (list_length(outer_inner->outer_inner_pair) == 2)
1780 foreach(l, outer_inner->outer_inner_pair)
1782 if (!OuterInnerPairCheck(lfirst(l)))
1793 OuterInnerList(OuterInnerRels *outer_inner)
1795 List *outer_inner_list = NIL;
1797 OuterInnerRels *outer_inner_rels;
1799 foreach(l, outer_inner->outer_inner_pair)
1801 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
1803 if (outer_inner_rels->relation != NULL)
1804 outer_inner_list = lappend(outer_inner_list,
1805 outer_inner_rels->relation);
1807 outer_inner_list = list_concat(outer_inner_list,
1808 OuterInnerList(outer_inner_rels));
1810 return outer_inner_list;
1814 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1817 List *name_list = NIL;
1818 OuterInnerRels *outer_inner = NULL;
1820 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
1824 if (outer_inner != NULL)
1825 name_list = OuterInnerList(outer_inner);
1827 hint->relations = name_list;
1828 hint->outer_inner = outer_inner;
1830 /* A Leading hint requires at least two relations */
1831 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
1833 hint_ereport(hint->base.hint_str,
1834 ("%s hint requires at least two relations.",
1836 hint->base.state = HINT_STATE_ERROR;
1838 else if (hint->outer_inner != NULL &&
1839 !OuterInnerPairCheck(hint->outer_inner))
1841 hint_ereport(hint->base.hint_str,
1842 ("%s hint requires two sets of relations when parentheses nests.",
1844 hint->base.state = HINT_STATE_ERROR;
1851 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1853 List *name_list = NIL;
1855 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
1859 hint->words = name_list;
1861 /* We need both name and value to set GUC parameter. */
1862 if (list_length(name_list) == 2)
1864 hint->name = linitial(name_list);
1865 hint->value = lsecond(name_list);
1869 hint_ereport(hint->base.hint_str,
1870 ("%s hint requires name and value of GUC parameter.",
1872 hint->base.state = HINT_STATE_ERROR;
1879 * set GUC parameter functions
1883 set_config_option_wrapper(const char *name, const char *value,
1884 GucContext context, GucSource source,
1885 GucAction action, bool changeVal, int elevel)
1888 MemoryContext ccxt = CurrentMemoryContext;
1892 #if PG_VERSION_NUM >= 90200
1893 result = set_config_option(name, value, context, source,
1894 action, changeVal, 0);
1896 result = set_config_option(name, value, context, source,
1904 /* Save error info */
1905 MemoryContextSwitchTo(ccxt);
1906 errdata = CopyErrorData();
1909 ereport(elevel, (errcode(errdata->sqlerrcode),
1910 errmsg("%s", errdata->message),
1911 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1912 errdata->hint ? errhint("%s", errdata->hint) : 0));
1913 FreeErrorData(errdata);
1921 set_config_options(SetHint **options, int noptions, GucContext context)
1926 save_nestlevel = NewGUCNestLevel();
1928 for (i = 0; i < noptions; i++)
1930 SetHint *hint = options[i];
1933 if (!hint_state_enabled(hint))
1936 result = set_config_option_wrapper(hint->name, hint->value, context,
1937 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1938 pg_hint_plan_parse_messages);
1940 hint->base.state = HINT_STATE_USED;
1942 hint->base.state = HINT_STATE_ERROR;
1945 return save_nestlevel;
1948 #define SET_CONFIG_OPTION(name, type_bits) \
1949 set_config_option_wrapper((name), \
1950 (mask & (type_bits)) ? "true" : "false", \
1951 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1954 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1958 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1959 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1960 #if PG_VERSION_NUM >= 90200
1961 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1964 mask = enforce_mask;
1966 mask = enforce_mask & current_hint->init_scan_mask;
1968 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1969 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1970 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1971 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1972 #if PG_VERSION_NUM >= 90200
1973 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1978 set_join_config_options(unsigned char enforce_mask, GucContext context)
1982 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1983 enforce_mask == ENABLE_HASHJOIN)
1984 mask = enforce_mask;
1986 mask = enforce_mask & current_hint->init_join_mask;
1988 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1989 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1990 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1994 * pg_hint_plan hook functions
1998 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1999 ParamListInfo params, bool isTopLevel,
2000 DestReceiver *dest, char *completionTag)
2004 if (!pg_hint_plan_enable_hint)
2006 if (prev_ProcessUtility)
2007 (*prev_ProcessUtility) (parsetree, queryString, params,
2008 isTopLevel, dest, completionTag);
2010 standard_ProcessUtility(parsetree, queryString, params,
2011 isTopLevel, dest, completionTag);
2017 if (IsA(node, ExplainStmt))
2020 * Draw out parse tree of actual query from Query struct of EXPLAIN
2026 stmt = (ExplainStmt *) node;
2028 Assert(IsA(stmt->query, Query));
2029 query = (Query *) stmt->query;
2031 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2032 node = query->utilityStmt;
2036 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2037 * specified to preceding PREPARE command to use it as source of hints.
2039 if (IsA(node, ExecuteStmt))
2043 stmt = (ExecuteStmt *) node;
2044 stmt_name = stmt->name;
2046 #if PG_VERSION_NUM >= 90200
2048 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2051 if (IsA(node, CreateTableAsStmt))
2053 CreateTableAsStmt *stmt;
2056 stmt = (CreateTableAsStmt *) node;
2057 Assert(IsA(stmt->query, Query));
2058 query = (Query *) stmt->query;
2060 if (query->commandType == CMD_UTILITY &&
2061 IsA(query->utilityStmt, ExecuteStmt))
2063 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2064 stmt_name = estmt->name;
2072 if (prev_ProcessUtility)
2073 (*prev_ProcessUtility) (parsetree, queryString, params,
2074 isTopLevel, dest, completionTag);
2076 standard_ProcessUtility(parsetree, queryString, params,
2077 isTopLevel, dest, completionTag);
2091 if (prev_ProcessUtility)
2092 (*prev_ProcessUtility) (parsetree, queryString, params,
2093 isTopLevel, dest, completionTag);
2095 standard_ProcessUtility(parsetree, queryString, params,
2096 isTopLevel, dest, completionTag);
2100 * Push a hint into hint stack which is implemented with List struct. Head of
2101 * list is top of stack.
2104 push_hint(HintState *hstate)
2106 /* Prepend new hint to the list means pushing to stack. */
2107 HintStateStack = lcons(hstate, HintStateStack);
2109 /* Pushed hint is the one which should be used hereafter. */
2110 current_hint = hstate;
2113 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2117 /* Hint stack must not be empty. */
2118 if(HintStateStack == NIL)
2119 elog(ERROR, "hint stack is empty");
2122 * Take a hint at the head from the list, and free it. Switch current_hint
2123 * to point new head (NULL if the list is empty).
2125 HintStateStack = list_delete_first(HintStateStack);
2126 HintStateDelete(current_hint);
2127 if(HintStateStack == NIL)
2128 current_hint = NULL;
2130 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2133 static PlannedStmt *
2134 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2139 PlannedStmt *result;
2143 * Use standard planner if pg_hint_plan is disabled. Other hook functions
2144 * try to change plan with current_hint if any, so set it to NULL.
2146 if (!pg_hint_plan_enable_hint)
2147 goto standard_planner_proc;
2149 /* Create hint struct from client-supplied query string. */
2150 query = get_query_string();
2153 * get_hints_from_table
2154 * TODO: replace "app1" with current application_name setting of the
2156 * XXX: use something instead of debug_query_string?
2158 hints = get_hints_from_table(query, application_name);
2160 "pg_hint_plan: get_hints_from_table [%s][%s]=>[%s]",
2161 query, application_name,
2162 hints ? hints : "(none)");
2164 hints = get_hints_from_comment(query);
2165 hstate = create_hintstate(parse, hints);
2168 * Use standard planner if the statement has not valid hint. Other hook
2169 * functions try to change plan with current_hint if any, so set it to
2173 goto standard_planner_proc;
2176 * Push new hint struct to the hint stack to disable previous hint context.
2180 /* Set GUC parameters which are specified with Set hint. */
2181 save_nestlevel = set_config_options(current_hint->set_hints,
2182 current_hint->num_hints[HINT_TYPE_SET],
2183 current_hint->context);
2186 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2187 if (enable_indexscan)
2188 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2189 if (enable_bitmapscan)
2190 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2192 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2193 #if PG_VERSION_NUM >= 90200
2194 if (enable_indexonlyscan)
2195 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2197 if (enable_nestloop)
2198 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2199 if (enable_mergejoin)
2200 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2201 if (enable_hashjoin)
2202 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2205 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2206 * state when this planner started when error occurred in planner.
2211 result = (*prev_planner) (parse, cursorOptions, boundParams);
2213 result = standard_planner(parse, cursorOptions, boundParams);
2218 * Rollback changes of GUC parameters, and pop current hint context
2219 * from hint stack to rewind the state.
2221 AtEOXact_GUC(true, save_nestlevel);
2227 /* Print hint in debug mode. */
2228 if (pg_hint_plan_debug_print)
2229 HintStateDump(current_hint);
2232 * Rollback changes of GUC parameters, and pop current hint context from
2233 * hint stack to rewind the state.
2235 AtEOXact_GUC(true, save_nestlevel);
2240 standard_planner_proc:
2241 current_hint = NULL;
2243 return (*prev_planner) (parse, cursorOptions, boundParams);
2245 return standard_planner(parse, cursorOptions, boundParams);
2249 * Return scan method hint which matches given aliasname.
2251 static ScanMethodHint *
2252 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2258 * We can't apply scan method hint if the relation is:
2259 * - not a base relation
2260 * - not an ordinary relation (such as join and subquery)
2262 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2265 rte = root->simple_rte_array[rel->relid];
2267 /* We can't force scan method of foreign tables */
2268 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2271 /* Find scan method hint, which matches given names, from the list. */
2272 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2274 ScanMethodHint *hint = current_hint->scan_hints[i];
2276 /* We ignore disabled hints. */
2277 if (!hint_state_enabled(hint))
2280 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2290 * Returns TRUE on match, FALSE on no match.
2292 * s1 --- the data to match against
2293 * s2 --- the pattern
2295 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2298 regexpeq(const char *s1, const char *s2)
2304 strcpy(name.data, s1);
2305 regexp = cstring_to_text(s2);
2307 result = DirectFunctionCall2Coll(nameregexeq,
2308 DEFAULT_COLLATION_OID,
2309 NameGetDatum(&name),
2310 PointerGetDatum(regexp));
2311 return DatumGetBool(result);
2315 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2323 * We delete all the IndexOptInfo list and prevent you from being usable by
2326 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2327 hint->enforce_mask == ENABLE_TIDSCAN)
2329 list_free_deep(rel->indexlist);
2330 rel->indexlist = NIL;
2331 hint->base.state = HINT_STATE_USED;
2337 * When a list of indexes is not specified, we just use all indexes.
2339 if (hint->indexnames == NIL)
2343 * Leaving only an specified index, we delete it from a IndexOptInfo list
2347 if (pg_hint_plan_debug_print)
2348 initStringInfo(&buf);
2350 for (cell = list_head(rel->indexlist); cell; cell = next)
2352 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2353 char *indexname = get_rel_name(info->indexoid);
2355 bool use_index = false;
2359 foreach(l, hint->indexnames)
2361 char *hintname = (char *) lfirst(l);
2365 result = regexpeq(indexname, hintname);
2367 result = RelnameCmp(&indexname, &hintname) == 0;
2372 if (pg_hint_plan_debug_print)
2374 appendStringInfoCharMacro(&buf, ' ');
2375 quote_value(&buf, indexname);
2383 * to make the index a candidate when definition of this index is
2384 * matched with the index's definition of current_hint.
2386 if (OidIsValid(relationObjectId) && !use_index)
2388 foreach(l, current_hint->parent_index_infos)
2392 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2394 /* check to match the parameter of unique */
2395 if (p_info->indisunique != info->unique)
2398 /* check to match the parameter of index's method */
2399 if (p_info->method != info->relam)
2402 /* to check to match the indexkey's configuration */
2403 if ((list_length(p_info->column_names)) !=
2407 /* check to match the indexkey's configuration */
2408 for (i = 0; i < info->ncolumns; i++)
2410 char *c_attname = NULL;
2411 char *p_attname = NULL;
2414 list_nth(p_info->column_names, i);
2416 /* both are expressions */
2417 if (info->indexkeys[i] == 0 && !p_attname)
2420 /* one's column is expression, the other is not */
2421 if (info->indexkeys[i] == 0 || !p_attname)
2424 c_attname = get_attname(relationObjectId,
2425 info->indexkeys[i]);
2427 if (strcmp(p_attname, c_attname) != 0)
2430 if (p_info->indcollation[i] != info->indexcollations[i])
2433 if (p_info->opclass[i] != info->opcintype[i])
2436 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2437 info->reverse_sort[i])
2440 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2441 info->nulls_first[i])
2446 if (i != info->ncolumns)
2449 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2450 (p_info->indpred_str && (info->indpred != NIL)))
2453 * Fetch the pg_index tuple by the Oid of the index
2455 ht_idx = SearchSysCache1(INDEXRELID,
2456 ObjectIdGetDatum(info->indexoid));
2458 /* check to match the expression's parameter of index */
2459 if (p_info->expression_str &&
2460 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2467 * to change the expression's parameter of child's
2470 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2471 Anum_pg_index_indexprs,
2474 result = DirectFunctionCall2(pg_get_expr,
2479 if (strcmp(p_info->expression_str,
2480 text_to_cstring(DatumGetTextP(result))) != 0)
2483 ReleaseSysCache(ht_idx);
2489 /* Check to match the predicate's paraameter of index */
2490 if (p_info->indpred_str &&
2491 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2498 * to change the predicate's parabeter of child's
2501 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2502 Anum_pg_index_indpred,
2505 result = DirectFunctionCall2(pg_get_expr,
2510 if (strcmp(p_info->indpred_str,
2511 text_to_cstring(DatumGetTextP(result))) != 0)
2514 ReleaseSysCache(ht_idx);
2521 ReleaseSysCache(ht_idx);
2523 else if (p_info->expression_str || (info->indexprs != NIL))
2525 else if (p_info->indpred_str || (info->indpred != NIL))
2530 /* to log the candidate of index */
2531 if (pg_hint_plan_debug_print)
2533 appendStringInfoCharMacro(&buf, ' ');
2534 quote_value(&buf, indexname);
2542 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2549 if (pg_hint_plan_debug_print)
2552 StringInfoData rel_buf;
2554 if (OidIsValid(relationObjectId))
2555 relname = get_rel_name(relationObjectId);
2557 relname = hint->relname;
2559 initStringInfo(&rel_buf);
2560 quote_value(&rel_buf, relname);
2563 (errmsg("available indexes for %s(%s):%s",
2568 pfree(rel_buf.data);
2573 * Return information of index definition.
2575 static ParentIndexInfo *
2576 get_parent_index_info(Oid indexoid, Oid relid)
2578 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
2579 Relation indexRelation;
2580 Form_pg_index index;
2584 indexRelation = index_open(indexoid, RowExclusiveLock);
2586 index = indexRelation->rd_index;
2588 p_info->indisunique = index->indisunique;
2589 p_info->method = indexRelation->rd_rel->relam;
2591 p_info->column_names = NIL;
2592 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2593 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2594 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
2596 for (i = 0; i < index->indnatts; i++)
2598 attname = get_attname(relid, index->indkey.values[i]);
2599 p_info->column_names = lappend(p_info->column_names, attname);
2601 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
2602 p_info->opclass[i] = indexRelation->rd_opcintype[i];
2603 p_info->indoption[i] = indexRelation->rd_indoption[i];
2607 * to check to match the expression's paraameter of index with child indexes
2609 p_info->expression_str = NULL;
2610 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
2616 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2617 Anum_pg_index_indexprs, &isnull);
2619 result = DirectFunctionCall2(pg_get_expr,
2621 ObjectIdGetDatum(relid));
2623 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
2627 * to check to match the predicate's paraameter of index with child indexes
2629 p_info->indpred_str = NULL;
2630 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
2636 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2637 Anum_pg_index_indpred, &isnull);
2639 result = DirectFunctionCall2(pg_get_expr,
2641 ObjectIdGetDatum(relid));
2643 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
2646 index_close(indexRelation, NoLock);
2652 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2653 bool inhparent, RelOptInfo *rel)
2655 ScanMethodHint *hint;
2657 if (prev_get_relation_info)
2658 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2660 /* Do nothing if we don't have valid hint in this context. */
2666 /* store does relids of parent table. */
2667 current_hint->parent_relid = rel->relid;
2668 current_hint->parent_rel_oid = relationObjectId;
2670 else if (current_hint->parent_relid != 0)
2673 * We use the same GUC parameter if this table is the child table of a
2674 * table called pg_hint_plan_get_relation_info just before that.
2678 /* append_rel_list contains all append rels; ignore others */
2679 foreach(l, root->append_rel_list)
2681 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2683 /* This rel is child table. */
2684 if (appinfo->parent_relid == current_hint->parent_relid &&
2685 appinfo->child_relid == rel->relid)
2687 if (current_hint->parent_hint)
2688 delete_indexes(current_hint->parent_hint, rel,
2695 /* This rel is not inherit table. */
2696 current_hint->parent_relid = 0;
2697 current_hint->parent_rel_oid = InvalidOid;
2698 current_hint->parent_hint = NULL;
2702 * If scan method hint was given, reset GUC parameters which control
2703 * planner behavior about choosing scan methods.
2705 if ((hint = find_scan_hint(root, rel)) == NULL)
2707 set_scan_config_options(current_hint->init_scan_mask,
2708 current_hint->context);
2711 set_scan_config_options(hint->enforce_mask, current_hint->context);
2712 hint->base.state = HINT_STATE_USED;
2720 current_hint->parent_hint = hint;
2722 relation = heap_open(relationObjectId, NoLock);
2723 indexoidlist = RelationGetIndexList(relation);
2725 foreach(l, indexoidlist)
2727 Oid indexoid = lfirst_oid(l);
2728 char *indexname = get_rel_name(indexoid);
2729 bool use_index = false;
2731 ParentIndexInfo *parent_index_info;
2733 foreach(lc, hint->indexnames)
2735 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
2744 parent_index_info = get_parent_index_info(indexoid,
2746 current_hint->parent_index_infos =
2747 lappend(current_hint->parent_index_infos, parent_index_info);
2749 heap_close(relation, NoLock);
2752 delete_indexes(hint, rel, InvalidOid);
2756 * Return index of relation which matches given aliasname, or 0 if not found.
2757 * If same aliasname was used multiple times in a query, return -1.
2760 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
2766 for (i = 1; i < root->simple_rel_array_size; i++)
2770 if (root->simple_rel_array[i] == NULL)
2773 Assert(i == root->simple_rel_array[i]->relid);
2775 if (RelnameCmp(&aliasname,
2776 &root->simple_rte_array[i]->eref->aliasname) != 0)
2779 foreach(l, initial_rels)
2781 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2783 if (rel->reloptkind == RELOPT_BASEREL)
2785 if (rel->relid != i)
2790 Assert(rel->reloptkind == RELOPT_JOINREL);
2792 if (!bms_is_member(i, rel->relids))
2799 ("Relation name \"%s\" is ambiguous.",
2814 * Return join hint which matches given joinrelids.
2816 static JoinMethodHint *
2817 find_join_hint(Relids joinrelids)
2822 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
2824 foreach(l, join_hint)
2826 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
2828 if (bms_equal(joinrelids, hint->joinrelids))
2836 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
2837 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
2839 OuterInnerRels *outer_rels;
2840 OuterInnerRels *inner_rels;
2841 Relids outer_relids;
2842 Relids inner_relids;
2844 JoinMethodHint *hint;
2846 if (outer_inner->relation != NULL)
2848 return bms_make_singleton(
2849 find_relid_aliasname(root, outer_inner->relation,
2851 leading_hint->base.hint_str));
2854 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
2855 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
2857 outer_relids = OuterInnerJoinCreate(outer_rels,
2863 inner_relids = OuterInnerJoinCreate(inner_rels,
2870 join_relids = bms_add_members(outer_relids, inner_relids);
2872 if (bms_num_members(join_relids) > nbaserel)
2876 * If we don't have join method hint, create new one for the
2877 * join combination with all join methods are enabled.
2879 hint = find_join_hint(join_relids);
2883 * Here relnames is not set, since Relids bitmap is sufficient to
2884 * control paths of this query afterward.
2886 hint = (JoinMethodHint *) JoinMethodHintCreate(
2887 leading_hint->base.hint_str,
2889 HINT_KEYWORD_LEADING);
2890 hint->base.state = HINT_STATE_USED;
2891 hint->nrels = bms_num_members(join_relids);
2892 hint->enforce_mask = ENABLE_ALL_JOIN;
2893 hint->joinrelids = bms_copy(join_relids);
2894 hint->inner_nrels = bms_num_members(inner_relids);
2895 hint->inner_joinrelids = bms_copy(inner_relids);
2897 hstate->join_hint_level[hint->nrels] =
2898 lappend(hstate->join_hint_level[hint->nrels], hint);
2902 hint->inner_nrels = bms_num_members(inner_relids);
2903 hint->inner_joinrelids = bms_copy(inner_relids);
2910 * Transform join method hint into handy form.
2912 * - create bitmap of relids from alias names, to make it easier to check
2913 * whether a join path matches a join method hint.
2914 * - add join method hints which are necessary to enforce join order
2915 * specified by Leading hint
2918 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2919 List *initial_rels, JoinMethodHint **join_method_hints)
2927 LeadingHint *lhint = NULL;
2930 * Create bitmap of relids from alias names for each join method hint.
2931 * Bitmaps are more handy than strings in join searching.
2933 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2935 JoinMethodHint *hint = hstate->join_hints[i];
2938 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
2941 bms_free(hint->joinrelids);
2942 hint->joinrelids = NULL;
2944 for (j = 0; j < hint->nrels; j++)
2946 relname = hint->relnames[j];
2948 relid = find_relid_aliasname(root, relname, initial_rels,
2949 hint->base.hint_str);
2952 hint->base.state = HINT_STATE_ERROR;
2957 if (bms_is_member(relid, hint->joinrelids))
2959 hint_ereport(hint->base.hint_str,
2960 ("Relation name \"%s\" is duplicated.", relname));
2961 hint->base.state = HINT_STATE_ERROR;
2965 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
2968 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
2971 hstate->join_hint_level[hint->nrels] =
2972 lappend(hstate->join_hint_level[hint->nrels], hint);
2975 /* Do nothing if no Leading hint was supplied. */
2976 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2980 * Decide to use Leading hint。
2982 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
2984 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
2987 if (leading_hint->base.state == HINT_STATE_ERROR)
2993 foreach(l, leading_hint->relations)
2995 relname = (char *)lfirst(l);;
2997 relid = find_relid_aliasname(root, relname, initial_rels,
2998 leading_hint->base.hint_str);
3000 leading_hint->base.state = HINT_STATE_ERROR;
3005 if (bms_is_member(relid, relids))
3007 hint_ereport(leading_hint->base.hint_str,
3008 ("Relation name \"%s\" is duplicated.", relname));
3009 leading_hint->base.state = HINT_STATE_ERROR;
3013 relids = bms_add_member(relids, relid);
3016 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3021 hint_ereport(lhint->base.hint_str,
3022 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3023 lhint->base.state = HINT_STATE_DUPLICATION;
3025 leading_hint->base.state = HINT_STATE_USED;
3026 lhint = leading_hint;
3029 /* check to exist Leading hint marked with 'used'. */
3034 * We need join method hints which fit specified join order in every join
3035 * level. For example, Leading(A B C) virtually requires following join
3036 * method hints, if no join method hint supplied:
3038 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3039 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3041 * If we already have join method hint which fits specified join order in
3042 * that join level, we leave it as-is and don't add new hints.
3046 if (lhint->outer_inner == NULL)
3048 foreach(l, lhint->relations)
3050 JoinMethodHint *hint;
3052 relname = (char *)lfirst(l);
3055 * Find relid of the relation which has given name. If we have the
3056 * name given in Leading hint multiple times in the join, nothing to
3059 relid = find_relid_aliasname(root, relname, initial_rels,
3062 /* Create bitmap of relids for current join level. */
3063 joinrelids = bms_add_member(joinrelids, relid);
3066 /* We never have join method hint for single relation. */
3071 * If we don't have join method hint, create new one for the
3072 * join combination with all join methods are enabled.
3074 hint = find_join_hint(joinrelids);
3078 * Here relnames is not set, since Relids bitmap is sufficient
3079 * to control paths of this query afterward.
3081 hint = (JoinMethodHint *) JoinMethodHintCreate(
3082 lhint->base.hint_str,
3084 HINT_KEYWORD_LEADING);
3085 hint->base.state = HINT_STATE_USED;
3086 hint->nrels = njoinrels;
3087 hint->enforce_mask = ENABLE_ALL_JOIN;
3088 hint->joinrelids = bms_copy(joinrelids);
3091 join_method_hints[njoinrels] = hint;
3093 if (njoinrels >= nbaserel)
3096 bms_free(joinrelids);
3102 * Delete all join hints which have different combination from Leading
3105 for (i = 2; i <= njoinrels; i++)
3107 list_free(hstate->join_hint_level[i]);
3109 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3114 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3121 njoinrels = bms_num_members(joinrelids);
3122 Assert(njoinrels >= 2);
3125 * Delete all join hints which have different combination from Leading
3128 for (i = 2;i <= njoinrels; i++)
3130 if (hstate->join_hint_level[i] != NIL)
3132 ListCell *prev = NULL;
3133 ListCell *next = NULL;
3134 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3137 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3141 if (hint->inner_nrels == 0 &&
3142 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3143 bms_equal(bms_union(hint->joinrelids, joinrelids),
3146 hstate->join_hint_level[i] =
3147 list_delete_cell(hstate->join_hint_level[i], l,
3156 bms_free(joinrelids);
3159 if (hint_state_enabled(lhint))
3161 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3168 * set_plain_rel_pathlist
3169 * Build access paths for a plain relation (no subquery, no inheritance)
3171 * This function was copied and edited from set_plain_rel_pathlist() in
3172 * src/backend/optimizer/path/allpaths.c
3175 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3177 /* Consider sequential scan */
3178 #if PG_VERSION_NUM >= 90200
3179 add_path(rel, create_seqscan_path(root, rel, NULL));
3181 add_path(rel, create_seqscan_path(root, rel));
3184 /* Consider index scans */
3185 create_index_paths(root, rel);
3187 /* Consider TID scans */
3188 create_tidscan_paths(root, rel);
3190 /* Now find the cheapest of the paths for this rel */
3195 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3200 foreach(l, initial_rels)
3202 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3204 ScanMethodHint *hint;
3206 /* Skip relations which we can't choose scan method. */
3207 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3210 rte = root->simple_rte_array[rel->relid];
3212 /* We can't force scan method of foreign tables */
3213 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3217 * Create scan paths with GUC parameters which are at the beginning of
3218 * planner if scan method hint is not specified, otherwise use
3219 * specified hints and mark the hint as used.
3221 if ((hint = find_scan_hint(root, rel)) == NULL)
3222 set_scan_config_options(hstate->init_scan_mask,
3226 set_scan_config_options(hint->enforce_mask, hstate->context);
3227 hint->base.state = HINT_STATE_USED;
3230 list_free_deep(rel->pathlist);
3231 rel->pathlist = NIL;
3234 /* It's an "append relation", process accordingly */
3235 set_append_rel_pathlist(root, rel, rel->relid, rte);
3239 set_plain_rel_pathlist(root, rel, rte);
3244 * Restore the GUC variables we set above.
3246 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3250 * wrapper of make_join_rel()
3252 * call make_join_rel() after changing enable_* parameters according to given
3256 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3259 JoinMethodHint *hint;
3263 joinrelids = bms_union(rel1->relids, rel2->relids);
3264 hint = find_join_hint(joinrelids);
3265 bms_free(joinrelids);
3268 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3270 if (hint->inner_nrels == 0)
3272 save_nestlevel = NewGUCNestLevel();
3274 set_join_config_options(hint->enforce_mask, current_hint->context);
3276 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3277 hint->base.state = HINT_STATE_USED;
3280 * Restore the GUC variables we set above.
3282 AtEOXact_GUC(true, save_nestlevel);
3285 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3294 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3295 RelOptInfo *joinrel,
3296 RelOptInfo *outerrel,
3297 RelOptInfo *innerrel,
3299 SpecialJoinInfo *sjinfo,
3302 ScanMethodHint *scan_hint = NULL;
3304 JoinMethodHint *join_hint;
3307 if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
3309 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3310 scan_hint->base.state = HINT_STATE_USED;
3313 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3314 join_hint = find_join_hint(joinrelids);
3315 bms_free(joinrelids);
3317 if (join_hint && join_hint->inner_nrels != 0)
3319 save_nestlevel = NewGUCNestLevel();
3321 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3324 set_join_config_options(join_hint->enforce_mask,
3325 current_hint->context);
3327 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3328 sjinfo, restrictlist);
3329 join_hint->base.state = HINT_STATE_USED;
3333 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3334 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3335 sjinfo, restrictlist);
3339 * Restore the GUC variables we set above.
3341 AtEOXact_GUC(true, save_nestlevel);
3344 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3345 sjinfo, restrictlist);
3347 if (scan_hint != NULL)
3348 set_scan_config_options(current_hint->init_scan_mask,
3349 current_hint->context);
3353 get_num_baserels(List *initial_rels)
3358 foreach(l, initial_rels)
3360 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3362 if (rel->reloptkind == RELOPT_BASEREL)
3364 else if (rel->reloptkind ==RELOPT_JOINREL)
3365 nbaserel+= bms_num_members(rel->relids);
3368 /* other values not expected here */
3369 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3377 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3380 JoinMethodHint **join_method_hints;
3384 bool leading_hint_enable;
3387 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3388 * valid hint is supplied.
3392 if (prev_join_search)
3393 return (*prev_join_search) (root, levels_needed, initial_rels);
3394 else if (enable_geqo && levels_needed >= geqo_threshold)
3395 return geqo(root, levels_needed, initial_rels);
3397 return standard_join_search(root, levels_needed, initial_rels);
3400 /* We apply scan method hint rebuild scan path. */
3401 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3404 * In the case using GEQO, only scan method hints and Set hints have
3405 * effect. Join method and join order is not controllable by hints.
3407 if (enable_geqo && levels_needed >= geqo_threshold)
3408 return geqo(root, levels_needed, initial_rels);
3410 nbaserel = get_num_baserels(initial_rels);
3411 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3412 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3414 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3415 initial_rels, join_method_hints);
3417 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3419 for (i = 2; i <= nbaserel; i++)
3421 list_free(current_hint->join_hint_level[i]);
3423 /* free Leading hint only */
3424 if (join_method_hints[i] != NULL &&
3425 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3426 JoinMethodHintDelete(join_method_hints[i]);
3428 pfree(current_hint->join_hint_level);
3429 pfree(join_method_hints);
3431 if (leading_hint_enable)
3432 set_join_config_options(current_hint->init_join_mask,
3433 current_hint->context);
3440 * Build access paths for a base relation
3442 * This function was copied and edited from set_rel_pathlist() in
3443 * src/backend/optimizer/path/allpaths.c
3446 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3447 Index rti, RangeTblEntry *rte)
3449 #if PG_VERSION_NUM >= 90200
3450 if (IS_DUMMY_REL(rel))
3452 /* We already proved the relation empty, so nothing more to do */
3459 /* It's an "append relation", process accordingly */
3460 set_append_rel_pathlist(root, rel, rti, rte);
3464 if (rel->rtekind == RTE_RELATION)
3466 if (rte->relkind == RELKIND_RELATION)
3468 /* Plain relation */
3469 set_plain_rel_pathlist(root, rel, rte);
3472 elog(ERROR, "unexpected relkind: %c", rte->relkind);
3475 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
3480 pg_hint_plan_plpgsql_func_setup(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3482 (&plugin_funcs)->stmt_beg = pg_hint_plan_plpgsql_stmt_beg;
3483 (&plugin_funcs)->stmt_end = pg_hint_plan_plpgsql_stmt_end;
3487 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3489 if ((enum PLpgSQL_stmt_types) stmt->cmd_type == PLPGSQL_STMT_EXECSQL)
3491 PLpgSQL_expr *expr = ((PLpgSQL_stmt_execsql *) stmt)->sqlstmt;
3492 hint_query_string = expr->query;
3497 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3499 if ((enum PLpgSQL_stmt_types) stmt->cmd_type == PLPGSQL_STMT_EXECSQL)
3500 hint_query_string = NULL;
3503 #define standard_join_search pg_hint_plan_standard_join_search
3504 #define join_search_one_level pg_hint_plan_join_search_one_level
3505 #define make_join_rel make_join_rel_wrapper
3508 #undef make_join_rel
3509 #define make_join_rel pg_hint_plan_make_join_rel
3510 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
3511 #include "make_join_rel.c"