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"
36 #include "catalog/pg_class.h"
38 #include "executor/spi.h"
39 #include "catalog/pg_type.h"
41 * We have our own header file "plpgsql-9.1", which is necessary to support
42 * hints for queries in PL/pgSQL blocks, in pg_hint_plan source package,
43 * because PostgreSQL 9.1 doesn't provide the header file as a part of
44 * installation. This header file is a copy of src/pl/plpgsql/src/plpgsql.h in
45 * PostgreSQL 9.1.9 source tree,
47 * On the other hand, 9.2 installation provides that header file for external
48 * modules, so we include the header in ordinary place.
52 /* partially copied from pg_stat_statements */
53 #include "normalize_query.h"
56 #include "htup_details.h"
58 #ifdef PG_MODULE_MAGIC
62 #define BLOCK_COMMENT_START "/*"
63 #define BLOCK_COMMENT_END "*/"
64 #define HINT_COMMENT_KEYWORD "+"
65 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
66 #define HINT_END BLOCK_COMMENT_END
69 #define HINT_SEQSCAN "SeqScan"
70 #define HINT_INDEXSCAN "IndexScan"
71 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
72 #define HINT_BITMAPSCAN "BitmapScan"
73 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
74 #define HINT_TIDSCAN "TidScan"
75 #define HINT_NOSEQSCAN "NoSeqScan"
76 #define HINT_NOINDEXSCAN "NoIndexScan"
77 #define HINT_NOBITMAPSCAN "NoBitmapScan"
78 #define HINT_NOTIDSCAN "NoTidScan"
79 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
80 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
81 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
82 #define HINT_NESTLOOP "NestLoop"
83 #define HINT_MERGEJOIN "MergeJoin"
84 #define HINT_HASHJOIN "HashJoin"
85 #define HINT_NONESTLOOP "NoNestLoop"
86 #define HINT_NOMERGEJOIN "NoMergeJoin"
87 #define HINT_NOHASHJOIN "NoHashJoin"
88 #define HINT_LEADING "Leading"
89 #define HINT_SET "Set"
91 #define HINT_ARRAY_DEFAULT_INITSIZE 8
93 #define hint_ereport(str, detail) \
94 ereport(pg_hint_plan_parse_messages, \
95 (errmsg("hint syntax error at or near \"%s\"", (str)), \
98 #define skip_space(str) \
99 while (isspace(*str)) \
104 ENABLE_SEQSCAN = 0x01,
105 ENABLE_INDEXSCAN = 0x02,
106 ENABLE_BITMAPSCAN = 0x04,
107 ENABLE_TIDSCAN = 0x08,
108 ENABLE_INDEXONLYSCAN = 0x10
113 ENABLE_NESTLOOP = 0x01,
114 ENABLE_MERGEJOIN = 0x02,
115 ENABLE_HASHJOIN = 0x04
118 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
119 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
120 ENABLE_INDEXONLYSCAN)
121 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
122 #define DISABLE_ALL_SCAN 0
123 #define DISABLE_ALL_JOIN 0
125 /* hint keyword of enum type*/
126 typedef enum HintKeyword
128 HINT_KEYWORD_SEQSCAN,
129 HINT_KEYWORD_INDEXSCAN,
130 HINT_KEYWORD_INDEXSCANREGEXP,
131 HINT_KEYWORD_BITMAPSCAN,
132 HINT_KEYWORD_BITMAPSCANREGEXP,
133 HINT_KEYWORD_TIDSCAN,
134 HINT_KEYWORD_NOSEQSCAN,
135 HINT_KEYWORD_NOINDEXSCAN,
136 HINT_KEYWORD_NOBITMAPSCAN,
137 HINT_KEYWORD_NOTIDSCAN,
138 HINT_KEYWORD_INDEXONLYSCAN,
139 HINT_KEYWORD_INDEXONLYSCANREGEXP,
140 HINT_KEYWORD_NOINDEXONLYSCAN,
141 HINT_KEYWORD_NESTLOOP,
142 HINT_KEYWORD_MERGEJOIN,
143 HINT_KEYWORD_HASHJOIN,
144 HINT_KEYWORD_NONESTLOOP,
145 HINT_KEYWORD_NOMERGEJOIN,
146 HINT_KEYWORD_NOHASHJOIN,
147 HINT_KEYWORD_LEADING,
149 HINT_KEYWORD_UNRECOGNIZED
152 typedef struct Hint Hint;
153 typedef struct HintState HintState;
155 typedef Hint *(*HintCreateFunction) (const char *hint_str,
157 HintKeyword hint_keyword);
158 typedef void (*HintDeleteFunction) (Hint *hint);
159 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf);
160 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
161 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
162 Query *parse, const char *str);
165 #define NUM_HINT_TYPE 4
166 typedef enum HintType
168 HINT_TYPE_SCAN_METHOD,
169 HINT_TYPE_JOIN_METHOD,
174 static const char *HintTypeName[] = {
182 typedef enum HintStatus
184 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
185 HINT_STATE_USED, /* hint is used */
186 HINT_STATE_DUPLICATION, /* specified hint duplication */
187 HINT_STATE_ERROR /* execute error (parse error does not include
191 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
192 (hint)->base.state == HINT_STATE_USED)
194 /* common data for all hints. */
197 const char *hint_str; /* must not do pfree */
198 const char *keyword; /* must not do pfree */
199 HintKeyword hint_keyword;
202 HintDeleteFunction delete_func;
203 HintDescFunction desc_func;
204 HintCmpFunction cmp_func;
205 HintParseFunction parse_func;
208 /* scan method hints */
209 typedef struct ScanMethodHint
215 unsigned char enforce_mask;
218 typedef struct ParentIndexInfo
223 char *expression_str;
230 /* join method hints */
231 typedef struct JoinMethodHint
237 unsigned char enforce_mask;
239 Relids inner_joinrelids;
242 /* join order hints */
243 typedef struct OuterInnerRels
246 List *outer_inner_pair;
249 typedef struct LeadingHint
252 List *relations; /* relation names specified in Leading hint */
253 OuterInnerRels *outer_inner;
256 /* change a run-time parameter hints */
257 typedef struct SetHint
260 char *name; /* name of variable */
266 * Describes a context of hint processing.
270 char *hint_str; /* original hint string */
273 int nall_hints; /* # of valid all hints */
274 int max_all_hints; /* # of slots for all hints */
275 Hint **all_hints; /* parsed all hints */
277 /* # of each hints */
278 int num_hints[NUM_HINT_TYPE];
280 /* for scan method hints */
281 ScanMethodHint **scan_hints; /* parsed scan hints */
282 int init_scan_mask; /* initial value scan parameter */
283 Index parent_relid; /* inherit parent table relid */
284 Oid parent_rel_oid; /* inherit parent table relid */
285 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
286 List *parent_index_infos; /* information of inherit parent table's
289 /* for join method hints */
290 JoinMethodHint **join_hints; /* parsed join hints */
291 int init_join_mask; /* initial value join parameter */
292 List **join_hint_level;
294 /* for Leading hint */
295 LeadingHint **leading_hint; /* parsed Leading hints */
298 SetHint **set_hints; /* parsed Set hints */
299 GucContext context; /* which GUC parameters can we set? */
303 * Describes a hint parser module which is bound with particular hint keyword.
305 typedef struct HintParser
308 HintCreateFunction create_func;
309 HintKeyword hint_keyword;
312 /* Module callbacks */
316 static void push_hint(HintState *hstate);
317 static void pop_hint(void);
319 static void pg_hint_plan_ProcessUtility(Node *parsetree,
320 const char *queryString,
321 ProcessUtilityContext context,
322 ParamListInfo params,
323 DestReceiver *dest, 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 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
380 List *live_childrels,
381 List *all_child_pathkeys);
382 static List *accumulate_append_subpath(List *subpaths, Path *path);
383 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
386 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
388 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
392 static bool pg_hint_plan_enable_hint = true;
393 static bool pg_hint_plan_debug_print = false;
394 static int pg_hint_plan_parse_messages = INFO;
395 /* Default is off, to keep backward compatibility. */
396 static bool pg_hint_plan_enable_hint_table = false;
398 static const struct config_enum_entry parse_messages_level_options[] = {
399 {"debug", DEBUG2, true},
400 {"debug5", DEBUG5, false},
401 {"debug4", DEBUG4, false},
402 {"debug3", DEBUG3, false},
403 {"debug2", DEBUG2, false},
404 {"debug1", DEBUG1, false},
406 {"info", INFO, false},
407 {"notice", NOTICE, false},
408 {"warning", WARNING, false},
409 {"error", ERROR, false},
411 * {"fatal", FATAL, true},
412 * {"panic", PANIC, true},
417 /* Saved hook values in case of unload */
418 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
419 static planner_hook_type prev_planner = NULL;
420 static get_relation_info_hook_type prev_get_relation_info = NULL;
421 static join_search_hook_type prev_join_search = NULL;
423 /* Hold reference to currently active hint */
424 static HintState *current_hint = NULL;
427 * List of hint contexts. We treat the head of the list as the Top of the
428 * context stack, so current_hint always points the first element of this list.
430 static List *HintStateStack = NIL;
433 * Holds statement name during executing EXECUTE command. NULL for other
436 static char *stmt_name = NULL;
438 static const HintParser parsers[] = {
439 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
440 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
441 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
442 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
443 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
444 HINT_KEYWORD_BITMAPSCANREGEXP},
445 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
446 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
447 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
448 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
449 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
450 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
451 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
452 HINT_KEYWORD_INDEXONLYSCANREGEXP},
453 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
454 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
455 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
456 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
457 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
458 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
459 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
460 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
461 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
462 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
466 * PL/pgSQL plugin for retrieving string representation of each query during
467 * function execution.
469 const char *plpgsql_query_string = NULL;
470 PLpgSQL_plugin plugin_funcs = {
474 pg_hint_plan_plpgsql_stmt_beg,
475 pg_hint_plan_plpgsql_stmt_end,
480 /* Current nesting depth of SPI calls, used to prevent recursive calls */
481 static int nested_level = 0;
484 * Module load callbacks
489 PLpgSQL_plugin **var_ptr;
491 /* Define custom GUC variables. */
492 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
493 "Force planner to use plans specified in the hint comment preceding to the query.",
495 &pg_hint_plan_enable_hint,
503 DefineCustomBoolVariable("pg_hint_plan.debug_print",
504 "Logs results of hint parsing.",
506 &pg_hint_plan_debug_print,
514 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
515 "Message level of parse errors.",
517 &pg_hint_plan_parse_messages,
519 parse_messages_level_options,
526 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
527 "Force planner to not get hint by using table lookups.",
529 &pg_hint_plan_enable_hint_table,
538 prev_ProcessUtility = ProcessUtility_hook;
539 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
540 prev_planner = planner_hook;
541 planner_hook = pg_hint_plan_planner;
542 prev_get_relation_info = get_relation_info_hook;
543 get_relation_info_hook = pg_hint_plan_get_relation_info;
544 prev_join_search = join_search_hook;
545 join_search_hook = pg_hint_plan_join_search;
547 /* setup PL/pgSQL plugin hook */
548 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
549 *var_ptr = &plugin_funcs;
553 * Module unload callback
559 PLpgSQL_plugin **var_ptr;
561 /* Uninstall hooks. */
562 ProcessUtility_hook = prev_ProcessUtility;
563 planner_hook = prev_planner;
564 get_relation_info_hook = prev_get_relation_info;
565 join_search_hook = prev_join_search;
567 /* uninstall PL/pgSQL plugin hook */
568 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
573 * create and delete functions the hint object
577 ScanMethodHintCreate(const char *hint_str, const char *keyword,
578 HintKeyword hint_keyword)
580 ScanMethodHint *hint;
582 hint = palloc(sizeof(ScanMethodHint));
583 hint->base.hint_str = hint_str;
584 hint->base.keyword = keyword;
585 hint->base.hint_keyword = hint_keyword;
586 hint->base.type = HINT_TYPE_SCAN_METHOD;
587 hint->base.state = HINT_STATE_NOTUSED;
588 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
589 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
590 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
591 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
592 hint->relname = NULL;
593 hint->indexnames = NIL;
594 hint->regexp = false;
595 hint->enforce_mask = 0;
597 return (Hint *) hint;
601 ScanMethodHintDelete(ScanMethodHint *hint)
607 pfree(hint->relname);
608 list_free_deep(hint->indexnames);
613 JoinMethodHintCreate(const char *hint_str, const char *keyword,
614 HintKeyword hint_keyword)
616 JoinMethodHint *hint;
618 hint = palloc(sizeof(JoinMethodHint));
619 hint->base.hint_str = hint_str;
620 hint->base.keyword = keyword;
621 hint->base.hint_keyword = hint_keyword;
622 hint->base.type = HINT_TYPE_JOIN_METHOD;
623 hint->base.state = HINT_STATE_NOTUSED;
624 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
625 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
626 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
627 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
629 hint->inner_nrels = 0;
630 hint->relnames = NULL;
631 hint->enforce_mask = 0;
632 hint->joinrelids = NULL;
633 hint->inner_joinrelids = NULL;
635 return (Hint *) hint;
639 JoinMethodHintDelete(JoinMethodHint *hint)
648 for (i = 0; i < hint->nrels; i++)
649 pfree(hint->relnames[i]);
650 pfree(hint->relnames);
653 bms_free(hint->joinrelids);
654 bms_free(hint->inner_joinrelids);
659 LeadingHintCreate(const char *hint_str, const char *keyword,
660 HintKeyword hint_keyword)
664 hint = palloc(sizeof(LeadingHint));
665 hint->base.hint_str = hint_str;
666 hint->base.keyword = keyword;
667 hint->base.hint_keyword = hint_keyword;
668 hint->base.type = HINT_TYPE_LEADING;
669 hint->base.state = HINT_STATE_NOTUSED;
670 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
671 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
672 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
673 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
674 hint->relations = NIL;
675 hint->outer_inner = NULL;
677 return (Hint *) hint;
681 LeadingHintDelete(LeadingHint *hint)
686 list_free_deep(hint->relations);
687 if (hint->outer_inner)
688 pfree(hint->outer_inner);
693 SetHintCreate(const char *hint_str, const char *keyword,
694 HintKeyword hint_keyword)
698 hint = palloc(sizeof(SetHint));
699 hint->base.hint_str = hint_str;
700 hint->base.keyword = keyword;
701 hint->base.hint_keyword = hint_keyword;
702 hint->base.type = HINT_TYPE_SET;
703 hint->base.state = HINT_STATE_NOTUSED;
704 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
705 hint->base.desc_func = (HintDescFunction) SetHintDesc;
706 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
707 hint->base.parse_func = (HintParseFunction) SetHintParse;
712 return (Hint *) hint;
716 SetHintDelete(SetHint *hint)
726 list_free(hint->words);
731 HintStateCreate(void)
735 hstate = palloc(sizeof(HintState));
736 hstate->hint_str = NULL;
737 hstate->nall_hints = 0;
738 hstate->max_all_hints = 0;
739 hstate->all_hints = NULL;
740 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
741 hstate->scan_hints = NULL;
742 hstate->init_scan_mask = 0;
743 hstate->parent_relid = 0;
744 hstate->parent_rel_oid = InvalidOid;
745 hstate->parent_hint = NULL;
746 hstate->parent_index_infos = NIL;
747 hstate->join_hints = NULL;
748 hstate->init_join_mask = 0;
749 hstate->join_hint_level = NULL;
750 hstate->leading_hint = NULL;
751 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
752 hstate->set_hints = NULL;
758 HintStateDelete(HintState *hstate)
765 if (hstate->hint_str)
766 pfree(hstate->hint_str);
768 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
769 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
770 if (hstate->all_hints)
771 pfree(hstate->all_hints);
772 if (hstate->parent_index_infos)
773 list_free(hstate->parent_index_infos);
777 * Copy given value into buf, with quoting with '"' if necessary.
780 quote_value(StringInfo buf, const char *value)
782 bool need_quote = false;
785 for (str = value; *str != '\0'; str++)
787 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
790 appendStringInfoCharMacro(buf, '"');
795 for (str = value; *str != '\0'; str++)
798 appendStringInfoCharMacro(buf, '"');
800 appendStringInfoCharMacro(buf, *str);
804 appendStringInfoCharMacro(buf, '"');
808 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
812 appendStringInfo(buf, "%s(", hint->base.keyword);
813 if (hint->relname != NULL)
815 quote_value(buf, hint->relname);
816 foreach(l, hint->indexnames)
818 appendStringInfoCharMacro(buf, ' ');
819 quote_value(buf, (char *) lfirst(l));
822 appendStringInfoString(buf, ")\n");
826 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
830 appendStringInfo(buf, "%s(", hint->base.keyword);
831 if (hint->relnames != NULL)
833 quote_value(buf, hint->relnames[0]);
834 for (i = 1; i < hint->nrels; i++)
836 appendStringInfoCharMacro(buf, ' ');
837 quote_value(buf, hint->relnames[i]);
840 appendStringInfoString(buf, ")\n");
845 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
847 if (outer_inner->relation == NULL)
854 appendStringInfoCharMacro(buf, '(');
855 foreach(l, outer_inner->outer_inner_pair)
860 appendStringInfoCharMacro(buf, ' ');
862 OuterInnerDesc(lfirst(l), buf);
865 appendStringInfoCharMacro(buf, ')');
868 quote_value(buf, outer_inner->relation);
872 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
874 appendStringInfo(buf, "%s(", HINT_LEADING);
875 if (hint->outer_inner == NULL)
882 foreach(l, hint->relations)
887 appendStringInfoCharMacro(buf, ' ');
889 quote_value(buf, (char *) lfirst(l));
893 OuterInnerDesc(hint->outer_inner, buf);
895 appendStringInfoString(buf, ")\n");
899 SetHintDesc(SetHint *hint, StringInfo buf)
901 bool is_first = true;
904 appendStringInfo(buf, "%s(", HINT_SET);
905 foreach(l, hint->words)
910 appendStringInfoCharMacro(buf, ' ');
912 quote_value(buf, (char *) lfirst(l));
914 appendStringInfo(buf, ")\n");
918 * Append string which represents all hints in a given state to buf, with
919 * preceding title with them.
922 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
927 appendStringInfo(buf, "%s:\n", title);
928 for (i = 0; i < hstate->nall_hints; i++)
930 if (hstate->all_hints[i]->state != state)
933 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf);
938 * Dump contents of given hstate to server log with log level LOG.
941 HintStateDump(HintState *hstate)
947 elog(LOG, "pg_hint_plan:\nno hint");
951 initStringInfo(&buf);
953 appendStringInfoString(&buf, "pg_hint_plan:\n");
954 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
955 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
956 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
957 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
959 elog(LOG, "%s", buf.data);
969 RelnameCmp(const void *a, const void *b)
971 const char *relnamea = *((const char **) a);
972 const char *relnameb = *((const char **) b);
974 return strcmp(relnamea, relnameb);
978 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
980 return RelnameCmp(&a->relname, &b->relname);
984 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
988 if (a->nrels != b->nrels)
989 return a->nrels - b->nrels;
991 for (i = 0; i < a->nrels; i++)
994 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1002 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1008 SetHintCmp(const SetHint *a, const SetHint *b)
1010 return strcmp(a->name, b->name);
1014 HintCmp(const void *a, const void *b)
1016 const Hint *hinta = *((const Hint **) a);
1017 const Hint *hintb = *((const Hint **) b);
1019 if (hinta->type != hintb->type)
1020 return hinta->type - hintb->type;
1021 if (hinta->state == HINT_STATE_ERROR)
1023 if (hintb->state == HINT_STATE_ERROR)
1025 return hinta->cmp_func(hinta, hintb);
1029 * Returns byte offset of hint b from hint a. If hint a was specified before
1030 * b, positive value is returned.
1033 HintCmpWithPos(const void *a, const void *b)
1035 const Hint *hinta = *((const Hint **) a);
1036 const Hint *hintb = *((const Hint **) b);
1039 result = HintCmp(a, b);
1041 result = hinta->hint_str - hintb->hint_str;
1050 parse_keyword(const char *str, StringInfo buf)
1054 while (!isspace(*str) && *str != '(' && *str != '\0')
1055 appendStringInfoCharMacro(buf, *str++);
1061 skip_parenthesis(const char *str, char parenthesis)
1065 if (*str != parenthesis)
1067 if (parenthesis == '(')
1068 hint_ereport(str, ("Opening parenthesis is necessary."));
1069 else if (parenthesis == ')')
1070 hint_ereport(str, ("Closing parenthesis is necessary."));
1081 * Parse a token from str, and store malloc'd copy into word. A token can be
1082 * quoted with '"'. Return value is pointer to unparsed portion of original
1083 * string, or NULL if an error occurred.
1085 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1088 parse_quoted_value(const char *str, char **word, bool truncate)
1093 /* Skip leading spaces. */
1096 initStringInfo(&buf);
1109 /* Double quotation must be closed. */
1113 hint_ereport(str, ("Unterminated quoted string."));
1118 * Skip escaped double quotation.
1120 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1121 * block comments) to be an object name, so users must specify
1122 * alias for such object names.
1124 * Those special names can be allowed if we care escaped slashes
1125 * and asterisks, but we don't.
1134 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1138 appendStringInfoCharMacro(&buf, *str++);
1143 hint_ereport(str, ("Zero-length delimited string."));
1150 /* Truncate name if it's too long */
1152 truncate_identifier(buf.data, strlen(buf.data), true);
1159 static OuterInnerRels *
1160 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1162 OuterInnerRels *outer_inner;
1164 outer_inner = palloc(sizeof(OuterInnerRels));
1165 outer_inner->relation = name;
1166 outer_inner->outer_inner_pair = outer_inner_list;
1172 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1174 List *outer_inner_pair = NIL;
1176 if ((str = skip_parenthesis(str, '(')) == NULL)
1181 /* Store words in parentheses into outer_inner_list. */
1182 while(*str != ')' && *str != '\0')
1184 OuterInnerRels *outer_inner_rels;
1188 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1196 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1199 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1202 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1207 (str = skip_parenthesis(str, ')')) == NULL)
1209 list_free(outer_inner_pair);
1213 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1219 parse_parentheses_Leading(const char *str, List **name_list,
1220 OuterInnerRels **outer_inner)
1223 bool truncate = true;
1225 if ((str = skip_parenthesis(str, '(')) == NULL)
1231 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1236 /* Store words in parentheses into name_list. */
1237 while(*str != ')' && *str != '\0')
1239 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1241 list_free(*name_list);
1245 *name_list = lappend(*name_list, name);
1250 if ((str = skip_parenthesis(str, ')')) == NULL)
1256 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1259 bool truncate = true;
1261 if ((str = skip_parenthesis(str, '(')) == NULL)
1266 /* Store words in parentheses into name_list. */
1267 while(*str != ')' && *str != '\0')
1269 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1271 list_free(*name_list);
1275 *name_list = lappend(*name_list, name);
1278 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1279 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1280 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1281 keyword == HINT_KEYWORD_SET)
1287 if ((str = skip_parenthesis(str, ')')) == NULL)
1293 parse_hints(HintState *hstate, Query *parse, const char *str)
1298 initStringInfo(&buf);
1299 while (*str != '\0')
1301 const HintParser *parser;
1303 /* in error message, we output the comment including the keyword. */
1304 head = (char *) str;
1306 /* parse only the keyword of the hint. */
1307 resetStringInfo(&buf);
1308 str = parse_keyword(str, &buf);
1310 for (parser = parsers; parser->keyword != NULL; parser++)
1312 char *keyword = parser->keyword;
1315 if (strcasecmp(buf.data, keyword) != 0)
1318 hint = parser->create_func(head, keyword, parser->hint_keyword);
1320 /* parser of each hint does parse in a parenthesis. */
1321 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1323 hint->delete_func(hint);
1329 * Add hint information into all_hints array. If we don't have
1330 * enough space, double the array.
1332 if (hstate->nall_hints == 0)
1334 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1335 hstate->all_hints = (Hint **)
1336 palloc(sizeof(Hint *) * hstate->max_all_hints);
1338 else if (hstate->nall_hints == hstate->max_all_hints)
1340 hstate->max_all_hints *= 2;
1341 hstate->all_hints = (Hint **)
1342 repalloc(hstate->all_hints,
1343 sizeof(Hint *) * hstate->max_all_hints);
1346 hstate->all_hints[hstate->nall_hints] = hint;
1347 hstate->nall_hints++;
1354 if (parser->keyword == NULL)
1357 ("Unrecognized hint keyword \"%s\".", buf.data));
1368 * Get hints from table by client-supplied query string and application name.
1371 get_hints_from_table(const char *client_query, const char *client_application)
1373 const char *search_query =
1375 " FROM hint_plan.hints "
1376 " WHERE norm_query_string = $1 "
1377 " AND ( application_name = $2 "
1378 " OR application_name = '' ) "
1379 " ORDER BY application_name DESC";
1380 static SPIPlanPtr plan = NULL;
1382 Oid argtypes[2] = { TEXTOID, TEXTOID };
1384 bool nulls[2] = { false, false };
1397 p = SPI_prepare(search_query, 2, argtypes);
1398 plan = SPI_saveplan(p);
1402 qry = cstring_to_text(client_query);
1403 app = cstring_to_text(client_application);
1404 values[0] = PointerGetDatum(qry);
1405 values[1] = PointerGetDatum(app);
1407 SPI_execute_plan(plan, values, nulls, true, 1);
1409 if (SPI_processed > 0)
1413 hints = SPI_getvalue(SPI_tuptable->vals[0],
1414 SPI_tuptable->tupdesc, 1);
1416 * Here we use SPI_palloc to ensure that hints string is valid even
1417 * after SPI_finish call. We can't use simple palloc because it
1418 * allocates memory in SPI's context and that context is deleted in
1421 buf = SPI_palloc(strlen(hints) + 1);
1441 * Get client-supplied query string.
1444 get_query_string(void)
1450 PreparedStatement *entry;
1452 entry = FetchPreparedStatement(stmt_name, true);
1453 p = entry->plansource->query_string;
1455 else if (plpgsql_query_string)
1456 p = plpgsql_query_string;
1458 p = debug_query_string;
1464 * Get hints from the head block comment in client-supplied query string.
1467 get_hints_from_comment(const char *p)
1469 const char *hint_head;
1477 /* extract query head comment. */
1478 hint_head = strstr(p, HINT_START);
1479 if (hint_head == NULL)
1481 for (;p < hint_head; p++)
1484 * Allow these characters precedes hint comment:
1486 * - alphabets which are in ASCII range
1487 * - space, tabs and new-lines
1488 * - underscores, for identifier
1489 * - commas, for SELECT clause, EXPLAIN and PREPARE
1490 * - parentheses, for EXPLAIN and PREPARE
1492 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1493 * avoid behavior which depends on locale setting.
1495 if (!(*p >= '0' && *p <= '9') &&
1496 !(*p >= 'A' && *p <= 'Z') &&
1497 !(*p >= 'a' && *p <= 'z') &&
1501 *p != '(' && *p != ')')
1505 len = strlen(HINT_START);
1510 /* find hint end keyword. */
1511 if ((tail = strstr(p, HINT_END)) == NULL)
1513 hint_ereport(head, ("Unterminated block comment."));
1517 /* We don't support nested block comments. */
1518 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1520 hint_ereport(head, ("Nested block comments are not supported."));
1524 /* Make a copy of hint. */
1526 head = palloc(len + 1);
1527 memcpy(head, p, len);
1535 * Parse hints that got, create hint struct from parse tree and parse hints.
1538 create_hintstate(Query *parse, const char *hints)
1548 hstate = HintStateCreate();
1549 hstate->hint_str = (char *) hints;
1551 /* parse each hint. */
1552 parse_hints(hstate, parse, p);
1554 /* When nothing specified a hint, we free HintState and returns NULL. */
1555 if (hstate->nall_hints == 0)
1557 HintStateDelete(hstate);
1561 /* Sort hints in order of original position. */
1562 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1565 /* Count number of hints per hint-type. */
1566 for (i = 0; i < hstate->nall_hints; i++)
1568 Hint *cur_hint = hstate->all_hints[i];
1569 hstate->num_hints[cur_hint->type]++;
1573 * If an object (or a set of objects) has multiple hints of same hint-type,
1574 * only the last hint is valid and others are ignored in planning.
1575 * Hints except the last are marked as 'duplicated' to remember the order.
1577 for (i = 0; i < hstate->nall_hints - 1; i++)
1579 Hint *cur_hint = hstate->all_hints[i];
1580 Hint *next_hint = hstate->all_hints[i + 1];
1583 * Leading hint is marked as 'duplicated' in transform_join_hints.
1585 if (cur_hint->type == HINT_TYPE_LEADING &&
1586 next_hint->type == HINT_TYPE_LEADING)
1590 * Note that we need to pass addresses of hint pointers, because
1591 * HintCmp is designed to sort array of Hint* by qsort.
1593 if (HintCmp(&cur_hint, &next_hint) == 0)
1595 hint_ereport(cur_hint->hint_str,
1596 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1597 cur_hint->state = HINT_STATE_DUPLICATION;
1602 * Make sure that per-type array pointers point proper position in the
1603 * array which consists of all hints.
1605 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1606 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1607 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1608 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1609 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1610 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1611 hstate->num_hints[HINT_TYPE_LEADING]);
1617 * Parse inside of parentheses of scan-method hints.
1620 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1623 const char *keyword = hint->base.keyword;
1624 HintKeyword hint_keyword = hint->base.hint_keyword;
1625 List *name_list = NIL;
1628 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1631 /* Parse relation name and index name(s) if given hint accepts. */
1632 length = list_length(name_list);
1635 hint->relname = linitial(name_list);
1636 hint->indexnames = list_delete_first(name_list);
1638 /* check whether the hint accepts index name(s). */
1640 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1641 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1642 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1643 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1644 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1645 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1648 ("%s hint accepts only one relation.",
1649 hint->base.keyword));
1650 hint->base.state = HINT_STATE_ERROR;
1657 ("%s hint requires a relation.",
1658 hint->base.keyword));
1659 hint->base.state = HINT_STATE_ERROR;
1663 /* Set a bit for specified hint. */
1664 switch (hint_keyword)
1666 case HINT_KEYWORD_SEQSCAN:
1667 hint->enforce_mask = ENABLE_SEQSCAN;
1669 case HINT_KEYWORD_INDEXSCAN:
1670 hint->enforce_mask = ENABLE_INDEXSCAN;
1672 case HINT_KEYWORD_INDEXSCANREGEXP:
1673 hint->enforce_mask = ENABLE_INDEXSCAN;
1674 hint->regexp = true;
1676 case HINT_KEYWORD_BITMAPSCAN:
1677 hint->enforce_mask = ENABLE_BITMAPSCAN;
1679 case HINT_KEYWORD_BITMAPSCANREGEXP:
1680 hint->enforce_mask = ENABLE_BITMAPSCAN;
1681 hint->regexp = true;
1683 case HINT_KEYWORD_TIDSCAN:
1684 hint->enforce_mask = ENABLE_TIDSCAN;
1686 case HINT_KEYWORD_NOSEQSCAN:
1687 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1689 case HINT_KEYWORD_NOINDEXSCAN:
1690 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1692 case HINT_KEYWORD_NOBITMAPSCAN:
1693 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1695 case HINT_KEYWORD_NOTIDSCAN:
1696 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1698 case HINT_KEYWORD_INDEXONLYSCAN:
1699 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1701 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1702 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1703 hint->regexp = true;
1705 case HINT_KEYWORD_NOINDEXONLYSCAN:
1706 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1709 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1718 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1721 const char *keyword = hint->base.keyword;
1722 HintKeyword hint_keyword = hint->base.hint_keyword;
1723 List *name_list = NIL;
1725 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1728 hint->nrels = list_length(name_list);
1730 if (hint->nrels > 0)
1736 * Transform relation names from list to array to sort them with qsort
1739 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1740 foreach (l, name_list)
1742 hint->relnames[i] = lfirst(l);
1747 list_free(name_list);
1749 /* A join hint requires at least two relations */
1750 if (hint->nrels < 2)
1753 ("%s hint requires at least two relations.",
1754 hint->base.keyword));
1755 hint->base.state = HINT_STATE_ERROR;
1759 /* Sort hints in alphabetical order of relation names. */
1760 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1762 switch (hint_keyword)
1764 case HINT_KEYWORD_NESTLOOP:
1765 hint->enforce_mask = ENABLE_NESTLOOP;
1767 case HINT_KEYWORD_MERGEJOIN:
1768 hint->enforce_mask = ENABLE_MERGEJOIN;
1770 case HINT_KEYWORD_HASHJOIN:
1771 hint->enforce_mask = ENABLE_HASHJOIN;
1773 case HINT_KEYWORD_NONESTLOOP:
1774 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1776 case HINT_KEYWORD_NOMERGEJOIN:
1777 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1779 case HINT_KEYWORD_NOHASHJOIN:
1780 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1783 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1792 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1795 if (outer_inner->outer_inner_pair == NIL)
1797 if (outer_inner->relation)
1803 if (list_length(outer_inner->outer_inner_pair) == 2)
1805 foreach(l, outer_inner->outer_inner_pair)
1807 if (!OuterInnerPairCheck(lfirst(l)))
1818 OuterInnerList(OuterInnerRels *outer_inner)
1820 List *outer_inner_list = NIL;
1822 OuterInnerRels *outer_inner_rels;
1824 foreach(l, outer_inner->outer_inner_pair)
1826 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
1828 if (outer_inner_rels->relation != NULL)
1829 outer_inner_list = lappend(outer_inner_list,
1830 outer_inner_rels->relation);
1832 outer_inner_list = list_concat(outer_inner_list,
1833 OuterInnerList(outer_inner_rels));
1835 return outer_inner_list;
1839 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1842 List *name_list = NIL;
1843 OuterInnerRels *outer_inner = NULL;
1845 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
1849 if (outer_inner != NULL)
1850 name_list = OuterInnerList(outer_inner);
1852 hint->relations = name_list;
1853 hint->outer_inner = outer_inner;
1855 /* A Leading hint requires at least two relations */
1856 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
1858 hint_ereport(hint->base.hint_str,
1859 ("%s hint requires at least two relations.",
1861 hint->base.state = HINT_STATE_ERROR;
1863 else if (hint->outer_inner != NULL &&
1864 !OuterInnerPairCheck(hint->outer_inner))
1866 hint_ereport(hint->base.hint_str,
1867 ("%s hint requires two sets of relations when parentheses nests.",
1869 hint->base.state = HINT_STATE_ERROR;
1876 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1878 List *name_list = NIL;
1880 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
1884 hint->words = name_list;
1886 /* We need both name and value to set GUC parameter. */
1887 if (list_length(name_list) == 2)
1889 hint->name = linitial(name_list);
1890 hint->value = lsecond(name_list);
1894 hint_ereport(hint->base.hint_str,
1895 ("%s hint requires name and value of GUC parameter.",
1897 hint->base.state = HINT_STATE_ERROR;
1904 * set GUC parameter functions
1908 set_config_option_wrapper(const char *name, const char *value,
1909 GucContext context, GucSource source,
1910 GucAction action, bool changeVal, int elevel)
1913 MemoryContext ccxt = CurrentMemoryContext;
1917 result = set_config_option(name, value, context, source,
1918 action, changeVal, 0);
1924 /* Save error info */
1925 MemoryContextSwitchTo(ccxt);
1926 errdata = CopyErrorData();
1929 ereport(elevel, (errcode(errdata->sqlerrcode),
1930 errmsg("%s", errdata->message),
1931 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1932 errdata->hint ? errhint("%s", errdata->hint) : 0));
1933 FreeErrorData(errdata);
1941 set_config_options(SetHint **options, int noptions, GucContext context)
1946 save_nestlevel = NewGUCNestLevel();
1948 for (i = 0; i < noptions; i++)
1950 SetHint *hint = options[i];
1953 if (!hint_state_enabled(hint))
1956 result = set_config_option_wrapper(hint->name, hint->value, context,
1957 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1958 pg_hint_plan_parse_messages);
1960 hint->base.state = HINT_STATE_USED;
1962 hint->base.state = HINT_STATE_ERROR;
1965 return save_nestlevel;
1968 #define SET_CONFIG_OPTION(name, type_bits) \
1969 set_config_option_wrapper((name), \
1970 (mask & (type_bits)) ? "true" : "false", \
1971 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1974 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1978 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1979 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1980 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1982 mask = enforce_mask;
1984 mask = enforce_mask & current_hint->init_scan_mask;
1986 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1987 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1988 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1989 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1990 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1994 set_join_config_options(unsigned char enforce_mask, GucContext context)
1998 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1999 enforce_mask == ENABLE_HASHJOIN)
2000 mask = enforce_mask;
2002 mask = enforce_mask & current_hint->init_join_mask;
2004 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2005 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2006 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2010 * pg_hint_plan hook functions
2014 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
2015 ProcessUtilityContext context,
2016 ParamListInfo params,
2017 DestReceiver *dest, char *completionTag)
2022 * Use standard planner if pg_hint_plan is disabled or current nesting
2023 * depth is nesting depth of SPI calls.
2025 if (!pg_hint_plan_enable_hint || nested_level > 0)
2027 if (prev_ProcessUtility)
2028 (*prev_ProcessUtility) (parsetree, queryString,
2030 dest, completionTag);
2032 standard_ProcessUtility(parsetree, queryString,
2034 dest, completionTag);
2039 if (IsA(node, ExplainStmt))
2042 * Draw out parse tree of actual query from Query struct of EXPLAIN
2048 stmt = (ExplainStmt *) node;
2050 Assert(IsA(stmt->query, Query));
2051 query = (Query *) stmt->query;
2053 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2054 node = query->utilityStmt;
2058 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2059 * specified to preceding PREPARE command to use it as source of hints.
2061 if (IsA(node, ExecuteStmt))
2065 stmt = (ExecuteStmt *) node;
2066 stmt_name = stmt->name;
2070 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2073 if (IsA(node, CreateTableAsStmt))
2075 CreateTableAsStmt *stmt;
2078 stmt = (CreateTableAsStmt *) node;
2079 Assert(IsA(stmt->query, Query));
2080 query = (Query *) stmt->query;
2082 if (query->commandType == CMD_UTILITY &&
2083 IsA(query->utilityStmt, ExecuteStmt))
2085 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2086 stmt_name = estmt->name;
2094 if (prev_ProcessUtility)
2095 (*prev_ProcessUtility) (parsetree, queryString,
2097 dest, completionTag);
2099 standard_ProcessUtility(parsetree, queryString,
2101 dest, completionTag);
2115 if (prev_ProcessUtility)
2116 (*prev_ProcessUtility) (parsetree, queryString,
2118 dest, completionTag);
2120 standard_ProcessUtility(parsetree, queryString,
2122 dest, completionTag);
2126 * Push a hint into hint stack which is implemented with List struct. Head of
2127 * list is top of stack.
2130 push_hint(HintState *hstate)
2132 /* Prepend new hint to the list means pushing to stack. */
2133 HintStateStack = lcons(hstate, HintStateStack);
2135 /* Pushed hint is the one which should be used hereafter. */
2136 current_hint = hstate;
2139 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2143 /* Hint stack must not be empty. */
2144 if(HintStateStack == NIL)
2145 elog(ERROR, "hint stack is empty");
2148 * Take a hint at the head from the list, and free it. Switch current_hint
2149 * to point new head (NULL if the list is empty).
2151 HintStateStack = list_delete_first(HintStateStack);
2152 HintStateDelete(current_hint);
2153 if(HintStateStack == NIL)
2154 current_hint = NULL;
2156 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2159 static PlannedStmt *
2160 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2162 const char *hints = NULL;
2165 pgssJumbleState jstate;
2168 PlannedStmt *result;
2172 * Use standard planner if pg_hint_plan is disabled or current nesting
2173 * depth is nesting depth of SPI calls. Other hook functions try to change
2174 * plan with current_hint if any, so set it to NULL.
2176 if (!pg_hint_plan_enable_hint || nested_level > 0)
2177 goto standard_planner_proc;
2179 /* Create hint struct from client-supplied query string. */
2180 query = get_query_string();
2183 * Create hintstate from hint specified for the query, if any.
2185 * First we lookup hint in pg_hint.hints table by normalized query string,
2186 * unless pg_hint_plan.enable_hint_table is OFF.
2187 * This parameter provides option to avoid overhead of table lookup during
2190 * If no hint was found, then we try to get hint from special query comment.
2192 if (pg_hint_plan_enable_hint_table)
2195 * Search hint information which is stored for the query and the
2196 * application. Query string is normalized before using in condition
2197 * in order to allow fuzzy matching.
2199 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2200 * careful when supporting PostgreSQL's version up.
2202 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2203 jstate.jumble_len = 0;
2204 jstate.clocations_buf_size = 32;
2205 jstate.clocations = (pgssLocationLen *)
2206 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2207 jstate.clocations_count = 0;
2208 JumbleQuery(&jstate, parse);
2210 * generate_normalized_query() copies exact given query_len bytes, so we
2211 * add 1 byte for null-termination here. As comments on
2212 * generate_normalized_query says, generate_normalized_query doesn't
2213 * take care of null-terminate, but additional 1 byte ensures that '\0'
2214 * byte in the source buffer to be copied into norm_query.
2216 query_len = strlen(query) + 1;
2217 norm_query = generate_normalized_query(&jstate,
2220 GetDatabaseEncoding());
2221 hints = get_hints_from_table(norm_query, application_name);
2223 "pg_hint_plan: get_hints_from_table [%s][%s]=>[%s]",
2224 norm_query, application_name, hints ? hints : "(none)");
2227 hints = get_hints_from_comment(query);
2228 hstate = create_hintstate(parse, hints);
2231 * Use standard planner if the statement has not valid hint. Other hook
2232 * functions try to change plan with current_hint if any, so set it to
2236 goto standard_planner_proc;
2239 * Push new hint struct to the hint stack to disable previous hint context.
2243 /* Set GUC parameters which are specified with Set hint. */
2244 save_nestlevel = set_config_options(current_hint->set_hints,
2245 current_hint->num_hints[HINT_TYPE_SET],
2246 current_hint->context);
2249 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2250 if (enable_indexscan)
2251 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2252 if (enable_bitmapscan)
2253 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2255 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2256 if (enable_indexonlyscan)
2257 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2258 if (enable_nestloop)
2259 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2260 if (enable_mergejoin)
2261 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2262 if (enable_hashjoin)
2263 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2266 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2267 * state when this planner started when error occurred in planner.
2272 result = (*prev_planner) (parse, cursorOptions, boundParams);
2274 result = standard_planner(parse, cursorOptions, boundParams);
2279 * Rollback changes of GUC parameters, and pop current hint context
2280 * from hint stack to rewind the state.
2282 AtEOXact_GUC(true, save_nestlevel);
2288 /* Print hint in debug mode. */
2289 if (pg_hint_plan_debug_print)
2290 HintStateDump(current_hint);
2293 * Rollback changes of GUC parameters, and pop current hint context from
2294 * hint stack to rewind the state.
2296 AtEOXact_GUC(true, save_nestlevel);
2301 standard_planner_proc:
2302 current_hint = NULL;
2304 return (*prev_planner) (parse, cursorOptions, boundParams);
2306 return standard_planner(parse, cursorOptions, boundParams);
2310 * Return scan method hint which matches given aliasname.
2312 static ScanMethodHint *
2313 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2319 * We can't apply scan method hint if the relation is:
2320 * - not a base relation
2321 * - not an ordinary relation (such as join and subquery)
2323 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2326 rte = root->simple_rte_array[rel->relid];
2328 /* We can't force scan method of foreign tables */
2329 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2332 /* Find scan method hint, which matches given names, from the list. */
2333 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2335 ScanMethodHint *hint = current_hint->scan_hints[i];
2337 /* We ignore disabled hints. */
2338 if (!hint_state_enabled(hint))
2341 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2351 * Returns TRUE on match, FALSE on no match.
2353 * s1 --- the data to match against
2354 * s2 --- the pattern
2356 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2359 regexpeq(const char *s1, const char *s2)
2365 strcpy(name.data, s1);
2366 regexp = cstring_to_text(s2);
2368 result = DirectFunctionCall2Coll(nameregexeq,
2369 DEFAULT_COLLATION_OID,
2370 NameGetDatum(&name),
2371 PointerGetDatum(regexp));
2372 return DatumGetBool(result);
2376 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2384 * We delete all the IndexOptInfo list and prevent you from being usable by
2387 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2388 hint->enforce_mask == ENABLE_TIDSCAN)
2390 list_free_deep(rel->indexlist);
2391 rel->indexlist = NIL;
2392 hint->base.state = HINT_STATE_USED;
2398 * When a list of indexes is not specified, we just use all indexes.
2400 if (hint->indexnames == NIL)
2404 * Leaving only an specified index, we delete it from a IndexOptInfo list
2408 if (pg_hint_plan_debug_print)
2409 initStringInfo(&buf);
2411 for (cell = list_head(rel->indexlist); cell; cell = next)
2413 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2414 char *indexname = get_rel_name(info->indexoid);
2416 bool use_index = false;
2420 foreach(l, hint->indexnames)
2422 char *hintname = (char *) lfirst(l);
2426 result = regexpeq(indexname, hintname);
2428 result = RelnameCmp(&indexname, &hintname) == 0;
2433 if (pg_hint_plan_debug_print)
2435 appendStringInfoCharMacro(&buf, ' ');
2436 quote_value(&buf, indexname);
2444 * to make the index a candidate when definition of this index is
2445 * matched with the index's definition of current_hint.
2447 if (OidIsValid(relationObjectId) && !use_index)
2449 foreach(l, current_hint->parent_index_infos)
2453 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2455 /* check to match the parameter of unique */
2456 if (p_info->indisunique != info->unique)
2459 /* check to match the parameter of index's method */
2460 if (p_info->method != info->relam)
2463 /* to check to match the indexkey's configuration */
2464 if ((list_length(p_info->column_names)) !=
2468 /* check to match the indexkey's configuration */
2469 for (i = 0; i < info->ncolumns; i++)
2471 char *c_attname = NULL;
2472 char *p_attname = NULL;
2475 list_nth(p_info->column_names, i);
2477 /* both are expressions */
2478 if (info->indexkeys[i] == 0 && !p_attname)
2481 /* one's column is expression, the other is not */
2482 if (info->indexkeys[i] == 0 || !p_attname)
2485 c_attname = get_attname(relationObjectId,
2486 info->indexkeys[i]);
2488 if (strcmp(p_attname, c_attname) != 0)
2491 if (p_info->indcollation[i] != info->indexcollations[i])
2494 if (p_info->opclass[i] != info->opcintype[i])
2497 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2498 info->reverse_sort[i])
2501 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2502 info->nulls_first[i])
2507 if (i != info->ncolumns)
2510 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2511 (p_info->indpred_str && (info->indpred != NIL)))
2514 * Fetch the pg_index tuple by the Oid of the index
2516 ht_idx = SearchSysCache1(INDEXRELID,
2517 ObjectIdGetDatum(info->indexoid));
2519 /* check to match the expression's parameter of index */
2520 if (p_info->expression_str &&
2521 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2528 * to change the expression's parameter of child's
2531 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2532 Anum_pg_index_indexprs,
2535 result = DirectFunctionCall2(pg_get_expr,
2540 if (strcmp(p_info->expression_str,
2541 text_to_cstring(DatumGetTextP(result))) != 0)
2544 ReleaseSysCache(ht_idx);
2550 /* Check to match the predicate's parameter of index */
2551 if (p_info->indpred_str &&
2552 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2559 * to change the predicate's parameter of child's
2562 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2563 Anum_pg_index_indpred,
2566 result = DirectFunctionCall2(pg_get_expr,
2571 if (strcmp(p_info->indpred_str,
2572 text_to_cstring(DatumGetTextP(result))) != 0)
2575 ReleaseSysCache(ht_idx);
2582 ReleaseSysCache(ht_idx);
2584 else if (p_info->expression_str || (info->indexprs != NIL))
2586 else if (p_info->indpred_str || (info->indpred != NIL))
2591 /* to log the candidate of index */
2592 if (pg_hint_plan_debug_print)
2594 appendStringInfoCharMacro(&buf, ' ');
2595 quote_value(&buf, indexname);
2603 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2610 if (pg_hint_plan_debug_print)
2613 StringInfoData rel_buf;
2615 if (OidIsValid(relationObjectId))
2616 relname = get_rel_name(relationObjectId);
2618 relname = hint->relname;
2620 initStringInfo(&rel_buf);
2621 quote_value(&rel_buf, relname);
2624 (errmsg("available indexes for %s(%s):%s",
2629 pfree(rel_buf.data);
2634 * Return information of index definition.
2636 static ParentIndexInfo *
2637 get_parent_index_info(Oid indexoid, Oid relid)
2639 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
2640 Relation indexRelation;
2641 Form_pg_index index;
2645 indexRelation = index_open(indexoid, RowExclusiveLock);
2647 index = indexRelation->rd_index;
2649 p_info->indisunique = index->indisunique;
2650 p_info->method = indexRelation->rd_rel->relam;
2652 p_info->column_names = NIL;
2653 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2654 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2655 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
2657 for (i = 0; i < index->indnatts; i++)
2659 attname = get_attname(relid, index->indkey.values[i]);
2660 p_info->column_names = lappend(p_info->column_names, attname);
2662 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
2663 p_info->opclass[i] = indexRelation->rd_opcintype[i];
2664 p_info->indoption[i] = indexRelation->rd_indoption[i];
2668 * to check to match the expression's parameter of index with child indexes
2670 p_info->expression_str = NULL;
2671 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
2677 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2678 Anum_pg_index_indexprs, &isnull);
2680 result = DirectFunctionCall2(pg_get_expr,
2682 ObjectIdGetDatum(relid));
2684 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
2688 * to check to match the predicate's parameter of index with child indexes
2690 p_info->indpred_str = NULL;
2691 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
2697 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2698 Anum_pg_index_indpred, &isnull);
2700 result = DirectFunctionCall2(pg_get_expr,
2702 ObjectIdGetDatum(relid));
2704 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
2707 index_close(indexRelation, NoLock);
2713 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2714 bool inhparent, RelOptInfo *rel)
2716 ScanMethodHint *hint;
2718 if (prev_get_relation_info)
2719 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2722 * Do nothing if we don't have valid hint in this context or current
2723 * nesting depth is nesting depth of SPI calls.
2725 if (!current_hint || nested_level > 0)
2730 /* store does relids of parent table. */
2731 current_hint->parent_relid = rel->relid;
2732 current_hint->parent_rel_oid = relationObjectId;
2734 else if (current_hint->parent_relid != 0)
2737 * We use the same GUC parameter if this table is the child table of a
2738 * table called pg_hint_plan_get_relation_info just before that.
2742 /* append_rel_list contains all append rels; ignore others */
2743 foreach(l, root->append_rel_list)
2745 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2747 /* This rel is child table. */
2748 if (appinfo->parent_relid == current_hint->parent_relid &&
2749 appinfo->child_relid == rel->relid)
2751 if (current_hint->parent_hint)
2752 delete_indexes(current_hint->parent_hint, rel,
2759 /* This rel is not inherit table. */
2760 current_hint->parent_relid = 0;
2761 current_hint->parent_rel_oid = InvalidOid;
2762 current_hint->parent_hint = NULL;
2766 * If scan method hint was given, reset GUC parameters which control
2767 * planner behavior about choosing scan methods.
2769 if ((hint = find_scan_hint(root, rel)) == NULL)
2771 set_scan_config_options(current_hint->init_scan_mask,
2772 current_hint->context);
2775 set_scan_config_options(hint->enforce_mask, current_hint->context);
2776 hint->base.state = HINT_STATE_USED;
2784 current_hint->parent_hint = hint;
2786 relation = heap_open(relationObjectId, NoLock);
2787 indexoidlist = RelationGetIndexList(relation);
2789 foreach(l, indexoidlist)
2791 Oid indexoid = lfirst_oid(l);
2792 char *indexname = get_rel_name(indexoid);
2793 bool use_index = false;
2795 ParentIndexInfo *parent_index_info;
2797 foreach(lc, hint->indexnames)
2799 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
2808 parent_index_info = get_parent_index_info(indexoid,
2810 current_hint->parent_index_infos =
2811 lappend(current_hint->parent_index_infos, parent_index_info);
2813 heap_close(relation, NoLock);
2816 delete_indexes(hint, rel, InvalidOid);
2820 * Return index of relation which matches given aliasname, or 0 if not found.
2821 * If same aliasname was used multiple times in a query, return -1.
2824 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
2830 for (i = 1; i < root->simple_rel_array_size; i++)
2834 if (root->simple_rel_array[i] == NULL)
2837 Assert(i == root->simple_rel_array[i]->relid);
2839 if (RelnameCmp(&aliasname,
2840 &root->simple_rte_array[i]->eref->aliasname) != 0)
2843 foreach(l, initial_rels)
2845 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2847 if (rel->reloptkind == RELOPT_BASEREL)
2849 if (rel->relid != i)
2854 Assert(rel->reloptkind == RELOPT_JOINREL);
2856 if (!bms_is_member(i, rel->relids))
2863 ("Relation name \"%s\" is ambiguous.",
2878 * Return join hint which matches given joinrelids.
2880 static JoinMethodHint *
2881 find_join_hint(Relids joinrelids)
2886 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
2888 foreach(l, join_hint)
2890 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
2892 if (bms_equal(joinrelids, hint->joinrelids))
2900 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
2901 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
2903 OuterInnerRels *outer_rels;
2904 OuterInnerRels *inner_rels;
2905 Relids outer_relids;
2906 Relids inner_relids;
2908 JoinMethodHint *hint;
2910 if (outer_inner->relation != NULL)
2912 return bms_make_singleton(
2913 find_relid_aliasname(root, outer_inner->relation,
2915 leading_hint->base.hint_str));
2918 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
2919 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
2921 outer_relids = OuterInnerJoinCreate(outer_rels,
2927 inner_relids = OuterInnerJoinCreate(inner_rels,
2934 join_relids = bms_add_members(outer_relids, inner_relids);
2936 if (bms_num_members(join_relids) > nbaserel)
2940 * If we don't have join method hint, create new one for the
2941 * join combination with all join methods are enabled.
2943 hint = find_join_hint(join_relids);
2947 * Here relnames is not set, since Relids bitmap is sufficient to
2948 * control paths of this query afterward.
2950 hint = (JoinMethodHint *) JoinMethodHintCreate(
2951 leading_hint->base.hint_str,
2953 HINT_KEYWORD_LEADING);
2954 hint->base.state = HINT_STATE_USED;
2955 hint->nrels = bms_num_members(join_relids);
2956 hint->enforce_mask = ENABLE_ALL_JOIN;
2957 hint->joinrelids = bms_copy(join_relids);
2958 hint->inner_nrels = bms_num_members(inner_relids);
2959 hint->inner_joinrelids = bms_copy(inner_relids);
2961 hstate->join_hint_level[hint->nrels] =
2962 lappend(hstate->join_hint_level[hint->nrels], hint);
2966 hint->inner_nrels = bms_num_members(inner_relids);
2967 hint->inner_joinrelids = bms_copy(inner_relids);
2974 * Transform join method hint into handy form.
2976 * - create bitmap of relids from alias names, to make it easier to check
2977 * whether a join path matches a join method hint.
2978 * - add join method hints which are necessary to enforce join order
2979 * specified by Leading hint
2982 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2983 List *initial_rels, JoinMethodHint **join_method_hints)
2991 LeadingHint *lhint = NULL;
2994 * Create bitmap of relids from alias names for each join method hint.
2995 * Bitmaps are more handy than strings in join searching.
2997 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2999 JoinMethodHint *hint = hstate->join_hints[i];
3002 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3005 bms_free(hint->joinrelids);
3006 hint->joinrelids = NULL;
3008 for (j = 0; j < hint->nrels; j++)
3010 relname = hint->relnames[j];
3012 relid = find_relid_aliasname(root, relname, initial_rels,
3013 hint->base.hint_str);
3016 hint->base.state = HINT_STATE_ERROR;
3021 if (bms_is_member(relid, hint->joinrelids))
3023 hint_ereport(hint->base.hint_str,
3024 ("Relation name \"%s\" is duplicated.", relname));
3025 hint->base.state = HINT_STATE_ERROR;
3029 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
3032 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
3035 hstate->join_hint_level[hint->nrels] =
3036 lappend(hstate->join_hint_level[hint->nrels], hint);
3039 /* Do nothing if no Leading hint was supplied. */
3040 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
3044 * Decide to use Leading hint。
3046 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
3048 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
3051 if (leading_hint->base.state == HINT_STATE_ERROR)
3057 foreach(l, leading_hint->relations)
3059 relname = (char *)lfirst(l);;
3061 relid = find_relid_aliasname(root, relname, initial_rels,
3062 leading_hint->base.hint_str);
3064 leading_hint->base.state = HINT_STATE_ERROR;
3069 if (bms_is_member(relid, relids))
3071 hint_ereport(leading_hint->base.hint_str,
3072 ("Relation name \"%s\" is duplicated.", relname));
3073 leading_hint->base.state = HINT_STATE_ERROR;
3077 relids = bms_add_member(relids, relid);
3080 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3085 hint_ereport(lhint->base.hint_str,
3086 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3087 lhint->base.state = HINT_STATE_DUPLICATION;
3089 leading_hint->base.state = HINT_STATE_USED;
3090 lhint = leading_hint;
3093 /* check to exist Leading hint marked with 'used'. */
3098 * We need join method hints which fit specified join order in every join
3099 * level. For example, Leading(A B C) virtually requires following join
3100 * method hints, if no join method hint supplied:
3102 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3103 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3105 * If we already have join method hint which fits specified join order in
3106 * that join level, we leave it as-is and don't add new hints.
3110 if (lhint->outer_inner == NULL)
3112 foreach(l, lhint->relations)
3114 JoinMethodHint *hint;
3116 relname = (char *)lfirst(l);
3119 * Find relid of the relation which has given name. If we have the
3120 * name given in Leading hint multiple times in the join, nothing to
3123 relid = find_relid_aliasname(root, relname, initial_rels,
3126 /* Create bitmap of relids for current join level. */
3127 joinrelids = bms_add_member(joinrelids, relid);
3130 /* We never have join method hint for single relation. */
3135 * If we don't have join method hint, create new one for the
3136 * join combination with all join methods are enabled.
3138 hint = find_join_hint(joinrelids);
3142 * Here relnames is not set, since Relids bitmap is sufficient
3143 * to control paths of this query afterward.
3145 hint = (JoinMethodHint *) JoinMethodHintCreate(
3146 lhint->base.hint_str,
3148 HINT_KEYWORD_LEADING);
3149 hint->base.state = HINT_STATE_USED;
3150 hint->nrels = njoinrels;
3151 hint->enforce_mask = ENABLE_ALL_JOIN;
3152 hint->joinrelids = bms_copy(joinrelids);
3155 join_method_hints[njoinrels] = hint;
3157 if (njoinrels >= nbaserel)
3160 bms_free(joinrelids);
3166 * Delete all join hints which have different combination from Leading
3169 for (i = 2; i <= njoinrels; i++)
3171 list_free(hstate->join_hint_level[i]);
3173 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3178 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3185 njoinrels = bms_num_members(joinrelids);
3186 Assert(njoinrels >= 2);
3189 * Delete all join hints which have different combination from Leading
3192 for (i = 2;i <= njoinrels; i++)
3194 if (hstate->join_hint_level[i] != NIL)
3196 ListCell *prev = NULL;
3197 ListCell *next = NULL;
3198 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3201 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3205 if (hint->inner_nrels == 0 &&
3206 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3207 bms_equal(bms_union(hint->joinrelids, joinrelids),
3210 hstate->join_hint_level[i] =
3211 list_delete_cell(hstate->join_hint_level[i], l,
3220 bms_free(joinrelids);
3223 if (hint_state_enabled(lhint))
3225 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3232 * set_plain_rel_pathlist
3233 * Build access paths for a plain relation (no subquery, no inheritance)
3235 * This function was copied and edited from set_plain_rel_pathlist() in
3236 * src/backend/optimizer/path/allpaths.c
3239 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3241 /* Consider sequential scan */
3242 Relids required_outer;
3245 * We don't support pushing join clauses into the quals of a seqscan, but
3246 * it could still have required parameterization due to LATERAL refs in
3249 required_outer = rel->lateral_relids;
3251 /* Consider sequential scan */
3252 add_path(rel, create_seqscan_path(root, rel, required_outer));
3254 /* Consider index scans */
3255 create_index_paths(root, rel);
3257 /* Consider TID scans */
3258 create_tidscan_paths(root, rel);
3260 /* Now find the cheapest of the paths for this rel */
3265 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3270 foreach(l, initial_rels)
3272 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3274 ScanMethodHint *hint;
3276 /* Skip relations which we can't choose scan method. */
3277 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3280 rte = root->simple_rte_array[rel->relid];
3282 /* We can't force scan method of foreign tables */
3283 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3287 * Create scan paths with GUC parameters which are at the beginning of
3288 * planner if scan method hint is not specified, otherwise use
3289 * specified hints and mark the hint as used.
3291 if ((hint = find_scan_hint(root, rel)) == NULL)
3292 set_scan_config_options(hstate->init_scan_mask,
3296 set_scan_config_options(hint->enforce_mask, hstate->context);
3297 hint->base.state = HINT_STATE_USED;
3300 list_free_deep(rel->pathlist);
3301 rel->pathlist = NIL;
3304 /* It's an "append relation", process accordingly */
3305 set_append_rel_pathlist(root, rel, rel->relid, rte);
3309 set_plain_rel_pathlist(root, rel, rte);
3314 * Restore the GUC variables we set above.
3316 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3320 * wrapper of make_join_rel()
3322 * call make_join_rel() after changing enable_* parameters according to given
3326 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3329 JoinMethodHint *hint;
3333 joinrelids = bms_union(rel1->relids, rel2->relids);
3334 hint = find_join_hint(joinrelids);
3335 bms_free(joinrelids);
3338 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3340 if (hint->inner_nrels == 0)
3342 save_nestlevel = NewGUCNestLevel();
3344 set_join_config_options(hint->enforce_mask, current_hint->context);
3346 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3347 hint->base.state = HINT_STATE_USED;
3350 * Restore the GUC variables we set above.
3352 AtEOXact_GUC(true, save_nestlevel);
3355 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3364 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3365 RelOptInfo *joinrel,
3366 RelOptInfo *outerrel,
3367 RelOptInfo *innerrel,
3369 SpecialJoinInfo *sjinfo,
3372 ScanMethodHint *scan_hint = NULL;
3374 JoinMethodHint *join_hint;
3377 if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
3379 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3380 scan_hint->base.state = HINT_STATE_USED;
3383 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3384 join_hint = find_join_hint(joinrelids);
3385 bms_free(joinrelids);
3387 if (join_hint && join_hint->inner_nrels != 0)
3389 save_nestlevel = NewGUCNestLevel();
3391 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3394 set_join_config_options(join_hint->enforce_mask,
3395 current_hint->context);
3397 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3398 sjinfo, restrictlist);
3399 join_hint->base.state = HINT_STATE_USED;
3403 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3404 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3405 sjinfo, restrictlist);
3409 * Restore the GUC variables we set above.
3411 AtEOXact_GUC(true, save_nestlevel);
3414 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3415 sjinfo, restrictlist);
3417 if (scan_hint != NULL)
3418 set_scan_config_options(current_hint->init_scan_mask,
3419 current_hint->context);
3423 get_num_baserels(List *initial_rels)
3428 foreach(l, initial_rels)
3430 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3432 if (rel->reloptkind == RELOPT_BASEREL)
3434 else if (rel->reloptkind ==RELOPT_JOINREL)
3435 nbaserel+= bms_num_members(rel->relids);
3438 /* other values not expected here */
3439 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3447 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3450 JoinMethodHint **join_method_hints;
3454 bool leading_hint_enable;
3457 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3458 * valid hint is supplied or current nesting depth is nesting depth of SPI
3461 if (!current_hint || nested_level > 0)
3463 if (prev_join_search)
3464 return (*prev_join_search) (root, levels_needed, initial_rels);
3465 else if (enable_geqo && levels_needed >= geqo_threshold)
3466 return geqo(root, levels_needed, initial_rels);
3468 return standard_join_search(root, levels_needed, initial_rels);
3471 /* We apply scan method hint rebuild scan path. */
3472 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3475 * In the case using GEQO, only scan method hints and Set hints have
3476 * effect. Join method and join order is not controllable by hints.
3478 if (enable_geqo && levels_needed >= geqo_threshold)
3479 return geqo(root, levels_needed, initial_rels);
3481 nbaserel = get_num_baserels(initial_rels);
3482 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3483 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3485 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3486 initial_rels, join_method_hints);
3488 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3490 for (i = 2; i <= nbaserel; i++)
3492 list_free(current_hint->join_hint_level[i]);
3494 /* free Leading hint only */
3495 if (join_method_hints[i] != NULL &&
3496 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3497 JoinMethodHintDelete(join_method_hints[i]);
3499 pfree(current_hint->join_hint_level);
3500 pfree(join_method_hints);
3502 if (leading_hint_enable)
3503 set_join_config_options(current_hint->init_join_mask,
3504 current_hint->context);
3511 * Build access paths for a base relation
3513 * This function was copied and edited from set_rel_pathlist() in
3514 * src/backend/optimizer/path/allpaths.c
3517 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3518 Index rti, RangeTblEntry *rte)
3520 if (IS_DUMMY_REL(rel))
3522 /* We already proved the relation empty, so nothing more to do */
3526 /* It's an "append relation", process accordingly */
3527 set_append_rel_pathlist(root, rel, rti, rte);
3531 if (rel->rtekind == RTE_RELATION)
3533 if (rte->relkind == RELKIND_RELATION)
3535 /* Plain relation */
3536 set_plain_rel_pathlist(root, rel, rte);
3539 elog(ERROR, "unexpected relkind: %c", rte->relkind);
3542 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
3547 * stmt_beg callback is called when each query in PL/pgSQL function is about
3548 * to be executed. At that timing, we save query string in the global variable
3549 * plpgsql_query_string to use it in planner hook. It's safe to use one global
3550 * variable for the purpose, because its content is only necessary until
3551 * planner hook is called for the query, so recursive PL/pgSQL function calls
3552 * don't harm this mechanism.
3555 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3557 PLpgSQL_expr *expr = NULL;
3559 switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
3561 case PLPGSQL_STMT_FORS:
3562 expr = ((PLpgSQL_stmt_fors *) stmt)->query;
3564 case PLPGSQL_STMT_FORC:
3565 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_forc *)stmt)->curvar]))->cursor_explicit_expr;
3567 case PLPGSQL_STMT_RETURN_QUERY:
3568 if (((PLpgSQL_stmt_return_query *) stmt)->query != NULL)
3569 expr = ((PLpgSQL_stmt_return_query *) stmt)->query;
3571 expr = ((PLpgSQL_stmt_return_query *) stmt)->dynquery;
3573 case PLPGSQL_STMT_EXECSQL:
3574 expr = ((PLpgSQL_stmt_execsql *) stmt)->sqlstmt;
3576 case PLPGSQL_STMT_DYNEXECUTE:
3577 expr = ((PLpgSQL_stmt_dynexecute *) stmt)->query;
3579 case PLPGSQL_STMT_DYNFORS:
3580 expr = ((PLpgSQL_stmt_dynfors *) stmt)->query;
3582 case PLPGSQL_STMT_OPEN:
3583 if (((PLpgSQL_stmt_open *) stmt)->query != NULL)
3584 expr = ((PLpgSQL_stmt_open *) stmt)->query;
3585 else if (((PLpgSQL_stmt_open *) stmt)->dynquery != NULL)
3586 expr = ((PLpgSQL_stmt_open *) stmt)->dynquery;
3588 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_open *)stmt)->curvar]))->cursor_explicit_expr;
3595 plpgsql_query_string = expr->query;
3599 * stmt_end callback is called then each query in PL/pgSQL function has
3600 * finished. At that timing, we clear plpgsql_query_string to tell planner
3601 * hook that next call is not for a query written in PL/pgSQL block.
3604 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3606 if ((enum PLpgSQL_stmt_types) stmt->cmd_type == PLPGSQL_STMT_EXECSQL)
3607 plpgsql_query_string = NULL;
3610 #define standard_join_search pg_hint_plan_standard_join_search
3611 #define join_search_one_level pg_hint_plan_join_search_one_level
3612 #define make_join_rel make_join_rel_wrapper
3615 #undef make_join_rel
3616 #define make_join_rel pg_hint_plan_make_join_rel
3617 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
3618 #include "make_join_rel.c"
3620 #include "pg_stat_statements.c"