1 /*-------------------------------------------------------------------------
4 * do instructions or hints to the planner using C-style block comments
7 * Copyright (c) 2012-2014, 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 "nodes/params.h"
19 #include "optimizer/clauses.h"
20 #include "optimizer/cost.h"
21 #include "optimizer/geqo.h"
22 #include "optimizer/joininfo.h"
23 #include "optimizer/pathnode.h"
24 #include "optimizer/paths.h"
25 #include "optimizer/plancat.h"
26 #include "optimizer/planner.h"
27 #include "optimizer/prep.h"
28 #include "optimizer/restrictinfo.h"
29 #include "parser/analyze.h"
30 #include "parser/scansup.h"
31 #include "tcop/utility.h"
32 #include "utils/builtins.h"
33 #include "utils/lsyscache.h"
34 #include "utils/memutils.h"
35 #include "utils/rel.h"
36 #include "utils/snapmgr.h"
37 #include "utils/syscache.h"
38 #include "utils/resowner.h"
40 #include "catalog/pg_class.h"
42 #include "executor/spi.h"
43 #include "catalog/pg_type.h"
47 /* partially copied from pg_stat_statements */
48 #include "normalize_query.h"
51 #include "access/htup_details.h"
53 #ifdef PG_MODULE_MAGIC
57 #define BLOCK_COMMENT_START "/*"
58 #define BLOCK_COMMENT_END "*/"
59 #define HINT_COMMENT_KEYWORD "+"
60 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
61 #define HINT_END BLOCK_COMMENT_END
64 #define HINT_SEQSCAN "SeqScan"
65 #define HINT_INDEXSCAN "IndexScan"
66 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
67 #define HINT_BITMAPSCAN "BitmapScan"
68 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
69 #define HINT_TIDSCAN "TidScan"
70 #define HINT_NOSEQSCAN "NoSeqScan"
71 #define HINT_NOINDEXSCAN "NoIndexScan"
72 #define HINT_NOBITMAPSCAN "NoBitmapScan"
73 #define HINT_NOTIDSCAN "NoTidScan"
74 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
75 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
76 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
77 #define HINT_NESTLOOP "NestLoop"
78 #define HINT_MERGEJOIN "MergeJoin"
79 #define HINT_HASHJOIN "HashJoin"
80 #define HINT_NONESTLOOP "NoNestLoop"
81 #define HINT_NOMERGEJOIN "NoMergeJoin"
82 #define HINT_NOHASHJOIN "NoHashJoin"
83 #define HINT_LEADING "Leading"
84 #define HINT_SET "Set"
85 #define HINT_ROWS "Rows"
87 #define HINT_ARRAY_DEFAULT_INITSIZE 8
89 #define hint_ereport(str, detail) hint_parse_ereport(str, detail)
90 #define hint_parse_ereport(str, detail) \
92 ereport(pg_hint_plan_parse_message_level, \
93 (errmsg("pg_hint_plan: hint syntax error at or near \"%s\"", (str)), \
97 #define skip_space(str) \
98 while (isspace(*str)) \
103 ENABLE_SEQSCAN = 0x01,
104 ENABLE_INDEXSCAN = 0x02,
105 ENABLE_BITMAPSCAN = 0x04,
106 ENABLE_TIDSCAN = 0x08,
107 ENABLE_INDEXONLYSCAN = 0x10
112 ENABLE_NESTLOOP = 0x01,
113 ENABLE_MERGEJOIN = 0x02,
114 ENABLE_HASHJOIN = 0x04
117 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
118 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
119 ENABLE_INDEXONLYSCAN)
120 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
121 #define DISABLE_ALL_SCAN 0
122 #define DISABLE_ALL_JOIN 0
124 /* hint keyword of enum type*/
125 typedef enum HintKeyword
127 HINT_KEYWORD_SEQSCAN,
128 HINT_KEYWORD_INDEXSCAN,
129 HINT_KEYWORD_INDEXSCANREGEXP,
130 HINT_KEYWORD_BITMAPSCAN,
131 HINT_KEYWORD_BITMAPSCANREGEXP,
132 HINT_KEYWORD_TIDSCAN,
133 HINT_KEYWORD_NOSEQSCAN,
134 HINT_KEYWORD_NOINDEXSCAN,
135 HINT_KEYWORD_NOBITMAPSCAN,
136 HINT_KEYWORD_NOTIDSCAN,
137 HINT_KEYWORD_INDEXONLYSCAN,
138 HINT_KEYWORD_INDEXONLYSCANREGEXP,
139 HINT_KEYWORD_NOINDEXONLYSCAN,
140 HINT_KEYWORD_NESTLOOP,
141 HINT_KEYWORD_MERGEJOIN,
142 HINT_KEYWORD_HASHJOIN,
143 HINT_KEYWORD_NONESTLOOP,
144 HINT_KEYWORD_NOMERGEJOIN,
145 HINT_KEYWORD_NOHASHJOIN,
146 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, bool nolf);
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 5
166 typedef enum HintType
168 HINT_TYPE_SCAN_METHOD,
169 HINT_TYPE_JOIN_METHOD,
175 static const char *HintTypeName[] = {
184 typedef enum HintStatus
186 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
187 HINT_STATE_USED, /* hint is used */
188 HINT_STATE_DUPLICATION, /* specified hint duplication */
189 HINT_STATE_ERROR /* execute error (parse error does not include
193 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
194 (hint)->base.state == HINT_STATE_USED)
196 static unsigned int qno = 0;
197 static unsigned int msgqno = 0;
198 static char qnostr[32];
199 static const char *current_hint_str = NULL;
201 /* common data for all hints. */
204 const char *hint_str; /* must not do pfree */
205 const char *keyword; /* must not do pfree */
206 HintKeyword hint_keyword;
209 HintDeleteFunction delete_func;
210 HintDescFunction desc_func;
211 HintCmpFunction cmp_func;
212 HintParseFunction parse_func;
215 /* scan method hints */
216 typedef struct ScanMethodHint
222 unsigned char enforce_mask;
225 typedef struct ParentIndexInfo
230 char *expression_str;
237 /* join method hints */
238 typedef struct JoinMethodHint
244 unsigned char enforce_mask;
246 Relids inner_joinrelids;
249 /* join order hints */
250 typedef struct OuterInnerRels
253 List *outer_inner_pair;
256 typedef struct LeadingHint
259 List *relations; /* relation names specified in Leading hint */
260 OuterInnerRels *outer_inner;
263 /* change a run-time parameter hints */
264 typedef struct SetHint
267 char *name; /* name of variable */
273 typedef enum RowsValueType {
274 RVT_ABSOLUTE, /* Rows(... #1000) */
275 RVT_ADD, /* Rows(... +1000) */
276 RVT_SUB, /* Rows(... -1000) */
277 RVT_MULTI, /* Rows(... *1.2) */
279 typedef struct RowsHint
286 Relids inner_joinrelids;
288 RowsValueType value_type;
293 * Describes a context of hint processing.
297 char *hint_str; /* original hint string */
300 int nall_hints; /* # of valid all hints */
301 int max_all_hints; /* # of slots for all hints */
302 Hint **all_hints; /* parsed all hints */
304 /* # of each hints */
305 int num_hints[NUM_HINT_TYPE];
307 /* for scan method hints */
308 ScanMethodHint **scan_hints; /* parsed scan hints */
309 int init_scan_mask; /* initial value scan parameter */
310 PlannerInfo *current_root; /* PlannerInfo for the followings */
311 Index parent_relid; /* inherit parent table relid */
312 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
313 List *parent_index_infos; /* information of inherit parent table's
316 /* for join method hints */
317 JoinMethodHint **join_hints; /* parsed join hints */
318 int init_join_mask; /* initial value join parameter */
319 List **join_hint_level;
321 /* for Leading hint */
322 LeadingHint **leading_hint; /* parsed Leading hints */
325 SetHint **set_hints; /* parsed Set hints */
326 GucContext context; /* which GUC parameters can we set? */
329 RowsHint **rows_hints; /* parsed Rows hints */
333 * Describes a hint parser module which is bound with particular hint keyword.
335 typedef struct HintParser
338 HintCreateFunction create_func;
339 HintKeyword hint_keyword;
342 /* Module callbacks */
346 static void push_hint(HintState *hstate);
347 static void pop_hint(void);
349 static void pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query);
350 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
351 ParamListInfo boundParams);
352 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
353 Oid relationObjectId,
354 bool inhparent, RelOptInfo *rel);
355 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
359 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
360 HintKeyword hint_keyword);
361 static void ScanMethodHintDelete(ScanMethodHint *hint);
362 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
363 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
364 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
365 Query *parse, const char *str);
366 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
367 HintKeyword hint_keyword);
368 static void JoinMethodHintDelete(JoinMethodHint *hint);
369 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
370 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
371 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
372 Query *parse, const char *str);
373 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
374 HintKeyword hint_keyword);
375 static void LeadingHintDelete(LeadingHint *hint);
376 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
377 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
378 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
379 Query *parse, const char *str);
380 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
381 HintKeyword hint_keyword);
382 static void SetHintDelete(SetHint *hint);
383 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
384 static int SetHintCmp(const SetHint *a, const SetHint *b);
385 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
387 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
388 HintKeyword hint_keyword);
389 static void RowsHintDelete(RowsHint *hint);
390 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
391 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
392 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
393 Query *parse, const char *str);
394 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
395 HintKeyword hint_keyword);
397 static void quote_value(StringInfo buf, const char *value);
399 static const char *parse_quoted_value(const char *str, char **word,
402 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
405 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
406 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
407 ListCell *other_rels);
408 static void make_rels_by_clauseless_joins(PlannerInfo *root,
410 ListCell *other_rels);
411 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
412 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
413 Index rti, RangeTblEntry *rte);
414 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
415 List *live_childrels,
416 List *all_child_pathkeys);
417 static Path *get_cheapest_parameterized_child_path(PlannerInfo *root,
419 Relids required_outer);
420 static List *accumulate_append_subpath(List *subpaths, Path *path);
421 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
424 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
426 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
428 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
434 static bool pg_hint_plan_enable_hint = true;
435 static int debug_level = 0;
436 static int pg_hint_plan_parse_message_level = INFO;
437 static int pg_hint_plan_debug_message_level = LOG;
438 /* Default is off, to keep backward compatibility. */
439 static bool pg_hint_plan_enable_hint_table = false;
441 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
442 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
443 /* (This could not be above 1) */
445 static const struct config_enum_entry parse_messages_level_options[] = {
446 {"debug", DEBUG2, true},
447 {"debug5", DEBUG5, false},
448 {"debug4", DEBUG4, false},
449 {"debug3", DEBUG3, false},
450 {"debug2", DEBUG2, false},
451 {"debug1", DEBUG1, false},
453 {"info", INFO, false},
454 {"notice", NOTICE, false},
455 {"warning", WARNING, false},
456 {"error", ERROR, false},
458 * {"fatal", FATAL, true},
459 * {"panic", PANIC, true},
464 static const struct config_enum_entry parse_debug_level_options[] = {
467 {"detailed", 2, false},
468 {"verbose", 3, false},
480 /* Saved hook values in case of unload */
481 static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
482 static planner_hook_type prev_planner = NULL;
483 static get_relation_info_hook_type prev_get_relation_info = NULL;
484 static join_search_hook_type prev_join_search = NULL;
486 /* Hold reference to currently active hint */
487 static HintState *current_hint = NULL;
490 * List of hint contexts. We treat the head of the list as the Top of the
491 * context stack, so current_hint always points the first element of this list.
493 static List *HintStateStack = NIL;
495 static const HintParser parsers[] = {
496 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
497 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
498 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
499 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
500 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
501 HINT_KEYWORD_BITMAPSCANREGEXP},
502 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
503 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
504 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
505 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
506 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
507 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
508 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
509 HINT_KEYWORD_INDEXONLYSCANREGEXP},
510 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
511 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
512 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
513 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
514 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
515 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
516 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
517 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
518 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
519 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
520 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
523 PLpgSQL_plugin plugin_funcs = {
527 pg_hint_plan_plpgsql_stmt_beg,
528 pg_hint_plan_plpgsql_stmt_end,
534 * Module load callbacks
539 PLpgSQL_plugin **var_ptr;
541 /* Define custom GUC variables. */
542 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
543 "Force planner to use plans specified in the hint comment preceding to the query.",
545 &pg_hint_plan_enable_hint,
553 DefineCustomEnumVariable("pg_hint_plan.debug_print",
554 "Logs results of hint parsing.",
558 parse_debug_level_options,
565 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
566 "Message level of parse errors.",
568 &pg_hint_plan_parse_message_level,
570 parse_messages_level_options,
577 DefineCustomEnumVariable("pg_hint_plan.message_level",
578 "Message level of debug messages.",
580 &pg_hint_plan_debug_message_level,
582 parse_messages_level_options,
589 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
590 "Force planner to not get hint by using table lookups.",
592 &pg_hint_plan_enable_hint_table,
601 prev_post_parse_analyze_hook = post_parse_analyze_hook;
602 post_parse_analyze_hook = pg_hint_plan_post_parse_analyze;
603 prev_planner = planner_hook;
604 planner_hook = pg_hint_plan_planner;
605 prev_get_relation_info = get_relation_info_hook;
606 get_relation_info_hook = pg_hint_plan_get_relation_info;
607 prev_join_search = join_search_hook;
608 join_search_hook = pg_hint_plan_join_search;
610 /* setup PL/pgSQL plugin hook */
611 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
612 *var_ptr = &plugin_funcs;
614 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
618 * Module unload callback
624 PLpgSQL_plugin **var_ptr;
626 /* Uninstall hooks. */
627 post_parse_analyze_hook = prev_post_parse_analyze_hook;
628 planner_hook = prev_planner;
629 get_relation_info_hook = prev_get_relation_info;
630 join_search_hook = prev_join_search;
632 /* uninstall PL/pgSQL plugin hook */
633 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
638 * create and delete functions the hint object
642 ScanMethodHintCreate(const char *hint_str, const char *keyword,
643 HintKeyword hint_keyword)
645 ScanMethodHint *hint;
647 hint = palloc(sizeof(ScanMethodHint));
648 hint->base.hint_str = hint_str;
649 hint->base.keyword = keyword;
650 hint->base.hint_keyword = hint_keyword;
651 hint->base.type = HINT_TYPE_SCAN_METHOD;
652 hint->base.state = HINT_STATE_NOTUSED;
653 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
654 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
655 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
656 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
657 hint->relname = NULL;
658 hint->indexnames = NIL;
659 hint->regexp = false;
660 hint->enforce_mask = 0;
662 return (Hint *) hint;
666 ScanMethodHintDelete(ScanMethodHint *hint)
672 pfree(hint->relname);
673 list_free_deep(hint->indexnames);
678 JoinMethodHintCreate(const char *hint_str, const char *keyword,
679 HintKeyword hint_keyword)
681 JoinMethodHint *hint;
683 hint = palloc(sizeof(JoinMethodHint));
684 hint->base.hint_str = hint_str;
685 hint->base.keyword = keyword;
686 hint->base.hint_keyword = hint_keyword;
687 hint->base.type = HINT_TYPE_JOIN_METHOD;
688 hint->base.state = HINT_STATE_NOTUSED;
689 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
690 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
691 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
692 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
694 hint->inner_nrels = 0;
695 hint->relnames = NULL;
696 hint->enforce_mask = 0;
697 hint->joinrelids = NULL;
698 hint->inner_joinrelids = NULL;
700 return (Hint *) hint;
704 JoinMethodHintDelete(JoinMethodHint *hint)
713 for (i = 0; i < hint->nrels; i++)
714 pfree(hint->relnames[i]);
715 pfree(hint->relnames);
718 bms_free(hint->joinrelids);
719 bms_free(hint->inner_joinrelids);
724 LeadingHintCreate(const char *hint_str, const char *keyword,
725 HintKeyword hint_keyword)
729 hint = palloc(sizeof(LeadingHint));
730 hint->base.hint_str = hint_str;
731 hint->base.keyword = keyword;
732 hint->base.hint_keyword = hint_keyword;
733 hint->base.type = HINT_TYPE_LEADING;
734 hint->base.state = HINT_STATE_NOTUSED;
735 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
736 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
737 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
738 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
739 hint->relations = NIL;
740 hint->outer_inner = NULL;
742 return (Hint *) hint;
746 LeadingHintDelete(LeadingHint *hint)
751 list_free_deep(hint->relations);
752 if (hint->outer_inner)
753 pfree(hint->outer_inner);
758 SetHintCreate(const char *hint_str, const char *keyword,
759 HintKeyword hint_keyword)
763 hint = palloc(sizeof(SetHint));
764 hint->base.hint_str = hint_str;
765 hint->base.keyword = keyword;
766 hint->base.hint_keyword = hint_keyword;
767 hint->base.type = HINT_TYPE_SET;
768 hint->base.state = HINT_STATE_NOTUSED;
769 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
770 hint->base.desc_func = (HintDescFunction) SetHintDesc;
771 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
772 hint->base.parse_func = (HintParseFunction) SetHintParse;
777 return (Hint *) hint;
781 SetHintDelete(SetHint *hint)
791 list_free(hint->words);
796 RowsHintCreate(const char *hint_str, const char *keyword,
797 HintKeyword hint_keyword)
801 hint = palloc(sizeof(RowsHint));
802 hint->base.hint_str = hint_str;
803 hint->base.keyword = keyword;
804 hint->base.hint_keyword = hint_keyword;
805 hint->base.type = HINT_TYPE_ROWS;
806 hint->base.state = HINT_STATE_NOTUSED;
807 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
808 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
809 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
810 hint->base.parse_func = (HintParseFunction) RowsHintParse;
812 hint->inner_nrels = 0;
813 hint->relnames = NULL;
814 hint->joinrelids = NULL;
815 hint->inner_joinrelids = NULL;
816 hint->rows_str = NULL;
817 hint->value_type = RVT_ABSOLUTE;
820 return (Hint *) hint;
824 RowsHintDelete(RowsHint *hint)
833 for (i = 0; i < hint->nrels; i++)
834 pfree(hint->relnames[i]);
835 pfree(hint->relnames);
838 bms_free(hint->joinrelids);
839 bms_free(hint->inner_joinrelids);
844 HintStateCreate(void)
848 hstate = palloc(sizeof(HintState));
849 hstate->hint_str = NULL;
850 hstate->nall_hints = 0;
851 hstate->max_all_hints = 0;
852 hstate->all_hints = NULL;
853 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
854 hstate->scan_hints = NULL;
855 hstate->init_scan_mask = 0;
856 hstate->current_root = NULL;
857 hstate->parent_relid = 0;
858 hstate->parent_hint = NULL;
859 hstate->parent_index_infos = NIL;
860 hstate->join_hints = NULL;
861 hstate->init_join_mask = 0;
862 hstate->join_hint_level = NULL;
863 hstate->leading_hint = NULL;
864 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
865 hstate->set_hints = NULL;
866 hstate->rows_hints = NULL;
872 HintStateDelete(HintState *hstate)
879 if (hstate->hint_str)
880 pfree(hstate->hint_str);
882 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
883 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
884 if (hstate->all_hints)
885 pfree(hstate->all_hints);
886 if (hstate->parent_index_infos)
887 list_free(hstate->parent_index_infos);
891 * Copy given value into buf, with quoting with '"' if necessary.
894 quote_value(StringInfo buf, const char *value)
896 bool need_quote = false;
899 for (str = value; *str != '\0'; str++)
901 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
904 appendStringInfoCharMacro(buf, '"');
909 for (str = value; *str != '\0'; str++)
912 appendStringInfoCharMacro(buf, '"');
914 appendStringInfoCharMacro(buf, *str);
918 appendStringInfoCharMacro(buf, '"');
922 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
926 appendStringInfo(buf, "%s(", hint->base.keyword);
927 if (hint->relname != NULL)
929 quote_value(buf, hint->relname);
930 foreach(l, hint->indexnames)
932 appendStringInfoCharMacro(buf, ' ');
933 quote_value(buf, (char *) lfirst(l));
936 appendStringInfoString(buf, ")");
938 appendStringInfoChar(buf, '\n');
942 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
946 appendStringInfo(buf, "%s(", hint->base.keyword);
947 if (hint->relnames != NULL)
949 quote_value(buf, hint->relnames[0]);
950 for (i = 1; i < hint->nrels; i++)
952 appendStringInfoCharMacro(buf, ' ');
953 quote_value(buf, hint->relnames[i]);
956 appendStringInfoString(buf, ")");
958 appendStringInfoChar(buf, '\n');
962 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
964 if (outer_inner->relation == NULL)
971 appendStringInfoCharMacro(buf, '(');
972 foreach(l, outer_inner->outer_inner_pair)
977 appendStringInfoCharMacro(buf, ' ');
979 OuterInnerDesc(lfirst(l), buf);
982 appendStringInfoCharMacro(buf, ')');
985 quote_value(buf, outer_inner->relation);
989 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
991 appendStringInfo(buf, "%s(", HINT_LEADING);
992 if (hint->outer_inner == NULL)
999 foreach(l, hint->relations)
1004 appendStringInfoCharMacro(buf, ' ');
1006 quote_value(buf, (char *) lfirst(l));
1010 OuterInnerDesc(hint->outer_inner, buf);
1012 appendStringInfoString(buf, ")");
1014 appendStringInfoChar(buf, '\n');
1018 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1020 bool is_first = true;
1023 appendStringInfo(buf, "%s(", HINT_SET);
1024 foreach(l, hint->words)
1029 appendStringInfoCharMacro(buf, ' ');
1031 quote_value(buf, (char *) lfirst(l));
1033 appendStringInfo(buf, ")");
1035 appendStringInfoChar(buf, '\n');
1039 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1043 appendStringInfo(buf, "%s(", hint->base.keyword);
1044 if (hint->relnames != NULL)
1046 quote_value(buf, hint->relnames[0]);
1047 for (i = 1; i < hint->nrels; i++)
1049 appendStringInfoCharMacro(buf, ' ');
1050 quote_value(buf, hint->relnames[i]);
1053 appendStringInfo(buf, " %s", hint->rows_str);
1054 appendStringInfoString(buf, ")");
1056 appendStringInfoChar(buf, '\n');
1060 * Append string which represents all hints in a given state to buf, with
1061 * preceding title with them.
1064 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1065 HintStatus state, bool nolf)
1069 appendStringInfo(buf, "%s:", title);
1071 appendStringInfoChar(buf, '\n');
1074 for (i = 0; i < hstate->nall_hints; i++)
1076 if (hstate->all_hints[i]->state != state)
1079 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1083 if (nolf && nshown == 0)
1084 appendStringInfoString(buf, "(none)");
1088 * Dump contents of given hstate to server log with log level LOG.
1091 HintStateDump(HintState *hstate)
1097 elog(pg_hint_plan_debug_message_level, "pg_hint_plan:\nno hint");
1101 initStringInfo(&buf);
1103 appendStringInfoString(&buf, "pg_hint_plan:\n");
1104 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1105 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1106 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1107 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1109 ereport(pg_hint_plan_debug_message_level,
1110 (errmsg ("%s", buf.data)));
1116 HintStateDump2(HintState *hstate)
1122 elog(pg_hint_plan_debug_message_level,
1123 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1127 initStringInfo(&buf);
1128 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1129 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1130 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1131 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1132 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1133 appendStringInfoChar(&buf, '}');
1135 ereport(pg_hint_plan_debug_message_level,
1136 (errmsg("%s", buf.data),
1138 errhidecontext(true)));
1148 RelnameCmp(const void *a, const void *b)
1150 const char *relnamea = *((const char **) a);
1151 const char *relnameb = *((const char **) b);
1153 return strcmp(relnamea, relnameb);
1157 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1159 return RelnameCmp(&a->relname, &b->relname);
1163 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1167 if (a->nrels != b->nrels)
1168 return a->nrels - b->nrels;
1170 for (i = 0; i < a->nrels; i++)
1173 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1181 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1187 SetHintCmp(const SetHint *a, const SetHint *b)
1189 return strcmp(a->name, b->name);
1193 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1197 if (a->nrels != b->nrels)
1198 return a->nrels - b->nrels;
1200 for (i = 0; i < a->nrels; i++)
1203 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1211 HintCmp(const void *a, const void *b)
1213 const Hint *hinta = *((const Hint **) a);
1214 const Hint *hintb = *((const Hint **) b);
1216 if (hinta->type != hintb->type)
1217 return hinta->type - hintb->type;
1218 if (hinta->state == HINT_STATE_ERROR)
1220 if (hintb->state == HINT_STATE_ERROR)
1222 return hinta->cmp_func(hinta, hintb);
1226 * Returns byte offset of hint b from hint a. If hint a was specified before
1227 * b, positive value is returned.
1230 HintCmpWithPos(const void *a, const void *b)
1232 const Hint *hinta = *((const Hint **) a);
1233 const Hint *hintb = *((const Hint **) b);
1236 result = HintCmp(a, b);
1238 result = hinta->hint_str - hintb->hint_str;
1247 parse_keyword(const char *str, StringInfo buf)
1251 while (!isspace(*str) && *str != '(' && *str != '\0')
1252 appendStringInfoCharMacro(buf, *str++);
1258 skip_parenthesis(const char *str, char parenthesis)
1262 if (*str != parenthesis)
1264 if (parenthesis == '(')
1265 hint_ereport(str, ("Opening parenthesis is necessary."));
1266 else if (parenthesis == ')')
1267 hint_ereport(str, ("Closing parenthesis is necessary."));
1278 * Parse a token from str, and store malloc'd copy into word. A token can be
1279 * quoted with '"'. Return value is pointer to unparsed portion of original
1280 * string, or NULL if an error occurred.
1282 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1285 parse_quoted_value(const char *str, char **word, bool truncate)
1290 /* Skip leading spaces. */
1293 initStringInfo(&buf);
1306 /* Double quotation must be closed. */
1310 hint_ereport(str, ("Unterminated quoted string."));
1315 * Skip escaped double quotation.
1317 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1318 * block comments) to be an object name, so users must specify
1319 * alias for such object names.
1321 * Those special names can be allowed if we care escaped slashes
1322 * and asterisks, but we don't.
1331 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1335 appendStringInfoCharMacro(&buf, *str++);
1340 hint_ereport(str, ("Zero-length delimited string."));
1347 /* Truncate name if it's too long */
1349 truncate_identifier(buf.data, strlen(buf.data), true);
1356 static OuterInnerRels *
1357 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1359 OuterInnerRels *outer_inner;
1361 outer_inner = palloc(sizeof(OuterInnerRels));
1362 outer_inner->relation = name;
1363 outer_inner->outer_inner_pair = outer_inner_list;
1369 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1371 List *outer_inner_pair = NIL;
1373 if ((str = skip_parenthesis(str, '(')) == NULL)
1378 /* Store words in parentheses into outer_inner_list. */
1379 while(*str != ')' && *str != '\0')
1381 OuterInnerRels *outer_inner_rels;
1385 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1393 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1396 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1399 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1404 (str = skip_parenthesis(str, ')')) == NULL)
1406 list_free(outer_inner_pair);
1410 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1416 parse_parentheses_Leading(const char *str, List **name_list,
1417 OuterInnerRels **outer_inner)
1420 bool truncate = true;
1422 if ((str = skip_parenthesis(str, '(')) == NULL)
1428 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1433 /* Store words in parentheses into name_list. */
1434 while(*str != ')' && *str != '\0')
1436 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1438 list_free(*name_list);
1442 *name_list = lappend(*name_list, name);
1447 if ((str = skip_parenthesis(str, ')')) == NULL)
1453 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1456 bool truncate = true;
1458 if ((str = skip_parenthesis(str, '(')) == NULL)
1463 /* Store words in parentheses into name_list. */
1464 while(*str != ')' && *str != '\0')
1466 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1468 list_free(*name_list);
1472 *name_list = lappend(*name_list, name);
1475 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1476 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1477 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1478 keyword == HINT_KEYWORD_SET)
1484 if ((str = skip_parenthesis(str, ')')) == NULL)
1490 parse_hints(HintState *hstate, Query *parse, const char *str)
1495 initStringInfo(&buf);
1496 while (*str != '\0')
1498 const HintParser *parser;
1500 /* in error message, we output the comment including the keyword. */
1501 head = (char *) str;
1503 /* parse only the keyword of the hint. */
1504 resetStringInfo(&buf);
1505 str = parse_keyword(str, &buf);
1507 for (parser = parsers; parser->keyword != NULL; parser++)
1509 char *keyword = parser->keyword;
1512 if (pg_strcasecmp(buf.data, keyword) != 0)
1515 hint = parser->create_func(head, keyword, parser->hint_keyword);
1517 /* parser of each hint does parse in a parenthesis. */
1518 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1520 hint->delete_func(hint);
1526 * Add hint information into all_hints array. If we don't have
1527 * enough space, double the array.
1529 if (hstate->nall_hints == 0)
1531 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1532 hstate->all_hints = (Hint **)
1533 palloc(sizeof(Hint *) * hstate->max_all_hints);
1535 else if (hstate->nall_hints == hstate->max_all_hints)
1537 hstate->max_all_hints *= 2;
1538 hstate->all_hints = (Hint **)
1539 repalloc(hstate->all_hints,
1540 sizeof(Hint *) * hstate->max_all_hints);
1543 hstate->all_hints[hstate->nall_hints] = hint;
1544 hstate->nall_hints++;
1551 if (parser->keyword == NULL)
1554 ("Unrecognized hint keyword \"%s\".", buf.data));
1565 * Get hints from table by client-supplied query string and application name.
1568 get_hints_from_table(const char *client_query, const char *client_application)
1570 const char *search_query =
1572 " FROM hint_plan.hints "
1573 " WHERE norm_query_string = $1 "
1574 " AND ( application_name = $2 "
1575 " OR application_name = '' ) "
1576 " ORDER BY application_name DESC";
1577 static SPIPlanPtr plan = NULL;
1579 Oid argtypes[2] = { TEXTOID, TEXTOID };
1581 bool nulls[2] = { false, false };
1587 bool snapshot_set = false;
1589 hint_inhibit_level++;
1591 if (!ActiveSnapshotSet())
1593 PushActiveSnapshot(GetTransactionSnapshot());
1594 snapshot_set = true;
1602 p = SPI_prepare(search_query, 2, argtypes);
1603 plan = SPI_saveplan(p);
1607 qry = cstring_to_text(client_query);
1608 app = cstring_to_text(client_application);
1609 values[0] = PointerGetDatum(qry);
1610 values[1] = PointerGetDatum(app);
1612 SPI_execute_plan(plan, values, nulls, true, 1);
1614 if (SPI_processed > 0)
1618 hints = SPI_getvalue(SPI_tuptable->vals[0],
1619 SPI_tuptable->tupdesc, 1);
1621 * Here we use SPI_palloc to ensure that hints string is valid even
1622 * after SPI_finish call. We can't use simple palloc because it
1623 * allocates memory in SPI's context and that context is deleted in
1626 buf = SPI_palloc(strlen(hints) + 1);
1634 PopActiveSnapshot();
1636 hint_inhibit_level--;
1640 hint_inhibit_level--;
1649 * Get client-supplied query string. Addtion to that the jumbled query is
1650 * supplied if the caller requested. From the restriction of JumbleQuery, some
1651 * kind of query needs special amendments. Reutrns NULL if this query doesn't
1652 * change the current hint. This function returns NULL also when something
1653 * wrong has happend and let the caller continue using the current hints.
1656 get_query_string(ParseState *pstate, Query *query, Query **jumblequery)
1658 const char *p = debug_query_string;
1661 * If debug_query_string is set, it is the top level statement. But in some
1662 * cases we reach here with debug_query_string set NULL for example in the
1663 * case of DESCRIBE message handling. We may still see a candidate
1664 * top-level query in pstate in the case.
1668 /* We don't see a query string, return NULL */
1669 if (!pstate->p_sourcetext)
1672 p = pstate->p_sourcetext;
1675 if (jumblequery != NULL)
1676 *jumblequery = query;
1678 /* Query for DeclareCursorStmt is CMD_SELECT and has query->utilityStmt */
1679 if (query->commandType == CMD_UTILITY || query->utilityStmt)
1681 Query *target_query = query;
1684 * Some utility statements have a subquery that we can hint on. Since
1685 * EXPLAIN can be placed before other kind of utility statements and
1686 * EXECUTE can be contained other kind of utility statements, these
1687 * conditions are not mutually exclusive and should be considered in
1690 if (IsA(target_query->utilityStmt, ExplainStmt))
1692 ExplainStmt *stmt = (ExplainStmt *)target_query->utilityStmt;
1694 Assert(IsA(stmt->query, Query));
1695 target_query = (Query *)stmt->query;
1697 /* strip out the top-level query for further processing */
1698 if (target_query->commandType == CMD_UTILITY &&
1699 target_query->utilityStmt != NULL)
1700 target_query = (Query *)target_query->utilityStmt;
1704 * JumbleQuery does not accept a Query that has utilityStmt. On the
1705 * other hand DeclareCursorStmt is in a bit strange shape that is
1706 * flipped upside down.
1708 if (IsA(target_query, Query) &&
1709 target_query->utilityStmt &&
1710 IsA(target_query->utilityStmt, DeclareCursorStmt))
1713 * The given Query cannot be modified so copy it and modify so that
1714 * JumbleQuery can accept it.
1716 Assert(IsA(target_query, Query) &&
1717 target_query->commandType == CMD_SELECT);
1718 target_query = copyObject(target_query);
1719 target_query->utilityStmt = NULL;
1722 if (IsA(target_query, CreateTableAsStmt))
1724 CreateTableAsStmt *stmt = (CreateTableAsStmt *) target_query;
1726 Assert(IsA(stmt->query, Query));
1727 target_query = (Query *) stmt->query;
1729 /* strip out the top-level query for further processing */
1730 if (target_query->commandType == CMD_UTILITY &&
1731 target_query->utilityStmt != NULL)
1732 target_query = (Query *)target_query->utilityStmt;
1735 if (IsA(target_query, ExecuteStmt))
1738 * Use the prepared query for EXECUTE. The Query for jumble
1739 * also replaced with the corresponding one.
1741 ExecuteStmt *stmt = (ExecuteStmt *)target_query;
1742 PreparedStatement *entry;
1744 entry = FetchPreparedStatement(stmt->name, true);
1745 p = entry->plansource->query_string;
1746 target_query = (Query *) linitial (entry->plansource->query_list);
1749 /* JumbleQuery accespts only a non-utility Query */
1750 if (!IsA(target_query, Query) ||
1751 target_query->utilityStmt != NULL)
1752 target_query = NULL;
1755 *jumblequery = target_query;
1758 /* Return NULL if the pstate is not identical to the top-level query */
1759 else if (strcmp(pstate->p_sourcetext, p) != 0)
1766 * Get hints from the head block comment in client-supplied query string.
1769 get_hints_from_comment(const char *p)
1771 const char *hint_head;
1779 /* extract query head comment. */
1780 hint_head = strstr(p, HINT_START);
1781 if (hint_head == NULL)
1783 for (;p < hint_head; p++)
1786 * Allow these characters precedes hint comment:
1788 * - alphabets which are in ASCII range
1789 * - space, tabs and new-lines
1790 * - underscores, for identifier
1791 * - commas, for SELECT clause, EXPLAIN and PREPARE
1792 * - parentheses, for EXPLAIN and PREPARE
1794 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1795 * avoid behavior which depends on locale setting.
1797 if (!(*p >= '0' && *p <= '9') &&
1798 !(*p >= 'A' && *p <= 'Z') &&
1799 !(*p >= 'a' && *p <= 'z') &&
1803 *p != '(' && *p != ')')
1807 len = strlen(HINT_START);
1812 /* find hint end keyword. */
1813 if ((tail = strstr(p, HINT_END)) == NULL)
1815 hint_ereport(head, ("Unterminated block comment."));
1819 /* We don't support nested block comments. */
1820 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1822 hint_ereport(head, ("Nested block comments are not supported."));
1826 /* Make a copy of hint. */
1828 head = palloc(len + 1);
1829 memcpy(head, p, len);
1837 * Parse hints that got, create hint struct from parse tree and parse hints.
1840 create_hintstate(Query *parse, const char *hints)
1850 hstate = HintStateCreate();
1851 hstate->hint_str = (char *) hints;
1853 /* parse each hint. */
1854 parse_hints(hstate, parse, p);
1856 /* When nothing specified a hint, we free HintState and returns NULL. */
1857 if (hstate->nall_hints == 0)
1859 HintStateDelete(hstate);
1863 /* Sort hints in order of original position. */
1864 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1867 /* Count number of hints per hint-type. */
1868 for (i = 0; i < hstate->nall_hints; i++)
1870 Hint *cur_hint = hstate->all_hints[i];
1871 hstate->num_hints[cur_hint->type]++;
1875 * If an object (or a set of objects) has multiple hints of same hint-type,
1876 * only the last hint is valid and others are ignored in planning.
1877 * Hints except the last are marked as 'duplicated' to remember the order.
1879 for (i = 0; i < hstate->nall_hints - 1; i++)
1881 Hint *cur_hint = hstate->all_hints[i];
1882 Hint *next_hint = hstate->all_hints[i + 1];
1885 * Leading hint is marked as 'duplicated' in transform_join_hints.
1887 if (cur_hint->type == HINT_TYPE_LEADING &&
1888 next_hint->type == HINT_TYPE_LEADING)
1892 * Note that we need to pass addresses of hint pointers, because
1893 * HintCmp is designed to sort array of Hint* by qsort.
1895 if (HintCmp(&cur_hint, &next_hint) == 0)
1897 hint_ereport(cur_hint->hint_str,
1898 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1899 cur_hint->state = HINT_STATE_DUPLICATION;
1904 * Make sure that per-type array pointers point proper position in the
1905 * array which consists of all hints.
1907 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1908 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1909 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1910 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1911 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1912 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1913 hstate->num_hints[HINT_TYPE_LEADING]);
1914 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
1915 hstate->num_hints[HINT_TYPE_SET]);
1921 * Parse inside of parentheses of scan-method hints.
1924 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1927 const char *keyword = hint->base.keyword;
1928 HintKeyword hint_keyword = hint->base.hint_keyword;
1929 List *name_list = NIL;
1932 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1935 /* Parse relation name and index name(s) if given hint accepts. */
1936 length = list_length(name_list);
1939 hint->relname = linitial(name_list);
1940 hint->indexnames = list_delete_first(name_list);
1942 /* check whether the hint accepts index name(s). */
1944 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1945 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1946 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1947 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1948 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1949 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1952 ("%s hint accepts only one relation.",
1953 hint->base.keyword));
1954 hint->base.state = HINT_STATE_ERROR;
1961 ("%s hint requires a relation.",
1962 hint->base.keyword));
1963 hint->base.state = HINT_STATE_ERROR;
1967 /* Set a bit for specified hint. */
1968 switch (hint_keyword)
1970 case HINT_KEYWORD_SEQSCAN:
1971 hint->enforce_mask = ENABLE_SEQSCAN;
1973 case HINT_KEYWORD_INDEXSCAN:
1974 hint->enforce_mask = ENABLE_INDEXSCAN;
1976 case HINT_KEYWORD_INDEXSCANREGEXP:
1977 hint->enforce_mask = ENABLE_INDEXSCAN;
1978 hint->regexp = true;
1980 case HINT_KEYWORD_BITMAPSCAN:
1981 hint->enforce_mask = ENABLE_BITMAPSCAN;
1983 case HINT_KEYWORD_BITMAPSCANREGEXP:
1984 hint->enforce_mask = ENABLE_BITMAPSCAN;
1985 hint->regexp = true;
1987 case HINT_KEYWORD_TIDSCAN:
1988 hint->enforce_mask = ENABLE_TIDSCAN;
1990 case HINT_KEYWORD_NOSEQSCAN:
1991 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1993 case HINT_KEYWORD_NOINDEXSCAN:
1994 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1996 case HINT_KEYWORD_NOBITMAPSCAN:
1997 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1999 case HINT_KEYWORD_NOTIDSCAN:
2000 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
2002 case HINT_KEYWORD_INDEXONLYSCAN:
2003 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2005 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
2006 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2007 hint->regexp = true;
2009 case HINT_KEYWORD_NOINDEXONLYSCAN:
2010 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
2013 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2022 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2025 const char *keyword = hint->base.keyword;
2026 HintKeyword hint_keyword = hint->base.hint_keyword;
2027 List *name_list = NIL;
2029 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2032 hint->nrels = list_length(name_list);
2034 if (hint->nrels > 0)
2040 * Transform relation names from list to array to sort them with qsort
2043 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2044 foreach (l, name_list)
2046 hint->relnames[i] = lfirst(l);
2051 list_free(name_list);
2053 /* A join hint requires at least two relations */
2054 if (hint->nrels < 2)
2057 ("%s hint requires at least two relations.",
2058 hint->base.keyword));
2059 hint->base.state = HINT_STATE_ERROR;
2063 /* Sort hints in alphabetical order of relation names. */
2064 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2066 switch (hint_keyword)
2068 case HINT_KEYWORD_NESTLOOP:
2069 hint->enforce_mask = ENABLE_NESTLOOP;
2071 case HINT_KEYWORD_MERGEJOIN:
2072 hint->enforce_mask = ENABLE_MERGEJOIN;
2074 case HINT_KEYWORD_HASHJOIN:
2075 hint->enforce_mask = ENABLE_HASHJOIN;
2077 case HINT_KEYWORD_NONESTLOOP:
2078 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2080 case HINT_KEYWORD_NOMERGEJOIN:
2081 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2083 case HINT_KEYWORD_NOHASHJOIN:
2084 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2087 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2096 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2099 if (outer_inner->outer_inner_pair == NIL)
2101 if (outer_inner->relation)
2107 if (list_length(outer_inner->outer_inner_pair) == 2)
2109 foreach(l, outer_inner->outer_inner_pair)
2111 if (!OuterInnerPairCheck(lfirst(l)))
2122 OuterInnerList(OuterInnerRels *outer_inner)
2124 List *outer_inner_list = NIL;
2126 OuterInnerRels *outer_inner_rels;
2128 foreach(l, outer_inner->outer_inner_pair)
2130 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2132 if (outer_inner_rels->relation != NULL)
2133 outer_inner_list = lappend(outer_inner_list,
2134 outer_inner_rels->relation);
2136 outer_inner_list = list_concat(outer_inner_list,
2137 OuterInnerList(outer_inner_rels));
2139 return outer_inner_list;
2143 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2146 List *name_list = NIL;
2147 OuterInnerRels *outer_inner = NULL;
2149 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2153 if (outer_inner != NULL)
2154 name_list = OuterInnerList(outer_inner);
2156 hint->relations = name_list;
2157 hint->outer_inner = outer_inner;
2159 /* A Leading hint requires at least two relations */
2160 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2162 hint_ereport(hint->base.hint_str,
2163 ("%s hint requires at least two relations.",
2165 hint->base.state = HINT_STATE_ERROR;
2167 else if (hint->outer_inner != NULL &&
2168 !OuterInnerPairCheck(hint->outer_inner))
2170 hint_ereport(hint->base.hint_str,
2171 ("%s hint requires two sets of relations when parentheses nests.",
2173 hint->base.state = HINT_STATE_ERROR;
2180 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2182 List *name_list = NIL;
2184 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2188 hint->words = name_list;
2190 /* We need both name and value to set GUC parameter. */
2191 if (list_length(name_list) == 2)
2193 hint->name = linitial(name_list);
2194 hint->value = lsecond(name_list);
2198 hint_ereport(hint->base.hint_str,
2199 ("%s hint requires name and value of GUC parameter.",
2201 hint->base.state = HINT_STATE_ERROR;
2208 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2211 HintKeyword hint_keyword = hint->base.hint_keyword;
2212 List *name_list = NIL;
2216 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2219 /* Last element must be rows specification */
2220 hint->nrels = list_length(name_list) - 1;
2222 if (hint->nrels > 0)
2228 * Transform relation names from list to array to sort them with qsort
2231 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2232 foreach (l, name_list)
2234 if (hint->nrels <= i)
2236 hint->relnames[i] = lfirst(l);
2241 /* Retieve rows estimation */
2242 rows_str = list_nth(name_list, hint->nrels);
2243 hint->rows_str = rows_str; /* store as-is for error logging */
2244 if (rows_str[0] == '#')
2246 hint->value_type = RVT_ABSOLUTE;
2249 else if (rows_str[0] == '+')
2251 hint->value_type = RVT_ADD;
2254 else if (rows_str[0] == '-')
2256 hint->value_type = RVT_SUB;
2259 else if (rows_str[0] == '*')
2261 hint->value_type = RVT_MULTI;
2266 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2267 hint->base.state = HINT_STATE_ERROR;
2270 hint->rows = strtod(rows_str, &end_ptr);
2273 hint_ereport(rows_str,
2274 ("%s hint requires valid number as rows estimation.",
2275 hint->base.keyword));
2276 hint->base.state = HINT_STATE_ERROR;
2280 /* A join hint requires at least two relations */
2281 if (hint->nrels < 2)
2284 ("%s hint requires at least two relations.",
2285 hint->base.keyword));
2286 hint->base.state = HINT_STATE_ERROR;
2290 list_free(name_list);
2292 /* Sort relnames in alphabetical order. */
2293 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2299 * set GUC parameter functions
2303 set_config_option_wrapper(const char *name, const char *value,
2304 GucContext context, GucSource source,
2305 GucAction action, bool changeVal, int elevel)
2308 MemoryContext ccxt = CurrentMemoryContext;
2312 result = set_config_option(name, value, context, source,
2313 action, changeVal, 0, false);
2319 /* Save error info */
2320 MemoryContextSwitchTo(ccxt);
2321 errdata = CopyErrorData();
2325 (errcode(errdata->sqlerrcode),
2326 errmsg("%s", errdata->message),
2327 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2328 errdata->hint ? errhint("%s", errdata->hint) : 0));
2330 FreeErrorData(errdata);
2338 set_config_options(SetHint **options, int noptions, GucContext context)
2343 save_nestlevel = NewGUCNestLevel();
2345 for (i = 0; i < noptions; i++)
2347 SetHint *hint = options[i];
2350 if (!hint_state_enabled(hint))
2353 result = set_config_option_wrapper(hint->name, hint->value, context,
2354 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2355 pg_hint_plan_parse_message_level);
2357 hint->base.state = HINT_STATE_USED;
2359 hint->base.state = HINT_STATE_ERROR;
2362 return save_nestlevel;
2365 #define SET_CONFIG_OPTION(name, type_bits) \
2366 set_config_option_wrapper((name), \
2367 (mask & (type_bits)) ? "true" : "false", \
2368 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2371 set_scan_config_options(unsigned char enforce_mask, GucContext context)
2375 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2376 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2377 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2379 mask = enforce_mask;
2381 mask = enforce_mask & current_hint->init_scan_mask;
2383 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2384 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2385 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2386 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2387 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2391 set_join_config_options(unsigned char enforce_mask, GucContext context)
2395 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2396 enforce_mask == ENABLE_HASHJOIN)
2397 mask = enforce_mask;
2399 mask = enforce_mask & current_hint->init_join_mask;
2401 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2402 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2403 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2407 * Push a hint into hint stack which is implemented with List struct. Head of
2408 * list is top of stack.
2411 push_hint(HintState *hstate)
2413 /* Prepend new hint to the list means pushing to stack. */
2414 HintStateStack = lcons(hstate, HintStateStack);
2416 /* Pushed hint is the one which should be used hereafter. */
2417 current_hint = hstate;
2420 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2424 /* Hint stack must not be empty. */
2425 if(HintStateStack == NIL)
2426 elog(ERROR, "hint stack is empty");
2429 * Take a hint at the head from the list, and free it. Switch current_hint
2430 * to point new head (NULL if the list is empty).
2432 HintStateStack = list_delete_first(HintStateStack);
2433 HintStateDelete(current_hint);
2434 if(HintStateStack == NIL)
2435 current_hint = NULL;
2437 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2441 * Retrieve and store a hint string from given query or from the hint table.
2442 * If we are using the hint table, the query string is needed to be normalized.
2443 * However, ParseState, which is not available in planner_hook, is required to
2444 * check if the query tree (Query) is surely corresponding to the target query.
2447 pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query)
2449 const char *query_str;
2450 MemoryContext oldcontext;
2452 if (prev_post_parse_analyze_hook)
2453 prev_post_parse_analyze_hook(pstate, query);
2455 /* do nothing under hint table search */
2456 if (hint_inhibit_level > 0)
2459 if (!pg_hint_plan_enable_hint)
2461 if (current_hint_str)
2463 pfree((void *)current_hint_str);
2464 current_hint_str = NULL;
2469 /* increment the query number */
2471 if (debug_level > 1)
2472 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2475 /* search the hint table for a hint if requested */
2476 if (pg_hint_plan_enable_hint_table)
2479 pgssJumbleState jstate;
2481 char *normalized_query = NULL;
2483 query_str = get_query_string(pstate, query, &jumblequery);
2485 /* If this query is not for hint, just return */
2489 /* clear the previous hint string */
2490 if (current_hint_str)
2492 pfree((void *)current_hint_str);
2493 current_hint_str = NULL;
2499 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2500 * careful to PostgreSQL's version up.
2502 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2503 jstate.jumble_len = 0;
2504 jstate.clocations_buf_size = 32;
2505 jstate.clocations = (pgssLocationLen *)
2506 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2507 jstate.clocations_count = 0;
2509 JumbleQuery(&jstate, jumblequery);
2512 * Normalize the query string by replacing constants with '?'
2515 * Search hint string which is stored keyed by query string
2516 * and application name. The query string is normalized to allow
2519 * Adding 1 byte to query_len ensures that the returned string has
2520 * a terminating NULL.
2522 query_len = strlen(query_str) + 1;
2524 generate_normalized_query(&jstate, query_str,
2526 GetDatabaseEncoding());
2529 * find a hint for the normalized query. the result should be in
2532 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2534 get_hints_from_table(normalized_query, application_name);
2535 MemoryContextSwitchTo(oldcontext);
2537 if (debug_level > 1)
2539 if (current_hint_str)
2540 ereport(pg_hint_plan_debug_message_level,
2541 (errmsg("pg_hint_plan[qno=0x%x]: "
2542 "post_parse_analyze_hook: "
2543 "hints from table: \"%s\": "
2544 "normalized_query=\"%s\", "
2545 "application name =\"%s\"",
2546 qno, current_hint_str,
2547 normalized_query, application_name),
2548 errhidestmt(msgqno != qno),
2549 errhidecontext(msgqno != qno)));
2551 ereport(pg_hint_plan_debug_message_level,
2552 (errmsg("pg_hint_plan[qno=0x%x]: "
2553 "no match found in table: "
2554 "application name = \"%s\", "
2555 "normalized_query=\"%s\"",
2556 qno, application_name,
2558 errhidestmt(msgqno != qno),
2559 errhidecontext(msgqno != qno)));
2565 /* retrun if we have hint here */
2566 if (current_hint_str)
2570 query_str = get_query_string(pstate, query, NULL);
2575 * get hints from the comment. However we may have the same query
2576 * string with the previous call, but just retrieving hints is expected
2577 * to be faster than checking for identicalness before retrieval.
2579 if (current_hint_str)
2580 pfree((void *)current_hint_str);
2582 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2583 current_hint_str = get_hints_from_comment(query_str);
2584 MemoryContextSwitchTo(oldcontext);
2587 if (debug_level > 1)
2589 if (debug_level == 1 && query_str && debug_query_string &&
2590 strcmp(query_str, debug_query_string))
2591 ereport(pg_hint_plan_debug_message_level,
2592 (errmsg("hints in comment=\"%s\"",
2593 current_hint_str ? current_hint_str : "(none)"),
2594 errhidestmt(msgqno != qno),
2595 errhidecontext(msgqno != qno)));
2597 ereport(pg_hint_plan_debug_message_level,
2598 (errmsg("hints in comment=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2599 current_hint_str ? current_hint_str : "(none)",
2600 query_str ? query_str : "(none)",
2601 debug_query_string ? debug_query_string : "(none)"),
2602 errhidestmt(msgqno != qno),
2603 errhidecontext(msgqno != qno)));
2609 * Read and set up hint information
2611 static PlannedStmt *
2612 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2615 PlannedStmt *result;
2619 * Use standard planner if pg_hint_plan is disabled or current nesting
2620 * depth is nesting depth of SPI calls. Other hook functions try to change
2621 * plan with current_hint if any, so set it to NULL.
2623 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2625 if (debug_level > 1)
2626 ereport(pg_hint_plan_debug_message_level,
2627 (errmsg ("pg_hint_plan%s: planner: enable_hint=%d,"
2628 " hint_inhibit_level=%d",
2629 qnostr, pg_hint_plan_enable_hint,
2630 hint_inhibit_level),
2631 errhidestmt(msgqno != qno)));
2634 goto standard_planner_proc;
2638 * Support for nested plpgsql functions. This is quite ugly but this is the
2639 * only point I could find where I can get the query string.
2641 if (plpgsql_recurse_level > 0)
2643 MemoryContext oldcontext;
2645 if (current_hint_str)
2646 pfree((void *)current_hint_str);
2648 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2650 get_hints_from_comment((char *)error_context_stack->arg);
2651 MemoryContextSwitchTo(oldcontext);
2654 if (!current_hint_str)
2655 goto standard_planner_proc;
2657 /* parse the hint into hint state struct */
2658 hstate = create_hintstate(parse, pstrdup(current_hint_str));
2660 /* run standard planner if the statement has not valid hint */
2662 goto standard_planner_proc;
2665 * Push new hint struct to the hint stack to disable previous hint context.
2669 /* Set GUC parameters which are specified with Set hint. */
2670 save_nestlevel = set_config_options(current_hint->set_hints,
2671 current_hint->num_hints[HINT_TYPE_SET],
2672 current_hint->context);
2675 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2676 if (enable_indexscan)
2677 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2678 if (enable_bitmapscan)
2679 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2681 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2682 if (enable_indexonlyscan)
2683 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2684 if (enable_nestloop)
2685 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2686 if (enable_mergejoin)
2687 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2688 if (enable_hashjoin)
2689 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2691 if (debug_level > 1)
2693 ereport(pg_hint_plan_debug_message_level,
2694 (errhidestmt(msgqno != qno),
2695 errmsg("pg_hint_plan%s: planner", qnostr)));
2700 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2701 * state when this planner started when error occurred in planner.
2706 result = (*prev_planner) (parse, cursorOptions, boundParams);
2708 result = standard_planner(parse, cursorOptions, boundParams);
2713 * Rollback changes of GUC parameters, and pop current hint context
2714 * from hint stack to rewind the state.
2716 AtEOXact_GUC(true, save_nestlevel);
2722 /* Print hint in debug mode. */
2723 if (debug_level == 1)
2724 HintStateDump(current_hint);
2725 else if (debug_level > 1)
2726 HintStateDump2(current_hint);
2729 * Rollback changes of GUC parameters, and pop current hint context from
2730 * hint stack to rewind the state.
2732 AtEOXact_GUC(true, save_nestlevel);
2737 standard_planner_proc:
2738 if (debug_level > 1)
2740 ereport(pg_hint_plan_debug_message_level,
2741 (errhidestmt(msgqno != qno),
2742 errmsg("pg_hint_plan%s: planner: no valid hint",
2746 current_hint = NULL;
2748 return (*prev_planner) (parse, cursorOptions, boundParams);
2750 return standard_planner(parse, cursorOptions, boundParams);
2754 * Return scan method hint which matches given aliasname.
2756 static ScanMethodHint *
2757 find_scan_hint(PlannerInfo *root, Index relid, RelOptInfo *rel)
2763 * We can't apply scan method hint if the relation is:
2764 * - not a base relation
2765 * - not an ordinary relation (such as join and subquery)
2767 if (rel && (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION))
2770 rte = root->simple_rte_array[relid];
2772 /* We can't force scan method of foreign tables */
2773 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2776 /* Find scan method hint, which matches given names, from the list. */
2777 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2779 ScanMethodHint *hint = current_hint->scan_hints[i];
2781 /* We ignore disabled hints. */
2782 if (!hint_state_enabled(hint))
2785 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2795 * Returns TRUE on match, FALSE on no match.
2797 * s1 --- the data to match against
2798 * s2 --- the pattern
2800 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2803 regexpeq(const char *s1, const char *s2)
2809 strcpy(name.data, s1);
2810 regexp = cstring_to_text(s2);
2812 result = DirectFunctionCall2Coll(nameregexeq,
2813 DEFAULT_COLLATION_OID,
2814 NameGetDatum(&name),
2815 PointerGetDatum(regexp));
2816 return DatumGetBool(result);
2820 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2828 * We delete all the IndexOptInfo list and prevent you from being usable by
2831 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2832 hint->enforce_mask == ENABLE_TIDSCAN)
2834 list_free_deep(rel->indexlist);
2835 rel->indexlist = NIL;
2836 hint->base.state = HINT_STATE_USED;
2842 * When a list of indexes is not specified, we just use all indexes.
2844 if (hint->indexnames == NIL)
2848 * Leaving only an specified index, we delete it from a IndexOptInfo list
2852 if (debug_level > 0)
2853 initStringInfo(&buf);
2855 for (cell = list_head(rel->indexlist); cell; cell = next)
2857 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2858 char *indexname = get_rel_name(info->indexoid);
2860 bool use_index = false;
2864 foreach(l, hint->indexnames)
2866 char *hintname = (char *) lfirst(l);
2870 result = regexpeq(indexname, hintname);
2872 result = RelnameCmp(&indexname, &hintname) == 0;
2877 if (debug_level > 0)
2879 appendStringInfoCharMacro(&buf, ' ');
2880 quote_value(&buf, indexname);
2888 * to make the index a candidate when definition of this index is
2889 * matched with the index's definition of current_hint.
2891 if (OidIsValid(relationObjectId) && !use_index)
2893 foreach(l, current_hint->parent_index_infos)
2897 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2899 /* check to match the parameter of unique */
2900 if (p_info->indisunique != info->unique)
2903 /* check to match the parameter of index's method */
2904 if (p_info->method != info->relam)
2907 /* to check to match the indexkey's configuration */
2908 if ((list_length(p_info->column_names)) !=
2912 /* check to match the indexkey's configuration */
2913 for (i = 0; i < info->ncolumns; i++)
2915 char *c_attname = NULL;
2916 char *p_attname = NULL;
2919 list_nth(p_info->column_names, i);
2921 /* both are expressions */
2922 if (info->indexkeys[i] == 0 && !p_attname)
2925 /* one's column is expression, the other is not */
2926 if (info->indexkeys[i] == 0 || !p_attname)
2929 c_attname = get_attname(relationObjectId,
2930 info->indexkeys[i]);
2932 if (strcmp(p_attname, c_attname) != 0)
2935 if (p_info->indcollation[i] != info->indexcollations[i])
2938 if (p_info->opclass[i] != info->opcintype[i])
2941 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2942 info->reverse_sort[i])
2945 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2946 info->nulls_first[i])
2951 if (i != info->ncolumns)
2954 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2955 (p_info->indpred_str && (info->indpred != NIL)))
2958 * Fetch the pg_index tuple by the Oid of the index
2960 ht_idx = SearchSysCache1(INDEXRELID,
2961 ObjectIdGetDatum(info->indexoid));
2963 /* check to match the expression's parameter of index */
2964 if (p_info->expression_str &&
2965 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2972 * to change the expression's parameter of child's
2975 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2976 Anum_pg_index_indexprs,
2979 result = DirectFunctionCall2(pg_get_expr,
2984 if (strcmp(p_info->expression_str,
2985 text_to_cstring(DatumGetTextP(result))) != 0)
2988 ReleaseSysCache(ht_idx);
2994 /* Check to match the predicate's parameter of index */
2995 if (p_info->indpred_str &&
2996 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
3003 * to change the predicate's parameter of child's
3006 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3007 Anum_pg_index_indpred,
3010 result = DirectFunctionCall2(pg_get_expr,
3015 if (strcmp(p_info->indpred_str,
3016 text_to_cstring(DatumGetTextP(result))) != 0)
3019 ReleaseSysCache(ht_idx);
3026 ReleaseSysCache(ht_idx);
3028 else if (p_info->expression_str || (info->indexprs != NIL))
3030 else if (p_info->indpred_str || (info->indpred != NIL))
3035 /* to log the candidate of index */
3036 if (debug_level > 0)
3038 appendStringInfoCharMacro(&buf, ' ');
3039 quote_value(&buf, indexname);
3047 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
3054 if (debug_level == 1)
3057 StringInfoData rel_buf;
3059 if (OidIsValid(relationObjectId))
3060 relname = get_rel_name(relationObjectId);
3062 relname = hint->relname;
3064 initStringInfo(&rel_buf);
3065 quote_value(&rel_buf, relname);
3067 ereport(pg_hint_plan_debug_message_level,
3068 (errmsg("available indexes for %s(%s):%s",
3073 pfree(rel_buf.data);
3078 * Return information of index definition.
3080 static ParentIndexInfo *
3081 get_parent_index_info(Oid indexoid, Oid relid)
3083 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3084 Relation indexRelation;
3085 Form_pg_index index;
3089 indexRelation = index_open(indexoid, RowExclusiveLock);
3091 index = indexRelation->rd_index;
3093 p_info->indisunique = index->indisunique;
3094 p_info->method = indexRelation->rd_rel->relam;
3096 p_info->column_names = NIL;
3097 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3098 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3099 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3101 for (i = 0; i < index->indnatts; i++)
3103 attname = get_attname(relid, index->indkey.values[i]);
3104 p_info->column_names = lappend(p_info->column_names, attname);
3106 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3107 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3108 p_info->indoption[i] = indexRelation->rd_indoption[i];
3112 * to check to match the expression's parameter of index with child indexes
3114 p_info->expression_str = NULL;
3115 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
3121 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3122 Anum_pg_index_indexprs, &isnull);
3124 result = DirectFunctionCall2(pg_get_expr,
3126 ObjectIdGetDatum(relid));
3128 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3132 * to check to match the predicate's parameter of index with child indexes
3134 p_info->indpred_str = NULL;
3135 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
3141 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3142 Anum_pg_index_indpred, &isnull);
3144 result = DirectFunctionCall2(pg_get_expr,
3146 ObjectIdGetDatum(relid));
3148 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3151 index_close(indexRelation, NoLock);
3157 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
3158 bool inhparent, RelOptInfo *rel)
3160 ScanMethodHint *hint = NULL;
3162 Index new_parent_relid = 0;
3164 if (prev_get_relation_info)
3165 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
3168 * Do nothing if we don't have a valid hint in this context or current
3169 * nesting depth is at SPI calls.
3171 if (!current_hint || hint_inhibit_level > 0)
3173 if (debug_level > 1)
3174 ereport(pg_hint_plan_debug_message_level,
3176 errmsg ("pg_hint_plan%s: get_relation_info"
3177 " no hint to apply: relation=%u(%s), inhparent=%d,"
3178 " current_hint=%p, hint_inhibit_level=%d",
3179 qnostr, relationObjectId,
3180 get_rel_name(relationObjectId),
3181 inhparent, current_hint, hint_inhibit_level)));
3186 * We could register the parent relation of the following children here
3187 * when inhparent == true but inheritnce planner doesn't request
3188 * information for inheritance parents. We also cannot distinguish the
3189 * caller so we should always find the parents without this function being
3194 if (debug_level > 1)
3195 ereport(pg_hint_plan_debug_message_level,
3197 errmsg ("pg_hint_plan%s: get_relation_info"
3198 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3199 " current_hint=%p, hint_inhibit_level=%d",
3200 qnostr, relationObjectId,
3201 get_rel_name(relationObjectId),
3202 inhparent, current_hint, hint_inhibit_level)));
3206 /* Forget about the parent of another subquery */
3207 if (root != current_hint->current_root)
3208 current_hint->parent_relid = 0;
3210 /* Find the parent for this relation other than the registered parent */
3211 foreach (l, root->append_rel_list)
3213 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3215 if (appinfo->child_relid == rel->relid)
3217 if (current_hint->parent_relid != appinfo->parent_relid)
3219 new_parent_relid = appinfo->parent_relid;
3220 current_hint->current_root = root;
3228 /* This relation doesn't have a parent. Cancel current_hint. */
3229 current_hint->parent_relid = 0;
3230 current_hint->parent_hint = NULL;
3233 if (new_parent_relid > 0)
3236 * Here we found a parent relation different from the remembered one.
3237 * Remember it, apply the scan mask of it and then resolve the index
3238 * restriction in order to be used by its children.
3240 int scanmask = current_hint->init_scan_mask;
3241 ScanMethodHint *parent_hint;
3243 current_hint->parent_relid = new_parent_relid;
3246 * Get and apply the hint for the new parent relation. It should be an
3247 * ordinary relation so calling find_scan_hint with rel == NULL is
3250 current_hint->parent_hint = parent_hint =
3251 find_scan_hint(root, current_hint->parent_relid, NULL);
3255 scanmask = current_hint->parent_hint->enforce_mask;
3256 parent_hint->base.state = HINT_STATE_USED;
3258 /* Resolve index name mask (if any) using the parent. */
3259 if (parent_hint->indexnames)
3262 Relation parent_rel;
3265 root->simple_rte_array[current_hint->parent_relid]->relid;
3266 parent_rel = heap_open(parentrel_oid, NoLock);
3268 /* Search the parent relation for indexes match the hint spec */
3269 foreach(l, RelationGetIndexList(parent_rel))
3271 Oid indexoid = lfirst_oid(l);
3272 char *indexname = get_rel_name(indexoid);
3274 ParentIndexInfo *parent_index_info;
3276 foreach(lc, parent_hint->indexnames)
3278 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3285 get_parent_index_info(indexoid, parentrel_oid);
3286 current_hint->parent_index_infos =
3287 lappend(current_hint->parent_index_infos, parent_index_info);
3289 heap_close(parent_rel, NoLock);
3293 set_scan_config_options(scanmask, current_hint->context);
3296 if (current_hint->parent_hint != 0)
3298 delete_indexes(current_hint->parent_hint, rel,
3301 /* Scan fixation status is the same to the parent. */
3302 if (debug_level > 1)
3303 ereport(pg_hint_plan_debug_message_level,
3305 errmsg("pg_hint_plan%s: get_relation_info:"
3306 " index deletion by parent hint: "
3307 "relation=%u(%s), inhparent=%d, current_hint=%p,"
3308 " hint_inhibit_level=%d",
3309 qnostr, relationObjectId,
3310 get_rel_name(relationObjectId),
3311 inhparent, current_hint, hint_inhibit_level)));
3315 /* This table doesn't have a parent hint. Apply its own hint if any. */
3316 if ((hint = find_scan_hint(root, rel->relid, rel)) != NULL)
3318 set_scan_config_options(hint->enforce_mask, current_hint->context);
3319 hint->base.state = HINT_STATE_USED;
3321 delete_indexes(hint, rel, InvalidOid);
3323 if (debug_level > 1)
3324 ereport(pg_hint_plan_debug_message_level,
3326 errmsg ("pg_hint_plan%s: get_relation_info"
3328 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3329 " hint_inhibit_level=%d, scanmask=0x%x",
3330 qnostr, relationObjectId,
3331 get_rel_name(relationObjectId),
3332 inhparent, current_hint, hint_inhibit_level,
3333 hint->enforce_mask)));
3337 if (debug_level > 1)
3338 ereport(pg_hint_plan_debug_message_level,
3339 (errhidestmt (true),
3340 errmsg ("pg_hint_plan%s: get_relation_info"
3342 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3343 " hint_inhibit_level=%d, scanmask=0x%x",
3344 qnostr, relationObjectId,
3345 get_rel_name(relationObjectId),
3346 inhparent, current_hint, hint_inhibit_level,
3347 current_hint->init_scan_mask)));
3348 set_scan_config_options(current_hint->init_scan_mask,
3349 current_hint->context);
3355 * Return index of relation which matches given aliasname, or 0 if not found.
3356 * If same aliasname was used multiple times in a query, return -1.
3359 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3365 for (i = 1; i < root->simple_rel_array_size; i++)
3369 if (root->simple_rel_array[i] == NULL)
3372 Assert(i == root->simple_rel_array[i]->relid);
3374 if (RelnameCmp(&aliasname,
3375 &root->simple_rte_array[i]->eref->aliasname) != 0)
3378 foreach(l, initial_rels)
3380 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3382 if (rel->reloptkind == RELOPT_BASEREL)
3384 if (rel->relid != i)
3389 Assert(rel->reloptkind == RELOPT_JOINREL);
3391 if (!bms_is_member(i, rel->relids))
3398 ("Relation name \"%s\" is ambiguous.",
3413 * Return join hint which matches given joinrelids.
3415 static JoinMethodHint *
3416 find_join_hint(Relids joinrelids)
3421 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
3423 foreach(l, join_hint)
3425 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3427 if (bms_equal(joinrelids, hint->joinrelids))
3435 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3436 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3438 OuterInnerRels *outer_rels;
3439 OuterInnerRels *inner_rels;
3440 Relids outer_relids;
3441 Relids inner_relids;
3443 JoinMethodHint *hint;
3445 if (outer_inner->relation != NULL)
3447 return bms_make_singleton(
3448 find_relid_aliasname(root, outer_inner->relation,
3450 leading_hint->base.hint_str));
3453 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3454 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3456 outer_relids = OuterInnerJoinCreate(outer_rels,
3462 inner_relids = OuterInnerJoinCreate(inner_rels,
3469 join_relids = bms_add_members(outer_relids, inner_relids);
3471 if (bms_num_members(join_relids) > nbaserel)
3475 * If we don't have join method hint, create new one for the
3476 * join combination with all join methods are enabled.
3478 hint = find_join_hint(join_relids);
3482 * Here relnames is not set, since Relids bitmap is sufficient to
3483 * control paths of this query afterward.
3485 hint = (JoinMethodHint *) JoinMethodHintCreate(
3486 leading_hint->base.hint_str,
3488 HINT_KEYWORD_LEADING);
3489 hint->base.state = HINT_STATE_USED;
3490 hint->nrels = bms_num_members(join_relids);
3491 hint->enforce_mask = ENABLE_ALL_JOIN;
3492 hint->joinrelids = bms_copy(join_relids);
3493 hint->inner_nrels = bms_num_members(inner_relids);
3494 hint->inner_joinrelids = bms_copy(inner_relids);
3496 hstate->join_hint_level[hint->nrels] =
3497 lappend(hstate->join_hint_level[hint->nrels], hint);
3501 hint->inner_nrels = bms_num_members(inner_relids);
3502 hint->inner_joinrelids = bms_copy(inner_relids);
3509 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3510 int nrels, char **relnames)
3513 Relids relids = NULL;
3517 for (j = 0; j < nrels; j++)
3519 relname = relnames[j];
3521 relid = find_relid_aliasname(root, relname, initial_rels,
3525 base->state = HINT_STATE_ERROR;
3528 * the aliasname is not found(relid == 0) or same aliasname was used
3529 * multiple times in a query(relid == -1)
3536 if (bms_is_member(relid, relids))
3538 hint_ereport(base->hint_str,
3539 ("Relation name \"%s\" is duplicated.", relname));
3540 base->state = HINT_STATE_ERROR;
3544 relids = bms_add_member(relids, relid);
3549 * Transform join method hint into handy form.
3551 * - create bitmap of relids from alias names, to make it easier to check
3552 * whether a join path matches a join method hint.
3553 * - add join method hints which are necessary to enforce join order
3554 * specified by Leading hint
3557 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
3558 List *initial_rels, JoinMethodHint **join_method_hints)
3566 LeadingHint *lhint = NULL;
3569 * Create bitmap of relids from alias names for each join method hint.
3570 * Bitmaps are more handy than strings in join searching.
3572 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
3574 JoinMethodHint *hint = hstate->join_hints[i];
3576 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3579 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3580 initial_rels, hint->nrels, hint->relnames);
3582 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
3585 hstate->join_hint_level[hint->nrels] =
3586 lappend(hstate->join_hint_level[hint->nrels], hint);
3590 * Create bitmap of relids from alias names for each rows hint.
3591 * Bitmaps are more handy than strings in join searching.
3593 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
3595 RowsHint *hint = hstate->rows_hints[i];
3597 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3600 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3601 initial_rels, hint->nrels, hint->relnames);
3604 /* Do nothing if no Leading hint was supplied. */
3605 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
3609 * Decide whether to use Leading hint
3611 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
3613 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
3616 if (leading_hint->base.state == HINT_STATE_ERROR)
3622 foreach(l, leading_hint->relations)
3624 relname = (char *)lfirst(l);;
3626 relid = find_relid_aliasname(root, relname, initial_rels,
3627 leading_hint->base.hint_str);
3629 leading_hint->base.state = HINT_STATE_ERROR;
3634 if (bms_is_member(relid, relids))
3636 hint_ereport(leading_hint->base.hint_str,
3637 ("Relation name \"%s\" is duplicated.", relname));
3638 leading_hint->base.state = HINT_STATE_ERROR;
3642 relids = bms_add_member(relids, relid);
3645 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3650 hint_ereport(lhint->base.hint_str,
3651 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3652 lhint->base.state = HINT_STATE_DUPLICATION;
3654 leading_hint->base.state = HINT_STATE_USED;
3655 lhint = leading_hint;
3658 /* check to exist Leading hint marked with 'used'. */
3663 * We need join method hints which fit specified join order in every join
3664 * level. For example, Leading(A B C) virtually requires following join
3665 * method hints, if no join method hint supplied:
3667 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3668 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3670 * If we already have join method hint which fits specified join order in
3671 * that join level, we leave it as-is and don't add new hints.
3675 if (lhint->outer_inner == NULL)
3677 foreach(l, lhint->relations)
3679 JoinMethodHint *hint;
3681 relname = (char *)lfirst(l);
3684 * Find relid of the relation which has given name. If we have the
3685 * name given in Leading hint multiple times in the join, nothing to
3688 relid = find_relid_aliasname(root, relname, initial_rels,
3691 /* Create bitmap of relids for current join level. */
3692 joinrelids = bms_add_member(joinrelids, relid);
3695 /* We never have join method hint for single relation. */
3700 * If we don't have join method hint, create new one for the
3701 * join combination with all join methods are enabled.
3703 hint = find_join_hint(joinrelids);
3707 * Here relnames is not set, since Relids bitmap is sufficient
3708 * to control paths of this query afterward.
3710 hint = (JoinMethodHint *) JoinMethodHintCreate(
3711 lhint->base.hint_str,
3713 HINT_KEYWORD_LEADING);
3714 hint->base.state = HINT_STATE_USED;
3715 hint->nrels = njoinrels;
3716 hint->enforce_mask = ENABLE_ALL_JOIN;
3717 hint->joinrelids = bms_copy(joinrelids);
3720 join_method_hints[njoinrels] = hint;
3722 if (njoinrels >= nbaserel)
3725 bms_free(joinrelids);
3731 * Delete all join hints which have different combination from Leading
3734 for (i = 2; i <= njoinrels; i++)
3736 list_free(hstate->join_hint_level[i]);
3738 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3743 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3750 njoinrels = bms_num_members(joinrelids);
3751 Assert(njoinrels >= 2);
3754 * Delete all join hints which have different combination from Leading
3757 for (i = 2;i <= njoinrels; i++)
3759 if (hstate->join_hint_level[i] != NIL)
3761 ListCell *prev = NULL;
3762 ListCell *next = NULL;
3763 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3766 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3770 if (hint->inner_nrels == 0 &&
3771 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3772 bms_equal(bms_union(hint->joinrelids, joinrelids),
3775 hstate->join_hint_level[i] =
3776 list_delete_cell(hstate->join_hint_level[i], l,
3785 bms_free(joinrelids);
3788 if (hint_state_enabled(lhint))
3790 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3797 * set_plain_rel_pathlist
3798 * Build access paths for a plain relation (no subquery, no inheritance)
3800 * This function was copied and edited from set_plain_rel_pathlist() in
3801 * src/backend/optimizer/path/allpaths.c
3804 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3806 /* Consider sequential scan */
3807 add_path(rel, create_seqscan_path(root, rel, NULL));
3809 /* Consider index scans */
3810 create_index_paths(root, rel);
3812 /* Consider TID scans */
3813 create_tidscan_paths(root, rel);
3815 /* Now find the cheapest of the paths for this rel */
3820 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3825 foreach(l, initial_rels)
3827 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3829 ScanMethodHint *hint;
3831 /* Skip relations which we can't choose scan method. */
3832 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3835 rte = root->simple_rte_array[rel->relid];
3837 /* We can't force scan method of foreign tables */
3838 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3842 * Create scan paths with GUC parameters which are at the beginning of
3843 * planner if scan method hint is not specified, otherwise use
3844 * specified hints and mark the hint as used.
3846 if ((hint = find_scan_hint(root, rel->relid, rel)) == NULL)
3847 set_scan_config_options(hstate->init_scan_mask,
3851 set_scan_config_options(hint->enforce_mask, hstate->context);
3852 hint->base.state = HINT_STATE_USED;
3855 list_free_deep(rel->pathlist);
3856 rel->pathlist = NIL;
3859 /* It's an "append relation", process accordingly */
3860 set_append_rel_pathlist(root, rel, rel->relid, rte);
3864 set_plain_rel_pathlist(root, rel, rte);
3871 * Restore the GUC variables we set above.
3873 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3877 * wrapper of make_join_rel()
3879 * call make_join_rel() after changing enable_* parameters according to given
3883 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3886 JoinMethodHint *hint;
3890 joinrelids = bms_union(rel1->relids, rel2->relids);
3891 hint = find_join_hint(joinrelids);
3892 bms_free(joinrelids);
3895 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3897 if (hint->inner_nrels == 0)
3899 save_nestlevel = NewGUCNestLevel();
3901 set_join_config_options(hint->enforce_mask, current_hint->context);
3903 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3904 hint->base.state = HINT_STATE_USED;
3907 * Restore the GUC variables we set above.
3909 AtEOXact_GUC(true, save_nestlevel);
3912 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3921 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3922 RelOptInfo *joinrel,
3923 RelOptInfo *outerrel,
3924 RelOptInfo *innerrel,
3926 SpecialJoinInfo *sjinfo,
3929 ScanMethodHint *scan_hint = NULL;
3931 JoinMethodHint *join_hint;
3934 if ((scan_hint = find_scan_hint(root, innerrel->relid, innerrel)) != NULL)
3936 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3937 scan_hint->base.state = HINT_STATE_USED;
3940 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3941 join_hint = find_join_hint(joinrelids);
3942 bms_free(joinrelids);
3944 if (join_hint && join_hint->inner_nrels != 0)
3946 save_nestlevel = NewGUCNestLevel();
3948 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3951 set_join_config_options(join_hint->enforce_mask,
3952 current_hint->context);
3954 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3955 sjinfo, restrictlist);
3956 join_hint->base.state = HINT_STATE_USED;
3960 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3961 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3962 sjinfo, restrictlist);
3966 * Restore the GUC variables we set above.
3968 AtEOXact_GUC(true, save_nestlevel);
3971 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3972 sjinfo, restrictlist);
3974 if (scan_hint != NULL)
3975 set_scan_config_options(current_hint->init_scan_mask,
3976 current_hint->context);
3980 get_num_baserels(List *initial_rels)
3985 foreach(l, initial_rels)
3987 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3989 if (rel->reloptkind == RELOPT_BASEREL)
3991 else if (rel->reloptkind ==RELOPT_JOINREL)
3992 nbaserel+= bms_num_members(rel->relids);
3995 /* other values not expected here */
3996 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
4004 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
4007 JoinMethodHint **join_method_hints;
4011 bool leading_hint_enable;
4014 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
4015 * valid hint is supplied or current nesting depth is nesting depth of SPI
4018 if (!current_hint || hint_inhibit_level > 0)
4020 if (prev_join_search)
4021 return (*prev_join_search) (root, levels_needed, initial_rels);
4022 else if (enable_geqo && levels_needed >= geqo_threshold)
4023 return geqo(root, levels_needed, initial_rels);
4025 return standard_join_search(root, levels_needed, initial_rels);
4028 /* We apply scan method hint rebuild scan path. */
4029 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
4032 * In the case using GEQO, only scan method hints and Set hints have
4033 * effect. Join method and join order is not controllable by hints.
4035 if (enable_geqo && levels_needed >= geqo_threshold)
4036 return geqo(root, levels_needed, initial_rels);
4038 nbaserel = get_num_baserels(initial_rels);
4039 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
4040 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4042 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
4043 initial_rels, join_method_hints);
4045 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4047 for (i = 2; i <= nbaserel; i++)
4049 list_free(current_hint->join_hint_level[i]);
4051 /* free Leading hint only */
4052 if (join_method_hints[i] != NULL &&
4053 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4054 JoinMethodHintDelete(join_method_hints[i]);
4056 pfree(current_hint->join_hint_level);
4057 pfree(join_method_hints);
4059 if (leading_hint_enable)
4060 set_join_config_options(current_hint->init_join_mask,
4061 current_hint->context);
4068 * Build access paths for a base relation
4070 * This function was copied and edited from set_rel_pathlist() in
4071 * src/backend/optimizer/path/allpaths.c
4074 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4075 Index rti, RangeTblEntry *rte)
4077 if (IS_DUMMY_REL(rel))
4079 /* We already proved the relation empty, so nothing more to do */
4083 /* It's an "append relation", process accordingly */
4084 set_append_rel_pathlist(root, rel, rti, rte);
4088 if (rel->rtekind == RTE_RELATION)
4090 if (rte->relkind == RELKIND_RELATION)
4092 /* Plain relation */
4093 set_plain_rel_pathlist(root, rel, rte);
4096 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4099 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4104 * stmt_beg callback is called when each query in PL/pgSQL function is about
4105 * to be executed. At that timing, we save query string in the global variable
4106 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4107 * variable for the purpose, because its content is only necessary until
4108 * planner hook is called for the query, so recursive PL/pgSQL function calls
4109 * don't harm this mechanism.
4112 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4114 plpgsql_recurse_level++;
4118 * stmt_end callback is called then each query in PL/pgSQL function has
4119 * finished. At that timing, we clear plpgsql_query_string to tell planner
4120 * hook that next call is not for a query written in PL/pgSQL block.
4123 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4125 plpgsql_recurse_level--;
4128 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4133 if (!isTopLevel || phase != RESOURCE_RELEASE_AFTER_LOCKS)
4135 /* Cancel plpgsql nest level*/
4136 plpgsql_recurse_level = 0;
4139 #define standard_join_search pg_hint_plan_standard_join_search
4140 #define join_search_one_level pg_hint_plan_join_search_one_level
4141 #define make_join_rel make_join_rel_wrapper
4144 #undef make_join_rel
4145 #define make_join_rel pg_hint_plan_make_join_rel
4146 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4147 #include "make_join_rel.c"
4149 #include "pg_stat_statements.c"