1 /*-------------------------------------------------------------------------
4 * do instructions or hints to the planner using C-style block comments
7 * Copyright (c) 2012, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
9 *-------------------------------------------------------------------------
12 #include "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 #if PG_VERSION_NUM >= 90200
35 #include "catalog/pg_class.h"
38 #ifdef PG_MODULE_MAGIC
42 #if PG_VERSION_NUM < 90100
43 #error unsupported PostgreSQL version
46 #define BLOCK_COMMENT_START "/*"
47 #define BLOCK_COMMENT_END "*/"
48 #define HINT_COMMENT_KEYWORD "+"
49 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
50 #define HINT_END BLOCK_COMMENT_END
53 #define HINT_SEQSCAN "SeqScan"
54 #define HINT_INDEXSCAN "IndexScan"
55 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
56 #define HINT_BITMAPSCAN "BitmapScan"
57 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
58 #define HINT_TIDSCAN "TidScan"
59 #define HINT_NOSEQSCAN "NoSeqScan"
60 #define HINT_NOINDEXSCAN "NoIndexScan"
61 #define HINT_NOBITMAPSCAN "NoBitmapScan"
62 #define HINT_NOTIDSCAN "NoTidScan"
63 #if PG_VERSION_NUM >= 90200
64 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
65 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
66 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
68 #define HINT_NESTLOOP "NestLoop"
69 #define HINT_MERGEJOIN "MergeJoin"
70 #define HINT_HASHJOIN "HashJoin"
71 #define HINT_NONESTLOOP "NoNestLoop"
72 #define HINT_NOMERGEJOIN "NoMergeJoin"
73 #define HINT_NOHASHJOIN "NoHashJoin"
74 #define HINT_LEADING "Leading"
75 #define HINT_SET "Set"
77 #define HINT_ARRAY_DEFAULT_INITSIZE 8
79 #define hint_ereport(str, detail) \
80 ereport(pg_hint_plan_parse_messages, \
81 (errmsg("hint syntax error at or near \"%s\"", (str)), \
84 #define skip_space(str) \
85 while (isspace(*str)) \
90 ENABLE_SEQSCAN = 0x01,
91 ENABLE_INDEXSCAN = 0x02,
92 ENABLE_BITMAPSCAN = 0x04,
93 ENABLE_TIDSCAN = 0x08,
94 #if PG_VERSION_NUM >= 90200
95 ENABLE_INDEXONLYSCAN = 0x10
101 ENABLE_NESTLOOP = 0x01,
102 ENABLE_MERGEJOIN = 0x02,
103 ENABLE_HASHJOIN = 0x04
106 #if PG_VERSION_NUM >= 90200
107 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
108 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
109 ENABLE_INDEXONLYSCAN)
111 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
112 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN)
114 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
115 #define DISABLE_ALL_SCAN 0
116 #define DISABLE_ALL_JOIN 0
118 /* hint keyword of enum type*/
119 typedef enum HintKeyword
121 HINT_KEYWORD_SEQSCAN,
122 HINT_KEYWORD_INDEXSCAN,
123 HINT_KEYWORD_INDEXSCANREGEXP,
124 HINT_KEYWORD_BITMAPSCAN,
125 HINT_KEYWORD_BITMAPSCANREGEXP,
126 HINT_KEYWORD_TIDSCAN,
127 HINT_KEYWORD_NOSEQSCAN,
128 HINT_KEYWORD_NOINDEXSCAN,
129 HINT_KEYWORD_NOBITMAPSCAN,
130 HINT_KEYWORD_NOTIDSCAN,
131 #if PG_VERSION_NUM >= 90200
132 HINT_KEYWORD_INDEXONLYSCAN,
133 HINT_KEYWORD_INDEXONLYSCANREGEXP,
134 HINT_KEYWORD_NOINDEXONLYSCAN,
136 HINT_KEYWORD_NESTLOOP,
137 HINT_KEYWORD_MERGEJOIN,
138 HINT_KEYWORD_HASHJOIN,
139 HINT_KEYWORD_NONESTLOOP,
140 HINT_KEYWORD_NOMERGEJOIN,
141 HINT_KEYWORD_NOHASHJOIN,
142 HINT_KEYWORD_LEADING,
144 HINT_KEYWORD_UNRECOGNIZED
147 typedef struct Hint Hint;
148 typedef struct HintState HintState;
150 typedef Hint *(*HintCreateFunction) (const char *hint_str,
152 HintKeyword hint_keyword);
153 typedef void (*HintDeleteFunction) (Hint *hint);
154 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf);
155 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
156 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
157 Query *parse, const char *str);
160 #define NUM_HINT_TYPE 4
161 typedef enum HintType
163 HINT_TYPE_SCAN_METHOD,
164 HINT_TYPE_JOIN_METHOD,
169 static const char *HintTypeName[] = {
177 typedef enum HintStatus
179 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
180 HINT_STATE_USED, /* hint is used */
181 HINT_STATE_DUPLICATION, /* specified hint duplication */
182 HINT_STATE_ERROR /* execute error (parse error does not include
186 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
187 (hint)->base.state == HINT_STATE_USED)
189 /* common data for all hints. */
192 const char *hint_str; /* must not do pfree */
193 const char *keyword; /* must not do pfree */
194 HintKeyword hint_keyword;
197 HintDeleteFunction delete_func;
198 HintDescFunction desc_func;
199 HintCmpFunction cmp_func;
200 HintParseFunction parse_func;
203 /* scan method hints */
204 typedef struct ScanMethodHint
210 unsigned char enforce_mask;
213 /* join method hints */
214 typedef struct JoinMethodHint
220 unsigned char enforce_mask;
222 Relids inner_joinrelids;
225 /* join order hints */
226 typedef struct OuterInnerRels
229 List *outer_inner_pair;
232 typedef struct LeadingHint
235 List *relations; /* relation names specified in Leading hint */
236 OuterInnerRels *outer_inner;
239 /* change a run-time parameter hints */
240 typedef struct SetHint
243 char *name; /* name of variable */
249 * Describes a context of hint processing.
253 char *hint_str; /* original hint string */
256 int nall_hints; /* # of valid all hints */
257 int max_all_hints; /* # of slots for all hints */
258 Hint **all_hints; /* parsed all hints */
260 /* # of each hints */
261 int num_hints[NUM_HINT_TYPE];
263 /* for scan method hints */
264 ScanMethodHint **scan_hints; /* parsed scan hints */
265 int init_scan_mask; /* initial value scan parameter */
266 Index parent_relid; /* inherit parent table relid */
267 Oid parent_rel_oid; /* inherit parent table relid */
268 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
269 List *parent_ind_atts; /* attnums of inherit parent table's
272 /* for join method hints */
273 JoinMethodHint **join_hints; /* parsed join hints */
274 int init_join_mask; /* initial value join parameter */
275 List **join_hint_level;
277 /* for Leading hint */
278 LeadingHint **leading_hint; /* parsed Leading hints */
281 SetHint **set_hints; /* parsed Set hints */
282 GucContext context; /* which GUC parameters can we set? */
286 * Describes a hint parser module which is bound with particular hint keyword.
288 typedef struct HintParser
291 HintCreateFunction create_func;
292 HintKeyword hint_keyword;
295 /* Module callbacks */
299 static void push_hint(HintState *hstate);
300 static void pop_hint(void);
302 static void pg_hint_plan_ProcessUtility(Node *parsetree,
303 const char *queryString,
304 ParamListInfo params, bool isTopLevel,
306 char *completionTag);
307 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
308 ParamListInfo boundParams);
309 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
310 Oid relationObjectId,
311 bool inhparent, RelOptInfo *rel);
312 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
316 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
317 HintKeyword hint_keyword);
318 static void ScanMethodHintDelete(ScanMethodHint *hint);
319 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf);
320 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
321 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
322 Query *parse, const char *str);
323 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
324 HintKeyword hint_keyword);
325 static void JoinMethodHintDelete(JoinMethodHint *hint);
326 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf);
327 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
328 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
329 Query *parse, const char *str);
330 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
331 HintKeyword hint_keyword);
332 static void LeadingHintDelete(LeadingHint *hint);
333 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf);
334 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
335 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
336 Query *parse, const char *str);
337 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
338 HintKeyword hint_keyword);
339 static void SetHintDelete(SetHint *hint);
340 static void SetHintDesc(SetHint *hint, StringInfo buf);
341 static int SetHintCmp(const SetHint *a, const SetHint *b);
342 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
345 static void quote_value(StringInfo buf, const char *value);
347 static const char *parse_quoted_value(const char *str, char **word,
350 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
353 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
354 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
355 ListCell *other_rels);
356 static void make_rels_by_clauseless_joins(PlannerInfo *root,
358 ListCell *other_rels);
359 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
360 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
361 Index rti, RangeTblEntry *rte);
362 #if PG_VERSION_NUM >= 90200
363 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
364 List *live_childrels,
365 List *all_child_pathkeys);
367 static List *accumulate_append_subpath(List *subpaths, Path *path);
368 #if PG_VERSION_NUM < 90200
369 static void set_dummy_rel_pathlist(RelOptInfo *rel);
371 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
375 static bool pg_hint_plan_enable_hint = true;
376 static bool pg_hint_plan_debug_print = false;
377 static int pg_hint_plan_parse_messages = INFO;
379 static const struct config_enum_entry parse_messages_level_options[] = {
380 {"debug", DEBUG2, true},
381 {"debug5", DEBUG5, false},
382 {"debug4", DEBUG4, false},
383 {"debug3", DEBUG3, false},
384 {"debug2", DEBUG2, false},
385 {"debug1", DEBUG1, false},
387 {"info", INFO, false},
388 {"notice", NOTICE, false},
389 {"warning", WARNING, false},
390 {"error", ERROR, false},
392 * {"fatal", FATAL, true},
393 * {"panic", PANIC, true},
398 /* Saved hook values in case of unload */
399 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
400 static planner_hook_type prev_planner = NULL;
401 static get_relation_info_hook_type prev_get_relation_info = NULL;
402 static join_search_hook_type prev_join_search = NULL;
404 /* Hold reference to currently active hint */
405 static HintState *current_hint = NULL;
408 * List of hint contexts. We treat the head of the list as the Top of the
409 * context stack, so current_hint always points the first element of this list.
411 static List *HintStateStack = NIL;
414 * Holds statement name during executing EXECUTE command. NULL for other
417 static char *stmt_name = NULL;
419 static const HintParser parsers[] = {
420 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
421 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
422 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
423 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
424 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
425 HINT_KEYWORD_BITMAPSCANREGEXP},
426 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
427 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
428 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
429 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
430 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
431 #if PG_VERSION_NUM >= 90200
432 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
433 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
434 HINT_KEYWORD_INDEXONLYSCANREGEXP},
435 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
437 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
438 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
439 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
440 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
441 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
442 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
443 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
444 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
445 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
449 * Module load callbacks
454 /* Define custom GUC variables. */
455 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
456 "Force planner to use plans specified in the hint comment preceding to the query.",
458 &pg_hint_plan_enable_hint,
466 DefineCustomBoolVariable("pg_hint_plan.debug_print",
467 "Logs results of hint parsing.",
469 &pg_hint_plan_debug_print,
477 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
478 "Message level of parse errors.",
480 &pg_hint_plan_parse_messages,
482 parse_messages_level_options,
490 prev_ProcessUtility = ProcessUtility_hook;
491 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
492 prev_planner = planner_hook;
493 planner_hook = pg_hint_plan_planner;
494 prev_get_relation_info = get_relation_info_hook;
495 get_relation_info_hook = pg_hint_plan_get_relation_info;
496 prev_join_search = join_search_hook;
497 join_search_hook = pg_hint_plan_join_search;
501 * Module unload callback
507 /* Uninstall hooks. */
508 ProcessUtility_hook = prev_ProcessUtility;
509 planner_hook = prev_planner;
510 get_relation_info_hook = prev_get_relation_info;
511 join_search_hook = prev_join_search;
515 * create and delete functions the hint object
519 ScanMethodHintCreate(const char *hint_str, const char *keyword,
520 HintKeyword hint_keyword)
522 ScanMethodHint *hint;
524 hint = palloc(sizeof(ScanMethodHint));
525 hint->base.hint_str = hint_str;
526 hint->base.keyword = keyword;
527 hint->base.hint_keyword = hint_keyword;
528 hint->base.type = HINT_TYPE_SCAN_METHOD;
529 hint->base.state = HINT_STATE_NOTUSED;
530 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
531 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
532 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
533 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
534 hint->relname = NULL;
535 hint->indexnames = NIL;
536 hint->regexp = false;
537 hint->enforce_mask = 0;
539 return (Hint *) hint;
543 ScanMethodHintDelete(ScanMethodHint *hint)
549 pfree(hint->relname);
550 list_free_deep(hint->indexnames);
555 JoinMethodHintCreate(const char *hint_str, const char *keyword,
556 HintKeyword hint_keyword)
558 JoinMethodHint *hint;
560 hint = palloc(sizeof(JoinMethodHint));
561 hint->base.hint_str = hint_str;
562 hint->base.keyword = keyword;
563 hint->base.hint_keyword = hint_keyword;
564 hint->base.type = HINT_TYPE_JOIN_METHOD;
565 hint->base.state = HINT_STATE_NOTUSED;
566 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
567 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
568 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
569 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
571 hint->inner_nrels = 0;
572 hint->relnames = NULL;
573 hint->enforce_mask = 0;
574 hint->joinrelids = NULL;
575 hint->inner_joinrelids = NULL;
577 return (Hint *) hint;
581 JoinMethodHintDelete(JoinMethodHint *hint)
590 for (i = 0; i < hint->nrels; i++)
591 pfree(hint->relnames[i]);
592 pfree(hint->relnames);
595 bms_free(hint->joinrelids);
596 bms_free(hint->inner_joinrelids);
601 LeadingHintCreate(const char *hint_str, const char *keyword,
602 HintKeyword hint_keyword)
606 hint = palloc(sizeof(LeadingHint));
607 hint->base.hint_str = hint_str;
608 hint->base.keyword = keyword;
609 hint->base.hint_keyword = hint_keyword;
610 hint->base.type = HINT_TYPE_LEADING;
611 hint->base.state = HINT_STATE_NOTUSED;
612 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
613 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
614 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
615 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
616 hint->relations = NIL;
617 hint->outer_inner = NULL;
619 return (Hint *) hint;
623 LeadingHintDelete(LeadingHint *hint)
628 list_free_deep(hint->relations);
629 if (hint->outer_inner)
630 pfree(hint->outer_inner);
635 SetHintCreate(const char *hint_str, const char *keyword,
636 HintKeyword hint_keyword)
640 hint = palloc(sizeof(SetHint));
641 hint->base.hint_str = hint_str;
642 hint->base.keyword = keyword;
643 hint->base.hint_keyword = hint_keyword;
644 hint->base.type = HINT_TYPE_SET;
645 hint->base.state = HINT_STATE_NOTUSED;
646 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
647 hint->base.desc_func = (HintDescFunction) SetHintDesc;
648 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
649 hint->base.parse_func = (HintParseFunction) SetHintParse;
654 return (Hint *) hint;
658 SetHintDelete(SetHint *hint)
668 list_free(hint->words);
673 HintStateCreate(void)
677 hstate = palloc(sizeof(HintState));
678 hstate->hint_str = NULL;
679 hstate->nall_hints = 0;
680 hstate->max_all_hints = 0;
681 hstate->all_hints = NULL;
682 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
683 hstate->scan_hints = NULL;
684 hstate->init_scan_mask = 0;
685 hstate->parent_relid = 0;
686 hstate->parent_rel_oid = InvalidOid;
687 hstate->parent_hint = NULL;
688 hstate->parent_ind_atts = NIL;
689 hstate->join_hints = NULL;
690 hstate->init_join_mask = 0;
691 hstate->join_hint_level = NULL;
692 hstate->leading_hint = NULL;
693 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
694 hstate->set_hints = NULL;
700 HintStateDelete(HintState *hstate)
707 if (hstate->hint_str)
708 pfree(hstate->hint_str);
710 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
711 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
712 if (hstate->all_hints)
713 pfree(hstate->all_hints);
714 if (hstate->parent_ind_atts)
715 list_free(hstate->parent_ind_atts);
719 * Copy given value into buf, with quoting with '"' if necessary.
722 quote_value(StringInfo buf, const char *value)
724 bool need_quote = false;
727 for (str = value; *str != '\0'; str++)
729 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
732 appendStringInfoCharMacro(buf, '"');
737 for (str = value; *str != '\0'; str++)
740 appendStringInfoCharMacro(buf, '"');
742 appendStringInfoCharMacro(buf, *str);
746 appendStringInfoCharMacro(buf, '"');
750 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
754 appendStringInfo(buf, "%s(", hint->base.keyword);
755 if (hint->relname != NULL)
757 quote_value(buf, hint->relname);
758 foreach(l, hint->indexnames)
760 appendStringInfoCharMacro(buf, ' ');
761 quote_value(buf, (char *) lfirst(l));
764 appendStringInfoString(buf, ")\n");
768 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
772 appendStringInfo(buf, "%s(", hint->base.keyword);
773 if (hint->relnames != NULL)
775 quote_value(buf, hint->relnames[0]);
776 for (i = 1; i < hint->nrels; i++)
778 appendStringInfoCharMacro(buf, ' ');
779 quote_value(buf, hint->relnames[i]);
782 appendStringInfoString(buf, ")\n");
787 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
789 if (outer_inner->relation == NULL)
796 appendStringInfoCharMacro(buf, '(');
797 foreach(l, outer_inner->outer_inner_pair)
802 appendStringInfoCharMacro(buf, ' ');
804 OuterInnerDesc(lfirst(l), buf);
807 appendStringInfoCharMacro(buf, ')');
810 quote_value(buf, outer_inner->relation);
814 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
816 appendStringInfo(buf, "%s(", HINT_LEADING);
817 if (hint->outer_inner == NULL)
824 foreach(l, hint->relations)
829 appendStringInfoCharMacro(buf, ' ');
831 quote_value(buf, (char *) lfirst(l));
835 OuterInnerDesc(hint->outer_inner, buf);
837 appendStringInfoString(buf, ")\n");
841 SetHintDesc(SetHint *hint, StringInfo buf)
843 bool is_first = true;
846 appendStringInfo(buf, "%s(", HINT_SET);
847 foreach(l, hint->words)
852 appendStringInfoCharMacro(buf, ' ');
854 quote_value(buf, (char *) lfirst(l));
856 appendStringInfo(buf, ")\n");
860 * Append string which repserents all hints in a given state to buf, with
861 * preceding title with them.
864 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
869 appendStringInfo(buf, "%s:\n", title);
870 for (i = 0; i < hstate->nall_hints; i++)
872 if (hstate->all_hints[i]->state != state)
875 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf);
880 * Dump contents of given hstate to server log with log level LOG.
883 HintStateDump(HintState *hstate)
889 elog(LOG, "pg_hint_plan:\nno hint");
893 initStringInfo(&buf);
895 appendStringInfoString(&buf, "pg_hint_plan:\n");
896 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
897 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
898 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
899 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
901 elog(LOG, "%s", buf.data);
911 RelnameCmp(const void *a, const void *b)
913 const char *relnamea = *((const char **) a);
914 const char *relnameb = *((const char **) b);
916 return strcmp(relnamea, relnameb);
920 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
922 return RelnameCmp(&a->relname, &b->relname);
926 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
930 if (a->nrels != b->nrels)
931 return a->nrels - b->nrels;
933 for (i = 0; i < a->nrels; i++)
936 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
944 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
950 SetHintCmp(const SetHint *a, const SetHint *b)
952 return strcmp(a->name, b->name);
956 HintCmp(const void *a, const void *b)
958 const Hint *hinta = *((const Hint **) a);
959 const Hint *hintb = *((const Hint **) b);
961 if (hinta->type != hintb->type)
962 return hinta->type - hintb->type;
963 if (hinta->state == HINT_STATE_ERROR)
965 if (hintb->state == HINT_STATE_ERROR)
967 return hinta->cmp_func(hinta, hintb);
971 * Returns byte offset of hint b from hint a. If hint a was specified before
972 * b, positive value is returned.
975 HintCmpWithPos(const void *a, const void *b)
977 const Hint *hinta = *((const Hint **) a);
978 const Hint *hintb = *((const Hint **) b);
981 result = HintCmp(a, b);
983 result = hinta->hint_str - hintb->hint_str;
992 parse_keyword(const char *str, StringInfo buf)
996 while (!isspace(*str) && *str != '(' && *str != '\0')
997 appendStringInfoCharMacro(buf, *str++);
1003 skip_parenthesis(const char *str, char parenthesis)
1007 if (*str != parenthesis)
1009 if (parenthesis == '(')
1010 hint_ereport(str, ("Opening parenthesis is necessary."));
1011 else if (parenthesis == ')')
1012 hint_ereport(str, ("Closing parenthesis is necessary."));
1023 * Parse a token from str, and store malloc'd copy into word. A token can be
1024 * quoted with '"'. Return value is pointer to unparsed portion of original
1025 * string, or NULL if an error occurred.
1027 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1030 parse_quoted_value(const char *str, char **word, bool truncate)
1035 /* Skip leading spaces. */
1038 initStringInfo(&buf);
1051 /* Double quotation must be closed. */
1055 hint_ereport(str, ("Unterminated quoted string."));
1060 * Skip escaped double quotation.
1062 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1063 * block comments) to be an object name, so users must specify
1064 * alias for such object names.
1066 * Those special names can be allowed if we care escaped slashes
1067 * and asterisks, but we don't.
1076 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1080 appendStringInfoCharMacro(&buf, *str++);
1085 hint_ereport(str, ("Zero-length delimited string."));
1092 /* Truncate name if it's too long */
1094 truncate_identifier(buf.data, strlen(buf.data), true);
1101 static OuterInnerRels *
1102 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1104 OuterInnerRels *outer_inner;
1106 outer_inner = palloc(sizeof(OuterInnerRels));
1107 outer_inner->relation = name;
1108 outer_inner->outer_inner_pair = outer_inner_list;
1114 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1116 List *outer_inner_pair = NIL;
1118 if ((str = skip_parenthesis(str, '(')) == NULL)
1123 /* Store words in parentheses into outer_inner_list. */
1124 while(*str != ')' && *str != '\0')
1126 OuterInnerRels *outer_inner_rels;
1130 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1138 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1141 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1144 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1149 (str = skip_parenthesis(str, ')')) == NULL)
1151 list_free(outer_inner_pair);
1155 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1161 parse_parentheses_Leading(const char *str, List **name_list,
1162 OuterInnerRels **outer_inner)
1165 bool truncate = true;
1167 if ((str = skip_parenthesis(str, '(')) == NULL)
1173 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1178 /* Store words in parentheses into name_list. */
1179 while(*str != ')' && *str != '\0')
1181 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1183 list_free(*name_list);
1187 *name_list = lappend(*name_list, name);
1192 if ((str = skip_parenthesis(str, ')')) == NULL)
1198 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1201 bool truncate = true;
1203 if ((str = skip_parenthesis(str, '(')) == NULL)
1208 /* Store words in parentheses into name_list. */
1209 while(*str != ')' && *str != '\0')
1211 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1213 list_free(*name_list);
1217 *name_list = lappend(*name_list, name);
1220 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1221 #if PG_VERSION_NUM >= 90200
1222 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1224 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1225 keyword == HINT_KEYWORD_SET)
1231 if ((str = skip_parenthesis(str, ')')) == NULL)
1237 parse_hints(HintState *hstate, Query *parse, const char *str)
1242 initStringInfo(&buf);
1243 while (*str != '\0')
1245 const HintParser *parser;
1247 /* in error message, we output the comment including the keyword. */
1248 head = (char *) str;
1250 /* parse only the keyword of the hint. */
1251 resetStringInfo(&buf);
1252 str = parse_keyword(str, &buf);
1254 for (parser = parsers; parser->keyword != NULL; parser++)
1256 char *keyword = parser->keyword;
1259 if (strcasecmp(buf.data, keyword) != 0)
1262 hint = parser->create_func(head, keyword, parser->hint_keyword);
1264 /* parser of each hint does parse in a parenthesis. */
1265 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1267 hint->delete_func(hint);
1273 * Add hint information into all_hints array. If we don't have
1274 * enough space, double the array.
1276 if (hstate->nall_hints == 0)
1278 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1279 hstate->all_hints = (Hint **)
1280 palloc(sizeof(Hint *) * hstate->max_all_hints);
1282 else if (hstate->nall_hints == hstate->max_all_hints)
1284 hstate->max_all_hints *= 2;
1285 hstate->all_hints = (Hint **)
1286 repalloc(hstate->all_hints,
1287 sizeof(Hint *) * hstate->max_all_hints);
1290 hstate->all_hints[hstate->nall_hints] = hint;
1291 hstate->nall_hints++;
1298 if (parser->keyword == NULL)
1301 ("Unrecognized hint keyword \"%s\".", buf.data));
1311 * Do basic parsing of the query head comment.
1314 parse_head_comment(Query *parse)
1323 /* get client-supplied query string. */
1326 PreparedStatement *entry;
1328 entry = FetchPreparedStatement(stmt_name, true);
1329 p = entry->plansource->query_string;
1332 p = debug_query_string;
1337 /* extract query head comment. */
1338 len = strlen(HINT_START);
1340 if (strncmp(p, HINT_START, len))
1347 /* find hint end keyword. */
1348 if ((tail = strstr(p, HINT_END)) == NULL)
1350 hint_ereport(head, ("Unterminated block comment."));
1354 /* We don't support nested block comments. */
1355 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1357 hint_ereport(head, ("Nested block comments are not supported."));
1361 /* Make a copy of hint. */
1363 head = palloc(len + 1);
1364 memcpy(head, p, len);
1368 hstate = HintStateCreate();
1369 hstate->hint_str = head;
1371 /* parse each hint. */
1372 parse_hints(hstate, parse, p);
1374 /* When nothing specified a hint, we free HintState and returns NULL. */
1375 if (hstate->nall_hints == 0)
1377 HintStateDelete(hstate);
1381 /* Sort hints in order of original position. */
1382 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1385 /* Count number of hints per hint-type. */
1386 for (i = 0; i < hstate->nall_hints; i++)
1388 Hint *cur_hint = hstate->all_hints[i];
1389 hstate->num_hints[cur_hint->type]++;
1393 * If an object (or a set of objects) has multiple hints of same hint-type,
1394 * only the last hint is valid and others are igonred in planning.
1395 * Hints except the last are marked as 'duplicated' to remember the order.
1397 for (i = 0; i < hstate->nall_hints - 1; i++)
1399 Hint *cur_hint = hstate->all_hints[i];
1400 Hint *next_hint = hstate->all_hints[i + 1];
1403 * Leading hint is marked as 'duplicated' in transform_join_hints.
1405 if (cur_hint->type == HINT_TYPE_LEADING &&
1406 next_hint->type == HINT_TYPE_LEADING)
1410 * Note that we need to pass addresses of hint pointers, because
1411 * HintCmp is designed to sort array of Hint* by qsort.
1413 if (HintCmp(&cur_hint, &next_hint) == 0)
1415 hint_ereport(cur_hint->hint_str,
1416 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1417 cur_hint->state = HINT_STATE_DUPLICATION;
1422 * Make sure that per-type array pointers point proper position in the
1423 * array which consists of all hints.
1425 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1426 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1427 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1428 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1429 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1430 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1431 hstate->num_hints[HINT_TYPE_LEADING]);
1437 * Parse inside of parentheses of scan-method hints.
1440 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1443 const char *keyword = hint->base.keyword;
1444 HintKeyword hint_keyword = hint->base.hint_keyword;
1445 List *name_list = NIL;
1448 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1451 /* Parse relation name and index name(s) if given hint accepts. */
1452 length = list_length(name_list);
1455 hint->relname = linitial(name_list);
1456 hint->indexnames = list_delete_first(name_list);
1458 /* check whether the hint accepts index name(s). */
1460 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1461 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1462 #if PG_VERSION_NUM >= 90200
1463 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1464 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1466 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1467 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1470 ("%s hint accepts only one relation.",
1471 hint->base.keyword));
1472 hint->base.state = HINT_STATE_ERROR;
1479 ("%s hint requires a relation.",
1480 hint->base.keyword));
1481 hint->base.state = HINT_STATE_ERROR;
1485 /* Set a bit for specified hint. */
1486 switch (hint_keyword)
1488 case HINT_KEYWORD_SEQSCAN:
1489 hint->enforce_mask = ENABLE_SEQSCAN;
1491 case HINT_KEYWORD_INDEXSCAN:
1492 hint->enforce_mask = ENABLE_INDEXSCAN;
1494 case HINT_KEYWORD_INDEXSCANREGEXP:
1495 hint->enforce_mask = ENABLE_INDEXSCAN;
1496 hint->regexp = true;
1498 case HINT_KEYWORD_BITMAPSCAN:
1499 hint->enforce_mask = ENABLE_BITMAPSCAN;
1501 case HINT_KEYWORD_BITMAPSCANREGEXP:
1502 hint->enforce_mask = ENABLE_BITMAPSCAN;
1503 hint->regexp = true;
1505 case HINT_KEYWORD_TIDSCAN:
1506 hint->enforce_mask = ENABLE_TIDSCAN;
1508 case HINT_KEYWORD_NOSEQSCAN:
1509 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1511 case HINT_KEYWORD_NOINDEXSCAN:
1512 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1514 case HINT_KEYWORD_NOBITMAPSCAN:
1515 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1517 case HINT_KEYWORD_NOTIDSCAN:
1518 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1520 #if PG_VERSION_NUM >= 90200
1521 case HINT_KEYWORD_INDEXONLYSCAN:
1522 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1524 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1525 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1526 hint->regexp = true;
1528 case HINT_KEYWORD_NOINDEXONLYSCAN:
1529 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1533 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1542 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1545 const char *keyword = hint->base.keyword;
1546 HintKeyword hint_keyword = hint->base.hint_keyword;
1547 List *name_list = NIL;
1549 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1552 hint->nrels = list_length(name_list);
1554 if (hint->nrels > 0)
1560 * Transform relation names from list to array to sort them with qsort
1563 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1564 foreach (l, name_list)
1566 hint->relnames[i] = lfirst(l);
1571 list_free(name_list);
1573 /* A join hint requires at least two relations */
1574 if (hint->nrels < 2)
1577 ("%s hint requires at least two relations.",
1578 hint->base.keyword));
1579 hint->base.state = HINT_STATE_ERROR;
1583 /* Sort hints in alphabetical order of relation names. */
1584 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1586 switch (hint_keyword)
1588 case HINT_KEYWORD_NESTLOOP:
1589 hint->enforce_mask = ENABLE_NESTLOOP;
1591 case HINT_KEYWORD_MERGEJOIN:
1592 hint->enforce_mask = ENABLE_MERGEJOIN;
1594 case HINT_KEYWORD_HASHJOIN:
1595 hint->enforce_mask = ENABLE_HASHJOIN;
1597 case HINT_KEYWORD_NONESTLOOP:
1598 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1600 case HINT_KEYWORD_NOMERGEJOIN:
1601 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1603 case HINT_KEYWORD_NOHASHJOIN:
1604 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1607 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1616 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1619 if (outer_inner->outer_inner_pair == NIL)
1621 if (outer_inner->relation)
1627 if (list_length(outer_inner->outer_inner_pair) == 2)
1629 foreach(l, outer_inner->outer_inner_pair)
1631 if (!OuterInnerPairCheck(lfirst(l)))
1642 OuterInnerList(OuterInnerRels *outer_inner)
1644 List *outer_inner_list = NIL;
1646 OuterInnerRels *outer_inner_rels;
1648 foreach(l, outer_inner->outer_inner_pair)
1650 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
1652 if (outer_inner_rels->relation != NULL)
1653 outer_inner_list = lappend(outer_inner_list,
1654 outer_inner_rels->relation);
1656 outer_inner_list = list_concat(outer_inner_list,
1657 OuterInnerList(outer_inner_rels));
1659 return outer_inner_list;
1663 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1666 List *name_list = NIL;
1667 OuterInnerRels *outer_inner = NULL;
1669 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
1673 if (outer_inner != NULL)
1674 name_list = OuterInnerList(outer_inner);
1676 hint->relations = name_list;
1677 hint->outer_inner = outer_inner;
1679 /* A Leading hint requires at least two relations */
1680 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
1682 hint_ereport(hint->base.hint_str,
1683 ("%s hint requires at least two relations.",
1685 hint->base.state = HINT_STATE_ERROR;
1687 else if (hint->outer_inner != NULL &&
1688 !OuterInnerPairCheck(hint->outer_inner))
1690 hint_ereport(hint->base.hint_str,
1691 ("%s hint requires two sets of relations when parentheses nests.",
1693 hint->base.state = HINT_STATE_ERROR;
1700 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1702 List *name_list = NIL;
1704 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
1708 hint->words = name_list;
1710 /* We need both name and value to set GUC parameter. */
1711 if (list_length(name_list) == 2)
1713 hint->name = linitial(name_list);
1714 hint->value = lsecond(name_list);
1718 hint_ereport(hint->base.hint_str,
1719 ("%s hint requires name and value of GUC parameter.",
1721 hint->base.state = HINT_STATE_ERROR;
1728 * set GUC parameter functions
1732 set_config_option_wrapper(const char *name, const char *value,
1733 GucContext context, GucSource source,
1734 GucAction action, bool changeVal, int elevel)
1737 MemoryContext ccxt = CurrentMemoryContext;
1741 #if PG_VERSION_NUM >= 90200
1742 result = set_config_option(name, value, context, source,
1743 action, changeVal, 0);
1745 result = set_config_option(name, value, context, source,
1753 /* Save error info */
1754 MemoryContextSwitchTo(ccxt);
1755 errdata = CopyErrorData();
1758 ereport(elevel, (errcode(errdata->sqlerrcode),
1759 errmsg("%s", errdata->message),
1760 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1761 errdata->hint ? errhint("%s", errdata->hint) : 0));
1762 FreeErrorData(errdata);
1770 set_config_options(SetHint **options, int noptions, GucContext context)
1775 save_nestlevel = NewGUCNestLevel();
1777 for (i = 0; i < noptions; i++)
1779 SetHint *hint = options[i];
1782 if (!hint_state_enabled(hint))
1785 result = set_config_option_wrapper(hint->name, hint->value, context,
1786 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1787 pg_hint_plan_parse_messages);
1789 hint->base.state = HINT_STATE_USED;
1791 hint->base.state = HINT_STATE_ERROR;
1794 return save_nestlevel;
1797 #define SET_CONFIG_OPTION(name, type_bits) \
1798 set_config_option_wrapper((name), \
1799 (mask & (type_bits)) ? "true" : "false", \
1800 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1803 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1807 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1808 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1809 #if PG_VERSION_NUM >= 90200
1810 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1813 mask = enforce_mask;
1815 mask = enforce_mask & current_hint->init_scan_mask;
1817 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1818 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1819 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1820 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1821 #if PG_VERSION_NUM >= 90200
1822 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1827 set_join_config_options(unsigned char enforce_mask, GucContext context)
1831 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1832 enforce_mask == ENABLE_HASHJOIN)
1833 mask = enforce_mask;
1835 mask = enforce_mask & current_hint->init_join_mask;
1837 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1838 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1839 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1843 * pg_hint_plan hook functions
1847 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1848 ParamListInfo params, bool isTopLevel,
1849 DestReceiver *dest, char *completionTag)
1853 if (!pg_hint_plan_enable_hint)
1855 if (prev_ProcessUtility)
1856 (*prev_ProcessUtility) (parsetree, queryString, params,
1857 isTopLevel, dest, completionTag);
1859 standard_ProcessUtility(parsetree, queryString, params,
1860 isTopLevel, dest, completionTag);
1866 if (IsA(node, ExplainStmt))
1869 * Draw out parse tree of actual query from Query struct of EXPLAIN
1875 stmt = (ExplainStmt *) node;
1877 Assert(IsA(stmt->query, Query));
1878 query = (Query *) stmt->query;
1880 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1881 node = query->utilityStmt;
1885 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
1886 * specified to preceding PREPARE command to use it as source of hints.
1888 if (IsA(node, ExecuteStmt))
1892 stmt = (ExecuteStmt *) node;
1893 stmt_name = stmt->name;
1895 #if PG_VERSION_NUM >= 90200
1897 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
1900 if (IsA(node, CreateTableAsStmt))
1902 CreateTableAsStmt *stmt;
1905 stmt = (CreateTableAsStmt *) node;
1906 Assert(IsA(stmt->query, Query));
1907 query = (Query *) stmt->query;
1909 if (query->commandType == CMD_UTILITY &&
1910 IsA(query->utilityStmt, ExecuteStmt))
1912 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
1913 stmt_name = estmt->name;
1921 if (prev_ProcessUtility)
1922 (*prev_ProcessUtility) (parsetree, queryString, params,
1923 isTopLevel, dest, completionTag);
1925 standard_ProcessUtility(parsetree, queryString, params,
1926 isTopLevel, dest, completionTag);
1940 if (prev_ProcessUtility)
1941 (*prev_ProcessUtility) (parsetree, queryString, params,
1942 isTopLevel, dest, completionTag);
1944 standard_ProcessUtility(parsetree, queryString, params,
1945 isTopLevel, dest, completionTag);
1949 * Push a hint into hint stack which is implemented with List struct. Head of
1950 * list is top of stack.
1953 push_hint(HintState *hstate)
1955 /* Prepend new hint to the list means pushing to stack. */
1956 HintStateStack = lcons(hstate, HintStateStack);
1958 /* Pushed hint is the one which should be used hereafter. */
1959 current_hint = hstate;
1962 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
1966 /* Hint stack must not be empty. */
1967 if(HintStateStack == NIL)
1968 elog(ERROR, "hint stack is empty");
1971 * Take a hint at the head from the list, and free it. Switch current_hint
1972 * to point new head (NULL if the list is empty).
1974 HintStateStack = list_delete_first(HintStateStack);
1975 HintStateDelete(current_hint);
1976 if(HintStateStack == NIL)
1977 current_hint = NULL;
1979 current_hint = (HintState *) lfirst(list_head(HintStateStack));
1982 static PlannedStmt *
1983 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1986 PlannedStmt *result;
1990 * Use standard planner if pg_hint_plan is disabled. Other hook functions
1991 * try to change plan with current_hint if any, so set it to NULL.
1993 if (!pg_hint_plan_enable_hint)
1995 current_hint = NULL;
1998 return (*prev_planner) (parse, cursorOptions, boundParams);
2000 return standard_planner(parse, cursorOptions, boundParams);
2003 /* Create hint struct from parse tree. */
2004 hstate = parse_head_comment(parse);
2007 * Use standard planner if the statement has not valid hint. Other hook
2008 * functions try to change plan with current_hint if any, so set it to
2013 current_hint = NULL;
2016 return (*prev_planner) (parse, cursorOptions, boundParams);
2018 return standard_planner(parse, cursorOptions, boundParams);
2022 * Push new hint struct to the hint stack to disable previous hint context.
2026 /* Set GUC parameters which are specified with Set hint. */
2027 save_nestlevel = set_config_options(current_hint->set_hints,
2028 current_hint->num_hints[HINT_TYPE_SET],
2029 current_hint->context);
2032 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2033 if (enable_indexscan)
2034 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2035 if (enable_bitmapscan)
2036 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2038 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2039 #if PG_VERSION_NUM >= 90200
2040 if (enable_indexonlyscan)
2041 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2043 if (enable_nestloop)
2044 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2045 if (enable_mergejoin)
2046 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2047 if (enable_hashjoin)
2048 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2051 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2052 * state when this planner started when error occurred in planner.
2057 result = (*prev_planner) (parse, cursorOptions, boundParams);
2059 result = standard_planner(parse, cursorOptions, boundParams);
2064 * Rollback changes of GUC parameters, and pop current hint context
2065 * from hint stack to rewind the state.
2067 AtEOXact_GUC(true, save_nestlevel);
2073 /* Print hint in debug mode. */
2074 if (pg_hint_plan_debug_print)
2075 HintStateDump(current_hint);
2078 * Rollback changes of GUC parameters, and pop current hint context from
2079 * hint stack to rewind the state.
2081 AtEOXact_GUC(true, save_nestlevel);
2088 * Return scan method hint which matches given aliasname.
2090 static ScanMethodHint *
2091 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2097 * We can't apply scan method hint if the relation is:
2098 * - not a base relation
2099 * - not an ordinary relation (such as join and subquery)
2101 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2104 rte = root->simple_rte_array[rel->relid];
2106 /* We can't force scan method of foreign tables */
2107 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2110 /* Find scan method hint, which matches given names, from the list. */
2111 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2113 ScanMethodHint *hint = current_hint->scan_hints[i];
2115 /* We ignore disabled hints. */
2116 if (!hint_state_enabled(hint))
2119 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2129 * Returns TRUE on match, FALSE on no match.
2131 * s1 --- the data to match against
2132 * s2 --- the pattern
2134 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2137 regexpeq(const char *s1, const char *s2)
2143 strcpy(name.data, s1);
2144 regexp = cstring_to_text(s2);
2146 result = DirectFunctionCall2Coll(nameregexeq,
2147 DEFAULT_COLLATION_OID,
2148 NameGetDatum(&name),
2149 PointerGetDatum(regexp));
2150 return DatumGetBool(result);
2154 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2162 * We delete all the IndexOptInfo list and prevent you from being usable by
2165 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2166 hint->enforce_mask == ENABLE_TIDSCAN)
2168 list_free_deep(rel->indexlist);
2169 rel->indexlist = NIL;
2170 hint->base.state = HINT_STATE_USED;
2176 * When a list of indexes is not specified, we just use all indexes.
2178 if (hint->indexnames == NIL)
2182 * Leaving only an specified index, we delete it from a IndexOptInfo list
2186 if (pg_hint_plan_debug_print)
2187 initStringInfo(&buf);
2189 for (cell = list_head(rel->indexlist); cell; cell = next)
2191 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2192 char *indexname = get_rel_name(info->indexoid);
2194 bool use_index = false;
2198 foreach(l, hint->indexnames)
2200 char *hintname = (char *) lfirst(l);
2204 result = regexpeq(indexname, hintname);
2206 result = RelnameCmp(&indexname, &hintname) == 0;
2211 if (pg_hint_plan_debug_print)
2213 appendStringInfoCharMacro(&buf, ' ');
2214 quote_value(&buf, indexname);
2221 if (OidIsValid(relationObjectId) && !use_index)
2224 char *child_attname = NULL;
2225 char *parent_attname = NULL;
2227 foreach(l, current_hint->parent_ind_atts)
2229 List *attnums = (List *)lfirst(l);
2231 if ((list_length(attnums)) != info->ncolumns)
2234 for (i = 0; i < info->ncolumns; i++)
2236 child_attname = get_attname(relationObjectId,
2237 info->indexkeys[i]);
2238 parent_attname = get_attname(current_hint->parent_rel_oid,
2239 list_nth_int(attnums, i));
2240 if (strcmp(parent_attname, child_attname) != 0)
2251 if (pg_hint_plan_debug_print)
2253 appendStringInfoCharMacro(&buf, ' ');
2254 quote_value(&buf, indexname);
2262 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2269 if (pg_hint_plan_debug_print)
2272 StringInfoData rel_buf;
2274 if (OidIsValid(relationObjectId))
2275 relname = get_rel_name(relationObjectId);
2277 relname = hint->relname;
2279 initStringInfo(&rel_buf);
2280 quote_value(&rel_buf, relname);
2283 (errmsg("available indexes for %s(%s):%s",
2288 pfree(rel_buf.data);
2293 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2294 bool inhparent, RelOptInfo *rel)
2296 ScanMethodHint *hint;
2298 if (prev_get_relation_info)
2299 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2301 /* Do nothing if we don't have valid hint in this context. */
2307 /* store does relids of parent table. */
2308 current_hint->parent_relid = rel->relid;
2309 current_hint->parent_rel_oid = relationObjectId;
2311 else if (current_hint->parent_relid != 0)
2314 * We use the same GUC parameter if this table is the child table of a
2315 * table called pg_hint_plan_get_relation_info just before that.
2319 /* append_rel_list contains all append rels; ignore others */
2320 foreach(l, root->append_rel_list)
2322 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2324 /* This rel is child table. */
2325 if (appinfo->parent_relid == current_hint->parent_relid &&
2326 appinfo->child_relid == rel->relid)
2328 if (current_hint->parent_hint)
2329 delete_indexes(current_hint->parent_hint, rel,
2336 /* This rel is not inherit table. */
2337 current_hint->parent_relid = 0;
2338 current_hint->parent_rel_oid = InvalidOid;
2339 current_hint->parent_hint = NULL;
2343 * If scan method hint was given, reset GUC parameters which control
2344 * planner behavior about choosing scan methods.
2346 if ((hint = find_scan_hint(root, rel)) == NULL)
2348 set_scan_config_options(current_hint->init_scan_mask,
2349 current_hint->context);
2352 set_scan_config_options(hint->enforce_mask, current_hint->context);
2353 hint->base.state = HINT_STATE_USED;
2361 current_hint->parent_hint = hint;
2363 relation = heap_open(relationObjectId, NoLock);
2364 indexoidlist = RelationGetIndexList(relation);
2366 foreach(l, indexoidlist)
2369 Oid indexoid = lfirst_oid(l);
2370 char *indexname = get_rel_name(indexoid);
2371 bool use_index = false;
2372 Relation indexRelation;
2373 Form_pg_index index;
2375 List *attnums = NIL;
2377 foreach(lc, hint->indexnames)
2379 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
2388 indexRelation = index_open(indexoid, RowExclusiveLock);
2390 index = indexRelation->rd_index;
2392 for (i = 0; i < index->indnatts; i++)
2393 attnums = lappend_int(attnums, index->indkey.values[i]);
2395 current_hint->parent_ind_atts =
2396 lappend(current_hint->parent_ind_atts, attnums);
2398 index_close(indexRelation, NoLock);
2400 heap_close(relation, NoLock);
2403 delete_indexes(hint, rel, InvalidOid);
2407 * Return index of relation which matches given aliasname, or 0 if not found.
2408 * If same aliasname was used multiple times in a query, return -1.
2411 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
2417 for (i = 1; i < root->simple_rel_array_size; i++)
2421 if (root->simple_rel_array[i] == NULL)
2424 Assert(i == root->simple_rel_array[i]->relid);
2426 if (RelnameCmp(&aliasname,
2427 &root->simple_rte_array[i]->eref->aliasname) != 0)
2430 foreach(l, initial_rels)
2432 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2434 if (rel->reloptkind == RELOPT_BASEREL)
2436 if (rel->relid != i)
2441 Assert(rel->reloptkind == RELOPT_JOINREL);
2443 if (!bms_is_member(i, rel->relids))
2450 ("Relation name \"%s\" is ambiguous.",
2465 * Return join hint which matches given joinrelids.
2467 static JoinMethodHint *
2468 find_join_hint(Relids joinrelids)
2473 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
2475 foreach(l, join_hint)
2477 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
2479 if (bms_equal(joinrelids, hint->joinrelids))
2487 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
2488 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
2490 OuterInnerRels *outer_rels;
2491 OuterInnerRels *inner_rels;
2492 Relids outer_relids;
2493 Relids inner_relids;
2495 JoinMethodHint *hint;
2497 if (outer_inner->relation != NULL)
2499 return bms_make_singleton(
2500 find_relid_aliasname(root, outer_inner->relation,
2502 leading_hint->base.hint_str));
2505 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
2506 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
2508 outer_relids = OuterInnerJoinCreate(outer_rels,
2514 inner_relids = OuterInnerJoinCreate(inner_rels,
2521 join_relids = bms_add_members(outer_relids, inner_relids);
2523 if (bms_num_members(join_relids) > nbaserel)
2527 * If we don't have join method hint, create new one for the
2528 * join combination with all join methods are enabled.
2530 hint = find_join_hint(join_relids);
2534 * Here relnames is not set, since Relids bitmap is sufficient to
2535 * control paths of this query afterward.
2537 hint = (JoinMethodHint *) JoinMethodHintCreate(
2538 leading_hint->base.hint_str,
2540 HINT_KEYWORD_LEADING);
2541 hint->base.state = HINT_STATE_USED;
2542 hint->nrels = bms_num_members(join_relids);
2543 hint->enforce_mask = ENABLE_ALL_JOIN;
2544 hint->joinrelids = bms_copy(join_relids);
2545 hint->inner_nrels = bms_num_members(inner_relids);
2546 hint->inner_joinrelids = bms_copy(inner_relids);
2548 hstate->join_hint_level[hint->nrels] =
2549 lappend(hstate->join_hint_level[hint->nrels], hint);
2553 hint->inner_nrels = bms_num_members(inner_relids);
2554 hint->inner_joinrelids = bms_copy(inner_relids);
2561 * Transform join method hint into handy form.
2563 * - create bitmap of relids from alias names, to make it easier to check
2564 * whether a join path matches a join method hint.
2565 * - add join method hints which are necessary to enforce join order
2566 * specified by Leading hint
2569 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2570 List *initial_rels, JoinMethodHint **join_method_hints)
2578 LeadingHint *lhint = NULL;
2581 * Create bitmap of relids from alias names for each join method hint.
2582 * Bitmaps are more handy than strings in join searching.
2584 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2586 JoinMethodHint *hint = hstate->join_hints[i];
2589 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
2592 bms_free(hint->joinrelids);
2593 hint->joinrelids = NULL;
2595 for (j = 0; j < hint->nrels; j++)
2597 relname = hint->relnames[j];
2599 relid = find_relid_aliasname(root, relname, initial_rels,
2600 hint->base.hint_str);
2603 hint->base.state = HINT_STATE_ERROR;
2608 if (bms_is_member(relid, hint->joinrelids))
2610 hint_ereport(hint->base.hint_str,
2611 ("Relation name \"%s\" is duplicated.", relname));
2612 hint->base.state = HINT_STATE_ERROR;
2616 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
2619 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
2622 hstate->join_hint_level[hint->nrels] =
2623 lappend(hstate->join_hint_level[hint->nrels], hint);
2626 /* Do nothing if no Leading hint was supplied. */
2627 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2631 * Decide to use Leading hint。
2633 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
2635 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
2638 if (leading_hint->base.state == HINT_STATE_ERROR)
2644 foreach(l, leading_hint->relations)
2646 relname = (char *)lfirst(l);;
2648 relid = find_relid_aliasname(root, relname, initial_rels,
2649 leading_hint->base.hint_str);
2651 leading_hint->base.state = HINT_STATE_ERROR;
2656 if (bms_is_member(relid, relids))
2658 hint_ereport(leading_hint->base.hint_str,
2659 ("Relation name \"%s\" is duplicated.", relname));
2660 leading_hint->base.state = HINT_STATE_ERROR;
2664 relids = bms_add_member(relids, relid);
2667 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
2672 hint_ereport(lhint->base.hint_str,
2673 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
2674 lhint->base.state = HINT_STATE_DUPLICATION;
2676 leading_hint->base.state = HINT_STATE_USED;
2677 lhint = leading_hint;
2680 /* check to exist Leading hint marked with 'used'. */
2685 * We need join method hints which fit specified join order in every join
2686 * level. For example, Leading(A B C) virtually requires following join
2687 * method hints, if no join method hint supplied:
2689 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
2690 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
2692 * If we already have join method hint which fits specified join order in
2693 * that join level, we leave it as-is and don't add new hints.
2697 if (lhint->outer_inner == NULL)
2699 foreach(l, lhint->relations)
2701 JoinMethodHint *hint;
2703 relname = (char *)lfirst(l);
2706 * Find relid of the relation which has given name. If we have the
2707 * name given in Leading hint multiple times in the join, nothing to
2710 relid = find_relid_aliasname(root, relname, initial_rels,
2713 /* Create bitmap of relids for current join level. */
2714 joinrelids = bms_add_member(joinrelids, relid);
2717 /* We never have join method hint for single relation. */
2722 * If we don't have join method hint, create new one for the
2723 * join combination with all join methods are enabled.
2725 hint = find_join_hint(joinrelids);
2729 * Here relnames is not set, since Relids bitmap is sufficient
2730 * to control paths of this query afterward.
2732 hint = (JoinMethodHint *) JoinMethodHintCreate(
2733 lhint->base.hint_str,
2735 HINT_KEYWORD_LEADING);
2736 hint->base.state = HINT_STATE_USED;
2737 hint->nrels = njoinrels;
2738 hint->enforce_mask = ENABLE_ALL_JOIN;
2739 hint->joinrelids = bms_copy(joinrelids);
2742 join_method_hints[njoinrels] = hint;
2744 if (njoinrels >= nbaserel)
2747 bms_free(joinrelids);
2753 * Delete all join hints which have different combination from Leading
2756 for (i = 2; i <= njoinrels; i++)
2758 list_free(hstate->join_hint_level[i]);
2760 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
2765 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
2772 njoinrels = bms_num_members(joinrelids);
2773 Assert(njoinrels >= 2);
2776 * Delete all join hints which have different combination from Leading
2779 for (i = 2;i <= njoinrels; i++)
2781 if (hstate->join_hint_level[i] != NIL)
2783 ListCell *prev = NULL;
2784 ListCell *next = NULL;
2785 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
2788 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
2792 if (hint->inner_nrels == 0 &&
2793 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
2794 bms_equal(bms_union(hint->joinrelids, joinrelids),
2797 hstate->join_hint_level[i] =
2798 list_delete_cell(hstate->join_hint_level[i], l,
2807 bms_free(joinrelids);
2810 if (hint_state_enabled(lhint))
2812 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2819 * set_plain_rel_pathlist
2820 * Build access paths for a plain relation (no subquery, no inheritance)
2822 * This function was copied and edited from set_plain_rel_pathlist() in
2823 * src/backend/optimizer/path/allpaths.c
2826 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2828 /* Consider sequential scan */
2829 #if PG_VERSION_NUM >= 90200
2830 add_path(rel, create_seqscan_path(root, rel, NULL));
2832 add_path(rel, create_seqscan_path(root, rel));
2835 /* Consider index scans */
2836 create_index_paths(root, rel);
2838 /* Consider TID scans */
2839 create_tidscan_paths(root, rel);
2841 /* Now find the cheapest of the paths for this rel */
2846 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
2851 foreach(l, initial_rels)
2853 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2855 ScanMethodHint *hint;
2857 /* Skip relations which we can't choose scan method. */
2858 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2861 rte = root->simple_rte_array[rel->relid];
2863 /* We can't force scan method of foreign tables */
2864 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2868 * Create scan paths with GUC parameters which are at the beginning of
2869 * planner if scan method hint is not specified, otherwise use
2870 * specified hints and mark the hint as used.
2872 if ((hint = find_scan_hint(root, rel)) == NULL)
2873 set_scan_config_options(hstate->init_scan_mask,
2877 set_scan_config_options(hint->enforce_mask, hstate->context);
2878 hint->base.state = HINT_STATE_USED;
2881 list_free_deep(rel->pathlist);
2882 rel->pathlist = NIL;
2885 /* It's an "append relation", process accordingly */
2886 set_append_rel_pathlist(root, rel, rel->relid, rte);
2890 set_plain_rel_pathlist(root, rel, rte);
2895 * Restore the GUC variables we set above.
2897 set_scan_config_options(hstate->init_scan_mask, hstate->context);
2901 * wrapper of make_join_rel()
2903 * call make_join_rel() after changing enable_* parameters according to given
2907 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
2910 JoinMethodHint *hint;
2914 joinrelids = bms_union(rel1->relids, rel2->relids);
2915 hint = find_join_hint(joinrelids);
2916 bms_free(joinrelids);
2919 return pg_hint_plan_make_join_rel(root, rel1, rel2);
2921 if (hint->inner_nrels == 0)
2923 save_nestlevel = NewGUCNestLevel();
2925 set_join_config_options(hint->enforce_mask, current_hint->context);
2927 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2928 hint->base.state = HINT_STATE_USED;
2931 * Restore the GUC variables we set above.
2933 AtEOXact_GUC(true, save_nestlevel);
2936 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2945 add_paths_to_joinrel_wrapper(PlannerInfo *root,
2946 RelOptInfo *joinrel,
2947 RelOptInfo *outerrel,
2948 RelOptInfo *innerrel,
2950 SpecialJoinInfo *sjinfo,
2953 ScanMethodHint *scan_hint = NULL;
2955 JoinMethodHint *join_hint;
2958 if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
2960 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
2961 scan_hint->base.state = HINT_STATE_USED;
2964 joinrelids = bms_union(outerrel->relids, innerrel->relids);
2965 join_hint = find_join_hint(joinrelids);
2966 bms_free(joinrelids);
2968 if (join_hint && join_hint->inner_nrels != 0)
2970 save_nestlevel = NewGUCNestLevel();
2972 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
2975 set_join_config_options(join_hint->enforce_mask,
2976 current_hint->context);
2978 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
2979 sjinfo, restrictlist);
2980 join_hint->base.state = HINT_STATE_USED;
2984 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2985 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
2986 sjinfo, restrictlist);
2990 * Restore the GUC variables we set above.
2992 AtEOXact_GUC(true, save_nestlevel);
2995 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
2996 sjinfo, restrictlist);
2998 if (scan_hint != NULL)
2999 set_scan_config_options(current_hint->init_scan_mask,
3000 current_hint->context);
3004 get_num_baserels(List *initial_rels)
3009 foreach(l, initial_rels)
3011 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3013 if (rel->reloptkind == RELOPT_BASEREL)
3015 else if (rel->reloptkind ==RELOPT_JOINREL)
3016 nbaserel+= bms_num_members(rel->relids);
3019 /* other values not expected here */
3020 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3028 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3031 JoinMethodHint **join_method_hints;
3035 bool leading_hint_enable;
3038 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3039 * valid hint is supplied.
3043 if (prev_join_search)
3044 return (*prev_join_search) (root, levels_needed, initial_rels);
3045 else if (enable_geqo && levels_needed >= geqo_threshold)
3046 return geqo(root, levels_needed, initial_rels);
3048 return standard_join_search(root, levels_needed, initial_rels);
3051 /* We apply scan method hint rebuild scan path. */
3052 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3055 * In the case using GEQO, only scan method hints and Set hints have
3056 * effect. Join method and join order is not controllable by hints.
3058 if (enable_geqo && levels_needed >= geqo_threshold)
3059 return geqo(root, levels_needed, initial_rels);
3061 nbaserel = get_num_baserels(initial_rels);
3062 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3063 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3065 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3066 initial_rels, join_method_hints);
3068 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3070 for (i = 2; i <= nbaserel; i++)
3072 list_free(current_hint->join_hint_level[i]);
3074 /* free Leading hint only */
3075 if (join_method_hints[i] != NULL &&
3076 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3077 JoinMethodHintDelete(join_method_hints[i]);
3079 pfree(current_hint->join_hint_level);
3080 pfree(join_method_hints);
3082 if (leading_hint_enable)
3083 set_join_config_options(current_hint->init_join_mask,
3084 current_hint->context);
3091 * Build access paths for a base relation
3093 * This function was copied and edited from set_rel_pathlist() in
3094 * src/backend/optimizer/path/allpaths.c
3097 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3098 Index rti, RangeTblEntry *rte)
3100 #if PG_VERSION_NUM >= 90200
3101 if (IS_DUMMY_REL(rel))
3103 /* We already proved the relation empty, so nothing more to do */
3110 /* It's an "append relation", process accordingly */
3111 set_append_rel_pathlist(root, rel, rti, rte);
3115 if (rel->rtekind == RTE_RELATION)
3117 if (rte->relkind == RELKIND_RELATION)
3119 /* Plain relation */
3120 set_plain_rel_pathlist(root, rel, rte);
3123 elog(ERROR, "unexpected relkind: %c", rte->relkind);
3126 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
3130 #define standard_join_search pg_hint_plan_standard_join_search
3131 #define join_search_one_level pg_hint_plan_join_search_one_level
3132 #define make_join_rel make_join_rel_wrapper
3135 #undef make_join_rel
3136 #define make_join_rel pg_hint_plan_make_join_rel
3137 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
3138 #include "make_join_rel.c"