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"
41 #ifdef PG_MODULE_MAGIC
45 #if PG_VERSION_NUM < 90100
46 #error unsupported PostgreSQL version
49 #define BLOCK_COMMENT_START "/*"
50 #define BLOCK_COMMENT_END "*/"
51 #define HINT_COMMENT_KEYWORD "+"
52 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
53 #define HINT_END BLOCK_COMMENT_END
56 #define HINT_SEQSCAN "SeqScan"
57 #define HINT_INDEXSCAN "IndexScan"
58 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
59 #define HINT_BITMAPSCAN "BitmapScan"
60 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
61 #define HINT_TIDSCAN "TidScan"
62 #define HINT_NOSEQSCAN "NoSeqScan"
63 #define HINT_NOINDEXSCAN "NoIndexScan"
64 #define HINT_NOBITMAPSCAN "NoBitmapScan"
65 #define HINT_NOTIDSCAN "NoTidScan"
66 #if PG_VERSION_NUM >= 90200
67 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
68 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
69 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
71 #define HINT_NESTLOOP "NestLoop"
72 #define HINT_MERGEJOIN "MergeJoin"
73 #define HINT_HASHJOIN "HashJoin"
74 #define HINT_NONESTLOOP "NoNestLoop"
75 #define HINT_NOMERGEJOIN "NoMergeJoin"
76 #define HINT_NOHASHJOIN "NoHashJoin"
77 #define HINT_LEADING "Leading"
78 #define HINT_SET "Set"
80 #define HINT_ARRAY_DEFAULT_INITSIZE 8
82 #define hint_ereport(str, detail) \
83 ereport(pg_hint_plan_parse_messages, \
84 (errmsg("hint syntax error at or near \"%s\"", (str)), \
87 #define skip_space(str) \
88 while (isspace(*str)) \
93 ENABLE_SEQSCAN = 0x01,
94 ENABLE_INDEXSCAN = 0x02,
95 ENABLE_BITMAPSCAN = 0x04,
96 ENABLE_TIDSCAN = 0x08,
97 #if PG_VERSION_NUM >= 90200
98 ENABLE_INDEXONLYSCAN = 0x10
104 ENABLE_NESTLOOP = 0x01,
105 ENABLE_MERGEJOIN = 0x02,
106 ENABLE_HASHJOIN = 0x04
109 #if PG_VERSION_NUM >= 90200
110 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
111 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
112 ENABLE_INDEXONLYSCAN)
114 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
115 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN)
117 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
118 #define DISABLE_ALL_SCAN 0
119 #define DISABLE_ALL_JOIN 0
121 /* hint keyword of enum type*/
122 typedef enum HintKeyword
124 HINT_KEYWORD_SEQSCAN,
125 HINT_KEYWORD_INDEXSCAN,
126 HINT_KEYWORD_INDEXSCANREGEXP,
127 HINT_KEYWORD_BITMAPSCAN,
128 HINT_KEYWORD_BITMAPSCANREGEXP,
129 HINT_KEYWORD_TIDSCAN,
130 HINT_KEYWORD_NOSEQSCAN,
131 HINT_KEYWORD_NOINDEXSCAN,
132 HINT_KEYWORD_NOBITMAPSCAN,
133 HINT_KEYWORD_NOTIDSCAN,
134 #if PG_VERSION_NUM >= 90200
135 HINT_KEYWORD_INDEXONLYSCAN,
136 HINT_KEYWORD_INDEXONLYSCANREGEXP,
137 HINT_KEYWORD_NOINDEXONLYSCAN,
139 HINT_KEYWORD_NESTLOOP,
140 HINT_KEYWORD_MERGEJOIN,
141 HINT_KEYWORD_HASHJOIN,
142 HINT_KEYWORD_NONESTLOOP,
143 HINT_KEYWORD_NOMERGEJOIN,
144 HINT_KEYWORD_NOHASHJOIN,
145 HINT_KEYWORD_LEADING,
147 HINT_KEYWORD_UNRECOGNIZED
150 typedef struct Hint Hint;
151 typedef struct HintState HintState;
153 typedef Hint *(*HintCreateFunction) (const char *hint_str,
155 HintKeyword hint_keyword);
156 typedef void (*HintDeleteFunction) (Hint *hint);
157 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf);
158 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
159 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
160 Query *parse, const char *str);
163 #define NUM_HINT_TYPE 4
164 typedef enum HintType
166 HINT_TYPE_SCAN_METHOD,
167 HINT_TYPE_JOIN_METHOD,
172 static const char *HintTypeName[] = {
180 typedef enum HintStatus
182 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
183 HINT_STATE_USED, /* hint is used */
184 HINT_STATE_DUPLICATION, /* specified hint duplication */
185 HINT_STATE_ERROR /* execute error (parse error does not include
189 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
190 (hint)->base.state == HINT_STATE_USED)
192 /* common data for all hints. */
195 const char *hint_str; /* must not do pfree */
196 const char *keyword; /* must not do pfree */
197 HintKeyword hint_keyword;
200 HintDeleteFunction delete_func;
201 HintDescFunction desc_func;
202 HintCmpFunction cmp_func;
203 HintParseFunction parse_func;
206 /* scan method hints */
207 typedef struct ScanMethodHint
213 unsigned char enforce_mask;
216 typedef struct ParentIndexInfo
221 char *expression_str;
228 /* join method hints */
229 typedef struct JoinMethodHint
235 unsigned char enforce_mask;
237 Relids inner_joinrelids;
240 /* join order hints */
241 typedef struct OuterInnerRels
244 List *outer_inner_pair;
247 typedef struct LeadingHint
250 List *relations; /* relation names specified in Leading hint */
251 OuterInnerRels *outer_inner;
254 /* change a run-time parameter hints */
255 typedef struct SetHint
258 char *name; /* name of variable */
264 * Describes a context of hint processing.
268 char *hint_str; /* original hint string */
271 int nall_hints; /* # of valid all hints */
272 int max_all_hints; /* # of slots for all hints */
273 Hint **all_hints; /* parsed all hints */
275 /* # of each hints */
276 int num_hints[NUM_HINT_TYPE];
278 /* for scan method hints */
279 ScanMethodHint **scan_hints; /* parsed scan hints */
280 int init_scan_mask; /* initial value scan parameter */
281 Index parent_relid; /* inherit parent table relid */
282 Oid parent_rel_oid; /* inherit parent table relid */
283 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
284 List *parent_index_infos; /* infomation of inherit parent table's
287 /* for join method hints */
288 JoinMethodHint **join_hints; /* parsed join hints */
289 int init_join_mask; /* initial value join parameter */
290 List **join_hint_level;
292 /* for Leading hint */
293 LeadingHint **leading_hint; /* parsed Leading hints */
296 SetHint **set_hints; /* parsed Set hints */
297 GucContext context; /* which GUC parameters can we set? */
301 * Describes a hint parser module which is bound with particular hint keyword.
303 typedef struct HintParser
306 HintCreateFunction create_func;
307 HintKeyword hint_keyword;
310 /* Module callbacks */
314 void set_plpgsql_plugin(void);
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 = NULL;
476 * Module load callbacks
481 /* Define custom GUC variables. */
482 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
483 "Force planner to use plans specified in the hint comment preceding to the query.",
485 &pg_hint_plan_enable_hint,
493 DefineCustomBoolVariable("pg_hint_plan.debug_print",
494 "Logs results of hint parsing.",
496 &pg_hint_plan_debug_print,
504 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
505 "Message level of parse errors.",
507 &pg_hint_plan_parse_messages,
509 parse_messages_level_options,
517 prev_ProcessUtility = ProcessUtility_hook;
518 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
519 prev_planner = planner_hook;
520 planner_hook = pg_hint_plan_planner;
521 prev_get_relation_info = get_relation_info_hook;
522 get_relation_info_hook = pg_hint_plan_get_relation_info;
523 prev_join_search = join_search_hook;
524 join_search_hook = pg_hint_plan_join_search;
526 /* PL/pgSQL plugin hook */
527 set_plpgsql_plugin();
529 (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
533 * Module unload callback
539 /* Uninstall hooks. */
540 ProcessUtility_hook = prev_ProcessUtility;
541 planner_hook = prev_planner;
542 get_relation_info_hook = prev_get_relation_info;
543 join_search_hook = prev_join_search;
547 set_plpgsql_plugin(void)
549 plugin_funcs = palloc(sizeof(void *));
550 *plugin_funcs = palloc(sizeof(PLpgSQL_plugin));
552 (*plugin_funcs)->func_setup = (void *)pg_hint_plan_plpgsql_func_setup;
553 (*plugin_funcs)->func_beg = NULL;
554 (*plugin_funcs)->func_end = NULL;
555 (*plugin_funcs)->stmt_beg = NULL;
556 (*plugin_funcs)->stmt_end = NULL;
557 (*plugin_funcs)->error_callback = NULL;
558 (*plugin_funcs)->assign_expr = NULL;
562 * create and delete functions the hint object
566 ScanMethodHintCreate(const char *hint_str, const char *keyword,
567 HintKeyword hint_keyword)
569 ScanMethodHint *hint;
571 hint = palloc(sizeof(ScanMethodHint));
572 hint->base.hint_str = hint_str;
573 hint->base.keyword = keyword;
574 hint->base.hint_keyword = hint_keyword;
575 hint->base.type = HINT_TYPE_SCAN_METHOD;
576 hint->base.state = HINT_STATE_NOTUSED;
577 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
578 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
579 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
580 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
581 hint->relname = NULL;
582 hint->indexnames = NIL;
583 hint->regexp = false;
584 hint->enforce_mask = 0;
586 return (Hint *) hint;
590 ScanMethodHintDelete(ScanMethodHint *hint)
596 pfree(hint->relname);
597 list_free_deep(hint->indexnames);
602 JoinMethodHintCreate(const char *hint_str, const char *keyword,
603 HintKeyword hint_keyword)
605 JoinMethodHint *hint;
607 hint = palloc(sizeof(JoinMethodHint));
608 hint->base.hint_str = hint_str;
609 hint->base.keyword = keyword;
610 hint->base.hint_keyword = hint_keyword;
611 hint->base.type = HINT_TYPE_JOIN_METHOD;
612 hint->base.state = HINT_STATE_NOTUSED;
613 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
614 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
615 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
616 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
618 hint->inner_nrels = 0;
619 hint->relnames = NULL;
620 hint->enforce_mask = 0;
621 hint->joinrelids = NULL;
622 hint->inner_joinrelids = NULL;
624 return (Hint *) hint;
628 JoinMethodHintDelete(JoinMethodHint *hint)
637 for (i = 0; i < hint->nrels; i++)
638 pfree(hint->relnames[i]);
639 pfree(hint->relnames);
642 bms_free(hint->joinrelids);
643 bms_free(hint->inner_joinrelids);
648 LeadingHintCreate(const char *hint_str, const char *keyword,
649 HintKeyword hint_keyword)
653 hint = palloc(sizeof(LeadingHint));
654 hint->base.hint_str = hint_str;
655 hint->base.keyword = keyword;
656 hint->base.hint_keyword = hint_keyword;
657 hint->base.type = HINT_TYPE_LEADING;
658 hint->base.state = HINT_STATE_NOTUSED;
659 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
660 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
661 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
662 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
663 hint->relations = NIL;
664 hint->outer_inner = NULL;
666 return (Hint *) hint;
670 LeadingHintDelete(LeadingHint *hint)
675 list_free_deep(hint->relations);
676 if (hint->outer_inner)
677 pfree(hint->outer_inner);
682 SetHintCreate(const char *hint_str, const char *keyword,
683 HintKeyword hint_keyword)
687 hint = palloc(sizeof(SetHint));
688 hint->base.hint_str = hint_str;
689 hint->base.keyword = keyword;
690 hint->base.hint_keyword = hint_keyword;
691 hint->base.type = HINT_TYPE_SET;
692 hint->base.state = HINT_STATE_NOTUSED;
693 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
694 hint->base.desc_func = (HintDescFunction) SetHintDesc;
695 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
696 hint->base.parse_func = (HintParseFunction) SetHintParse;
701 return (Hint *) hint;
705 SetHintDelete(SetHint *hint)
715 list_free(hint->words);
720 HintStateCreate(void)
724 hstate = palloc(sizeof(HintState));
725 hstate->hint_str = NULL;
726 hstate->nall_hints = 0;
727 hstate->max_all_hints = 0;
728 hstate->all_hints = NULL;
729 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
730 hstate->scan_hints = NULL;
731 hstate->init_scan_mask = 0;
732 hstate->parent_relid = 0;
733 hstate->parent_rel_oid = InvalidOid;
734 hstate->parent_hint = NULL;
735 hstate->parent_index_infos = NIL;
736 hstate->join_hints = NULL;
737 hstate->init_join_mask = 0;
738 hstate->join_hint_level = NULL;
739 hstate->leading_hint = NULL;
740 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
741 hstate->set_hints = NULL;
747 HintStateDelete(HintState *hstate)
754 if (hstate->hint_str)
755 pfree(hstate->hint_str);
757 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
758 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
759 if (hstate->all_hints)
760 pfree(hstate->all_hints);
761 if (hstate->parent_index_infos)
762 list_free(hstate->parent_index_infos);
766 * Copy given value into buf, with quoting with '"' if necessary.
769 quote_value(StringInfo buf, const char *value)
771 bool need_quote = false;
774 for (str = value; *str != '\0'; str++)
776 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
779 appendStringInfoCharMacro(buf, '"');
784 for (str = value; *str != '\0'; str++)
787 appendStringInfoCharMacro(buf, '"');
789 appendStringInfoCharMacro(buf, *str);
793 appendStringInfoCharMacro(buf, '"');
797 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
801 appendStringInfo(buf, "%s(", hint->base.keyword);
802 if (hint->relname != NULL)
804 quote_value(buf, hint->relname);
805 foreach(l, hint->indexnames)
807 appendStringInfoCharMacro(buf, ' ');
808 quote_value(buf, (char *) lfirst(l));
811 appendStringInfoString(buf, ")\n");
815 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
819 appendStringInfo(buf, "%s(", hint->base.keyword);
820 if (hint->relnames != NULL)
822 quote_value(buf, hint->relnames[0]);
823 for (i = 1; i < hint->nrels; i++)
825 appendStringInfoCharMacro(buf, ' ');
826 quote_value(buf, hint->relnames[i]);
829 appendStringInfoString(buf, ")\n");
834 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
836 if (outer_inner->relation == NULL)
843 appendStringInfoCharMacro(buf, '(');
844 foreach(l, outer_inner->outer_inner_pair)
849 appendStringInfoCharMacro(buf, ' ');
851 OuterInnerDesc(lfirst(l), buf);
854 appendStringInfoCharMacro(buf, ')');
857 quote_value(buf, outer_inner->relation);
861 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
863 appendStringInfo(buf, "%s(", HINT_LEADING);
864 if (hint->outer_inner == NULL)
871 foreach(l, hint->relations)
876 appendStringInfoCharMacro(buf, ' ');
878 quote_value(buf, (char *) lfirst(l));
882 OuterInnerDesc(hint->outer_inner, buf);
884 appendStringInfoString(buf, ")\n");
888 SetHintDesc(SetHint *hint, StringInfo buf)
890 bool is_first = true;
893 appendStringInfo(buf, "%s(", HINT_SET);
894 foreach(l, hint->words)
899 appendStringInfoCharMacro(buf, ' ');
901 quote_value(buf, (char *) lfirst(l));
903 appendStringInfo(buf, ")\n");
907 * Append string which repserents all hints in a given state to buf, with
908 * preceding title with them.
911 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
916 appendStringInfo(buf, "%s:\n", title);
917 for (i = 0; i < hstate->nall_hints; i++)
919 if (hstate->all_hints[i]->state != state)
922 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf);
927 * Dump contents of given hstate to server log with log level LOG.
930 HintStateDump(HintState *hstate)
936 elog(LOG, "pg_hint_plan:\nno hint");
940 initStringInfo(&buf);
942 appendStringInfoString(&buf, "pg_hint_plan:\n");
943 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
944 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
945 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
946 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
948 elog(LOG, "%s", buf.data);
958 RelnameCmp(const void *a, const void *b)
960 const char *relnamea = *((const char **) a);
961 const char *relnameb = *((const char **) b);
963 return strcmp(relnamea, relnameb);
967 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
969 return RelnameCmp(&a->relname, &b->relname);
973 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
977 if (a->nrels != b->nrels)
978 return a->nrels - b->nrels;
980 for (i = 0; i < a->nrels; i++)
983 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
991 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
997 SetHintCmp(const SetHint *a, const SetHint *b)
999 return strcmp(a->name, b->name);
1003 HintCmp(const void *a, const void *b)
1005 const Hint *hinta = *((const Hint **) a);
1006 const Hint *hintb = *((const Hint **) b);
1008 if (hinta->type != hintb->type)
1009 return hinta->type - hintb->type;
1010 if (hinta->state == HINT_STATE_ERROR)
1012 if (hintb->state == HINT_STATE_ERROR)
1014 return hinta->cmp_func(hinta, hintb);
1018 * Returns byte offset of hint b from hint a. If hint a was specified before
1019 * b, positive value is returned.
1022 HintCmpWithPos(const void *a, const void *b)
1024 const Hint *hinta = *((const Hint **) a);
1025 const Hint *hintb = *((const Hint **) b);
1028 result = HintCmp(a, b);
1030 result = hinta->hint_str - hintb->hint_str;
1039 parse_keyword(const char *str, StringInfo buf)
1043 while (!isspace(*str) && *str != '(' && *str != '\0')
1044 appendStringInfoCharMacro(buf, *str++);
1050 skip_parenthesis(const char *str, char parenthesis)
1054 if (*str != parenthesis)
1056 if (parenthesis == '(')
1057 hint_ereport(str, ("Opening parenthesis is necessary."));
1058 else if (parenthesis == ')')
1059 hint_ereport(str, ("Closing parenthesis is necessary."));
1070 * Parse a token from str, and store malloc'd copy into word. A token can be
1071 * quoted with '"'. Return value is pointer to unparsed portion of original
1072 * string, or NULL if an error occurred.
1074 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1077 parse_quoted_value(const char *str, char **word, bool truncate)
1082 /* Skip leading spaces. */
1085 initStringInfo(&buf);
1098 /* Double quotation must be closed. */
1102 hint_ereport(str, ("Unterminated quoted string."));
1107 * Skip escaped double quotation.
1109 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1110 * block comments) to be an object name, so users must specify
1111 * alias for such object names.
1113 * Those special names can be allowed if we care escaped slashes
1114 * and asterisks, but we don't.
1123 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1127 appendStringInfoCharMacro(&buf, *str++);
1132 hint_ereport(str, ("Zero-length delimited string."));
1139 /* Truncate name if it's too long */
1141 truncate_identifier(buf.data, strlen(buf.data), true);
1148 static OuterInnerRels *
1149 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1151 OuterInnerRels *outer_inner;
1153 outer_inner = palloc(sizeof(OuterInnerRels));
1154 outer_inner->relation = name;
1155 outer_inner->outer_inner_pair = outer_inner_list;
1161 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1163 List *outer_inner_pair = NIL;
1165 if ((str = skip_parenthesis(str, '(')) == NULL)
1170 /* Store words in parentheses into outer_inner_list. */
1171 while(*str != ')' && *str != '\0')
1173 OuterInnerRels *outer_inner_rels;
1177 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1185 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1188 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1191 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1196 (str = skip_parenthesis(str, ')')) == NULL)
1198 list_free(outer_inner_pair);
1202 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1208 parse_parentheses_Leading(const char *str, List **name_list,
1209 OuterInnerRels **outer_inner)
1212 bool truncate = true;
1214 if ((str = skip_parenthesis(str, '(')) == NULL)
1220 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1225 /* Store words in parentheses into name_list. */
1226 while(*str != ')' && *str != '\0')
1228 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1230 list_free(*name_list);
1234 *name_list = lappend(*name_list, name);
1239 if ((str = skip_parenthesis(str, ')')) == NULL)
1245 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1248 bool truncate = true;
1250 if ((str = skip_parenthesis(str, '(')) == NULL)
1255 /* Store words in parentheses into name_list. */
1256 while(*str != ')' && *str != '\0')
1258 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1260 list_free(*name_list);
1264 *name_list = lappend(*name_list, name);
1267 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1268 #if PG_VERSION_NUM >= 90200
1269 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1271 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1272 keyword == HINT_KEYWORD_SET)
1278 if ((str = skip_parenthesis(str, ')')) == NULL)
1284 parse_hints(HintState *hstate, Query *parse, const char *str)
1289 initStringInfo(&buf);
1290 while (*str != '\0')
1292 const HintParser *parser;
1294 /* in error message, we output the comment including the keyword. */
1295 head = (char *) str;
1297 /* parse only the keyword of the hint. */
1298 resetStringInfo(&buf);
1299 str = parse_keyword(str, &buf);
1301 for (parser = parsers; parser->keyword != NULL; parser++)
1303 char *keyword = parser->keyword;
1306 if (strcasecmp(buf.data, keyword) != 0)
1309 hint = parser->create_func(head, keyword, parser->hint_keyword);
1311 /* parser of each hint does parse in a parenthesis. */
1312 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1314 hint->delete_func(hint);
1320 * Add hint information into all_hints array. If we don't have
1321 * enough space, double the array.
1323 if (hstate->nall_hints == 0)
1325 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1326 hstate->all_hints = (Hint **)
1327 palloc(sizeof(Hint *) * hstate->max_all_hints);
1329 else if (hstate->nall_hints == hstate->max_all_hints)
1331 hstate->max_all_hints *= 2;
1332 hstate->all_hints = (Hint **)
1333 repalloc(hstate->all_hints,
1334 sizeof(Hint *) * hstate->max_all_hints);
1337 hstate->all_hints[hstate->nall_hints] = hint;
1338 hstate->nall_hints++;
1345 if (parser->keyword == NULL)
1348 ("Unrecognized hint keyword \"%s\".", buf.data));
1358 * Do basic parsing of the query head comment.
1361 parse_head_comment(Query *parse)
1364 const char *hint_head;
1371 /* get client-supplied query string. */
1374 PreparedStatement *entry;
1376 entry = FetchPreparedStatement(stmt_name, true);
1377 p = entry->plansource->query_string;
1379 else if (hint_query_string)
1380 p = hint_query_string;
1382 p = debug_query_string;
1387 /* extract query head comment. */
1388 hint_head = strstr(p, HINT_START);
1389 if (hint_head == NULL)
1391 for (;p < hint_head; p++)
1394 * Allow these characters precedes hint comment:
1396 * - alphabets which are in ASCII range
1397 * - space, tabs and new-lines
1398 * - underscores, for identifier
1399 * - commas, for SELECT clause, EXPLAIN and PREPARE
1400 * - parentheses, for EXPLAIN and PREPARE
1402 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1403 * avoid behavior which depends on locale setting.
1405 if (!(*p >= '0' && *p <= '9') &&
1406 !(*p >= 'A' && *p <= 'Z') &&
1407 !(*p >= 'a' && *p <= 'z') &&
1411 *p != '(' && *p != ')')
1415 len = strlen(HINT_START);
1420 /* find hint end keyword. */
1421 if ((tail = strstr(p, HINT_END)) == NULL)
1423 hint_ereport(head, ("Unterminated block comment."));
1427 /* We don't support nested block comments. */
1428 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1430 hint_ereport(head, ("Nested block comments are not supported."));
1434 /* Make a copy of hint. */
1436 head = palloc(len + 1);
1437 memcpy(head, p, len);
1441 hstate = HintStateCreate();
1442 hstate->hint_str = head;
1444 /* parse each hint. */
1445 parse_hints(hstate, parse, p);
1447 /* When nothing specified a hint, we free HintState and returns NULL. */
1448 if (hstate->nall_hints == 0)
1450 HintStateDelete(hstate);
1454 /* Sort hints in order of original position. */
1455 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1458 /* Count number of hints per hint-type. */
1459 for (i = 0; i < hstate->nall_hints; i++)
1461 Hint *cur_hint = hstate->all_hints[i];
1462 hstate->num_hints[cur_hint->type]++;
1466 * If an object (or a set of objects) has multiple hints of same hint-type,
1467 * only the last hint is valid and others are igonred in planning.
1468 * Hints except the last are marked as 'duplicated' to remember the order.
1470 for (i = 0; i < hstate->nall_hints - 1; i++)
1472 Hint *cur_hint = hstate->all_hints[i];
1473 Hint *next_hint = hstate->all_hints[i + 1];
1476 * Leading hint is marked as 'duplicated' in transform_join_hints.
1478 if (cur_hint->type == HINT_TYPE_LEADING &&
1479 next_hint->type == HINT_TYPE_LEADING)
1483 * Note that we need to pass addresses of hint pointers, because
1484 * HintCmp is designed to sort array of Hint* by qsort.
1486 if (HintCmp(&cur_hint, &next_hint) == 0)
1488 hint_ereport(cur_hint->hint_str,
1489 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1490 cur_hint->state = HINT_STATE_DUPLICATION;
1495 * Make sure that per-type array pointers point proper position in the
1496 * array which consists of all hints.
1498 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1499 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1500 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1501 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1502 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1503 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1504 hstate->num_hints[HINT_TYPE_LEADING]);
1510 * Parse inside of parentheses of scan-method hints.
1513 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1516 const char *keyword = hint->base.keyword;
1517 HintKeyword hint_keyword = hint->base.hint_keyword;
1518 List *name_list = NIL;
1521 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1524 /* Parse relation name and index name(s) if given hint accepts. */
1525 length = list_length(name_list);
1528 hint->relname = linitial(name_list);
1529 hint->indexnames = list_delete_first(name_list);
1531 /* check whether the hint accepts index name(s). */
1533 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1534 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1535 #if PG_VERSION_NUM >= 90200
1536 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1537 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1539 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1540 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1543 ("%s hint accepts only one relation.",
1544 hint->base.keyword));
1545 hint->base.state = HINT_STATE_ERROR;
1552 ("%s hint requires a relation.",
1553 hint->base.keyword));
1554 hint->base.state = HINT_STATE_ERROR;
1558 /* Set a bit for specified hint. */
1559 switch (hint_keyword)
1561 case HINT_KEYWORD_SEQSCAN:
1562 hint->enforce_mask = ENABLE_SEQSCAN;
1564 case HINT_KEYWORD_INDEXSCAN:
1565 hint->enforce_mask = ENABLE_INDEXSCAN;
1567 case HINT_KEYWORD_INDEXSCANREGEXP:
1568 hint->enforce_mask = ENABLE_INDEXSCAN;
1569 hint->regexp = true;
1571 case HINT_KEYWORD_BITMAPSCAN:
1572 hint->enforce_mask = ENABLE_BITMAPSCAN;
1574 case HINT_KEYWORD_BITMAPSCANREGEXP:
1575 hint->enforce_mask = ENABLE_BITMAPSCAN;
1576 hint->regexp = true;
1578 case HINT_KEYWORD_TIDSCAN:
1579 hint->enforce_mask = ENABLE_TIDSCAN;
1581 case HINT_KEYWORD_NOSEQSCAN:
1582 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1584 case HINT_KEYWORD_NOINDEXSCAN:
1585 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1587 case HINT_KEYWORD_NOBITMAPSCAN:
1588 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1590 case HINT_KEYWORD_NOTIDSCAN:
1591 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1593 #if PG_VERSION_NUM >= 90200
1594 case HINT_KEYWORD_INDEXONLYSCAN:
1595 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1597 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1598 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1599 hint->regexp = true;
1601 case HINT_KEYWORD_NOINDEXONLYSCAN:
1602 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1606 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1615 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1618 const char *keyword = hint->base.keyword;
1619 HintKeyword hint_keyword = hint->base.hint_keyword;
1620 List *name_list = NIL;
1622 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1625 hint->nrels = list_length(name_list);
1627 if (hint->nrels > 0)
1633 * Transform relation names from list to array to sort them with qsort
1636 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1637 foreach (l, name_list)
1639 hint->relnames[i] = lfirst(l);
1644 list_free(name_list);
1646 /* A join hint requires at least two relations */
1647 if (hint->nrels < 2)
1650 ("%s hint requires at least two relations.",
1651 hint->base.keyword));
1652 hint->base.state = HINT_STATE_ERROR;
1656 /* Sort hints in alphabetical order of relation names. */
1657 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1659 switch (hint_keyword)
1661 case HINT_KEYWORD_NESTLOOP:
1662 hint->enforce_mask = ENABLE_NESTLOOP;
1664 case HINT_KEYWORD_MERGEJOIN:
1665 hint->enforce_mask = ENABLE_MERGEJOIN;
1667 case HINT_KEYWORD_HASHJOIN:
1668 hint->enforce_mask = ENABLE_HASHJOIN;
1670 case HINT_KEYWORD_NONESTLOOP:
1671 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1673 case HINT_KEYWORD_NOMERGEJOIN:
1674 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1676 case HINT_KEYWORD_NOHASHJOIN:
1677 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1680 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1689 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1692 if (outer_inner->outer_inner_pair == NIL)
1694 if (outer_inner->relation)
1700 if (list_length(outer_inner->outer_inner_pair) == 2)
1702 foreach(l, outer_inner->outer_inner_pair)
1704 if (!OuterInnerPairCheck(lfirst(l)))
1715 OuterInnerList(OuterInnerRels *outer_inner)
1717 List *outer_inner_list = NIL;
1719 OuterInnerRels *outer_inner_rels;
1721 foreach(l, outer_inner->outer_inner_pair)
1723 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
1725 if (outer_inner_rels->relation != NULL)
1726 outer_inner_list = lappend(outer_inner_list,
1727 outer_inner_rels->relation);
1729 outer_inner_list = list_concat(outer_inner_list,
1730 OuterInnerList(outer_inner_rels));
1732 return outer_inner_list;
1736 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1739 List *name_list = NIL;
1740 OuterInnerRels *outer_inner = NULL;
1742 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
1746 if (outer_inner != NULL)
1747 name_list = OuterInnerList(outer_inner);
1749 hint->relations = name_list;
1750 hint->outer_inner = outer_inner;
1752 /* A Leading hint requires at least two relations */
1753 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
1755 hint_ereport(hint->base.hint_str,
1756 ("%s hint requires at least two relations.",
1758 hint->base.state = HINT_STATE_ERROR;
1760 else if (hint->outer_inner != NULL &&
1761 !OuterInnerPairCheck(hint->outer_inner))
1763 hint_ereport(hint->base.hint_str,
1764 ("%s hint requires two sets of relations when parentheses nests.",
1766 hint->base.state = HINT_STATE_ERROR;
1773 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1775 List *name_list = NIL;
1777 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
1781 hint->words = name_list;
1783 /* We need both name and value to set GUC parameter. */
1784 if (list_length(name_list) == 2)
1786 hint->name = linitial(name_list);
1787 hint->value = lsecond(name_list);
1791 hint_ereport(hint->base.hint_str,
1792 ("%s hint requires name and value of GUC parameter.",
1794 hint->base.state = HINT_STATE_ERROR;
1801 * set GUC parameter functions
1805 set_config_option_wrapper(const char *name, const char *value,
1806 GucContext context, GucSource source,
1807 GucAction action, bool changeVal, int elevel)
1810 MemoryContext ccxt = CurrentMemoryContext;
1814 #if PG_VERSION_NUM >= 90200
1815 result = set_config_option(name, value, context, source,
1816 action, changeVal, 0);
1818 result = set_config_option(name, value, context, source,
1826 /* Save error info */
1827 MemoryContextSwitchTo(ccxt);
1828 errdata = CopyErrorData();
1831 ereport(elevel, (errcode(errdata->sqlerrcode),
1832 errmsg("%s", errdata->message),
1833 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1834 errdata->hint ? errhint("%s", errdata->hint) : 0));
1835 FreeErrorData(errdata);
1843 set_config_options(SetHint **options, int noptions, GucContext context)
1848 save_nestlevel = NewGUCNestLevel();
1850 for (i = 0; i < noptions; i++)
1852 SetHint *hint = options[i];
1855 if (!hint_state_enabled(hint))
1858 result = set_config_option_wrapper(hint->name, hint->value, context,
1859 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1860 pg_hint_plan_parse_messages);
1862 hint->base.state = HINT_STATE_USED;
1864 hint->base.state = HINT_STATE_ERROR;
1867 return save_nestlevel;
1870 #define SET_CONFIG_OPTION(name, type_bits) \
1871 set_config_option_wrapper((name), \
1872 (mask & (type_bits)) ? "true" : "false", \
1873 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1876 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1880 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1881 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1882 #if PG_VERSION_NUM >= 90200
1883 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1886 mask = enforce_mask;
1888 mask = enforce_mask & current_hint->init_scan_mask;
1890 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1891 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1892 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1893 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1894 #if PG_VERSION_NUM >= 90200
1895 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1900 set_join_config_options(unsigned char enforce_mask, GucContext context)
1904 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1905 enforce_mask == ENABLE_HASHJOIN)
1906 mask = enforce_mask;
1908 mask = enforce_mask & current_hint->init_join_mask;
1910 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1911 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1912 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1916 * pg_hint_plan hook functions
1920 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1921 ParamListInfo params, bool isTopLevel,
1922 DestReceiver *dest, char *completionTag)
1926 if (!pg_hint_plan_enable_hint)
1928 if (prev_ProcessUtility)
1929 (*prev_ProcessUtility) (parsetree, queryString, params,
1930 isTopLevel, dest, completionTag);
1932 standard_ProcessUtility(parsetree, queryString, params,
1933 isTopLevel, dest, completionTag);
1939 if (IsA(node, ExplainStmt))
1942 * Draw out parse tree of actual query from Query struct of EXPLAIN
1948 stmt = (ExplainStmt *) node;
1950 Assert(IsA(stmt->query, Query));
1951 query = (Query *) stmt->query;
1953 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1954 node = query->utilityStmt;
1958 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
1959 * specified to preceding PREPARE command to use it as source of hints.
1961 if (IsA(node, ExecuteStmt))
1965 stmt = (ExecuteStmt *) node;
1966 stmt_name = stmt->name;
1968 #if PG_VERSION_NUM >= 90200
1970 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
1973 if (IsA(node, CreateTableAsStmt))
1975 CreateTableAsStmt *stmt;
1978 stmt = (CreateTableAsStmt *) node;
1979 Assert(IsA(stmt->query, Query));
1980 query = (Query *) stmt->query;
1982 if (query->commandType == CMD_UTILITY &&
1983 IsA(query->utilityStmt, ExecuteStmt))
1985 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
1986 stmt_name = estmt->name;
1994 if (prev_ProcessUtility)
1995 (*prev_ProcessUtility) (parsetree, queryString, params,
1996 isTopLevel, dest, completionTag);
1998 standard_ProcessUtility(parsetree, queryString, params,
1999 isTopLevel, dest, completionTag);
2013 if (prev_ProcessUtility)
2014 (*prev_ProcessUtility) (parsetree, queryString, params,
2015 isTopLevel, dest, completionTag);
2017 standard_ProcessUtility(parsetree, queryString, params,
2018 isTopLevel, dest, completionTag);
2022 * Push a hint into hint stack which is implemented with List struct. Head of
2023 * list is top of stack.
2026 push_hint(HintState *hstate)
2028 /* Prepend new hint to the list means pushing to stack. */
2029 HintStateStack = lcons(hstate, HintStateStack);
2031 /* Pushed hint is the one which should be used hereafter. */
2032 current_hint = hstate;
2035 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2039 /* Hint stack must not be empty. */
2040 if(HintStateStack == NIL)
2041 elog(ERROR, "hint stack is empty");
2044 * Take a hint at the head from the list, and free it. Switch current_hint
2045 * to point new head (NULL if the list is empty).
2047 HintStateStack = list_delete_first(HintStateStack);
2048 HintStateDelete(current_hint);
2049 if(HintStateStack == NIL)
2050 current_hint = NULL;
2052 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2055 static PlannedStmt *
2056 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2059 PlannedStmt *result;
2063 * Use standard planner if pg_hint_plan is disabled. Other hook functions
2064 * try to change plan with current_hint if any, so set it to NULL.
2066 if (!pg_hint_plan_enable_hint)
2068 current_hint = NULL;
2071 return (*prev_planner) (parse, cursorOptions, boundParams);
2073 return standard_planner(parse, cursorOptions, boundParams);
2076 /* Create hint struct from parse tree. */
2077 hstate = parse_head_comment(parse);
2080 * Use standard planner if the statement has not valid hint. Other hook
2081 * functions try to change plan with current_hint if any, so set it to
2086 current_hint = NULL;
2089 return (*prev_planner) (parse, cursorOptions, boundParams);
2091 return standard_planner(parse, cursorOptions, boundParams);
2095 * Push new hint struct to the hint stack to disable previous hint context.
2099 /* Set GUC parameters which are specified with Set hint. */
2100 save_nestlevel = set_config_options(current_hint->set_hints,
2101 current_hint->num_hints[HINT_TYPE_SET],
2102 current_hint->context);
2105 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2106 if (enable_indexscan)
2107 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2108 if (enable_bitmapscan)
2109 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2111 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2112 #if PG_VERSION_NUM >= 90200
2113 if (enable_indexonlyscan)
2114 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2116 if (enable_nestloop)
2117 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2118 if (enable_mergejoin)
2119 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2120 if (enable_hashjoin)
2121 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2124 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2125 * state when this planner started when error occurred in planner.
2130 result = (*prev_planner) (parse, cursorOptions, boundParams);
2132 result = standard_planner(parse, cursorOptions, boundParams);
2137 * Rollback changes of GUC parameters, and pop current hint context
2138 * from hint stack to rewind the state.
2140 AtEOXact_GUC(true, save_nestlevel);
2146 /* Print hint in debug mode. */
2147 if (pg_hint_plan_debug_print)
2148 HintStateDump(current_hint);
2151 * Rollback changes of GUC parameters, and pop current hint context from
2152 * hint stack to rewind the state.
2154 AtEOXact_GUC(true, save_nestlevel);
2161 * Return scan method hint which matches given aliasname.
2163 static ScanMethodHint *
2164 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2170 * We can't apply scan method hint if the relation is:
2171 * - not a base relation
2172 * - not an ordinary relation (such as join and subquery)
2174 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2177 rte = root->simple_rte_array[rel->relid];
2179 /* We can't force scan method of foreign tables */
2180 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2183 /* Find scan method hint, which matches given names, from the list. */
2184 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2186 ScanMethodHint *hint = current_hint->scan_hints[i];
2188 /* We ignore disabled hints. */
2189 if (!hint_state_enabled(hint))
2192 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2202 * Returns TRUE on match, FALSE on no match.
2204 * s1 --- the data to match against
2205 * s2 --- the pattern
2207 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2210 regexpeq(const char *s1, const char *s2)
2216 strcpy(name.data, s1);
2217 regexp = cstring_to_text(s2);
2219 result = DirectFunctionCall2Coll(nameregexeq,
2220 DEFAULT_COLLATION_OID,
2221 NameGetDatum(&name),
2222 PointerGetDatum(regexp));
2223 return DatumGetBool(result);
2227 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2235 * We delete all the IndexOptInfo list and prevent you from being usable by
2238 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2239 hint->enforce_mask == ENABLE_TIDSCAN)
2241 list_free_deep(rel->indexlist);
2242 rel->indexlist = NIL;
2243 hint->base.state = HINT_STATE_USED;
2249 * When a list of indexes is not specified, we just use all indexes.
2251 if (hint->indexnames == NIL)
2255 * Leaving only an specified index, we delete it from a IndexOptInfo list
2259 if (pg_hint_plan_debug_print)
2260 initStringInfo(&buf);
2262 for (cell = list_head(rel->indexlist); cell; cell = next)
2264 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2265 char *indexname = get_rel_name(info->indexoid);
2267 bool use_index = false;
2271 foreach(l, hint->indexnames)
2273 char *hintname = (char *) lfirst(l);
2277 result = regexpeq(indexname, hintname);
2279 result = RelnameCmp(&indexname, &hintname) == 0;
2284 if (pg_hint_plan_debug_print)
2286 appendStringInfoCharMacro(&buf, ' ');
2287 quote_value(&buf, indexname);
2295 * to make the index a candidate when definition of this index is
2296 * matched with the index's definition of current_hint.
2298 if (OidIsValid(relationObjectId) && !use_index)
2300 foreach(l, current_hint->parent_index_infos)
2304 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2306 /* check to match the parameter of unique */
2307 if (p_info->indisunique != info->unique)
2310 /* check to match the parameter of index's method */
2311 if (p_info->method != info->relam)
2314 /* to check to match the indexkey's configuration */
2315 if ((list_length(p_info->column_names)) !=
2319 /* check to match the indexkey's configuration */
2320 for (i = 0; i < info->ncolumns; i++)
2322 char *c_attname = NULL;
2323 char *p_attname = NULL;
2326 list_nth(p_info->column_names, i);
2328 /* both are expressions */
2329 if (info->indexkeys[i] == 0 && !p_attname)
2332 /* one's column is expression, the other is not */
2333 if (info->indexkeys[i] == 0 || !p_attname)
2336 c_attname = get_attname(relationObjectId,
2337 info->indexkeys[i]);
2339 if (strcmp(p_attname, c_attname) != 0)
2342 if (p_info->indcollation[i] != info->indexcollations[i])
2345 if (p_info->opclass[i] != info->opcintype[i])
2348 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2349 info->reverse_sort[i])
2352 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2353 info->nulls_first[i])
2358 if (i != info->ncolumns)
2361 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2362 (p_info->indpred_str && (info->indpred != NIL)))
2365 * Fetch the pg_index tuple by the Oid of the index
2367 ht_idx = SearchSysCache1(INDEXRELID,
2368 ObjectIdGetDatum(info->indexoid));
2370 /* check to match the expression's parameter of index */
2371 if (p_info->expression_str &&
2372 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2379 * to change the expression's parameter of child's
2382 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2383 Anum_pg_index_indexprs,
2386 result = DirectFunctionCall2(pg_get_expr,
2391 if (strcmp(p_info->expression_str,
2392 text_to_cstring(DatumGetTextP(result))) != 0)
2395 ReleaseSysCache(ht_idx);
2401 /* Check to match the predicate's paraameter of index */
2402 if (p_info->indpred_str &&
2403 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2410 * to change the predicate's parabeter of child's
2413 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2414 Anum_pg_index_indpred,
2417 result = DirectFunctionCall2(pg_get_expr,
2422 if (strcmp(p_info->indpred_str,
2423 text_to_cstring(DatumGetTextP(result))) != 0)
2426 ReleaseSysCache(ht_idx);
2433 ReleaseSysCache(ht_idx);
2435 else if (p_info->expression_str || (info->indexprs != NIL))
2437 else if (p_info->indpred_str || (info->indpred != NIL))
2442 /* to log the candidate of index */
2443 if (pg_hint_plan_debug_print)
2445 appendStringInfoCharMacro(&buf, ' ');
2446 quote_value(&buf, indexname);
2454 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2461 if (pg_hint_plan_debug_print)
2464 StringInfoData rel_buf;
2466 if (OidIsValid(relationObjectId))
2467 relname = get_rel_name(relationObjectId);
2469 relname = hint->relname;
2471 initStringInfo(&rel_buf);
2472 quote_value(&rel_buf, relname);
2475 (errmsg("available indexes for %s(%s):%s",
2480 pfree(rel_buf.data);
2485 * Return information of index definition.
2487 static ParentIndexInfo *
2488 get_parent_index_info(Oid indexoid, Oid relid)
2490 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
2491 Relation indexRelation;
2492 Form_pg_index index;
2496 indexRelation = index_open(indexoid, RowExclusiveLock);
2498 index = indexRelation->rd_index;
2500 p_info->indisunique = index->indisunique;
2501 p_info->method = indexRelation->rd_rel->relam;
2503 p_info->column_names = NIL;
2504 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2505 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2506 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
2508 for (i = 0; i < index->indnatts; i++)
2510 attname = get_attname(relid, index->indkey.values[i]);
2511 p_info->column_names = lappend(p_info->column_names, attname);
2513 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
2514 p_info->opclass[i] = indexRelation->rd_opcintype[i];
2515 p_info->indoption[i] = indexRelation->rd_indoption[i];
2519 * to check to match the expression's paraameter of index with child indexes
2521 p_info->expression_str = NULL;
2522 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
2528 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2529 Anum_pg_index_indexprs, &isnull);
2531 result = DirectFunctionCall2(pg_get_expr,
2533 ObjectIdGetDatum(relid));
2535 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
2539 * to check to match the predicate's paraameter of index with child indexes
2541 p_info->indpred_str = NULL;
2542 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
2548 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2549 Anum_pg_index_indpred, &isnull);
2551 result = DirectFunctionCall2(pg_get_expr,
2553 ObjectIdGetDatum(relid));
2555 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
2558 index_close(indexRelation, NoLock);
2564 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2565 bool inhparent, RelOptInfo *rel)
2567 ScanMethodHint *hint;
2569 if (prev_get_relation_info)
2570 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2572 /* Do nothing if we don't have valid hint in this context. */
2578 /* store does relids of parent table. */
2579 current_hint->parent_relid = rel->relid;
2580 current_hint->parent_rel_oid = relationObjectId;
2582 else if (current_hint->parent_relid != 0)
2585 * We use the same GUC parameter if this table is the child table of a
2586 * table called pg_hint_plan_get_relation_info just before that.
2590 /* append_rel_list contains all append rels; ignore others */
2591 foreach(l, root->append_rel_list)
2593 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2595 /* This rel is child table. */
2596 if (appinfo->parent_relid == current_hint->parent_relid &&
2597 appinfo->child_relid == rel->relid)
2599 if (current_hint->parent_hint)
2600 delete_indexes(current_hint->parent_hint, rel,
2607 /* This rel is not inherit table. */
2608 current_hint->parent_relid = 0;
2609 current_hint->parent_rel_oid = InvalidOid;
2610 current_hint->parent_hint = NULL;
2614 * If scan method hint was given, reset GUC parameters which control
2615 * planner behavior about choosing scan methods.
2617 if ((hint = find_scan_hint(root, rel)) == NULL)
2619 set_scan_config_options(current_hint->init_scan_mask,
2620 current_hint->context);
2623 set_scan_config_options(hint->enforce_mask, current_hint->context);
2624 hint->base.state = HINT_STATE_USED;
2632 current_hint->parent_hint = hint;
2634 relation = heap_open(relationObjectId, NoLock);
2635 indexoidlist = RelationGetIndexList(relation);
2637 foreach(l, indexoidlist)
2639 Oid indexoid = lfirst_oid(l);
2640 char *indexname = get_rel_name(indexoid);
2641 bool use_index = false;
2643 ParentIndexInfo *parent_index_info;
2645 foreach(lc, hint->indexnames)
2647 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
2656 parent_index_info = get_parent_index_info(indexoid,
2658 current_hint->parent_index_infos =
2659 lappend(current_hint->parent_index_infos, parent_index_info);
2661 heap_close(relation, NoLock);
2664 delete_indexes(hint, rel, InvalidOid);
2668 * Return index of relation which matches given aliasname, or 0 if not found.
2669 * If same aliasname was used multiple times in a query, return -1.
2672 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
2678 for (i = 1; i < root->simple_rel_array_size; i++)
2682 if (root->simple_rel_array[i] == NULL)
2685 Assert(i == root->simple_rel_array[i]->relid);
2687 if (RelnameCmp(&aliasname,
2688 &root->simple_rte_array[i]->eref->aliasname) != 0)
2691 foreach(l, initial_rels)
2693 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2695 if (rel->reloptkind == RELOPT_BASEREL)
2697 if (rel->relid != i)
2702 Assert(rel->reloptkind == RELOPT_JOINREL);
2704 if (!bms_is_member(i, rel->relids))
2711 ("Relation name \"%s\" is ambiguous.",
2726 * Return join hint which matches given joinrelids.
2728 static JoinMethodHint *
2729 find_join_hint(Relids joinrelids)
2734 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
2736 foreach(l, join_hint)
2738 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
2740 if (bms_equal(joinrelids, hint->joinrelids))
2748 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
2749 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
2751 OuterInnerRels *outer_rels;
2752 OuterInnerRels *inner_rels;
2753 Relids outer_relids;
2754 Relids inner_relids;
2756 JoinMethodHint *hint;
2758 if (outer_inner->relation != NULL)
2760 return bms_make_singleton(
2761 find_relid_aliasname(root, outer_inner->relation,
2763 leading_hint->base.hint_str));
2766 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
2767 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
2769 outer_relids = OuterInnerJoinCreate(outer_rels,
2775 inner_relids = OuterInnerJoinCreate(inner_rels,
2782 join_relids = bms_add_members(outer_relids, inner_relids);
2784 if (bms_num_members(join_relids) > nbaserel)
2788 * If we don't have join method hint, create new one for the
2789 * join combination with all join methods are enabled.
2791 hint = find_join_hint(join_relids);
2795 * Here relnames is not set, since Relids bitmap is sufficient to
2796 * control paths of this query afterward.
2798 hint = (JoinMethodHint *) JoinMethodHintCreate(
2799 leading_hint->base.hint_str,
2801 HINT_KEYWORD_LEADING);
2802 hint->base.state = HINT_STATE_USED;
2803 hint->nrels = bms_num_members(join_relids);
2804 hint->enforce_mask = ENABLE_ALL_JOIN;
2805 hint->joinrelids = bms_copy(join_relids);
2806 hint->inner_nrels = bms_num_members(inner_relids);
2807 hint->inner_joinrelids = bms_copy(inner_relids);
2809 hstate->join_hint_level[hint->nrels] =
2810 lappend(hstate->join_hint_level[hint->nrels], hint);
2814 hint->inner_nrels = bms_num_members(inner_relids);
2815 hint->inner_joinrelids = bms_copy(inner_relids);
2822 * Transform join method hint into handy form.
2824 * - create bitmap of relids from alias names, to make it easier to check
2825 * whether a join path matches a join method hint.
2826 * - add join method hints which are necessary to enforce join order
2827 * specified by Leading hint
2830 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2831 List *initial_rels, JoinMethodHint **join_method_hints)
2839 LeadingHint *lhint = NULL;
2842 * Create bitmap of relids from alias names for each join method hint.
2843 * Bitmaps are more handy than strings in join searching.
2845 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2847 JoinMethodHint *hint = hstate->join_hints[i];
2850 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
2853 bms_free(hint->joinrelids);
2854 hint->joinrelids = NULL;
2856 for (j = 0; j < hint->nrels; j++)
2858 relname = hint->relnames[j];
2860 relid = find_relid_aliasname(root, relname, initial_rels,
2861 hint->base.hint_str);
2864 hint->base.state = HINT_STATE_ERROR;
2869 if (bms_is_member(relid, hint->joinrelids))
2871 hint_ereport(hint->base.hint_str,
2872 ("Relation name \"%s\" is duplicated.", relname));
2873 hint->base.state = HINT_STATE_ERROR;
2877 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
2880 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
2883 hstate->join_hint_level[hint->nrels] =
2884 lappend(hstate->join_hint_level[hint->nrels], hint);
2887 /* Do nothing if no Leading hint was supplied. */
2888 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2892 * Decide to use Leading hint。
2894 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
2896 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
2899 if (leading_hint->base.state == HINT_STATE_ERROR)
2905 foreach(l, leading_hint->relations)
2907 relname = (char *)lfirst(l);;
2909 relid = find_relid_aliasname(root, relname, initial_rels,
2910 leading_hint->base.hint_str);
2912 leading_hint->base.state = HINT_STATE_ERROR;
2917 if (bms_is_member(relid, relids))
2919 hint_ereport(leading_hint->base.hint_str,
2920 ("Relation name \"%s\" is duplicated.", relname));
2921 leading_hint->base.state = HINT_STATE_ERROR;
2925 relids = bms_add_member(relids, relid);
2928 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
2933 hint_ereport(lhint->base.hint_str,
2934 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
2935 lhint->base.state = HINT_STATE_DUPLICATION;
2937 leading_hint->base.state = HINT_STATE_USED;
2938 lhint = leading_hint;
2941 /* check to exist Leading hint marked with 'used'. */
2946 * We need join method hints which fit specified join order in every join
2947 * level. For example, Leading(A B C) virtually requires following join
2948 * method hints, if no join method hint supplied:
2950 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
2951 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
2953 * If we already have join method hint which fits specified join order in
2954 * that join level, we leave it as-is and don't add new hints.
2958 if (lhint->outer_inner == NULL)
2960 foreach(l, lhint->relations)
2962 JoinMethodHint *hint;
2964 relname = (char *)lfirst(l);
2967 * Find relid of the relation which has given name. If we have the
2968 * name given in Leading hint multiple times in the join, nothing to
2971 relid = find_relid_aliasname(root, relname, initial_rels,
2974 /* Create bitmap of relids for current join level. */
2975 joinrelids = bms_add_member(joinrelids, relid);
2978 /* We never have join method hint for single relation. */
2983 * If we don't have join method hint, create new one for the
2984 * join combination with all join methods are enabled.
2986 hint = find_join_hint(joinrelids);
2990 * Here relnames is not set, since Relids bitmap is sufficient
2991 * to control paths of this query afterward.
2993 hint = (JoinMethodHint *) JoinMethodHintCreate(
2994 lhint->base.hint_str,
2996 HINT_KEYWORD_LEADING);
2997 hint->base.state = HINT_STATE_USED;
2998 hint->nrels = njoinrels;
2999 hint->enforce_mask = ENABLE_ALL_JOIN;
3000 hint->joinrelids = bms_copy(joinrelids);
3003 join_method_hints[njoinrels] = hint;
3005 if (njoinrels >= nbaserel)
3008 bms_free(joinrelids);
3014 * Delete all join hints which have different combination from Leading
3017 for (i = 2; i <= njoinrels; i++)
3019 list_free(hstate->join_hint_level[i]);
3021 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3026 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3033 njoinrels = bms_num_members(joinrelids);
3034 Assert(njoinrels >= 2);
3037 * Delete all join hints which have different combination from Leading
3040 for (i = 2;i <= njoinrels; i++)
3042 if (hstate->join_hint_level[i] != NIL)
3044 ListCell *prev = NULL;
3045 ListCell *next = NULL;
3046 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3049 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3053 if (hint->inner_nrels == 0 &&
3054 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3055 bms_equal(bms_union(hint->joinrelids, joinrelids),
3058 hstate->join_hint_level[i] =
3059 list_delete_cell(hstate->join_hint_level[i], l,
3068 bms_free(joinrelids);
3071 if (hint_state_enabled(lhint))
3073 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3080 * set_plain_rel_pathlist
3081 * Build access paths for a plain relation (no subquery, no inheritance)
3083 * This function was copied and edited from set_plain_rel_pathlist() in
3084 * src/backend/optimizer/path/allpaths.c
3087 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3089 /* Consider sequential scan */
3090 #if PG_VERSION_NUM >= 90200
3091 add_path(rel, create_seqscan_path(root, rel, NULL));
3093 add_path(rel, create_seqscan_path(root, rel));
3096 /* Consider index scans */
3097 create_index_paths(root, rel);
3099 /* Consider TID scans */
3100 create_tidscan_paths(root, rel);
3102 /* Now find the cheapest of the paths for this rel */
3107 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3112 foreach(l, initial_rels)
3114 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3116 ScanMethodHint *hint;
3118 /* Skip relations which we can't choose scan method. */
3119 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3122 rte = root->simple_rte_array[rel->relid];
3124 /* We can't force scan method of foreign tables */
3125 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3129 * Create scan paths with GUC parameters which are at the beginning of
3130 * planner if scan method hint is not specified, otherwise use
3131 * specified hints and mark the hint as used.
3133 if ((hint = find_scan_hint(root, rel)) == NULL)
3134 set_scan_config_options(hstate->init_scan_mask,
3138 set_scan_config_options(hint->enforce_mask, hstate->context);
3139 hint->base.state = HINT_STATE_USED;
3142 list_free_deep(rel->pathlist);
3143 rel->pathlist = NIL;
3146 /* It's an "append relation", process accordingly */
3147 set_append_rel_pathlist(root, rel, rel->relid, rte);
3151 set_plain_rel_pathlist(root, rel, rte);
3156 * Restore the GUC variables we set above.
3158 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3162 * wrapper of make_join_rel()
3164 * call make_join_rel() after changing enable_* parameters according to given
3168 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3171 JoinMethodHint *hint;
3175 joinrelids = bms_union(rel1->relids, rel2->relids);
3176 hint = find_join_hint(joinrelids);
3177 bms_free(joinrelids);
3180 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3182 if (hint->inner_nrels == 0)
3184 save_nestlevel = NewGUCNestLevel();
3186 set_join_config_options(hint->enforce_mask, current_hint->context);
3188 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3189 hint->base.state = HINT_STATE_USED;
3192 * Restore the GUC variables we set above.
3194 AtEOXact_GUC(true, save_nestlevel);
3197 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3206 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3207 RelOptInfo *joinrel,
3208 RelOptInfo *outerrel,
3209 RelOptInfo *innerrel,
3211 SpecialJoinInfo *sjinfo,
3214 ScanMethodHint *scan_hint = NULL;
3216 JoinMethodHint *join_hint;
3219 if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
3221 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3222 scan_hint->base.state = HINT_STATE_USED;
3225 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3226 join_hint = find_join_hint(joinrelids);
3227 bms_free(joinrelids);
3229 if (join_hint && join_hint->inner_nrels != 0)
3231 save_nestlevel = NewGUCNestLevel();
3233 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3236 set_join_config_options(join_hint->enforce_mask,
3237 current_hint->context);
3239 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3240 sjinfo, restrictlist);
3241 join_hint->base.state = HINT_STATE_USED;
3245 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3246 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3247 sjinfo, restrictlist);
3251 * Restore the GUC variables we set above.
3253 AtEOXact_GUC(true, save_nestlevel);
3256 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3257 sjinfo, restrictlist);
3259 if (scan_hint != NULL)
3260 set_scan_config_options(current_hint->init_scan_mask,
3261 current_hint->context);
3265 get_num_baserels(List *initial_rels)
3270 foreach(l, initial_rels)
3272 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3274 if (rel->reloptkind == RELOPT_BASEREL)
3276 else if (rel->reloptkind ==RELOPT_JOINREL)
3277 nbaserel+= bms_num_members(rel->relids);
3280 /* other values not expected here */
3281 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3289 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3292 JoinMethodHint **join_method_hints;
3296 bool leading_hint_enable;
3299 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3300 * valid hint is supplied.
3304 if (prev_join_search)
3305 return (*prev_join_search) (root, levels_needed, initial_rels);
3306 else if (enable_geqo && levels_needed >= geqo_threshold)
3307 return geqo(root, levels_needed, initial_rels);
3309 return standard_join_search(root, levels_needed, initial_rels);
3312 /* We apply scan method hint rebuild scan path. */
3313 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3316 * In the case using GEQO, only scan method hints and Set hints have
3317 * effect. Join method and join order is not controllable by hints.
3319 if (enable_geqo && levels_needed >= geqo_threshold)
3320 return geqo(root, levels_needed, initial_rels);
3322 nbaserel = get_num_baserels(initial_rels);
3323 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3324 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3326 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3327 initial_rels, join_method_hints);
3329 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3331 for (i = 2; i <= nbaserel; i++)
3333 list_free(current_hint->join_hint_level[i]);
3335 /* free Leading hint only */
3336 if (join_method_hints[i] != NULL &&
3337 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3338 JoinMethodHintDelete(join_method_hints[i]);
3340 pfree(current_hint->join_hint_level);
3341 pfree(join_method_hints);
3343 if (leading_hint_enable)
3344 set_join_config_options(current_hint->init_join_mask,
3345 current_hint->context);
3352 * Build access paths for a base relation
3354 * This function was copied and edited from set_rel_pathlist() in
3355 * src/backend/optimizer/path/allpaths.c
3358 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3359 Index rti, RangeTblEntry *rte)
3361 #if PG_VERSION_NUM >= 90200
3362 if (IS_DUMMY_REL(rel))
3364 /* We already proved the relation empty, so nothing more to do */
3371 /* It's an "append relation", process accordingly */
3372 set_append_rel_pathlist(root, rel, rti, rte);
3376 if (rel->rtekind == RTE_RELATION)
3378 if (rte->relkind == RELKIND_RELATION)
3380 /* Plain relation */
3381 set_plain_rel_pathlist(root, rel, rte);
3384 elog(ERROR, "unexpected relkind: %c", rte->relkind);
3387 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
3392 pg_hint_plan_plpgsql_func_setup(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3394 (*plugin_funcs)->stmt_beg = pg_hint_plan_plpgsql_stmt_beg;
3395 (*plugin_funcs)->stmt_end = pg_hint_plan_plpgsql_stmt_end;
3399 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3401 if ((enum PLpgSQL_stmt_types) stmt->cmd_type == PLPGSQL_STMT_EXECSQL)
3403 PLpgSQL_expr *expr = ((PLpgSQL_stmt_execsql *) stmt)->sqlstmt;
3404 hint_query_string = expr->query;
3409 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3411 if ((enum PLpgSQL_stmt_types) stmt->cmd_type == PLPGSQL_STMT_EXECSQL)
3412 hint_query_string = NULL;
3415 #define standard_join_search pg_hint_plan_standard_join_search
3416 #define join_search_one_level pg_hint_plan_join_search_one_level
3417 #define make_join_rel make_join_rel_wrapper
3420 #undef make_join_rel
3421 #define make_join_rel pg_hint_plan_make_join_rel
3422 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
3423 #include "make_join_rel.c"