1 /*-------------------------------------------------------------------------
4 * do instructions or hints to the planner using C-style block comments
7 * Copyright (c) 2012-2013, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
9 *-------------------------------------------------------------------------
12 #include "catalog/pg_collation.h"
13 #include "catalog/pg_index.h"
14 #include "commands/prepare.h"
15 #include "mb/pg_wchar.h"
16 #include "miscadmin.h"
17 #include "nodes/nodeFuncs.h"
18 #include "optimizer/clauses.h"
19 #include "optimizer/cost.h"
20 #include "optimizer/geqo.h"
21 #include "optimizer/joininfo.h"
22 #include "optimizer/pathnode.h"
23 #include "optimizer/paths.h"
24 #include "optimizer/plancat.h"
25 #include "optimizer/planner.h"
26 #include "optimizer/prep.h"
27 #include "optimizer/restrictinfo.h"
28 #include "parser/scansup.h"
29 #include "tcop/utility.h"
30 #include "utils/builtins.h"
31 #include "utils/lsyscache.h"
32 #include "utils/memutils.h"
33 #include "utils/rel.h"
34 #include "utils/syscache.h"
35 #if PG_VERSION_NUM >= 90200
36 #include "catalog/pg_class.h"
39 #ifdef PG_MODULE_MAGIC
43 #if PG_VERSION_NUM < 90100
44 #error unsupported PostgreSQL version
47 #define BLOCK_COMMENT_START "/*"
48 #define BLOCK_COMMENT_END "*/"
49 #define HINT_COMMENT_KEYWORD "+"
50 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
51 #define HINT_END BLOCK_COMMENT_END
54 #define HINT_SEQSCAN "SeqScan"
55 #define HINT_INDEXSCAN "IndexScan"
56 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
57 #define HINT_BITMAPSCAN "BitmapScan"
58 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
59 #define HINT_TIDSCAN "TidScan"
60 #define HINT_NOSEQSCAN "NoSeqScan"
61 #define HINT_NOINDEXSCAN "NoIndexScan"
62 #define HINT_NOBITMAPSCAN "NoBitmapScan"
63 #define HINT_NOTIDSCAN "NoTidScan"
64 #if PG_VERSION_NUM >= 90200
65 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
66 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
67 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
69 #define HINT_NESTLOOP "NestLoop"
70 #define HINT_MERGEJOIN "MergeJoin"
71 #define HINT_HASHJOIN "HashJoin"
72 #define HINT_NONESTLOOP "NoNestLoop"
73 #define HINT_NOMERGEJOIN "NoMergeJoin"
74 #define HINT_NOHASHJOIN "NoHashJoin"
75 #define HINT_LEADING "Leading"
76 #define HINT_SET "Set"
78 #define HINT_ARRAY_DEFAULT_INITSIZE 8
80 #define hint_ereport(str, detail) \
81 ereport(pg_hint_plan_parse_messages, \
82 (errmsg("hint syntax error at or near \"%s\"", (str)), \
85 #define skip_space(str) \
86 while (isspace(*str)) \
91 ENABLE_SEQSCAN = 0x01,
92 ENABLE_INDEXSCAN = 0x02,
93 ENABLE_BITMAPSCAN = 0x04,
94 ENABLE_TIDSCAN = 0x08,
95 #if PG_VERSION_NUM >= 90200
96 ENABLE_INDEXONLYSCAN = 0x10
102 ENABLE_NESTLOOP = 0x01,
103 ENABLE_MERGEJOIN = 0x02,
104 ENABLE_HASHJOIN = 0x04
107 #if PG_VERSION_NUM >= 90200
108 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
109 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
110 ENABLE_INDEXONLYSCAN)
112 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
113 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN)
115 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
116 #define DISABLE_ALL_SCAN 0
117 #define DISABLE_ALL_JOIN 0
119 /* hint keyword of enum type*/
120 typedef enum HintKeyword
122 HINT_KEYWORD_SEQSCAN,
123 HINT_KEYWORD_INDEXSCAN,
124 HINT_KEYWORD_INDEXSCANREGEXP,
125 HINT_KEYWORD_BITMAPSCAN,
126 HINT_KEYWORD_BITMAPSCANREGEXP,
127 HINT_KEYWORD_TIDSCAN,
128 HINT_KEYWORD_NOSEQSCAN,
129 HINT_KEYWORD_NOINDEXSCAN,
130 HINT_KEYWORD_NOBITMAPSCAN,
131 HINT_KEYWORD_NOTIDSCAN,
132 #if PG_VERSION_NUM >= 90200
133 HINT_KEYWORD_INDEXONLYSCAN,
134 HINT_KEYWORD_INDEXONLYSCANREGEXP,
135 HINT_KEYWORD_NOINDEXONLYSCAN,
137 HINT_KEYWORD_NESTLOOP,
138 HINT_KEYWORD_MERGEJOIN,
139 HINT_KEYWORD_HASHJOIN,
140 HINT_KEYWORD_NONESTLOOP,
141 HINT_KEYWORD_NOMERGEJOIN,
142 HINT_KEYWORD_NOHASHJOIN,
143 HINT_KEYWORD_LEADING,
145 HINT_KEYWORD_UNRECOGNIZED
148 typedef struct Hint Hint;
149 typedef struct HintState HintState;
151 typedef Hint *(*HintCreateFunction) (const char *hint_str,
153 HintKeyword hint_keyword);
154 typedef void (*HintDeleteFunction) (Hint *hint);
155 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf);
156 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
157 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
158 Query *parse, const char *str);
161 #define NUM_HINT_TYPE 4
162 typedef enum HintType
164 HINT_TYPE_SCAN_METHOD,
165 HINT_TYPE_JOIN_METHOD,
170 static const char *HintTypeName[] = {
178 typedef enum HintStatus
180 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
181 HINT_STATE_USED, /* hint is used */
182 HINT_STATE_DUPLICATION, /* specified hint duplication */
183 HINT_STATE_ERROR /* execute error (parse error does not include
187 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
188 (hint)->base.state == HINT_STATE_USED)
190 /* common data for all hints. */
193 const char *hint_str; /* must not do pfree */
194 const char *keyword; /* must not do pfree */
195 HintKeyword hint_keyword;
198 HintDeleteFunction delete_func;
199 HintDescFunction desc_func;
200 HintCmpFunction cmp_func;
201 HintParseFunction parse_func;
204 /* scan method hints */
205 typedef struct ScanMethodHint
211 unsigned char enforce_mask;
214 typedef struct ParentIndexInfo
219 char *expression_str;
226 /* join method hints */
227 typedef struct JoinMethodHint
233 unsigned char enforce_mask;
235 Relids inner_joinrelids;
238 /* join order hints */
239 typedef struct OuterInnerRels
242 List *outer_inner_pair;
245 typedef struct LeadingHint
248 List *relations; /* relation names specified in Leading hint */
249 OuterInnerRels *outer_inner;
252 /* change a run-time parameter hints */
253 typedef struct SetHint
256 char *name; /* name of variable */
262 * Describes a context of hint processing.
266 char *hint_str; /* original hint string */
269 int nall_hints; /* # of valid all hints */
270 int max_all_hints; /* # of slots for all hints */
271 Hint **all_hints; /* parsed all hints */
273 /* # of each hints */
274 int num_hints[NUM_HINT_TYPE];
276 /* for scan method hints */
277 ScanMethodHint **scan_hints; /* parsed scan hints */
278 int init_scan_mask; /* initial value scan parameter */
279 Index parent_relid; /* inherit parent table relid */
280 Oid parent_rel_oid; /* inherit parent table relid */
281 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
282 List *parent_index_infos; /* infomation of inherit parent table's
285 /* for join method hints */
286 JoinMethodHint **join_hints; /* parsed join hints */
287 int init_join_mask; /* initial value join parameter */
288 List **join_hint_level;
290 /* for Leading hint */
291 LeadingHint **leading_hint; /* parsed Leading hints */
294 SetHint **set_hints; /* parsed Set hints */
295 GucContext context; /* which GUC parameters can we set? */
299 * Describes a hint parser module which is bound with particular hint keyword.
301 typedef struct HintParser
304 HintCreateFunction create_func;
305 HintKeyword hint_keyword;
308 /* Module callbacks */
312 static void push_hint(HintState *hstate);
313 static void pop_hint(void);
315 static void pg_hint_plan_ProcessUtility(Node *parsetree,
316 const char *queryString,
317 ParamListInfo params, bool isTopLevel,
319 char *completionTag);
320 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
321 ParamListInfo boundParams);
322 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
323 Oid relationObjectId,
324 bool inhparent, RelOptInfo *rel);
325 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
329 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
330 HintKeyword hint_keyword);
331 static void ScanMethodHintDelete(ScanMethodHint *hint);
332 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf);
333 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
334 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
335 Query *parse, const char *str);
336 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
337 HintKeyword hint_keyword);
338 static void JoinMethodHintDelete(JoinMethodHint *hint);
339 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf);
340 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
341 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
342 Query *parse, const char *str);
343 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
344 HintKeyword hint_keyword);
345 static void LeadingHintDelete(LeadingHint *hint);
346 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf);
347 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
348 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
349 Query *parse, const char *str);
350 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
351 HintKeyword hint_keyword);
352 static void SetHintDelete(SetHint *hint);
353 static void SetHintDesc(SetHint *hint, StringInfo buf);
354 static int SetHintCmp(const SetHint *a, const SetHint *b);
355 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
358 static void quote_value(StringInfo buf, const char *value);
360 static const char *parse_quoted_value(const char *str, char **word,
363 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
366 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
367 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
368 ListCell *other_rels);
369 static void make_rels_by_clauseless_joins(PlannerInfo *root,
371 ListCell *other_rels);
372 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
373 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
374 Index rti, RangeTblEntry *rte);
375 #if PG_VERSION_NUM >= 90200
376 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
377 List *live_childrels,
378 List *all_child_pathkeys);
380 static List *accumulate_append_subpath(List *subpaths, Path *path);
381 #if PG_VERSION_NUM < 90200
382 static void set_dummy_rel_pathlist(RelOptInfo *rel);
384 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
388 static bool pg_hint_plan_enable_hint = true;
389 static bool pg_hint_plan_debug_print = false;
390 static int pg_hint_plan_parse_messages = INFO;
392 static const struct config_enum_entry parse_messages_level_options[] = {
393 {"debug", DEBUG2, true},
394 {"debug5", DEBUG5, false},
395 {"debug4", DEBUG4, false},
396 {"debug3", DEBUG3, false},
397 {"debug2", DEBUG2, false},
398 {"debug1", DEBUG1, false},
400 {"info", INFO, false},
401 {"notice", NOTICE, false},
402 {"warning", WARNING, false},
403 {"error", ERROR, false},
405 * {"fatal", FATAL, true},
406 * {"panic", PANIC, true},
411 /* Saved hook values in case of unload */
412 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
413 static planner_hook_type prev_planner = NULL;
414 static get_relation_info_hook_type prev_get_relation_info = NULL;
415 static join_search_hook_type prev_join_search = NULL;
417 /* Hold reference to currently active hint */
418 static HintState *current_hint = NULL;
421 * List of hint contexts. We treat the head of the list as the Top of the
422 * context stack, so current_hint always points the first element of this list.
424 static List *HintStateStack = NIL;
427 * Holds statement name during executing EXECUTE command. NULL for other
430 static char *stmt_name = NULL;
432 static const HintParser parsers[] = {
433 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
434 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
435 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
436 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
437 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
438 HINT_KEYWORD_BITMAPSCANREGEXP},
439 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
440 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
441 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
442 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
443 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
444 #if PG_VERSION_NUM >= 90200
445 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
446 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
447 HINT_KEYWORD_INDEXONLYSCANREGEXP},
448 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
450 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
451 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
452 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
453 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
454 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
455 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
456 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
457 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
458 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
462 * Module load callbacks
467 /* Define custom GUC variables. */
468 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
469 "Force planner to use plans specified in the hint comment preceding to the query.",
471 &pg_hint_plan_enable_hint,
479 DefineCustomBoolVariable("pg_hint_plan.debug_print",
480 "Logs results of hint parsing.",
482 &pg_hint_plan_debug_print,
490 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
491 "Message level of parse errors.",
493 &pg_hint_plan_parse_messages,
495 parse_messages_level_options,
503 prev_ProcessUtility = ProcessUtility_hook;
504 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
505 prev_planner = planner_hook;
506 planner_hook = pg_hint_plan_planner;
507 prev_get_relation_info = get_relation_info_hook;
508 get_relation_info_hook = pg_hint_plan_get_relation_info;
509 prev_join_search = join_search_hook;
510 join_search_hook = pg_hint_plan_join_search;
514 * Module unload callback
520 /* Uninstall hooks. */
521 ProcessUtility_hook = prev_ProcessUtility;
522 planner_hook = prev_planner;
523 get_relation_info_hook = prev_get_relation_info;
524 join_search_hook = prev_join_search;
528 * create and delete functions the hint object
532 ScanMethodHintCreate(const char *hint_str, const char *keyword,
533 HintKeyword hint_keyword)
535 ScanMethodHint *hint;
537 hint = palloc(sizeof(ScanMethodHint));
538 hint->base.hint_str = hint_str;
539 hint->base.keyword = keyword;
540 hint->base.hint_keyword = hint_keyword;
541 hint->base.type = HINT_TYPE_SCAN_METHOD;
542 hint->base.state = HINT_STATE_NOTUSED;
543 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
544 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
545 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
546 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
547 hint->relname = NULL;
548 hint->indexnames = NIL;
549 hint->regexp = false;
550 hint->enforce_mask = 0;
552 return (Hint *) hint;
556 ScanMethodHintDelete(ScanMethodHint *hint)
562 pfree(hint->relname);
563 list_free_deep(hint->indexnames);
568 JoinMethodHintCreate(const char *hint_str, const char *keyword,
569 HintKeyword hint_keyword)
571 JoinMethodHint *hint;
573 hint = palloc(sizeof(JoinMethodHint));
574 hint->base.hint_str = hint_str;
575 hint->base.keyword = keyword;
576 hint->base.hint_keyword = hint_keyword;
577 hint->base.type = HINT_TYPE_JOIN_METHOD;
578 hint->base.state = HINT_STATE_NOTUSED;
579 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
580 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
581 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
582 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
584 hint->inner_nrels = 0;
585 hint->relnames = NULL;
586 hint->enforce_mask = 0;
587 hint->joinrelids = NULL;
588 hint->inner_joinrelids = NULL;
590 return (Hint *) hint;
594 JoinMethodHintDelete(JoinMethodHint *hint)
603 for (i = 0; i < hint->nrels; i++)
604 pfree(hint->relnames[i]);
605 pfree(hint->relnames);
608 bms_free(hint->joinrelids);
609 bms_free(hint->inner_joinrelids);
614 LeadingHintCreate(const char *hint_str, const char *keyword,
615 HintKeyword hint_keyword)
619 hint = palloc(sizeof(LeadingHint));
620 hint->base.hint_str = hint_str;
621 hint->base.keyword = keyword;
622 hint->base.hint_keyword = hint_keyword;
623 hint->base.type = HINT_TYPE_LEADING;
624 hint->base.state = HINT_STATE_NOTUSED;
625 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
626 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
627 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
628 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
629 hint->relations = NIL;
630 hint->outer_inner = NULL;
632 return (Hint *) hint;
636 LeadingHintDelete(LeadingHint *hint)
641 list_free_deep(hint->relations);
642 if (hint->outer_inner)
643 pfree(hint->outer_inner);
648 SetHintCreate(const char *hint_str, const char *keyword,
649 HintKeyword hint_keyword)
653 hint = palloc(sizeof(SetHint));
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_SET;
658 hint->base.state = HINT_STATE_NOTUSED;
659 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
660 hint->base.desc_func = (HintDescFunction) SetHintDesc;
661 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
662 hint->base.parse_func = (HintParseFunction) SetHintParse;
667 return (Hint *) hint;
671 SetHintDelete(SetHint *hint)
681 list_free(hint->words);
686 HintStateCreate(void)
690 hstate = palloc(sizeof(HintState));
691 hstate->hint_str = NULL;
692 hstate->nall_hints = 0;
693 hstate->max_all_hints = 0;
694 hstate->all_hints = NULL;
695 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
696 hstate->scan_hints = NULL;
697 hstate->init_scan_mask = 0;
698 hstate->parent_relid = 0;
699 hstate->parent_rel_oid = InvalidOid;
700 hstate->parent_hint = NULL;
701 hstate->parent_index_infos = NIL;
702 hstate->join_hints = NULL;
703 hstate->init_join_mask = 0;
704 hstate->join_hint_level = NULL;
705 hstate->leading_hint = NULL;
706 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
707 hstate->set_hints = NULL;
713 HintStateDelete(HintState *hstate)
720 if (hstate->hint_str)
721 pfree(hstate->hint_str);
723 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
724 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
725 if (hstate->all_hints)
726 pfree(hstate->all_hints);
727 if (hstate->parent_index_infos)
728 list_free(hstate->parent_index_infos);
732 * Copy given value into buf, with quoting with '"' if necessary.
735 quote_value(StringInfo buf, const char *value)
737 bool need_quote = false;
740 for (str = value; *str != '\0'; str++)
742 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
745 appendStringInfoCharMacro(buf, '"');
750 for (str = value; *str != '\0'; str++)
753 appendStringInfoCharMacro(buf, '"');
755 appendStringInfoCharMacro(buf, *str);
759 appendStringInfoCharMacro(buf, '"');
763 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
767 appendStringInfo(buf, "%s(", hint->base.keyword);
768 if (hint->relname != NULL)
770 quote_value(buf, hint->relname);
771 foreach(l, hint->indexnames)
773 appendStringInfoCharMacro(buf, ' ');
774 quote_value(buf, (char *) lfirst(l));
777 appendStringInfoString(buf, ")\n");
781 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
785 appendStringInfo(buf, "%s(", hint->base.keyword);
786 if (hint->relnames != NULL)
788 quote_value(buf, hint->relnames[0]);
789 for (i = 1; i < hint->nrels; i++)
791 appendStringInfoCharMacro(buf, ' ');
792 quote_value(buf, hint->relnames[i]);
795 appendStringInfoString(buf, ")\n");
800 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
802 if (outer_inner->relation == NULL)
809 appendStringInfoCharMacro(buf, '(');
810 foreach(l, outer_inner->outer_inner_pair)
815 appendStringInfoCharMacro(buf, ' ');
817 OuterInnerDesc(lfirst(l), buf);
820 appendStringInfoCharMacro(buf, ')');
823 quote_value(buf, outer_inner->relation);
827 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
829 appendStringInfo(buf, "%s(", HINT_LEADING);
830 if (hint->outer_inner == NULL)
837 foreach(l, hint->relations)
842 appendStringInfoCharMacro(buf, ' ');
844 quote_value(buf, (char *) lfirst(l));
848 OuterInnerDesc(hint->outer_inner, buf);
850 appendStringInfoString(buf, ")\n");
854 SetHintDesc(SetHint *hint, StringInfo buf)
856 bool is_first = true;
859 appendStringInfo(buf, "%s(", HINT_SET);
860 foreach(l, hint->words)
865 appendStringInfoCharMacro(buf, ' ');
867 quote_value(buf, (char *) lfirst(l));
869 appendStringInfo(buf, ")\n");
873 * Append string which repserents all hints in a given state to buf, with
874 * preceding title with them.
877 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
882 appendStringInfo(buf, "%s:\n", title);
883 for (i = 0; i < hstate->nall_hints; i++)
885 if (hstate->all_hints[i]->state != state)
888 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf);
893 * Dump contents of given hstate to server log with log level LOG.
896 HintStateDump(HintState *hstate)
902 elog(LOG, "pg_hint_plan:\nno hint");
906 initStringInfo(&buf);
908 appendStringInfoString(&buf, "pg_hint_plan:\n");
909 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
910 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
911 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
912 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
914 elog(LOG, "%s", buf.data);
924 RelnameCmp(const void *a, const void *b)
926 const char *relnamea = *((const char **) a);
927 const char *relnameb = *((const char **) b);
929 return strcmp(relnamea, relnameb);
933 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
935 return RelnameCmp(&a->relname, &b->relname);
939 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
943 if (a->nrels != b->nrels)
944 return a->nrels - b->nrels;
946 for (i = 0; i < a->nrels; i++)
949 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
957 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
963 SetHintCmp(const SetHint *a, const SetHint *b)
965 return strcmp(a->name, b->name);
969 HintCmp(const void *a, const void *b)
971 const Hint *hinta = *((const Hint **) a);
972 const Hint *hintb = *((const Hint **) b);
974 if (hinta->type != hintb->type)
975 return hinta->type - hintb->type;
976 if (hinta->state == HINT_STATE_ERROR)
978 if (hintb->state == HINT_STATE_ERROR)
980 return hinta->cmp_func(hinta, hintb);
984 * Returns byte offset of hint b from hint a. If hint a was specified before
985 * b, positive value is returned.
988 HintCmpWithPos(const void *a, const void *b)
990 const Hint *hinta = *((const Hint **) a);
991 const Hint *hintb = *((const Hint **) b);
994 result = HintCmp(a, b);
996 result = hinta->hint_str - hintb->hint_str;
1005 parse_keyword(const char *str, StringInfo buf)
1009 while (!isspace(*str) && *str != '(' && *str != '\0')
1010 appendStringInfoCharMacro(buf, *str++);
1016 skip_parenthesis(const char *str, char parenthesis)
1020 if (*str != parenthesis)
1022 if (parenthesis == '(')
1023 hint_ereport(str, ("Opening parenthesis is necessary."));
1024 else if (parenthesis == ')')
1025 hint_ereport(str, ("Closing parenthesis is necessary."));
1036 * Parse a token from str, and store malloc'd copy into word. A token can be
1037 * quoted with '"'. Return value is pointer to unparsed portion of original
1038 * string, or NULL if an error occurred.
1040 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1043 parse_quoted_value(const char *str, char **word, bool truncate)
1048 /* Skip leading spaces. */
1051 initStringInfo(&buf);
1064 /* Double quotation must be closed. */
1068 hint_ereport(str, ("Unterminated quoted string."));
1073 * Skip escaped double quotation.
1075 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1076 * block comments) to be an object name, so users must specify
1077 * alias for such object names.
1079 * Those special names can be allowed if we care escaped slashes
1080 * and asterisks, but we don't.
1089 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1093 appendStringInfoCharMacro(&buf, *str++);
1098 hint_ereport(str, ("Zero-length delimited string."));
1105 /* Truncate name if it's too long */
1107 truncate_identifier(buf.data, strlen(buf.data), true);
1114 static OuterInnerRels *
1115 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1117 OuterInnerRels *outer_inner;
1119 outer_inner = palloc(sizeof(OuterInnerRels));
1120 outer_inner->relation = name;
1121 outer_inner->outer_inner_pair = outer_inner_list;
1127 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1129 List *outer_inner_pair = NIL;
1131 if ((str = skip_parenthesis(str, '(')) == NULL)
1136 /* Store words in parentheses into outer_inner_list. */
1137 while(*str != ')' && *str != '\0')
1139 OuterInnerRels *outer_inner_rels;
1143 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1151 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1154 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1157 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1162 (str = skip_parenthesis(str, ')')) == NULL)
1164 list_free(outer_inner_pair);
1168 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1174 parse_parentheses_Leading(const char *str, List **name_list,
1175 OuterInnerRels **outer_inner)
1178 bool truncate = true;
1180 if ((str = skip_parenthesis(str, '(')) == NULL)
1186 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1191 /* Store words in parentheses into name_list. */
1192 while(*str != ')' && *str != '\0')
1194 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1196 list_free(*name_list);
1200 *name_list = lappend(*name_list, name);
1205 if ((str = skip_parenthesis(str, ')')) == NULL)
1211 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1214 bool truncate = true;
1216 if ((str = skip_parenthesis(str, '(')) == NULL)
1221 /* Store words in parentheses into name_list. */
1222 while(*str != ')' && *str != '\0')
1224 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1226 list_free(*name_list);
1230 *name_list = lappend(*name_list, name);
1233 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1234 #if PG_VERSION_NUM >= 90200
1235 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1237 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1238 keyword == HINT_KEYWORD_SET)
1244 if ((str = skip_parenthesis(str, ')')) == NULL)
1250 parse_hints(HintState *hstate, Query *parse, const char *str)
1255 initStringInfo(&buf);
1256 while (*str != '\0')
1258 const HintParser *parser;
1260 /* in error message, we output the comment including the keyword. */
1261 head = (char *) str;
1263 /* parse only the keyword of the hint. */
1264 resetStringInfo(&buf);
1265 str = parse_keyword(str, &buf);
1267 for (parser = parsers; parser->keyword != NULL; parser++)
1269 char *keyword = parser->keyword;
1272 if (strcasecmp(buf.data, keyword) != 0)
1275 hint = parser->create_func(head, keyword, parser->hint_keyword);
1277 /* parser of each hint does parse in a parenthesis. */
1278 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1280 hint->delete_func(hint);
1286 * Add hint information into all_hints array. If we don't have
1287 * enough space, double the array.
1289 if (hstate->nall_hints == 0)
1291 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1292 hstate->all_hints = (Hint **)
1293 palloc(sizeof(Hint *) * hstate->max_all_hints);
1295 else if (hstate->nall_hints == hstate->max_all_hints)
1297 hstate->max_all_hints *= 2;
1298 hstate->all_hints = (Hint **)
1299 repalloc(hstate->all_hints,
1300 sizeof(Hint *) * hstate->max_all_hints);
1303 hstate->all_hints[hstate->nall_hints] = hint;
1304 hstate->nall_hints++;
1311 if (parser->keyword == NULL)
1314 ("Unrecognized hint keyword \"%s\".", buf.data));
1324 * Do basic parsing of the query head comment.
1327 * クエリに記述されたヒントを見つける。
1330 find_hints_comment()
1333 const char *hint_head;
1338 /* get client-supplied query string. */
1341 PreparedStatement *entry;
1343 entry = FetchPreparedStatement(stmt_name, true);
1344 p = entry->plansource->query_string;
1347 p = debug_query_string;
1352 /* extract query head comment. */
1353 hint_head = strstr(p, HINT_START);
1354 if (hint_head == NULL)
1356 for (;p < hint_head; p++)
1359 * Allow these characters precedes hint comment:
1361 * - alphabets which are in ASCII range
1362 * - space, tabs and new-lines
1363 * - underscores, for identifier
1364 * - commas, for SELECT clause, EXPLAIN and PREPARE
1365 * - parentheses, for EXPLAIN and PREPARE
1367 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1368 * avoid behavior which depends on locale setting.
1370 if (!(*p >= '0' && *p <= '9') &&
1371 !(*p >= 'A' && *p <= 'Z') &&
1372 !(*p >= 'a' && *p <= 'z') &&
1376 *p != '(' && *p != ')')
1380 len = strlen(HINT_START);
1385 /* find hint end keyword. */
1386 if ((tail = strstr(p, HINT_END)) == NULL)
1388 hint_ereport(head, ("Unterminated block comment."));
1392 /* We don't support nested block comments. */
1393 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1395 hint_ereport(head, ("Nested block comments are not supported."));
1399 /* Make a copy of hint. */
1401 head = palloc(len + 1);
1402 memcpy(head, p, len);
1413 get_hintstate(Query *parse,
1424 hstate = HintStateCreate();
1425 hstate->hint_str = (char *) hints;
1427 /* parse each hint. */
1428 parse_hints(hstate, parse, p);
1430 /* When nothing specified a hint, we free HintState and returns NULL. */
1431 if (hstate->nall_hints == 0)
1433 HintStateDelete(hstate);
1437 /* Sort hints in order of original position. */
1438 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1441 /* Count number of hints per hint-type. */
1442 for (i = 0; i < hstate->nall_hints; i++)
1444 Hint *cur_hint = hstate->all_hints[i];
1445 hstate->num_hints[cur_hint->type]++;
1449 * If an object (or a set of objects) has multiple hints of same hint-type,
1450 * only the last hint is valid and others are igonred in planning.
1451 * Hints except the last are marked as 'duplicated' to remember the order.
1453 for (i = 0; i < hstate->nall_hints - 1; i++)
1455 Hint *cur_hint = hstate->all_hints[i];
1456 Hint *next_hint = hstate->all_hints[i + 1];
1459 * Leading hint is marked as 'duplicated' in transform_join_hints.
1461 if (cur_hint->type == HINT_TYPE_LEADING &&
1462 next_hint->type == HINT_TYPE_LEADING)
1466 * Note that we need to pass addresses of hint pointers, because
1467 * HintCmp is designed to sort array of Hint* by qsort.
1469 if (HintCmp(&cur_hint, &next_hint) == 0)
1471 hint_ereport(cur_hint->hint_str,
1472 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1473 cur_hint->state = HINT_STATE_DUPLICATION;
1478 * Make sure that per-type array pointers point proper position in the
1479 * array which consists of all hints.
1481 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1482 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1483 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1484 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1485 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1486 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1487 hstate->num_hints[HINT_TYPE_LEADING]);
1493 * Parse inside of parentheses of scan-method hints.
1496 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1499 const char *keyword = hint->base.keyword;
1500 HintKeyword hint_keyword = hint->base.hint_keyword;
1501 List *name_list = NIL;
1504 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1507 /* Parse relation name and index name(s) if given hint accepts. */
1508 length = list_length(name_list);
1511 hint->relname = linitial(name_list);
1512 hint->indexnames = list_delete_first(name_list);
1514 /* check whether the hint accepts index name(s). */
1516 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1517 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1518 #if PG_VERSION_NUM >= 90200
1519 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1520 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1522 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1523 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1526 ("%s hint accepts only one relation.",
1527 hint->base.keyword));
1528 hint->base.state = HINT_STATE_ERROR;
1535 ("%s hint requires a relation.",
1536 hint->base.keyword));
1537 hint->base.state = HINT_STATE_ERROR;
1541 /* Set a bit for specified hint. */
1542 switch (hint_keyword)
1544 case HINT_KEYWORD_SEQSCAN:
1545 hint->enforce_mask = ENABLE_SEQSCAN;
1547 case HINT_KEYWORD_INDEXSCAN:
1548 hint->enforce_mask = ENABLE_INDEXSCAN;
1550 case HINT_KEYWORD_INDEXSCANREGEXP:
1551 hint->enforce_mask = ENABLE_INDEXSCAN;
1552 hint->regexp = true;
1554 case HINT_KEYWORD_BITMAPSCAN:
1555 hint->enforce_mask = ENABLE_BITMAPSCAN;
1557 case HINT_KEYWORD_BITMAPSCANREGEXP:
1558 hint->enforce_mask = ENABLE_BITMAPSCAN;
1559 hint->regexp = true;
1561 case HINT_KEYWORD_TIDSCAN:
1562 hint->enforce_mask = ENABLE_TIDSCAN;
1564 case HINT_KEYWORD_NOSEQSCAN:
1565 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1567 case HINT_KEYWORD_NOINDEXSCAN:
1568 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1570 case HINT_KEYWORD_NOBITMAPSCAN:
1571 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1573 case HINT_KEYWORD_NOTIDSCAN:
1574 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1576 #if PG_VERSION_NUM >= 90200
1577 case HINT_KEYWORD_INDEXONLYSCAN:
1578 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1580 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1581 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1582 hint->regexp = true;
1584 case HINT_KEYWORD_NOINDEXONLYSCAN:
1585 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1589 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1598 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1601 const char *keyword = hint->base.keyword;
1602 HintKeyword hint_keyword = hint->base.hint_keyword;
1603 List *name_list = NIL;
1605 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1608 hint->nrels = list_length(name_list);
1610 if (hint->nrels > 0)
1616 * Transform relation names from list to array to sort them with qsort
1619 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1620 foreach (l, name_list)
1622 hint->relnames[i] = lfirst(l);
1627 list_free(name_list);
1629 /* A join hint requires at least two relations */
1630 if (hint->nrels < 2)
1633 ("%s hint requires at least two relations.",
1634 hint->base.keyword));
1635 hint->base.state = HINT_STATE_ERROR;
1639 /* Sort hints in alphabetical order of relation names. */
1640 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1642 switch (hint_keyword)
1644 case HINT_KEYWORD_NESTLOOP:
1645 hint->enforce_mask = ENABLE_NESTLOOP;
1647 case HINT_KEYWORD_MERGEJOIN:
1648 hint->enforce_mask = ENABLE_MERGEJOIN;
1650 case HINT_KEYWORD_HASHJOIN:
1651 hint->enforce_mask = ENABLE_HASHJOIN;
1653 case HINT_KEYWORD_NONESTLOOP:
1654 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1656 case HINT_KEYWORD_NOMERGEJOIN:
1657 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1659 case HINT_KEYWORD_NOHASHJOIN:
1660 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1663 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1672 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1675 if (outer_inner->outer_inner_pair == NIL)
1677 if (outer_inner->relation)
1683 if (list_length(outer_inner->outer_inner_pair) == 2)
1685 foreach(l, outer_inner->outer_inner_pair)
1687 if (!OuterInnerPairCheck(lfirst(l)))
1698 OuterInnerList(OuterInnerRels *outer_inner)
1700 List *outer_inner_list = NIL;
1702 OuterInnerRels *outer_inner_rels;
1704 foreach(l, outer_inner->outer_inner_pair)
1706 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
1708 if (outer_inner_rels->relation != NULL)
1709 outer_inner_list = lappend(outer_inner_list,
1710 outer_inner_rels->relation);
1712 outer_inner_list = list_concat(outer_inner_list,
1713 OuterInnerList(outer_inner_rels));
1715 return outer_inner_list;
1719 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1722 List *name_list = NIL;
1723 OuterInnerRels *outer_inner = NULL;
1725 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
1729 if (outer_inner != NULL)
1730 name_list = OuterInnerList(outer_inner);
1732 hint->relations = name_list;
1733 hint->outer_inner = outer_inner;
1735 /* A Leading hint requires at least two relations */
1736 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
1738 hint_ereport(hint->base.hint_str,
1739 ("%s hint requires at least two relations.",
1741 hint->base.state = HINT_STATE_ERROR;
1743 else if (hint->outer_inner != NULL &&
1744 !OuterInnerPairCheck(hint->outer_inner))
1746 hint_ereport(hint->base.hint_str,
1747 ("%s hint requires two sets of relations when parentheses nests.",
1749 hint->base.state = HINT_STATE_ERROR;
1756 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1758 List *name_list = NIL;
1760 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
1764 hint->words = name_list;
1766 /* We need both name and value to set GUC parameter. */
1767 if (list_length(name_list) == 2)
1769 hint->name = linitial(name_list);
1770 hint->value = lsecond(name_list);
1774 hint_ereport(hint->base.hint_str,
1775 ("%s hint requires name and value of GUC parameter.",
1777 hint->base.state = HINT_STATE_ERROR;
1784 * set GUC parameter functions
1788 set_config_option_wrapper(const char *name, const char *value,
1789 GucContext context, GucSource source,
1790 GucAction action, bool changeVal, int elevel)
1793 MemoryContext ccxt = CurrentMemoryContext;
1797 #if PG_VERSION_NUM >= 90200
1798 result = set_config_option(name, value, context, source,
1799 action, changeVal, 0);
1801 result = set_config_option(name, value, context, source,
1809 /* Save error info */
1810 MemoryContextSwitchTo(ccxt);
1811 errdata = CopyErrorData();
1814 ereport(elevel, (errcode(errdata->sqlerrcode),
1815 errmsg("%s", errdata->message),
1816 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1817 errdata->hint ? errhint("%s", errdata->hint) : 0));
1818 FreeErrorData(errdata);
1826 set_config_options(SetHint **options, int noptions, GucContext context)
1831 save_nestlevel = NewGUCNestLevel();
1833 for (i = 0; i < noptions; i++)
1835 SetHint *hint = options[i];
1838 if (!hint_state_enabled(hint))
1841 result = set_config_option_wrapper(hint->name, hint->value, context,
1842 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1843 pg_hint_plan_parse_messages);
1845 hint->base.state = HINT_STATE_USED;
1847 hint->base.state = HINT_STATE_ERROR;
1850 return save_nestlevel;
1853 #define SET_CONFIG_OPTION(name, type_bits) \
1854 set_config_option_wrapper((name), \
1855 (mask & (type_bits)) ? "true" : "false", \
1856 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1859 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1863 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1864 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1865 #if PG_VERSION_NUM >= 90200
1866 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1869 mask = enforce_mask;
1871 mask = enforce_mask & current_hint->init_scan_mask;
1873 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1874 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1875 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1876 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1877 #if PG_VERSION_NUM >= 90200
1878 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1883 set_join_config_options(unsigned char enforce_mask, GucContext context)
1887 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1888 enforce_mask == ENABLE_HASHJOIN)
1889 mask = enforce_mask;
1891 mask = enforce_mask & current_hint->init_join_mask;
1893 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1894 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1895 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1899 * pg_hint_plan hook functions
1903 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1904 ParamListInfo params, bool isTopLevel,
1905 DestReceiver *dest, char *completionTag)
1909 if (!pg_hint_plan_enable_hint)
1911 if (prev_ProcessUtility)
1912 (*prev_ProcessUtility) (parsetree, queryString, params,
1913 isTopLevel, dest, completionTag);
1915 standard_ProcessUtility(parsetree, queryString, params,
1916 isTopLevel, dest, completionTag);
1922 if (IsA(node, ExplainStmt))
1925 * Draw out parse tree of actual query from Query struct of EXPLAIN
1931 stmt = (ExplainStmt *) node;
1933 Assert(IsA(stmt->query, Query));
1934 query = (Query *) stmt->query;
1936 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1937 node = query->utilityStmt;
1941 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
1942 * specified to preceding PREPARE command to use it as source of hints.
1944 if (IsA(node, ExecuteStmt))
1948 stmt = (ExecuteStmt *) node;
1949 stmt_name = stmt->name;
1951 #if PG_VERSION_NUM >= 90200
1953 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
1956 if (IsA(node, CreateTableAsStmt))
1958 CreateTableAsStmt *stmt;
1961 stmt = (CreateTableAsStmt *) node;
1962 Assert(IsA(stmt->query, Query));
1963 query = (Query *) stmt->query;
1965 if (query->commandType == CMD_UTILITY &&
1966 IsA(query->utilityStmt, ExecuteStmt))
1968 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
1969 stmt_name = estmt->name;
1977 if (prev_ProcessUtility)
1978 (*prev_ProcessUtility) (parsetree, queryString, params,
1979 isTopLevel, dest, completionTag);
1981 standard_ProcessUtility(parsetree, queryString, params,
1982 isTopLevel, dest, completionTag);
1996 if (prev_ProcessUtility)
1997 (*prev_ProcessUtility) (parsetree, queryString, params,
1998 isTopLevel, dest, completionTag);
2000 standard_ProcessUtility(parsetree, queryString, params,
2001 isTopLevel, dest, completionTag);
2005 * Push a hint into hint stack which is implemented with List struct. Head of
2006 * list is top of stack.
2009 push_hint(HintState *hstate)
2011 /* Prepend new hint to the list means pushing to stack. */
2012 HintStateStack = lcons(hstate, HintStateStack);
2014 /* Pushed hint is the one which should be used hereafter. */
2015 current_hint = hstate;
2018 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2022 /* Hint stack must not be empty. */
2023 if(HintStateStack == NIL)
2024 elog(ERROR, "hint stack is empty");
2027 * Take a hint at the head from the list, and free it. Switch current_hint
2028 * to point new head (NULL if the list is empty).
2030 HintStateStack = list_delete_first(HintStateStack);
2031 HintStateDelete(current_hint);
2032 if(HintStateStack == NIL)
2033 current_hint = NULL;
2035 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2038 static PlannedStmt *
2039 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2043 PlannedStmt *result;
2047 * Use standard planner if pg_hint_plan is disabled. Other hook functions
2048 * try to change plan with current_hint if any, so set it to NULL.
2050 if (!pg_hint_plan_enable_hint)
2052 current_hint = NULL;
2055 return (*prev_planner) (parse, cursorOptions, boundParams);
2057 return standard_planner(parse, cursorOptions, boundParams);
2060 /* Create hint struct from parse tree. */
2062 * ヒント用テーブル方式を実装する前段階として、
2063 * parse_head_comment()をクエリに記述されたヒントを見つける処理と
2066 hints = find_hints_comment();
2067 elog(LOG, "pg_hint_plan: [%s] => [%s]", debug_query_string
2068 , hints ? hints : "(none)");
2069 hstate = get_hintstate(parse, hints);
2072 * Use standard planner if the statement has not valid hint. Other hook
2073 * functions try to change plan with current_hint if any, so set it to
2078 current_hint = NULL;
2081 return (*prev_planner) (parse, cursorOptions, boundParams);
2083 return standard_planner(parse, cursorOptions, boundParams);
2087 * Push new hint struct to the hint stack to disable previous hint context.
2091 /* Set GUC parameters which are specified with Set hint. */
2092 save_nestlevel = set_config_options(current_hint->set_hints,
2093 current_hint->num_hints[HINT_TYPE_SET],
2094 current_hint->context);
2097 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2098 if (enable_indexscan)
2099 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2100 if (enable_bitmapscan)
2101 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2103 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2104 #if PG_VERSION_NUM >= 90200
2105 if (enable_indexonlyscan)
2106 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2108 if (enable_nestloop)
2109 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2110 if (enable_mergejoin)
2111 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2112 if (enable_hashjoin)
2113 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2116 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2117 * state when this planner started when error occurred in planner.
2122 result = (*prev_planner) (parse, cursorOptions, boundParams);
2124 result = standard_planner(parse, cursorOptions, boundParams);
2129 * Rollback changes of GUC parameters, and pop current hint context
2130 * from hint stack to rewind the state.
2132 AtEOXact_GUC(true, save_nestlevel);
2138 /* Print hint in debug mode. */
2139 if (pg_hint_plan_debug_print)
2140 HintStateDump(current_hint);
2143 * Rollback changes of GUC parameters, and pop current hint context from
2144 * hint stack to rewind the state.
2146 AtEOXact_GUC(true, save_nestlevel);
2153 * Return scan method hint which matches given aliasname.
2155 static ScanMethodHint *
2156 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2162 * We can't apply scan method hint if the relation is:
2163 * - not a base relation
2164 * - not an ordinary relation (such as join and subquery)
2166 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2169 rte = root->simple_rte_array[rel->relid];
2171 /* We can't force scan method of foreign tables */
2172 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2175 /* Find scan method hint, which matches given names, from the list. */
2176 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2178 ScanMethodHint *hint = current_hint->scan_hints[i];
2180 /* We ignore disabled hints. */
2181 if (!hint_state_enabled(hint))
2184 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2194 * Returns TRUE on match, FALSE on no match.
2196 * s1 --- the data to match against
2197 * s2 --- the pattern
2199 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2202 regexpeq(const char *s1, const char *s2)
2208 strcpy(name.data, s1);
2209 regexp = cstring_to_text(s2);
2211 result = DirectFunctionCall2Coll(nameregexeq,
2212 DEFAULT_COLLATION_OID,
2213 NameGetDatum(&name),
2214 PointerGetDatum(regexp));
2215 return DatumGetBool(result);
2219 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2227 * We delete all the IndexOptInfo list and prevent you from being usable by
2230 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2231 hint->enforce_mask == ENABLE_TIDSCAN)
2233 list_free_deep(rel->indexlist);
2234 rel->indexlist = NIL;
2235 hint->base.state = HINT_STATE_USED;
2241 * When a list of indexes is not specified, we just use all indexes.
2243 if (hint->indexnames == NIL)
2247 * Leaving only an specified index, we delete it from a IndexOptInfo list
2251 if (pg_hint_plan_debug_print)
2252 initStringInfo(&buf);
2254 for (cell = list_head(rel->indexlist); cell; cell = next)
2256 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2257 char *indexname = get_rel_name(info->indexoid);
2259 bool use_index = false;
2263 foreach(l, hint->indexnames)
2265 char *hintname = (char *) lfirst(l);
2269 result = regexpeq(indexname, hintname);
2271 result = RelnameCmp(&indexname, &hintname) == 0;
2276 if (pg_hint_plan_debug_print)
2278 appendStringInfoCharMacro(&buf, ' ');
2279 quote_value(&buf, indexname);
2287 * to make the index a candidate when definition of this index is
2288 * matched with the index's definition of current_hint.
2290 if (OidIsValid(relationObjectId) && !use_index)
2292 foreach(l, current_hint->parent_index_infos)
2296 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2298 /* check to match the parameter of unique */
2299 if (p_info->indisunique != info->unique)
2302 /* check to match the parameter of index's method */
2303 if (p_info->method != info->relam)
2306 /* to check to match the indexkey's configuration */
2307 if ((list_length(p_info->column_names)) !=
2311 /* check to match the indexkey's configuration */
2312 for (i = 0; i < info->ncolumns; i++)
2314 char *c_attname = NULL;
2315 char *p_attname = NULL;
2318 list_nth(p_info->column_names, i);
2320 /* both are expressions */
2321 if (info->indexkeys[i] == 0 && !p_attname)
2324 /* one's column is expression, the other is not */
2325 if (info->indexkeys[i] == 0 || !p_attname)
2328 c_attname = get_attname(relationObjectId,
2329 info->indexkeys[i]);
2331 if (strcmp(p_attname, c_attname) != 0)
2334 if (p_info->indcollation[i] != info->indexcollations[i])
2337 if (p_info->opclass[i] != info->opcintype[i])
2340 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2341 info->reverse_sort[i])
2344 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2345 info->nulls_first[i])
2350 if (i != info->ncolumns)
2353 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2354 (p_info->indpred_str && (info->indpred != NIL)))
2357 * Fetch the pg_index tuple by the Oid of the index
2359 ht_idx = SearchSysCache1(INDEXRELID,
2360 ObjectIdGetDatum(info->indexoid));
2362 /* check to match the expression's parameter of index */
2363 if (p_info->expression_str &&
2364 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2371 * to change the expression's parameter of child's
2374 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2375 Anum_pg_index_indexprs,
2378 result = DirectFunctionCall2(pg_get_expr,
2383 if (strcmp(p_info->expression_str,
2384 text_to_cstring(DatumGetTextP(result))) != 0)
2387 ReleaseSysCache(ht_idx);
2393 /* Check to match the predicate's paraameter of index */
2394 if (p_info->indpred_str &&
2395 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2402 * to change the predicate's parabeter of child's
2405 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2406 Anum_pg_index_indpred,
2409 result = DirectFunctionCall2(pg_get_expr,
2414 if (strcmp(p_info->indpred_str,
2415 text_to_cstring(DatumGetTextP(result))) != 0)
2418 ReleaseSysCache(ht_idx);
2425 ReleaseSysCache(ht_idx);
2427 else if (p_info->expression_str || (info->indexprs != NIL))
2429 else if (p_info->indpred_str || (info->indpred != NIL))
2434 /* to log the candidate of index */
2435 if (pg_hint_plan_debug_print)
2437 appendStringInfoCharMacro(&buf, ' ');
2438 quote_value(&buf, indexname);
2446 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2453 if (pg_hint_plan_debug_print)
2456 StringInfoData rel_buf;
2458 if (OidIsValid(relationObjectId))
2459 relname = get_rel_name(relationObjectId);
2461 relname = hint->relname;
2463 initStringInfo(&rel_buf);
2464 quote_value(&rel_buf, relname);
2467 (errmsg("available indexes for %s(%s):%s",
2472 pfree(rel_buf.data);
2477 * Return information of index definition.
2479 static ParentIndexInfo *
2480 get_parent_index_info(Oid indexoid, Oid relid)
2482 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
2483 Relation indexRelation;
2484 Form_pg_index index;
2488 indexRelation = index_open(indexoid, RowExclusiveLock);
2490 index = indexRelation->rd_index;
2492 p_info->indisunique = index->indisunique;
2493 p_info->method = indexRelation->rd_rel->relam;
2495 p_info->column_names = NIL;
2496 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2497 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2498 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
2500 for (i = 0; i < index->indnatts; i++)
2502 attname = get_attname(relid, index->indkey.values[i]);
2503 p_info->column_names = lappend(p_info->column_names, attname);
2505 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
2506 p_info->opclass[i] = indexRelation->rd_opcintype[i];
2507 p_info->indoption[i] = indexRelation->rd_indoption[i];
2511 * to check to match the expression's paraameter of index with child indexes
2513 p_info->expression_str = NULL;
2514 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
2520 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2521 Anum_pg_index_indexprs, &isnull);
2523 result = DirectFunctionCall2(pg_get_expr,
2525 ObjectIdGetDatum(relid));
2527 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
2531 * to check to match the predicate's paraameter of index with child indexes
2533 p_info->indpred_str = NULL;
2534 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
2540 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2541 Anum_pg_index_indpred, &isnull);
2543 result = DirectFunctionCall2(pg_get_expr,
2545 ObjectIdGetDatum(relid));
2547 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
2550 index_close(indexRelation, NoLock);
2556 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2557 bool inhparent, RelOptInfo *rel)
2559 ScanMethodHint *hint;
2561 if (prev_get_relation_info)
2562 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2564 /* Do nothing if we don't have valid hint in this context. */
2570 /* store does relids of parent table. */
2571 current_hint->parent_relid = rel->relid;
2572 current_hint->parent_rel_oid = relationObjectId;
2574 else if (current_hint->parent_relid != 0)
2577 * We use the same GUC parameter if this table is the child table of a
2578 * table called pg_hint_plan_get_relation_info just before that.
2582 /* append_rel_list contains all append rels; ignore others */
2583 foreach(l, root->append_rel_list)
2585 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2587 /* This rel is child table. */
2588 if (appinfo->parent_relid == current_hint->parent_relid &&
2589 appinfo->child_relid == rel->relid)
2591 if (current_hint->parent_hint)
2592 delete_indexes(current_hint->parent_hint, rel,
2599 /* This rel is not inherit table. */
2600 current_hint->parent_relid = 0;
2601 current_hint->parent_rel_oid = InvalidOid;
2602 current_hint->parent_hint = NULL;
2606 * If scan method hint was given, reset GUC parameters which control
2607 * planner behavior about choosing scan methods.
2609 if ((hint = find_scan_hint(root, rel)) == NULL)
2611 set_scan_config_options(current_hint->init_scan_mask,
2612 current_hint->context);
2615 set_scan_config_options(hint->enforce_mask, current_hint->context);
2616 hint->base.state = HINT_STATE_USED;
2624 current_hint->parent_hint = hint;
2626 relation = heap_open(relationObjectId, NoLock);
2627 indexoidlist = RelationGetIndexList(relation);
2629 foreach(l, indexoidlist)
2631 Oid indexoid = lfirst_oid(l);
2632 char *indexname = get_rel_name(indexoid);
2633 bool use_index = false;
2635 ParentIndexInfo *parent_index_info;
2637 foreach(lc, hint->indexnames)
2639 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
2648 parent_index_info = get_parent_index_info(indexoid,
2650 current_hint->parent_index_infos =
2651 lappend(current_hint->parent_index_infos, parent_index_info);
2653 heap_close(relation, NoLock);
2656 delete_indexes(hint, rel, InvalidOid);
2660 * Return index of relation which matches given aliasname, or 0 if not found.
2661 * If same aliasname was used multiple times in a query, return -1.
2664 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
2670 for (i = 1; i < root->simple_rel_array_size; i++)
2674 if (root->simple_rel_array[i] == NULL)
2677 Assert(i == root->simple_rel_array[i]->relid);
2679 if (RelnameCmp(&aliasname,
2680 &root->simple_rte_array[i]->eref->aliasname) != 0)
2683 foreach(l, initial_rels)
2685 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2687 if (rel->reloptkind == RELOPT_BASEREL)
2689 if (rel->relid != i)
2694 Assert(rel->reloptkind == RELOPT_JOINREL);
2696 if (!bms_is_member(i, rel->relids))
2703 ("Relation name \"%s\" is ambiguous.",
2718 * Return join hint which matches given joinrelids.
2720 static JoinMethodHint *
2721 find_join_hint(Relids joinrelids)
2726 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
2728 foreach(l, join_hint)
2730 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
2732 if (bms_equal(joinrelids, hint->joinrelids))
2740 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
2741 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
2743 OuterInnerRels *outer_rels;
2744 OuterInnerRels *inner_rels;
2745 Relids outer_relids;
2746 Relids inner_relids;
2748 JoinMethodHint *hint;
2750 if (outer_inner->relation != NULL)
2752 return bms_make_singleton(
2753 find_relid_aliasname(root, outer_inner->relation,
2755 leading_hint->base.hint_str));
2758 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
2759 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
2761 outer_relids = OuterInnerJoinCreate(outer_rels,
2767 inner_relids = OuterInnerJoinCreate(inner_rels,
2774 join_relids = bms_add_members(outer_relids, inner_relids);
2776 if (bms_num_members(join_relids) > nbaserel)
2780 * If we don't have join method hint, create new one for the
2781 * join combination with all join methods are enabled.
2783 hint = find_join_hint(join_relids);
2787 * Here relnames is not set, since Relids bitmap is sufficient to
2788 * control paths of this query afterward.
2790 hint = (JoinMethodHint *) JoinMethodHintCreate(
2791 leading_hint->base.hint_str,
2793 HINT_KEYWORD_LEADING);
2794 hint->base.state = HINT_STATE_USED;
2795 hint->nrels = bms_num_members(join_relids);
2796 hint->enforce_mask = ENABLE_ALL_JOIN;
2797 hint->joinrelids = bms_copy(join_relids);
2798 hint->inner_nrels = bms_num_members(inner_relids);
2799 hint->inner_joinrelids = bms_copy(inner_relids);
2801 hstate->join_hint_level[hint->nrels] =
2802 lappend(hstate->join_hint_level[hint->nrels], hint);
2806 hint->inner_nrels = bms_num_members(inner_relids);
2807 hint->inner_joinrelids = bms_copy(inner_relids);
2814 * Transform join method hint into handy form.
2816 * - create bitmap of relids from alias names, to make it easier to check
2817 * whether a join path matches a join method hint.
2818 * - add join method hints which are necessary to enforce join order
2819 * specified by Leading hint
2822 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2823 List *initial_rels, JoinMethodHint **join_method_hints)
2831 LeadingHint *lhint = NULL;
2834 * Create bitmap of relids from alias names for each join method hint.
2835 * Bitmaps are more handy than strings in join searching.
2837 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2839 JoinMethodHint *hint = hstate->join_hints[i];
2842 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
2845 bms_free(hint->joinrelids);
2846 hint->joinrelids = NULL;
2848 for (j = 0; j < hint->nrels; j++)
2850 relname = hint->relnames[j];
2852 relid = find_relid_aliasname(root, relname, initial_rels,
2853 hint->base.hint_str);
2856 hint->base.state = HINT_STATE_ERROR;
2861 if (bms_is_member(relid, hint->joinrelids))
2863 hint_ereport(hint->base.hint_str,
2864 ("Relation name \"%s\" is duplicated.", relname));
2865 hint->base.state = HINT_STATE_ERROR;
2869 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
2872 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
2875 hstate->join_hint_level[hint->nrels] =
2876 lappend(hstate->join_hint_level[hint->nrels], hint);
2879 /* Do nothing if no Leading hint was supplied. */
2880 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2884 * Decide to use Leading hint。
2886 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
2888 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
2891 if (leading_hint->base.state == HINT_STATE_ERROR)
2897 foreach(l, leading_hint->relations)
2899 relname = (char *)lfirst(l);;
2901 relid = find_relid_aliasname(root, relname, initial_rels,
2902 leading_hint->base.hint_str);
2904 leading_hint->base.state = HINT_STATE_ERROR;
2909 if (bms_is_member(relid, relids))
2911 hint_ereport(leading_hint->base.hint_str,
2912 ("Relation name \"%s\" is duplicated.", relname));
2913 leading_hint->base.state = HINT_STATE_ERROR;
2917 relids = bms_add_member(relids, relid);
2920 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
2925 hint_ereport(lhint->base.hint_str,
2926 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
2927 lhint->base.state = HINT_STATE_DUPLICATION;
2929 leading_hint->base.state = HINT_STATE_USED;
2930 lhint = leading_hint;
2933 /* check to exist Leading hint marked with 'used'. */
2938 * We need join method hints which fit specified join order in every join
2939 * level. For example, Leading(A B C) virtually requires following join
2940 * method hints, if no join method hint supplied:
2942 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
2943 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
2945 * If we already have join method hint which fits specified join order in
2946 * that join level, we leave it as-is and don't add new hints.
2950 if (lhint->outer_inner == NULL)
2952 foreach(l, lhint->relations)
2954 JoinMethodHint *hint;
2956 relname = (char *)lfirst(l);
2959 * Find relid of the relation which has given name. If we have the
2960 * name given in Leading hint multiple times in the join, nothing to
2963 relid = find_relid_aliasname(root, relname, initial_rels,
2966 /* Create bitmap of relids for current join level. */
2967 joinrelids = bms_add_member(joinrelids, relid);
2970 /* We never have join method hint for single relation. */
2975 * If we don't have join method hint, create new one for the
2976 * join combination with all join methods are enabled.
2978 hint = find_join_hint(joinrelids);
2982 * Here relnames is not set, since Relids bitmap is sufficient
2983 * to control paths of this query afterward.
2985 hint = (JoinMethodHint *) JoinMethodHintCreate(
2986 lhint->base.hint_str,
2988 HINT_KEYWORD_LEADING);
2989 hint->base.state = HINT_STATE_USED;
2990 hint->nrels = njoinrels;
2991 hint->enforce_mask = ENABLE_ALL_JOIN;
2992 hint->joinrelids = bms_copy(joinrelids);
2995 join_method_hints[njoinrels] = hint;
2997 if (njoinrels >= nbaserel)
3000 bms_free(joinrelids);
3006 * Delete all join hints which have different combination from Leading
3009 for (i = 2; i <= njoinrels; i++)
3011 list_free(hstate->join_hint_level[i]);
3013 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3018 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3025 njoinrels = bms_num_members(joinrelids);
3026 Assert(njoinrels >= 2);
3029 * Delete all join hints which have different combination from Leading
3032 for (i = 2;i <= njoinrels; i++)
3034 if (hstate->join_hint_level[i] != NIL)
3036 ListCell *prev = NULL;
3037 ListCell *next = NULL;
3038 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3041 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3045 if (hint->inner_nrels == 0 &&
3046 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3047 bms_equal(bms_union(hint->joinrelids, joinrelids),
3050 hstate->join_hint_level[i] =
3051 list_delete_cell(hstate->join_hint_level[i], l,
3060 bms_free(joinrelids);
3063 if (hint_state_enabled(lhint))
3065 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3072 * set_plain_rel_pathlist
3073 * Build access paths for a plain relation (no subquery, no inheritance)
3075 * This function was copied and edited from set_plain_rel_pathlist() in
3076 * src/backend/optimizer/path/allpaths.c
3079 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3081 /* Consider sequential scan */
3082 #if PG_VERSION_NUM >= 90200
3083 add_path(rel, create_seqscan_path(root, rel, NULL));
3085 add_path(rel, create_seqscan_path(root, rel));
3088 /* Consider index scans */
3089 create_index_paths(root, rel);
3091 /* Consider TID scans */
3092 create_tidscan_paths(root, rel);
3094 /* Now find the cheapest of the paths for this rel */
3099 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3104 foreach(l, initial_rels)
3106 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3108 ScanMethodHint *hint;
3110 /* Skip relations which we can't choose scan method. */
3111 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3114 rte = root->simple_rte_array[rel->relid];
3116 /* We can't force scan method of foreign tables */
3117 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3121 * Create scan paths with GUC parameters which are at the beginning of
3122 * planner if scan method hint is not specified, otherwise use
3123 * specified hints and mark the hint as used.
3125 if ((hint = find_scan_hint(root, rel)) == NULL)
3126 set_scan_config_options(hstate->init_scan_mask,
3130 set_scan_config_options(hint->enforce_mask, hstate->context);
3131 hint->base.state = HINT_STATE_USED;
3134 list_free_deep(rel->pathlist);
3135 rel->pathlist = NIL;
3138 /* It's an "append relation", process accordingly */
3139 set_append_rel_pathlist(root, rel, rel->relid, rte);
3143 set_plain_rel_pathlist(root, rel, rte);
3148 * Restore the GUC variables we set above.
3150 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3154 * wrapper of make_join_rel()
3156 * call make_join_rel() after changing enable_* parameters according to given
3160 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3163 JoinMethodHint *hint;
3167 joinrelids = bms_union(rel1->relids, rel2->relids);
3168 hint = find_join_hint(joinrelids);
3169 bms_free(joinrelids);
3172 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3174 if (hint->inner_nrels == 0)
3176 save_nestlevel = NewGUCNestLevel();
3178 set_join_config_options(hint->enforce_mask, current_hint->context);
3180 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3181 hint->base.state = HINT_STATE_USED;
3184 * Restore the GUC variables we set above.
3186 AtEOXact_GUC(true, save_nestlevel);
3189 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3198 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3199 RelOptInfo *joinrel,
3200 RelOptInfo *outerrel,
3201 RelOptInfo *innerrel,
3203 SpecialJoinInfo *sjinfo,
3206 ScanMethodHint *scan_hint = NULL;
3208 JoinMethodHint *join_hint;
3211 if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
3213 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3214 scan_hint->base.state = HINT_STATE_USED;
3217 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3218 join_hint = find_join_hint(joinrelids);
3219 bms_free(joinrelids);
3221 if (join_hint && join_hint->inner_nrels != 0)
3223 save_nestlevel = NewGUCNestLevel();
3225 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3228 set_join_config_options(join_hint->enforce_mask,
3229 current_hint->context);
3231 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3232 sjinfo, restrictlist);
3233 join_hint->base.state = HINT_STATE_USED;
3237 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3238 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3239 sjinfo, restrictlist);
3243 * Restore the GUC variables we set above.
3245 AtEOXact_GUC(true, save_nestlevel);
3248 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3249 sjinfo, restrictlist);
3251 if (scan_hint != NULL)
3252 set_scan_config_options(current_hint->init_scan_mask,
3253 current_hint->context);
3257 get_num_baserels(List *initial_rels)
3262 foreach(l, initial_rels)
3264 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3266 if (rel->reloptkind == RELOPT_BASEREL)
3268 else if (rel->reloptkind ==RELOPT_JOINREL)
3269 nbaserel+= bms_num_members(rel->relids);
3272 /* other values not expected here */
3273 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3281 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3284 JoinMethodHint **join_method_hints;
3288 bool leading_hint_enable;
3291 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3292 * valid hint is supplied.
3296 if (prev_join_search)
3297 return (*prev_join_search) (root, levels_needed, initial_rels);
3298 else if (enable_geqo && levels_needed >= geqo_threshold)
3299 return geqo(root, levels_needed, initial_rels);
3301 return standard_join_search(root, levels_needed, initial_rels);
3304 /* We apply scan method hint rebuild scan path. */
3305 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3308 * In the case using GEQO, only scan method hints and Set hints have
3309 * effect. Join method and join order is not controllable by hints.
3311 if (enable_geqo && levels_needed >= geqo_threshold)
3312 return geqo(root, levels_needed, initial_rels);
3314 nbaserel = get_num_baserels(initial_rels);
3315 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3316 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3318 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3319 initial_rels, join_method_hints);
3321 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3323 for (i = 2; i <= nbaserel; i++)
3325 list_free(current_hint->join_hint_level[i]);
3327 /* free Leading hint only */
3328 if (join_method_hints[i] != NULL &&
3329 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3330 JoinMethodHintDelete(join_method_hints[i]);
3332 pfree(current_hint->join_hint_level);
3333 pfree(join_method_hints);
3335 if (leading_hint_enable)
3336 set_join_config_options(current_hint->init_join_mask,
3337 current_hint->context);
3344 * Build access paths for a base relation
3346 * This function was copied and edited from set_rel_pathlist() in
3347 * src/backend/optimizer/path/allpaths.c
3350 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3351 Index rti, RangeTblEntry *rte)
3353 #if PG_VERSION_NUM >= 90200
3354 if (IS_DUMMY_REL(rel))
3356 /* We already proved the relation empty, so nothing more to do */
3363 /* It's an "append relation", process accordingly */
3364 set_append_rel_pathlist(root, rel, rti, rte);
3368 if (rel->rtekind == RTE_RELATION)
3370 if (rte->relkind == RELKIND_RELATION)
3372 /* Plain relation */
3373 set_plain_rel_pathlist(root, rel, rte);
3376 elog(ERROR, "unexpected relkind: %c", rte->relkind);
3379 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
3383 #define standard_join_search pg_hint_plan_standard_join_search
3384 #define join_search_one_level pg_hint_plan_join_search_one_level
3385 #define make_join_rel make_join_rel_wrapper
3388 #undef make_join_rel
3389 #define make_join_rel pg_hint_plan_make_join_rel
3390 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
3391 #include "make_join_rel.c"