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"
42 * We have our own header file "plpgsql-9.1", which is necessary to support
43 * hints for queries in PL/pgSQL blocks, in pg_hint_plan source package,
44 * because PostgreSQL 9.1 doesn't provide the header file as a part of
45 * installation. This header file is a copy of src/pl/plpgsql/src/plpgsql.h in
46 * PostgreSQL 9.1.9 source tree,
48 * On the other hand, 9.2 installation provides that header file for external
49 * modules, so we include the header in ordinary place.
53 /* partially copied from pg_stat_statements */
54 #include "normalize_query.h"
56 #ifdef PG_MODULE_MAGIC
60 #define BLOCK_COMMENT_START "/*"
61 #define BLOCK_COMMENT_END "*/"
62 #define HINT_COMMENT_KEYWORD "+"
63 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
64 #define HINT_END BLOCK_COMMENT_END
67 #define HINT_SEQSCAN "SeqScan"
68 #define HINT_INDEXSCAN "IndexScan"
69 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
70 #define HINT_BITMAPSCAN "BitmapScan"
71 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
72 #define HINT_TIDSCAN "TidScan"
73 #define HINT_NOSEQSCAN "NoSeqScan"
74 #define HINT_NOINDEXSCAN "NoIndexScan"
75 #define HINT_NOBITMAPSCAN "NoBitmapScan"
76 #define HINT_NOTIDSCAN "NoTidScan"
77 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
78 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
79 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
80 #define HINT_NESTLOOP "NestLoop"
81 #define HINT_MERGEJOIN "MergeJoin"
82 #define HINT_HASHJOIN "HashJoin"
83 #define HINT_NONESTLOOP "NoNestLoop"
84 #define HINT_NOMERGEJOIN "NoMergeJoin"
85 #define HINT_NOHASHJOIN "NoHashJoin"
86 #define HINT_LEADING "Leading"
87 #define HINT_SET "Set"
89 #define HINT_ARRAY_DEFAULT_INITSIZE 8
91 #define hint_ereport(str, detail) \
92 ereport(pg_hint_plan_parse_messages, \
93 (errmsg("hint syntax error at or near \"%s\"", (str)), \
96 #define skip_space(str) \
97 while (isspace(*str)) \
102 ENABLE_SEQSCAN = 0x01,
103 ENABLE_INDEXSCAN = 0x02,
104 ENABLE_BITMAPSCAN = 0x04,
105 ENABLE_TIDSCAN = 0x08,
106 ENABLE_INDEXONLYSCAN = 0x10
111 ENABLE_NESTLOOP = 0x01,
112 ENABLE_MERGEJOIN = 0x02,
113 ENABLE_HASHJOIN = 0x04
116 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
117 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
118 ENABLE_INDEXONLYSCAN)
119 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
120 #define DISABLE_ALL_SCAN 0
121 #define DISABLE_ALL_JOIN 0
123 /* hint keyword of enum type*/
124 typedef enum HintKeyword
126 HINT_KEYWORD_SEQSCAN,
127 HINT_KEYWORD_INDEXSCAN,
128 HINT_KEYWORD_INDEXSCANREGEXP,
129 HINT_KEYWORD_BITMAPSCAN,
130 HINT_KEYWORD_BITMAPSCANREGEXP,
131 HINT_KEYWORD_TIDSCAN,
132 HINT_KEYWORD_NOSEQSCAN,
133 HINT_KEYWORD_NOINDEXSCAN,
134 HINT_KEYWORD_NOBITMAPSCAN,
135 HINT_KEYWORD_NOTIDSCAN,
136 HINT_KEYWORD_INDEXONLYSCAN,
137 HINT_KEYWORD_INDEXONLYSCANREGEXP,
138 HINT_KEYWORD_NOINDEXONLYSCAN,
139 HINT_KEYWORD_NESTLOOP,
140 HINT_KEYWORD_MERGEJOIN,
141 HINT_KEYWORD_HASHJOIN,
142 HINT_KEYWORD_NONESTLOOP,
143 HINT_KEYWORD_NOMERGEJOIN,
144 HINT_KEYWORD_NOHASHJOIN,
145 HINT_KEYWORD_LEADING,
147 HINT_KEYWORD_UNRECOGNIZED
150 typedef struct Hint Hint;
151 typedef struct HintState HintState;
153 typedef Hint *(*HintCreateFunction) (const char *hint_str,
155 HintKeyword hint_keyword);
156 typedef void (*HintDeleteFunction) (Hint *hint);
157 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf);
158 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
159 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
160 Query *parse, const char *str);
163 #define NUM_HINT_TYPE 4
164 typedef enum HintType
166 HINT_TYPE_SCAN_METHOD,
167 HINT_TYPE_JOIN_METHOD,
172 static const char *HintTypeName[] = {
180 typedef enum HintStatus
182 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
183 HINT_STATE_USED, /* hint is used */
184 HINT_STATE_DUPLICATION, /* specified hint duplication */
185 HINT_STATE_ERROR /* execute error (parse error does not include
189 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
190 (hint)->base.state == HINT_STATE_USED)
192 /* common data for all hints. */
195 const char *hint_str; /* must not do pfree */
196 const char *keyword; /* must not do pfree */
197 HintKeyword hint_keyword;
200 HintDeleteFunction delete_func;
201 HintDescFunction desc_func;
202 HintCmpFunction cmp_func;
203 HintParseFunction parse_func;
206 /* scan method hints */
207 typedef struct ScanMethodHint
213 unsigned char enforce_mask;
216 typedef struct ParentIndexInfo
221 char *expression_str;
228 /* join method hints */
229 typedef struct JoinMethodHint
235 unsigned char enforce_mask;
237 Relids inner_joinrelids;
240 /* join order hints */
241 typedef struct OuterInnerRels
244 List *outer_inner_pair;
247 typedef struct LeadingHint
250 List *relations; /* relation names specified in Leading hint */
251 OuterInnerRels *outer_inner;
254 /* change a run-time parameter hints */
255 typedef struct SetHint
258 char *name; /* name of variable */
264 * Describes a context of hint processing.
268 char *hint_str; /* original hint string */
271 int nall_hints; /* # of valid all hints */
272 int max_all_hints; /* # of slots for all hints */
273 Hint **all_hints; /* parsed all hints */
275 /* # of each hints */
276 int num_hints[NUM_HINT_TYPE];
278 /* for scan method hints */
279 ScanMethodHint **scan_hints; /* parsed scan hints */
280 int init_scan_mask; /* initial value scan parameter */
281 Index parent_relid; /* inherit parent table relid */
282 Oid parent_rel_oid; /* inherit parent table relid */
283 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
284 List *parent_index_infos; /* information of inherit parent table's
287 /* for join method hints */
288 JoinMethodHint **join_hints; /* parsed join hints */
289 int init_join_mask; /* initial value join parameter */
290 List **join_hint_level;
292 /* for Leading hint */
293 LeadingHint **leading_hint; /* parsed Leading hints */
296 SetHint **set_hints; /* parsed Set hints */
297 GucContext context; /* which GUC parameters can we set? */
301 * Describes a hint parser module which is bound with particular hint keyword.
303 typedef struct HintParser
306 HintCreateFunction create_func;
307 HintKeyword hint_keyword;
310 /* Module callbacks */
314 static void push_hint(HintState *hstate);
315 static void pop_hint(void);
317 static void pg_hint_plan_ProcessUtility(Node *parsetree,
318 const char *queryString,
319 ParamListInfo params, bool isTopLevel,
321 char *completionTag);
322 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
323 ParamListInfo boundParams);
324 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
325 Oid relationObjectId,
326 bool inhparent, RelOptInfo *rel);
327 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
331 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
332 HintKeyword hint_keyword);
333 static void ScanMethodHintDelete(ScanMethodHint *hint);
334 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf);
335 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
336 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
337 Query *parse, const char *str);
338 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
339 HintKeyword hint_keyword);
340 static void JoinMethodHintDelete(JoinMethodHint *hint);
341 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf);
342 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
343 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
344 Query *parse, const char *str);
345 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
346 HintKeyword hint_keyword);
347 static void LeadingHintDelete(LeadingHint *hint);
348 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf);
349 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
350 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
351 Query *parse, const char *str);
352 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
353 HintKeyword hint_keyword);
354 static void SetHintDelete(SetHint *hint);
355 static void SetHintDesc(SetHint *hint, StringInfo buf);
356 static int SetHintCmp(const SetHint *a, const SetHint *b);
357 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
360 static void quote_value(StringInfo buf, const char *value);
362 static const char *parse_quoted_value(const char *str, char **word,
365 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
368 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
369 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
370 ListCell *other_rels);
371 static void make_rels_by_clauseless_joins(PlannerInfo *root,
373 ListCell *other_rels);
374 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
375 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
376 Index rti, RangeTblEntry *rte);
377 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
378 List *live_childrels,
379 List *all_child_pathkeys);
380 static List *accumulate_append_subpath(List *subpaths, Path *path);
381 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
384 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
386 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
390 static bool pg_hint_plan_enable_hint = true;
391 static bool pg_hint_plan_debug_print = false;
392 static int pg_hint_plan_parse_messages = INFO;
393 /* Default is off, to keep backward compatibility. */
394 static bool pg_hint_plan_enable_hint_table = false;
396 static const struct config_enum_entry parse_messages_level_options[] = {
397 {"debug", DEBUG2, true},
398 {"debug5", DEBUG5, false},
399 {"debug4", DEBUG4, false},
400 {"debug3", DEBUG3, false},
401 {"debug2", DEBUG2, false},
402 {"debug1", DEBUG1, false},
404 {"info", INFO, false},
405 {"notice", NOTICE, false},
406 {"warning", WARNING, false},
407 {"error", ERROR, false},
409 * {"fatal", FATAL, true},
410 * {"panic", PANIC, true},
415 /* Saved hook values in case of unload */
416 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
417 static planner_hook_type prev_planner = NULL;
418 static get_relation_info_hook_type prev_get_relation_info = NULL;
419 static join_search_hook_type prev_join_search = NULL;
421 /* Hold reference to currently active hint */
422 static HintState *current_hint = NULL;
425 * List of hint contexts. We treat the head of the list as the Top of the
426 * context stack, so current_hint always points the first element of this list.
428 static List *HintStateStack = NIL;
431 * Holds statement name during executing EXECUTE command. NULL for other
434 static char *stmt_name = NULL;
436 static const HintParser parsers[] = {
437 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
438 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
439 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
440 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
441 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
442 HINT_KEYWORD_BITMAPSCANREGEXP},
443 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
444 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
445 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
446 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
447 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
448 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
449 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
450 HINT_KEYWORD_INDEXONLYSCANREGEXP},
451 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
452 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
453 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
454 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
455 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
456 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
457 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
458 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
459 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
460 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
464 * PL/pgSQL plugin for retrieving string representation of each query during
465 * function execution.
467 const char *plpgsql_query_string = NULL;
468 PLpgSQL_plugin plugin_funcs = {
472 pg_hint_plan_plpgsql_stmt_beg,
473 pg_hint_plan_plpgsql_stmt_end,
478 /* Current nesting depth of SPI calls, used to prevent recursive calls */
479 static int nested_level = 0;
482 * Module load callbacks
487 PLpgSQL_plugin **var_ptr;
489 /* Define custom GUC variables. */
490 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
491 "Force planner to use plans specified in the hint comment preceding to the query.",
493 &pg_hint_plan_enable_hint,
501 DefineCustomBoolVariable("pg_hint_plan.debug_print",
502 "Logs results of hint parsing.",
504 &pg_hint_plan_debug_print,
512 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
513 "Message level of parse errors.",
515 &pg_hint_plan_parse_messages,
517 parse_messages_level_options,
524 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
525 "Force planner to not get hint by using table lookups.",
527 &pg_hint_plan_enable_hint_table,
536 prev_ProcessUtility = ProcessUtility_hook;
537 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
538 prev_planner = planner_hook;
539 planner_hook = pg_hint_plan_planner;
540 prev_get_relation_info = get_relation_info_hook;
541 get_relation_info_hook = pg_hint_plan_get_relation_info;
542 prev_join_search = join_search_hook;
543 join_search_hook = pg_hint_plan_join_search;
545 /* setup PL/pgSQL plugin hook */
546 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
547 *var_ptr = &plugin_funcs;
551 * Module unload callback
557 PLpgSQL_plugin **var_ptr;
559 /* Uninstall hooks. */
560 ProcessUtility_hook = prev_ProcessUtility;
561 planner_hook = prev_planner;
562 get_relation_info_hook = prev_get_relation_info;
563 join_search_hook = prev_join_search;
565 /* uninstall PL/pgSQL plugin hook */
566 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
571 * create and delete functions the hint object
575 ScanMethodHintCreate(const char *hint_str, const char *keyword,
576 HintKeyword hint_keyword)
578 ScanMethodHint *hint;
580 hint = palloc(sizeof(ScanMethodHint));
581 hint->base.hint_str = hint_str;
582 hint->base.keyword = keyword;
583 hint->base.hint_keyword = hint_keyword;
584 hint->base.type = HINT_TYPE_SCAN_METHOD;
585 hint->base.state = HINT_STATE_NOTUSED;
586 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
587 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
588 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
589 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
590 hint->relname = NULL;
591 hint->indexnames = NIL;
592 hint->regexp = false;
593 hint->enforce_mask = 0;
595 return (Hint *) hint;
599 ScanMethodHintDelete(ScanMethodHint *hint)
605 pfree(hint->relname);
606 list_free_deep(hint->indexnames);
611 JoinMethodHintCreate(const char *hint_str, const char *keyword,
612 HintKeyword hint_keyword)
614 JoinMethodHint *hint;
616 hint = palloc(sizeof(JoinMethodHint));
617 hint->base.hint_str = hint_str;
618 hint->base.keyword = keyword;
619 hint->base.hint_keyword = hint_keyword;
620 hint->base.type = HINT_TYPE_JOIN_METHOD;
621 hint->base.state = HINT_STATE_NOTUSED;
622 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
623 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
624 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
625 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
627 hint->inner_nrels = 0;
628 hint->relnames = NULL;
629 hint->enforce_mask = 0;
630 hint->joinrelids = NULL;
631 hint->inner_joinrelids = NULL;
633 return (Hint *) hint;
637 JoinMethodHintDelete(JoinMethodHint *hint)
646 for (i = 0; i < hint->nrels; i++)
647 pfree(hint->relnames[i]);
648 pfree(hint->relnames);
651 bms_free(hint->joinrelids);
652 bms_free(hint->inner_joinrelids);
657 LeadingHintCreate(const char *hint_str, const char *keyword,
658 HintKeyword hint_keyword)
662 hint = palloc(sizeof(LeadingHint));
663 hint->base.hint_str = hint_str;
664 hint->base.keyword = keyword;
665 hint->base.hint_keyword = hint_keyword;
666 hint->base.type = HINT_TYPE_LEADING;
667 hint->base.state = HINT_STATE_NOTUSED;
668 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
669 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
670 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
671 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
672 hint->relations = NIL;
673 hint->outer_inner = NULL;
675 return (Hint *) hint;
679 LeadingHintDelete(LeadingHint *hint)
684 list_free_deep(hint->relations);
685 if (hint->outer_inner)
686 pfree(hint->outer_inner);
691 SetHintCreate(const char *hint_str, const char *keyword,
692 HintKeyword hint_keyword)
696 hint = palloc(sizeof(SetHint));
697 hint->base.hint_str = hint_str;
698 hint->base.keyword = keyword;
699 hint->base.hint_keyword = hint_keyword;
700 hint->base.type = HINT_TYPE_SET;
701 hint->base.state = HINT_STATE_NOTUSED;
702 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
703 hint->base.desc_func = (HintDescFunction) SetHintDesc;
704 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
705 hint->base.parse_func = (HintParseFunction) SetHintParse;
710 return (Hint *) hint;
714 SetHintDelete(SetHint *hint)
724 list_free(hint->words);
729 HintStateCreate(void)
733 hstate = palloc(sizeof(HintState));
734 hstate->hint_str = NULL;
735 hstate->nall_hints = 0;
736 hstate->max_all_hints = 0;
737 hstate->all_hints = NULL;
738 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
739 hstate->scan_hints = NULL;
740 hstate->init_scan_mask = 0;
741 hstate->parent_relid = 0;
742 hstate->parent_rel_oid = InvalidOid;
743 hstate->parent_hint = NULL;
744 hstate->parent_index_infos = NIL;
745 hstate->join_hints = NULL;
746 hstate->init_join_mask = 0;
747 hstate->join_hint_level = NULL;
748 hstate->leading_hint = NULL;
749 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
750 hstate->set_hints = NULL;
756 HintStateDelete(HintState *hstate)
763 if (hstate->hint_str)
764 pfree(hstate->hint_str);
766 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
767 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
768 if (hstate->all_hints)
769 pfree(hstate->all_hints);
770 if (hstate->parent_index_infos)
771 list_free(hstate->parent_index_infos);
775 * Copy given value into buf, with quoting with '"' if necessary.
778 quote_value(StringInfo buf, const char *value)
780 bool need_quote = false;
783 for (str = value; *str != '\0'; str++)
785 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
788 appendStringInfoCharMacro(buf, '"');
793 for (str = value; *str != '\0'; str++)
796 appendStringInfoCharMacro(buf, '"');
798 appendStringInfoCharMacro(buf, *str);
802 appendStringInfoCharMacro(buf, '"');
806 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
810 appendStringInfo(buf, "%s(", hint->base.keyword);
811 if (hint->relname != NULL)
813 quote_value(buf, hint->relname);
814 foreach(l, hint->indexnames)
816 appendStringInfoCharMacro(buf, ' ');
817 quote_value(buf, (char *) lfirst(l));
820 appendStringInfoString(buf, ")\n");
824 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
828 appendStringInfo(buf, "%s(", hint->base.keyword);
829 if (hint->relnames != NULL)
831 quote_value(buf, hint->relnames[0]);
832 for (i = 1; i < hint->nrels; i++)
834 appendStringInfoCharMacro(buf, ' ');
835 quote_value(buf, hint->relnames[i]);
838 appendStringInfoString(buf, ")\n");
843 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
845 if (outer_inner->relation == NULL)
852 appendStringInfoCharMacro(buf, '(');
853 foreach(l, outer_inner->outer_inner_pair)
858 appendStringInfoCharMacro(buf, ' ');
860 OuterInnerDesc(lfirst(l), buf);
863 appendStringInfoCharMacro(buf, ')');
866 quote_value(buf, outer_inner->relation);
870 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
872 appendStringInfo(buf, "%s(", HINT_LEADING);
873 if (hint->outer_inner == NULL)
880 foreach(l, hint->relations)
885 appendStringInfoCharMacro(buf, ' ');
887 quote_value(buf, (char *) lfirst(l));
891 OuterInnerDesc(hint->outer_inner, buf);
893 appendStringInfoString(buf, ")\n");
897 SetHintDesc(SetHint *hint, StringInfo buf)
899 bool is_first = true;
902 appendStringInfo(buf, "%s(", HINT_SET);
903 foreach(l, hint->words)
908 appendStringInfoCharMacro(buf, ' ');
910 quote_value(buf, (char *) lfirst(l));
912 appendStringInfo(buf, ")\n");
916 * Append string which represents all hints in a given state to buf, with
917 * preceding title with them.
920 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
925 appendStringInfo(buf, "%s:\n", title);
926 for (i = 0; i < hstate->nall_hints; i++)
928 if (hstate->all_hints[i]->state != state)
931 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf);
936 * Dump contents of given hstate to server log with log level LOG.
939 HintStateDump(HintState *hstate)
945 elog(LOG, "pg_hint_plan:\nno hint");
949 initStringInfo(&buf);
951 appendStringInfoString(&buf, "pg_hint_plan:\n");
952 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
953 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
954 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
955 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
957 elog(LOG, "%s", buf.data);
967 RelnameCmp(const void *a, const void *b)
969 const char *relnamea = *((const char **) a);
970 const char *relnameb = *((const char **) b);
972 return strcmp(relnamea, relnameb);
976 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
978 return RelnameCmp(&a->relname, &b->relname);
982 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
986 if (a->nrels != b->nrels)
987 return a->nrels - b->nrels;
989 for (i = 0; i < a->nrels; i++)
992 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1000 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1006 SetHintCmp(const SetHint *a, const SetHint *b)
1008 return strcmp(a->name, b->name);
1012 HintCmp(const void *a, const void *b)
1014 const Hint *hinta = *((const Hint **) a);
1015 const Hint *hintb = *((const Hint **) b);
1017 if (hinta->type != hintb->type)
1018 return hinta->type - hintb->type;
1019 if (hinta->state == HINT_STATE_ERROR)
1021 if (hintb->state == HINT_STATE_ERROR)
1023 return hinta->cmp_func(hinta, hintb);
1027 * Returns byte offset of hint b from hint a. If hint a was specified before
1028 * b, positive value is returned.
1031 HintCmpWithPos(const void *a, const void *b)
1033 const Hint *hinta = *((const Hint **) a);
1034 const Hint *hintb = *((const Hint **) b);
1037 result = HintCmp(a, b);
1039 result = hinta->hint_str - hintb->hint_str;
1048 parse_keyword(const char *str, StringInfo buf)
1052 while (!isspace(*str) && *str != '(' && *str != '\0')
1053 appendStringInfoCharMacro(buf, *str++);
1059 skip_parenthesis(const char *str, char parenthesis)
1063 if (*str != parenthesis)
1065 if (parenthesis == '(')
1066 hint_ereport(str, ("Opening parenthesis is necessary."));
1067 else if (parenthesis == ')')
1068 hint_ereport(str, ("Closing parenthesis is necessary."));
1079 * Parse a token from str, and store malloc'd copy into word. A token can be
1080 * quoted with '"'. Return value is pointer to unparsed portion of original
1081 * string, or NULL if an error occurred.
1083 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1086 parse_quoted_value(const char *str, char **word, bool truncate)
1091 /* Skip leading spaces. */
1094 initStringInfo(&buf);
1107 /* Double quotation must be closed. */
1111 hint_ereport(str, ("Unterminated quoted string."));
1116 * Skip escaped double quotation.
1118 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1119 * block comments) to be an object name, so users must specify
1120 * alias for such object names.
1122 * Those special names can be allowed if we care escaped slashes
1123 * and asterisks, but we don't.
1132 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1136 appendStringInfoCharMacro(&buf, *str++);
1141 hint_ereport(str, ("Zero-length delimited string."));
1148 /* Truncate name if it's too long */
1150 truncate_identifier(buf.data, strlen(buf.data), true);
1157 static OuterInnerRels *
1158 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1160 OuterInnerRels *outer_inner;
1162 outer_inner = palloc(sizeof(OuterInnerRels));
1163 outer_inner->relation = name;
1164 outer_inner->outer_inner_pair = outer_inner_list;
1170 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1172 List *outer_inner_pair = NIL;
1174 if ((str = skip_parenthesis(str, '(')) == NULL)
1179 /* Store words in parentheses into outer_inner_list. */
1180 while(*str != ')' && *str != '\0')
1182 OuterInnerRels *outer_inner_rels;
1186 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1194 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1197 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1200 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1205 (str = skip_parenthesis(str, ')')) == NULL)
1207 list_free(outer_inner_pair);
1211 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1217 parse_parentheses_Leading(const char *str, List **name_list,
1218 OuterInnerRels **outer_inner)
1221 bool truncate = true;
1223 if ((str = skip_parenthesis(str, '(')) == NULL)
1229 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1234 /* Store words in parentheses into name_list. */
1235 while(*str != ')' && *str != '\0')
1237 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1239 list_free(*name_list);
1243 *name_list = lappend(*name_list, name);
1248 if ((str = skip_parenthesis(str, ')')) == NULL)
1254 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1257 bool truncate = true;
1259 if ((str = skip_parenthesis(str, '(')) == NULL)
1264 /* Store words in parentheses into name_list. */
1265 while(*str != ')' && *str != '\0')
1267 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1269 list_free(*name_list);
1273 *name_list = lappend(*name_list, name);
1276 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1277 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1278 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1279 keyword == HINT_KEYWORD_SET)
1285 if ((str = skip_parenthesis(str, ')')) == NULL)
1291 parse_hints(HintState *hstate, Query *parse, const char *str)
1296 initStringInfo(&buf);
1297 while (*str != '\0')
1299 const HintParser *parser;
1301 /* in error message, we output the comment including the keyword. */
1302 head = (char *) str;
1304 /* parse only the keyword of the hint. */
1305 resetStringInfo(&buf);
1306 str = parse_keyword(str, &buf);
1308 for (parser = parsers; parser->keyword != NULL; parser++)
1310 char *keyword = parser->keyword;
1313 if (strcasecmp(buf.data, keyword) != 0)
1316 hint = parser->create_func(head, keyword, parser->hint_keyword);
1318 /* parser of each hint does parse in a parenthesis. */
1319 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1321 hint->delete_func(hint);
1327 * Add hint information into all_hints array. If we don't have
1328 * enough space, double the array.
1330 if (hstate->nall_hints == 0)
1332 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1333 hstate->all_hints = (Hint **)
1334 palloc(sizeof(Hint *) * hstate->max_all_hints);
1336 else if (hstate->nall_hints == hstate->max_all_hints)
1338 hstate->max_all_hints *= 2;
1339 hstate->all_hints = (Hint **)
1340 repalloc(hstate->all_hints,
1341 sizeof(Hint *) * hstate->max_all_hints);
1344 hstate->all_hints[hstate->nall_hints] = hint;
1345 hstate->nall_hints++;
1352 if (parser->keyword == NULL)
1355 ("Unrecognized hint keyword \"%s\".", buf.data));
1366 * Get hints from table by client-supplied query string and application name.
1369 get_hints_from_table(const char *client_query, const char *client_application)
1371 const char *search_query =
1373 " FROM hint_plan.hints "
1374 " WHERE norm_query_string = $1 "
1375 " AND ( application_name = $2 "
1376 " OR application_name = '' ) "
1377 " ORDER BY application_name DESC";
1378 static SPIPlanPtr plan = NULL;
1380 Oid argtypes[2] = { TEXTOID, TEXTOID };
1382 bool nulls[2] = { false, false };
1395 p = SPI_prepare(search_query, 2, argtypes);
1396 plan = SPI_saveplan(p);
1400 qry = cstring_to_text(client_query);
1401 app = cstring_to_text(client_application);
1402 values[0] = PointerGetDatum(qry);
1403 values[1] = PointerGetDatum(app);
1405 SPI_execute_plan(plan, values, nulls, true, 1);
1407 if (SPI_processed > 0)
1411 hints = SPI_getvalue(SPI_tuptable->vals[0],
1412 SPI_tuptable->tupdesc, 1);
1414 * Here we use SPI_palloc to ensure that hints string is valid even
1415 * after SPI_finish call. We can't use simple palloc because it
1416 * allocates memory in SPI's context and that context is deleted in
1419 buf = SPI_palloc(strlen(hints) + 1);
1439 * Get client-supplied query string.
1442 get_query_string(void)
1448 PreparedStatement *entry;
1450 entry = FetchPreparedStatement(stmt_name, true);
1451 p = entry->plansource->query_string;
1453 else if (plpgsql_query_string)
1454 p = plpgsql_query_string;
1456 p = debug_query_string;
1462 * Get hints from the head block comment in client-supplied query string.
1465 get_hints_from_comment(const char *p)
1467 const char *hint_head;
1475 /* extract query head comment. */
1476 hint_head = strstr(p, HINT_START);
1477 if (hint_head == NULL)
1479 for (;p < hint_head; p++)
1482 * Allow these characters precedes hint comment:
1484 * - alphabets which are in ASCII range
1485 * - space, tabs and new-lines
1486 * - underscores, for identifier
1487 * - commas, for SELECT clause, EXPLAIN and PREPARE
1488 * - parentheses, for EXPLAIN and PREPARE
1490 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1491 * avoid behavior which depends on locale setting.
1493 if (!(*p >= '0' && *p <= '9') &&
1494 !(*p >= 'A' && *p <= 'Z') &&
1495 !(*p >= 'a' && *p <= 'z') &&
1499 *p != '(' && *p != ')')
1503 len = strlen(HINT_START);
1508 /* find hint end keyword. */
1509 if ((tail = strstr(p, HINT_END)) == NULL)
1511 hint_ereport(head, ("Unterminated block comment."));
1515 /* We don't support nested block comments. */
1516 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1518 hint_ereport(head, ("Nested block comments are not supported."));
1522 /* Make a copy of hint. */
1524 head = palloc(len + 1);
1525 memcpy(head, p, len);
1533 * Parse hints that got, create hint struct from parse tree and parse hints.
1536 create_hintstate(Query *parse, const char *hints)
1546 hstate = HintStateCreate();
1547 hstate->hint_str = (char *) hints;
1549 /* parse each hint. */
1550 parse_hints(hstate, parse, p);
1552 /* When nothing specified a hint, we free HintState and returns NULL. */
1553 if (hstate->nall_hints == 0)
1555 HintStateDelete(hstate);
1559 /* Sort hints in order of original position. */
1560 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1563 /* Count number of hints per hint-type. */
1564 for (i = 0; i < hstate->nall_hints; i++)
1566 Hint *cur_hint = hstate->all_hints[i];
1567 hstate->num_hints[cur_hint->type]++;
1571 * If an object (or a set of objects) has multiple hints of same hint-type,
1572 * only the last hint is valid and others are ignored in planning.
1573 * Hints except the last are marked as 'duplicated' to remember the order.
1575 for (i = 0; i < hstate->nall_hints - 1; i++)
1577 Hint *cur_hint = hstate->all_hints[i];
1578 Hint *next_hint = hstate->all_hints[i + 1];
1581 * Leading hint is marked as 'duplicated' in transform_join_hints.
1583 if (cur_hint->type == HINT_TYPE_LEADING &&
1584 next_hint->type == HINT_TYPE_LEADING)
1588 * Note that we need to pass addresses of hint pointers, because
1589 * HintCmp is designed to sort array of Hint* by qsort.
1591 if (HintCmp(&cur_hint, &next_hint) == 0)
1593 hint_ereport(cur_hint->hint_str,
1594 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1595 cur_hint->state = HINT_STATE_DUPLICATION;
1600 * Make sure that per-type array pointers point proper position in the
1601 * array which consists of all hints.
1603 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1604 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1605 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1606 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1607 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1608 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1609 hstate->num_hints[HINT_TYPE_LEADING]);
1615 * Parse inside of parentheses of scan-method hints.
1618 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1621 const char *keyword = hint->base.keyword;
1622 HintKeyword hint_keyword = hint->base.hint_keyword;
1623 List *name_list = NIL;
1626 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1629 /* Parse relation name and index name(s) if given hint accepts. */
1630 length = list_length(name_list);
1633 hint->relname = linitial(name_list);
1634 hint->indexnames = list_delete_first(name_list);
1636 /* check whether the hint accepts index name(s). */
1638 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1639 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1640 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1641 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1642 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1643 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1646 ("%s hint accepts only one relation.",
1647 hint->base.keyword));
1648 hint->base.state = HINT_STATE_ERROR;
1655 ("%s hint requires a relation.",
1656 hint->base.keyword));
1657 hint->base.state = HINT_STATE_ERROR;
1661 /* Set a bit for specified hint. */
1662 switch (hint_keyword)
1664 case HINT_KEYWORD_SEQSCAN:
1665 hint->enforce_mask = ENABLE_SEQSCAN;
1667 case HINT_KEYWORD_INDEXSCAN:
1668 hint->enforce_mask = ENABLE_INDEXSCAN;
1670 case HINT_KEYWORD_INDEXSCANREGEXP:
1671 hint->enforce_mask = ENABLE_INDEXSCAN;
1672 hint->regexp = true;
1674 case HINT_KEYWORD_BITMAPSCAN:
1675 hint->enforce_mask = ENABLE_BITMAPSCAN;
1677 case HINT_KEYWORD_BITMAPSCANREGEXP:
1678 hint->enforce_mask = ENABLE_BITMAPSCAN;
1679 hint->regexp = true;
1681 case HINT_KEYWORD_TIDSCAN:
1682 hint->enforce_mask = ENABLE_TIDSCAN;
1684 case HINT_KEYWORD_NOSEQSCAN:
1685 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1687 case HINT_KEYWORD_NOINDEXSCAN:
1688 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1690 case HINT_KEYWORD_NOBITMAPSCAN:
1691 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1693 case HINT_KEYWORD_NOTIDSCAN:
1694 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1696 case HINT_KEYWORD_INDEXONLYSCAN:
1697 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1699 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1700 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1701 hint->regexp = true;
1703 case HINT_KEYWORD_NOINDEXONLYSCAN:
1704 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1707 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1716 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1719 const char *keyword = hint->base.keyword;
1720 HintKeyword hint_keyword = hint->base.hint_keyword;
1721 List *name_list = NIL;
1723 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1726 hint->nrels = list_length(name_list);
1728 if (hint->nrels > 0)
1734 * Transform relation names from list to array to sort them with qsort
1737 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1738 foreach (l, name_list)
1740 hint->relnames[i] = lfirst(l);
1745 list_free(name_list);
1747 /* A join hint requires at least two relations */
1748 if (hint->nrels < 2)
1751 ("%s hint requires at least two relations.",
1752 hint->base.keyword));
1753 hint->base.state = HINT_STATE_ERROR;
1757 /* Sort hints in alphabetical order of relation names. */
1758 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1760 switch (hint_keyword)
1762 case HINT_KEYWORD_NESTLOOP:
1763 hint->enforce_mask = ENABLE_NESTLOOP;
1765 case HINT_KEYWORD_MERGEJOIN:
1766 hint->enforce_mask = ENABLE_MERGEJOIN;
1768 case HINT_KEYWORD_HASHJOIN:
1769 hint->enforce_mask = ENABLE_HASHJOIN;
1771 case HINT_KEYWORD_NONESTLOOP:
1772 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1774 case HINT_KEYWORD_NOMERGEJOIN:
1775 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1777 case HINT_KEYWORD_NOHASHJOIN:
1778 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1781 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1790 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1793 if (outer_inner->outer_inner_pair == NIL)
1795 if (outer_inner->relation)
1801 if (list_length(outer_inner->outer_inner_pair) == 2)
1803 foreach(l, outer_inner->outer_inner_pair)
1805 if (!OuterInnerPairCheck(lfirst(l)))
1816 OuterInnerList(OuterInnerRels *outer_inner)
1818 List *outer_inner_list = NIL;
1820 OuterInnerRels *outer_inner_rels;
1822 foreach(l, outer_inner->outer_inner_pair)
1824 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
1826 if (outer_inner_rels->relation != NULL)
1827 outer_inner_list = lappend(outer_inner_list,
1828 outer_inner_rels->relation);
1830 outer_inner_list = list_concat(outer_inner_list,
1831 OuterInnerList(outer_inner_rels));
1833 return outer_inner_list;
1837 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1840 List *name_list = NIL;
1841 OuterInnerRels *outer_inner = NULL;
1843 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
1847 if (outer_inner != NULL)
1848 name_list = OuterInnerList(outer_inner);
1850 hint->relations = name_list;
1851 hint->outer_inner = outer_inner;
1853 /* A Leading hint requires at least two relations */
1854 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
1856 hint_ereport(hint->base.hint_str,
1857 ("%s hint requires at least two relations.",
1859 hint->base.state = HINT_STATE_ERROR;
1861 else if (hint->outer_inner != NULL &&
1862 !OuterInnerPairCheck(hint->outer_inner))
1864 hint_ereport(hint->base.hint_str,
1865 ("%s hint requires two sets of relations when parentheses nests.",
1867 hint->base.state = HINT_STATE_ERROR;
1874 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1876 List *name_list = NIL;
1878 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
1882 hint->words = name_list;
1884 /* We need both name and value to set GUC parameter. */
1885 if (list_length(name_list) == 2)
1887 hint->name = linitial(name_list);
1888 hint->value = lsecond(name_list);
1892 hint_ereport(hint->base.hint_str,
1893 ("%s hint requires name and value of GUC parameter.",
1895 hint->base.state = HINT_STATE_ERROR;
1902 * set GUC parameter functions
1906 set_config_option_wrapper(const char *name, const char *value,
1907 GucContext context, GucSource source,
1908 GucAction action, bool changeVal, int elevel)
1911 MemoryContext ccxt = CurrentMemoryContext;
1915 result = set_config_option(name, value, context, source,
1916 action, changeVal, 0);
1922 /* Save error info */
1923 MemoryContextSwitchTo(ccxt);
1924 errdata = CopyErrorData();
1927 ereport(elevel, (errcode(errdata->sqlerrcode),
1928 errmsg("%s", errdata->message),
1929 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1930 errdata->hint ? errhint("%s", errdata->hint) : 0));
1931 FreeErrorData(errdata);
1939 set_config_options(SetHint **options, int noptions, GucContext context)
1944 save_nestlevel = NewGUCNestLevel();
1946 for (i = 0; i < noptions; i++)
1948 SetHint *hint = options[i];
1951 if (!hint_state_enabled(hint))
1954 result = set_config_option_wrapper(hint->name, hint->value, context,
1955 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1956 pg_hint_plan_parse_messages);
1958 hint->base.state = HINT_STATE_USED;
1960 hint->base.state = HINT_STATE_ERROR;
1963 return save_nestlevel;
1966 #define SET_CONFIG_OPTION(name, type_bits) \
1967 set_config_option_wrapper((name), \
1968 (mask & (type_bits)) ? "true" : "false", \
1969 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1972 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1976 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1977 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1978 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1980 mask = enforce_mask;
1982 mask = enforce_mask & current_hint->init_scan_mask;
1984 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1985 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1986 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1987 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1988 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1992 set_join_config_options(unsigned char enforce_mask, GucContext context)
1996 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1997 enforce_mask == ENABLE_HASHJOIN)
1998 mask = enforce_mask;
2000 mask = enforce_mask & current_hint->init_join_mask;
2002 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2003 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2004 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2008 * pg_hint_plan hook functions
2012 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
2013 ParamListInfo params, bool isTopLevel,
2014 DestReceiver *dest, char *completionTag)
2019 * Use standard planner if pg_hint_plan is disabled or current nesting
2020 * depth is nesting depth of SPI calls.
2022 if (!pg_hint_plan_enable_hint || nested_level > 0)
2024 if (prev_ProcessUtility)
2025 (*prev_ProcessUtility) (parsetree, queryString, params,
2026 isTopLevel, dest, completionTag);
2028 standard_ProcessUtility(parsetree, queryString, params,
2029 isTopLevel, dest, completionTag);
2035 if (IsA(node, ExplainStmt))
2038 * Draw out parse tree of actual query from Query struct of EXPLAIN
2044 stmt = (ExplainStmt *) node;
2046 Assert(IsA(stmt->query, Query));
2047 query = (Query *) stmt->query;
2049 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2050 node = query->utilityStmt;
2054 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2055 * specified to preceding PREPARE command to use it as source of hints.
2057 if (IsA(node, ExecuteStmt))
2061 stmt = (ExecuteStmt *) node;
2062 stmt_name = stmt->name;
2066 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2069 if (IsA(node, CreateTableAsStmt))
2071 CreateTableAsStmt *stmt;
2074 stmt = (CreateTableAsStmt *) node;
2075 Assert(IsA(stmt->query, Query));
2076 query = (Query *) stmt->query;
2078 if (query->commandType == CMD_UTILITY &&
2079 IsA(query->utilityStmt, ExecuteStmt))
2081 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2082 stmt_name = estmt->name;
2090 if (prev_ProcessUtility)
2091 (*prev_ProcessUtility) (parsetree, queryString, params,
2092 isTopLevel, dest, completionTag);
2094 standard_ProcessUtility(parsetree, queryString, params,
2095 isTopLevel, dest, completionTag);
2109 if (prev_ProcessUtility)
2110 (*prev_ProcessUtility) (parsetree, queryString, params,
2111 isTopLevel, dest, completionTag);
2113 standard_ProcessUtility(parsetree, queryString, params,
2114 isTopLevel, dest, completionTag);
2118 * Push a hint into hint stack which is implemented with List struct. Head of
2119 * list is top of stack.
2122 push_hint(HintState *hstate)
2124 /* Prepend new hint to the list means pushing to stack. */
2125 HintStateStack = lcons(hstate, HintStateStack);
2127 /* Pushed hint is the one which should be used hereafter. */
2128 current_hint = hstate;
2131 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2135 /* Hint stack must not be empty. */
2136 if(HintStateStack == NIL)
2137 elog(ERROR, "hint stack is empty");
2140 * Take a hint at the head from the list, and free it. Switch current_hint
2141 * to point new head (NULL if the list is empty).
2143 HintStateStack = list_delete_first(HintStateStack);
2144 HintStateDelete(current_hint);
2145 if(HintStateStack == NIL)
2146 current_hint = NULL;
2148 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2151 static PlannedStmt *
2152 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2154 const char *hints = NULL;
2157 pgssJumbleState jstate;
2160 PlannedStmt *result;
2164 * Use standard planner if pg_hint_plan is disabled or current nesting
2165 * depth is nesting depth of SPI calls. Other hook functions try to change
2166 * plan with current_hint if any, so set it to NULL.
2168 if (!pg_hint_plan_enable_hint || nested_level > 0)
2169 goto standard_planner_proc;
2171 /* Create hint struct from client-supplied query string. */
2172 query = get_query_string();
2175 * Create hintstate from hint specified for the query, if any.
2177 * First we lookup hint in pg_hint.hints table by normalized query string,
2178 * unless pg_hint_plan.enable_hint_table is OFF.
2179 * This parameter provides option to avoid overhead of table lookup during
2182 * If no hint was found, then we try to get hint from special query comment.
2184 if (pg_hint_plan_enable_hint_table)
2187 * Search hint information which is stored for the query and the
2188 * application. Query string is normalized before using in condition
2189 * in order to allow fuzzy matching.
2191 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2192 * careful when supporting PostgreSQL's version up.
2194 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2195 jstate.jumble_len = 0;
2196 jstate.clocations_buf_size = 32;
2197 jstate.clocations = (pgssLocationLen *)
2198 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2199 jstate.clocations_count = 0;
2200 JumbleQuery(&jstate, parse);
2202 * generate_normalized_query() copies exact given query_len bytes, so we
2203 * add 1 byte for null-termination here. As comments on
2204 * generate_normalized_query says, generate_normalized_query doesn't
2205 * take care of null-terminate, but additional 1 byte ensures that '\0'
2206 * byte in the source buffer to be copied into norm_query.
2208 query_len = strlen(query) + 1;
2209 norm_query = generate_normalized_query(&jstate,
2212 GetDatabaseEncoding());
2213 hints = get_hints_from_table(norm_query, application_name);
2215 "pg_hint_plan: get_hints_from_table [%s][%s]=>[%s]",
2216 norm_query, application_name, hints ? hints : "(none)");
2219 hints = get_hints_from_comment(query);
2220 hstate = create_hintstate(parse, hints);
2223 * Use standard planner if the statement has not valid hint. Other hook
2224 * functions try to change plan with current_hint if any, so set it to
2228 goto standard_planner_proc;
2231 * Push new hint struct to the hint stack to disable previous hint context.
2235 /* Set GUC parameters which are specified with Set hint. */
2236 save_nestlevel = set_config_options(current_hint->set_hints,
2237 current_hint->num_hints[HINT_TYPE_SET],
2238 current_hint->context);
2241 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2242 if (enable_indexscan)
2243 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2244 if (enable_bitmapscan)
2245 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2247 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2248 if (enable_indexonlyscan)
2249 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2250 if (enable_nestloop)
2251 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2252 if (enable_mergejoin)
2253 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2254 if (enable_hashjoin)
2255 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2258 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2259 * state when this planner started when error occurred in planner.
2264 result = (*prev_planner) (parse, cursorOptions, boundParams);
2266 result = standard_planner(parse, cursorOptions, boundParams);
2271 * Rollback changes of GUC parameters, and pop current hint context
2272 * from hint stack to rewind the state.
2274 AtEOXact_GUC(true, save_nestlevel);
2280 /* Print hint in debug mode. */
2281 if (pg_hint_plan_debug_print)
2282 HintStateDump(current_hint);
2285 * Rollback changes of GUC parameters, and pop current hint context from
2286 * hint stack to rewind the state.
2288 AtEOXact_GUC(true, save_nestlevel);
2293 standard_planner_proc:
2294 current_hint = NULL;
2296 return (*prev_planner) (parse, cursorOptions, boundParams);
2298 return standard_planner(parse, cursorOptions, boundParams);
2302 * Return scan method hint which matches given aliasname.
2304 static ScanMethodHint *
2305 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2311 * We can't apply scan method hint if the relation is:
2312 * - not a base relation
2313 * - not an ordinary relation (such as join and subquery)
2315 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2318 rte = root->simple_rte_array[rel->relid];
2320 /* We can't force scan method of foreign tables */
2321 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2324 /* Find scan method hint, which matches given names, from the list. */
2325 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2327 ScanMethodHint *hint = current_hint->scan_hints[i];
2329 /* We ignore disabled hints. */
2330 if (!hint_state_enabled(hint))
2333 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2343 * Returns TRUE on match, FALSE on no match.
2345 * s1 --- the data to match against
2346 * s2 --- the pattern
2348 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2351 regexpeq(const char *s1, const char *s2)
2357 strcpy(name.data, s1);
2358 regexp = cstring_to_text(s2);
2360 result = DirectFunctionCall2Coll(nameregexeq,
2361 DEFAULT_COLLATION_OID,
2362 NameGetDatum(&name),
2363 PointerGetDatum(regexp));
2364 return DatumGetBool(result);
2368 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2376 * We delete all the IndexOptInfo list and prevent you from being usable by
2379 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2380 hint->enforce_mask == ENABLE_TIDSCAN)
2382 list_free_deep(rel->indexlist);
2383 rel->indexlist = NIL;
2384 hint->base.state = HINT_STATE_USED;
2390 * When a list of indexes is not specified, we just use all indexes.
2392 if (hint->indexnames == NIL)
2396 * Leaving only an specified index, we delete it from a IndexOptInfo list
2400 if (pg_hint_plan_debug_print)
2401 initStringInfo(&buf);
2403 for (cell = list_head(rel->indexlist); cell; cell = next)
2405 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2406 char *indexname = get_rel_name(info->indexoid);
2408 bool use_index = false;
2412 foreach(l, hint->indexnames)
2414 char *hintname = (char *) lfirst(l);
2418 result = regexpeq(indexname, hintname);
2420 result = RelnameCmp(&indexname, &hintname) == 0;
2425 if (pg_hint_plan_debug_print)
2427 appendStringInfoCharMacro(&buf, ' ');
2428 quote_value(&buf, indexname);
2436 * to make the index a candidate when definition of this index is
2437 * matched with the index's definition of current_hint.
2439 if (OidIsValid(relationObjectId) && !use_index)
2441 foreach(l, current_hint->parent_index_infos)
2445 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2447 /* check to match the parameter of unique */
2448 if (p_info->indisunique != info->unique)
2451 /* check to match the parameter of index's method */
2452 if (p_info->method != info->relam)
2455 /* to check to match the indexkey's configuration */
2456 if ((list_length(p_info->column_names)) !=
2460 /* check to match the indexkey's configuration */
2461 for (i = 0; i < info->ncolumns; i++)
2463 char *c_attname = NULL;
2464 char *p_attname = NULL;
2467 list_nth(p_info->column_names, i);
2469 /* both are expressions */
2470 if (info->indexkeys[i] == 0 && !p_attname)
2473 /* one's column is expression, the other is not */
2474 if (info->indexkeys[i] == 0 || !p_attname)
2477 c_attname = get_attname(relationObjectId,
2478 info->indexkeys[i]);
2480 if (strcmp(p_attname, c_attname) != 0)
2483 if (p_info->indcollation[i] != info->indexcollations[i])
2486 if (p_info->opclass[i] != info->opcintype[i])
2489 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2490 info->reverse_sort[i])
2493 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2494 info->nulls_first[i])
2499 if (i != info->ncolumns)
2502 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2503 (p_info->indpred_str && (info->indpred != NIL)))
2506 * Fetch the pg_index tuple by the Oid of the index
2508 ht_idx = SearchSysCache1(INDEXRELID,
2509 ObjectIdGetDatum(info->indexoid));
2511 /* check to match the expression's parameter of index */
2512 if (p_info->expression_str &&
2513 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2520 * to change the expression's parameter of child's
2523 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2524 Anum_pg_index_indexprs,
2527 result = DirectFunctionCall2(pg_get_expr,
2532 if (strcmp(p_info->expression_str,
2533 text_to_cstring(DatumGetTextP(result))) != 0)
2536 ReleaseSysCache(ht_idx);
2542 /* Check to match the predicate's parameter of index */
2543 if (p_info->indpred_str &&
2544 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2551 * to change the predicate's parameter of child's
2554 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2555 Anum_pg_index_indpred,
2558 result = DirectFunctionCall2(pg_get_expr,
2563 if (strcmp(p_info->indpred_str,
2564 text_to_cstring(DatumGetTextP(result))) != 0)
2567 ReleaseSysCache(ht_idx);
2574 ReleaseSysCache(ht_idx);
2576 else if (p_info->expression_str || (info->indexprs != NIL))
2578 else if (p_info->indpred_str || (info->indpred != NIL))
2583 /* to log the candidate of index */
2584 if (pg_hint_plan_debug_print)
2586 appendStringInfoCharMacro(&buf, ' ');
2587 quote_value(&buf, indexname);
2595 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2602 if (pg_hint_plan_debug_print)
2605 StringInfoData rel_buf;
2607 if (OidIsValid(relationObjectId))
2608 relname = get_rel_name(relationObjectId);
2610 relname = hint->relname;
2612 initStringInfo(&rel_buf);
2613 quote_value(&rel_buf, relname);
2616 (errmsg("available indexes for %s(%s):%s",
2621 pfree(rel_buf.data);
2626 * Return information of index definition.
2628 static ParentIndexInfo *
2629 get_parent_index_info(Oid indexoid, Oid relid)
2631 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
2632 Relation indexRelation;
2633 Form_pg_index index;
2637 indexRelation = index_open(indexoid, RowExclusiveLock);
2639 index = indexRelation->rd_index;
2641 p_info->indisunique = index->indisunique;
2642 p_info->method = indexRelation->rd_rel->relam;
2644 p_info->column_names = NIL;
2645 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2646 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2647 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
2649 for (i = 0; i < index->indnatts; i++)
2651 attname = get_attname(relid, index->indkey.values[i]);
2652 p_info->column_names = lappend(p_info->column_names, attname);
2654 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
2655 p_info->opclass[i] = indexRelation->rd_opcintype[i];
2656 p_info->indoption[i] = indexRelation->rd_indoption[i];
2660 * to check to match the expression's parameter of index with child indexes
2662 p_info->expression_str = NULL;
2663 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
2669 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2670 Anum_pg_index_indexprs, &isnull);
2672 result = DirectFunctionCall2(pg_get_expr,
2674 ObjectIdGetDatum(relid));
2676 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
2680 * to check to match the predicate's parameter of index with child indexes
2682 p_info->indpred_str = NULL;
2683 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
2689 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2690 Anum_pg_index_indpred, &isnull);
2692 result = DirectFunctionCall2(pg_get_expr,
2694 ObjectIdGetDatum(relid));
2696 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
2699 index_close(indexRelation, NoLock);
2705 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2706 bool inhparent, RelOptInfo *rel)
2708 ScanMethodHint *hint;
2710 if (prev_get_relation_info)
2711 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2714 * Do nothing if we don't have valid hint in this context or current
2715 * nesting depth is nesting depth of SPI calls.
2717 if (!current_hint || nested_level > 0)
2722 /* store does relids of parent table. */
2723 current_hint->parent_relid = rel->relid;
2724 current_hint->parent_rel_oid = relationObjectId;
2726 else if (current_hint->parent_relid != 0)
2729 * We use the same GUC parameter if this table is the child table of a
2730 * table called pg_hint_plan_get_relation_info just before that.
2734 /* append_rel_list contains all append rels; ignore others */
2735 foreach(l, root->append_rel_list)
2737 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2739 /* This rel is child table. */
2740 if (appinfo->parent_relid == current_hint->parent_relid &&
2741 appinfo->child_relid == rel->relid)
2743 if (current_hint->parent_hint)
2744 delete_indexes(current_hint->parent_hint, rel,
2751 /* This rel is not inherit table. */
2752 current_hint->parent_relid = 0;
2753 current_hint->parent_rel_oid = InvalidOid;
2754 current_hint->parent_hint = NULL;
2758 * If scan method hint was given, reset GUC parameters which control
2759 * planner behavior about choosing scan methods.
2761 if ((hint = find_scan_hint(root, rel)) == NULL)
2763 set_scan_config_options(current_hint->init_scan_mask,
2764 current_hint->context);
2767 set_scan_config_options(hint->enforce_mask, current_hint->context);
2768 hint->base.state = HINT_STATE_USED;
2776 current_hint->parent_hint = hint;
2778 relation = heap_open(relationObjectId, NoLock);
2779 indexoidlist = RelationGetIndexList(relation);
2781 foreach(l, indexoidlist)
2783 Oid indexoid = lfirst_oid(l);
2784 char *indexname = get_rel_name(indexoid);
2785 bool use_index = false;
2787 ParentIndexInfo *parent_index_info;
2789 foreach(lc, hint->indexnames)
2791 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
2800 parent_index_info = get_parent_index_info(indexoid,
2802 current_hint->parent_index_infos =
2803 lappend(current_hint->parent_index_infos, parent_index_info);
2805 heap_close(relation, NoLock);
2808 delete_indexes(hint, rel, InvalidOid);
2812 * Return index of relation which matches given aliasname, or 0 if not found.
2813 * If same aliasname was used multiple times in a query, return -1.
2816 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
2822 for (i = 1; i < root->simple_rel_array_size; i++)
2826 if (root->simple_rel_array[i] == NULL)
2829 Assert(i == root->simple_rel_array[i]->relid);
2831 if (RelnameCmp(&aliasname,
2832 &root->simple_rte_array[i]->eref->aliasname) != 0)
2835 foreach(l, initial_rels)
2837 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2839 if (rel->reloptkind == RELOPT_BASEREL)
2841 if (rel->relid != i)
2846 Assert(rel->reloptkind == RELOPT_JOINREL);
2848 if (!bms_is_member(i, rel->relids))
2855 ("Relation name \"%s\" is ambiguous.",
2870 * Return join hint which matches given joinrelids.
2872 static JoinMethodHint *
2873 find_join_hint(Relids joinrelids)
2878 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
2880 foreach(l, join_hint)
2882 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
2884 if (bms_equal(joinrelids, hint->joinrelids))
2892 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
2893 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
2895 OuterInnerRels *outer_rels;
2896 OuterInnerRels *inner_rels;
2897 Relids outer_relids;
2898 Relids inner_relids;
2900 JoinMethodHint *hint;
2902 if (outer_inner->relation != NULL)
2904 return bms_make_singleton(
2905 find_relid_aliasname(root, outer_inner->relation,
2907 leading_hint->base.hint_str));
2910 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
2911 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
2913 outer_relids = OuterInnerJoinCreate(outer_rels,
2919 inner_relids = OuterInnerJoinCreate(inner_rels,
2926 join_relids = bms_add_members(outer_relids, inner_relids);
2928 if (bms_num_members(join_relids) > nbaserel)
2932 * If we don't have join method hint, create new one for the
2933 * join combination with all join methods are enabled.
2935 hint = find_join_hint(join_relids);
2939 * Here relnames is not set, since Relids bitmap is sufficient to
2940 * control paths of this query afterward.
2942 hint = (JoinMethodHint *) JoinMethodHintCreate(
2943 leading_hint->base.hint_str,
2945 HINT_KEYWORD_LEADING);
2946 hint->base.state = HINT_STATE_USED;
2947 hint->nrels = bms_num_members(join_relids);
2948 hint->enforce_mask = ENABLE_ALL_JOIN;
2949 hint->joinrelids = bms_copy(join_relids);
2950 hint->inner_nrels = bms_num_members(inner_relids);
2951 hint->inner_joinrelids = bms_copy(inner_relids);
2953 hstate->join_hint_level[hint->nrels] =
2954 lappend(hstate->join_hint_level[hint->nrels], hint);
2958 hint->inner_nrels = bms_num_members(inner_relids);
2959 hint->inner_joinrelids = bms_copy(inner_relids);
2966 * Transform join method hint into handy form.
2968 * - create bitmap of relids from alias names, to make it easier to check
2969 * whether a join path matches a join method hint.
2970 * - add join method hints which are necessary to enforce join order
2971 * specified by Leading hint
2974 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2975 List *initial_rels, JoinMethodHint **join_method_hints)
2983 LeadingHint *lhint = NULL;
2986 * Create bitmap of relids from alias names for each join method hint.
2987 * Bitmaps are more handy than strings in join searching.
2989 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2991 JoinMethodHint *hint = hstate->join_hints[i];
2994 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
2997 bms_free(hint->joinrelids);
2998 hint->joinrelids = NULL;
3000 for (j = 0; j < hint->nrels; j++)
3002 relname = hint->relnames[j];
3004 relid = find_relid_aliasname(root, relname, initial_rels,
3005 hint->base.hint_str);
3008 hint->base.state = HINT_STATE_ERROR;
3013 if (bms_is_member(relid, hint->joinrelids))
3015 hint_ereport(hint->base.hint_str,
3016 ("Relation name \"%s\" is duplicated.", relname));
3017 hint->base.state = HINT_STATE_ERROR;
3021 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
3024 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
3027 hstate->join_hint_level[hint->nrels] =
3028 lappend(hstate->join_hint_level[hint->nrels], hint);
3031 /* Do nothing if no Leading hint was supplied. */
3032 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
3036 * Decide to use Leading hint。
3038 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
3040 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
3043 if (leading_hint->base.state == HINT_STATE_ERROR)
3049 foreach(l, leading_hint->relations)
3051 relname = (char *)lfirst(l);;
3053 relid = find_relid_aliasname(root, relname, initial_rels,
3054 leading_hint->base.hint_str);
3056 leading_hint->base.state = HINT_STATE_ERROR;
3061 if (bms_is_member(relid, relids))
3063 hint_ereport(leading_hint->base.hint_str,
3064 ("Relation name \"%s\" is duplicated.", relname));
3065 leading_hint->base.state = HINT_STATE_ERROR;
3069 relids = bms_add_member(relids, relid);
3072 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3077 hint_ereport(lhint->base.hint_str,
3078 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3079 lhint->base.state = HINT_STATE_DUPLICATION;
3081 leading_hint->base.state = HINT_STATE_USED;
3082 lhint = leading_hint;
3085 /* check to exist Leading hint marked with 'used'. */
3090 * We need join method hints which fit specified join order in every join
3091 * level. For example, Leading(A B C) virtually requires following join
3092 * method hints, if no join method hint supplied:
3094 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3095 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3097 * If we already have join method hint which fits specified join order in
3098 * that join level, we leave it as-is and don't add new hints.
3102 if (lhint->outer_inner == NULL)
3104 foreach(l, lhint->relations)
3106 JoinMethodHint *hint;
3108 relname = (char *)lfirst(l);
3111 * Find relid of the relation which has given name. If we have the
3112 * name given in Leading hint multiple times in the join, nothing to
3115 relid = find_relid_aliasname(root, relname, initial_rels,
3118 /* Create bitmap of relids for current join level. */
3119 joinrelids = bms_add_member(joinrelids, relid);
3122 /* We never have join method hint for single relation. */
3127 * If we don't have join method hint, create new one for the
3128 * join combination with all join methods are enabled.
3130 hint = find_join_hint(joinrelids);
3134 * Here relnames is not set, since Relids bitmap is sufficient
3135 * to control paths of this query afterward.
3137 hint = (JoinMethodHint *) JoinMethodHintCreate(
3138 lhint->base.hint_str,
3140 HINT_KEYWORD_LEADING);
3141 hint->base.state = HINT_STATE_USED;
3142 hint->nrels = njoinrels;
3143 hint->enforce_mask = ENABLE_ALL_JOIN;
3144 hint->joinrelids = bms_copy(joinrelids);
3147 join_method_hints[njoinrels] = hint;
3149 if (njoinrels >= nbaserel)
3152 bms_free(joinrelids);
3158 * Delete all join hints which have different combination from Leading
3161 for (i = 2; i <= njoinrels; i++)
3163 list_free(hstate->join_hint_level[i]);
3165 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3170 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3177 njoinrels = bms_num_members(joinrelids);
3178 Assert(njoinrels >= 2);
3181 * Delete all join hints which have different combination from Leading
3184 for (i = 2;i <= njoinrels; i++)
3186 if (hstate->join_hint_level[i] != NIL)
3188 ListCell *prev = NULL;
3189 ListCell *next = NULL;
3190 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3193 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3197 if (hint->inner_nrels == 0 &&
3198 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3199 bms_equal(bms_union(hint->joinrelids, joinrelids),
3202 hstate->join_hint_level[i] =
3203 list_delete_cell(hstate->join_hint_level[i], l,
3212 bms_free(joinrelids);
3215 if (hint_state_enabled(lhint))
3217 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3224 * set_plain_rel_pathlist
3225 * Build access paths for a plain relation (no subquery, no inheritance)
3227 * This function was copied and edited from set_plain_rel_pathlist() in
3228 * src/backend/optimizer/path/allpaths.c
3231 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3233 /* Consider sequential scan */
3234 add_path(rel, create_seqscan_path(root, rel, NULL));
3236 /* Consider index scans */
3237 create_index_paths(root, rel);
3239 /* Consider TID scans */
3240 create_tidscan_paths(root, rel);
3242 /* Now find the cheapest of the paths for this rel */
3247 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3252 foreach(l, initial_rels)
3254 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3256 ScanMethodHint *hint;
3258 /* Skip relations which we can't choose scan method. */
3259 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3262 rte = root->simple_rte_array[rel->relid];
3264 /* We can't force scan method of foreign tables */
3265 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3269 * Create scan paths with GUC parameters which are at the beginning of
3270 * planner if scan method hint is not specified, otherwise use
3271 * specified hints and mark the hint as used.
3273 if ((hint = find_scan_hint(root, rel)) == NULL)
3274 set_scan_config_options(hstate->init_scan_mask,
3278 set_scan_config_options(hint->enforce_mask, hstate->context);
3279 hint->base.state = HINT_STATE_USED;
3282 list_free_deep(rel->pathlist);
3283 rel->pathlist = NIL;
3286 /* It's an "append relation", process accordingly */
3287 set_append_rel_pathlist(root, rel, rel->relid, rte);
3291 set_plain_rel_pathlist(root, rel, rte);
3296 * Restore the GUC variables we set above.
3298 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3302 * wrapper of make_join_rel()
3304 * call make_join_rel() after changing enable_* parameters according to given
3308 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3311 JoinMethodHint *hint;
3315 joinrelids = bms_union(rel1->relids, rel2->relids);
3316 hint = find_join_hint(joinrelids);
3317 bms_free(joinrelids);
3320 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3322 if (hint->inner_nrels == 0)
3324 save_nestlevel = NewGUCNestLevel();
3326 set_join_config_options(hint->enforce_mask, current_hint->context);
3328 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3329 hint->base.state = HINT_STATE_USED;
3332 * Restore the GUC variables we set above.
3334 AtEOXact_GUC(true, save_nestlevel);
3337 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3346 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3347 RelOptInfo *joinrel,
3348 RelOptInfo *outerrel,
3349 RelOptInfo *innerrel,
3351 SpecialJoinInfo *sjinfo,
3354 ScanMethodHint *scan_hint = NULL;
3356 JoinMethodHint *join_hint;
3359 if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
3361 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3362 scan_hint->base.state = HINT_STATE_USED;
3365 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3366 join_hint = find_join_hint(joinrelids);
3367 bms_free(joinrelids);
3369 if (join_hint && join_hint->inner_nrels != 0)
3371 save_nestlevel = NewGUCNestLevel();
3373 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3376 set_join_config_options(join_hint->enforce_mask,
3377 current_hint->context);
3379 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3380 sjinfo, restrictlist);
3381 join_hint->base.state = HINT_STATE_USED;
3385 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3386 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3387 sjinfo, restrictlist);
3391 * Restore the GUC variables we set above.
3393 AtEOXact_GUC(true, save_nestlevel);
3396 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3397 sjinfo, restrictlist);
3399 if (scan_hint != NULL)
3400 set_scan_config_options(current_hint->init_scan_mask,
3401 current_hint->context);
3405 get_num_baserels(List *initial_rels)
3410 foreach(l, initial_rels)
3412 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3414 if (rel->reloptkind == RELOPT_BASEREL)
3416 else if (rel->reloptkind ==RELOPT_JOINREL)
3417 nbaserel+= bms_num_members(rel->relids);
3420 /* other values not expected here */
3421 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3429 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3432 JoinMethodHint **join_method_hints;
3436 bool leading_hint_enable;
3439 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3440 * valid hint is supplied or current nesting depth is nesting depth of SPI
3443 if (!current_hint || nested_level > 0)
3445 if (prev_join_search)
3446 return (*prev_join_search) (root, levels_needed, initial_rels);
3447 else if (enable_geqo && levels_needed >= geqo_threshold)
3448 return geqo(root, levels_needed, initial_rels);
3450 return standard_join_search(root, levels_needed, initial_rels);
3453 /* We apply scan method hint rebuild scan path. */
3454 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3457 * In the case using GEQO, only scan method hints and Set hints have
3458 * effect. Join method and join order is not controllable by hints.
3460 if (enable_geqo && levels_needed >= geqo_threshold)
3461 return geqo(root, levels_needed, initial_rels);
3463 nbaserel = get_num_baserels(initial_rels);
3464 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3465 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3467 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3468 initial_rels, join_method_hints);
3470 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3472 for (i = 2; i <= nbaserel; i++)
3474 list_free(current_hint->join_hint_level[i]);
3476 /* free Leading hint only */
3477 if (join_method_hints[i] != NULL &&
3478 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3479 JoinMethodHintDelete(join_method_hints[i]);
3481 pfree(current_hint->join_hint_level);
3482 pfree(join_method_hints);
3484 if (leading_hint_enable)
3485 set_join_config_options(current_hint->init_join_mask,
3486 current_hint->context);
3493 * Build access paths for a base relation
3495 * This function was copied and edited from set_rel_pathlist() in
3496 * src/backend/optimizer/path/allpaths.c
3499 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3500 Index rti, RangeTblEntry *rte)
3502 if (IS_DUMMY_REL(rel))
3504 /* We already proved the relation empty, so nothing more to do */
3508 /* It's an "append relation", process accordingly */
3509 set_append_rel_pathlist(root, rel, rti, rte);
3513 if (rel->rtekind == RTE_RELATION)
3515 if (rte->relkind == RELKIND_RELATION)
3517 /* Plain relation */
3518 set_plain_rel_pathlist(root, rel, rte);
3521 elog(ERROR, "unexpected relkind: %c", rte->relkind);
3524 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
3529 * stmt_beg callback is called when each query in PL/pgSQL function is about
3530 * to be executed. At that timing, we save query string in the global variable
3531 * plpgsql_query_string to use it in planner hook. It's safe to use one global
3532 * variable for the purpose, because its content is only necessary until
3533 * planner hook is called for the query, so recursive PL/pgSQL function calls
3534 * don't harm this mechanism.
3537 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3539 PLpgSQL_expr *expr = NULL;
3541 switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
3543 case PLPGSQL_STMT_FORS:
3544 expr = ((PLpgSQL_stmt_fors *) stmt)->query;
3546 case PLPGSQL_STMT_FORC:
3547 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_forc *)stmt)->curvar]))->cursor_explicit_expr;
3549 case PLPGSQL_STMT_RETURN_QUERY:
3550 if (((PLpgSQL_stmt_return_query *) stmt)->query != NULL)
3551 expr = ((PLpgSQL_stmt_return_query *) stmt)->query;
3553 expr = ((PLpgSQL_stmt_return_query *) stmt)->dynquery;
3555 case PLPGSQL_STMT_EXECSQL:
3556 expr = ((PLpgSQL_stmt_execsql *) stmt)->sqlstmt;
3558 case PLPGSQL_STMT_DYNEXECUTE:
3559 expr = ((PLpgSQL_stmt_dynexecute *) stmt)->query;
3561 case PLPGSQL_STMT_DYNFORS:
3562 expr = ((PLpgSQL_stmt_dynfors *) stmt)->query;
3564 case PLPGSQL_STMT_OPEN:
3565 if (((PLpgSQL_stmt_open *) stmt)->query != NULL)
3566 expr = ((PLpgSQL_stmt_open *) stmt)->query;
3567 else if (((PLpgSQL_stmt_open *) stmt)->dynquery != NULL)
3568 expr = ((PLpgSQL_stmt_open *) stmt)->dynquery;
3570 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_open *)stmt)->curvar]))->cursor_explicit_expr;
3577 plpgsql_query_string = expr->query;
3581 * stmt_end callback is called then each query in PL/pgSQL function has
3582 * finished. At that timing, we clear plpgsql_query_string to tell planner
3583 * hook that next call is not for a query written in PL/pgSQL block.
3586 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3588 if ((enum PLpgSQL_stmt_types) stmt->cmd_type == PLPGSQL_STMT_EXECSQL)
3589 plpgsql_query_string = NULL;
3592 #define standard_join_search pg_hint_plan_standard_join_search
3593 #define join_search_one_level pg_hint_plan_join_search_one_level
3594 #define make_join_rel make_join_rel_wrapper
3597 #undef make_join_rel
3598 #define make_join_rel pg_hint_plan_make_join_rel
3599 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
3600 #include "make_join_rel.c"
3602 #include "pg_stat_statements.c"