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 Index parent_relid; /* inherit parent table relid */
311 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
312 List *parent_index_infos; /* information of inherit parent table's
315 /* for join method hints */
316 JoinMethodHint **join_hints; /* parsed join hints */
317 int init_join_mask; /* initial value join parameter */
318 List **join_hint_level;
320 /* for Leading hint */
321 LeadingHint **leading_hint; /* parsed Leading hints */
324 SetHint **set_hints; /* parsed Set hints */
325 GucContext context; /* which GUC parameters can we set? */
328 RowsHint **rows_hints; /* parsed Rows hints */
332 * Describes a hint parser module which is bound with particular hint keyword.
334 typedef struct HintParser
337 HintCreateFunction create_func;
338 HintKeyword hint_keyword;
341 /* Module callbacks */
345 static void push_hint(HintState *hstate);
346 static void pop_hint(void);
348 static void pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query);
349 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
350 ParamListInfo boundParams);
351 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
352 Oid relationObjectId,
353 bool inhparent, RelOptInfo *rel);
354 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
358 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
359 HintKeyword hint_keyword);
360 static void ScanMethodHintDelete(ScanMethodHint *hint);
361 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
362 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
363 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
364 Query *parse, const char *str);
365 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
366 HintKeyword hint_keyword);
367 static void JoinMethodHintDelete(JoinMethodHint *hint);
368 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
369 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
370 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
371 Query *parse, const char *str);
372 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
373 HintKeyword hint_keyword);
374 static void LeadingHintDelete(LeadingHint *hint);
375 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
376 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
377 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
378 Query *parse, const char *str);
379 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
380 HintKeyword hint_keyword);
381 static void SetHintDelete(SetHint *hint);
382 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
383 static int SetHintCmp(const SetHint *a, const SetHint *b);
384 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
386 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
387 HintKeyword hint_keyword);
388 static void RowsHintDelete(RowsHint *hint);
389 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
390 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
391 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
392 Query *parse, const char *str);
393 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
394 HintKeyword hint_keyword);
396 static void quote_value(StringInfo buf, const char *value);
398 static const char *parse_quoted_value(const char *str, char **word,
401 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
404 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
405 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
406 ListCell *other_rels);
407 static void make_rels_by_clauseless_joins(PlannerInfo *root,
409 ListCell *other_rels);
410 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
411 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
412 Index rti, RangeTblEntry *rte);
413 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
414 List *live_childrels,
415 List *all_child_pathkeys);
416 static Path *get_cheapest_parameterized_child_path(PlannerInfo *root,
418 Relids required_outer);
419 static List *accumulate_append_subpath(List *subpaths, Path *path);
420 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
423 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
425 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
427 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
433 static bool pg_hint_plan_enable_hint = true;
434 static int debug_level = 0;
435 static int pg_hint_plan_parse_message_level = INFO;
436 static int pg_hint_plan_debug_message_level = LOG;
437 /* Default is off, to keep backward compatibility. */
438 static bool pg_hint_plan_enable_hint_table = false;
440 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
441 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
442 /* (This could not be above 1) */
444 static const struct config_enum_entry parse_messages_level_options[] = {
445 {"debug", DEBUG2, true},
446 {"debug5", DEBUG5, false},
447 {"debug4", DEBUG4, false},
448 {"debug3", DEBUG3, false},
449 {"debug2", DEBUG2, false},
450 {"debug1", DEBUG1, false},
452 {"info", INFO, false},
453 {"notice", NOTICE, false},
454 {"warning", WARNING, false},
455 {"error", ERROR, false},
457 * {"fatal", FATAL, true},
458 * {"panic", PANIC, true},
463 static const struct config_enum_entry parse_debug_level_options[] = {
466 {"detailed", 2, false},
467 {"verbose", 3, false},
479 /* Saved hook values in case of unload */
480 static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
481 static planner_hook_type prev_planner = NULL;
482 static get_relation_info_hook_type prev_get_relation_info = NULL;
483 static join_search_hook_type prev_join_search = NULL;
485 /* Hold reference to currently active hint */
486 static HintState *current_hint = NULL;
489 * List of hint contexts. We treat the head of the list as the Top of the
490 * context stack, so current_hint always points the first element of this list.
492 static List *HintStateStack = NIL;
495 * Holds statement name during executing EXECUTE command. NULL for other
498 static char *stmt_name = NULL;
500 static const HintParser parsers[] = {
501 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
502 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
503 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
504 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
505 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
506 HINT_KEYWORD_BITMAPSCANREGEXP},
507 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
508 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
509 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
510 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
511 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
512 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
513 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
514 HINT_KEYWORD_INDEXONLYSCANREGEXP},
515 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
516 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
517 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
518 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
519 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
520 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
521 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
522 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
523 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
524 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
525 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
528 PLpgSQL_plugin plugin_funcs = {
532 pg_hint_plan_plpgsql_stmt_beg,
533 pg_hint_plan_plpgsql_stmt_end,
539 * Module load callbacks
544 PLpgSQL_plugin **var_ptr;
546 /* Define custom GUC variables. */
547 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
548 "Force planner to use plans specified in the hint comment preceding to the query.",
550 &pg_hint_plan_enable_hint,
558 DefineCustomEnumVariable("pg_hint_plan.debug_print",
559 "Logs results of hint parsing.",
563 parse_debug_level_options,
570 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
571 "Message level of parse errors.",
573 &pg_hint_plan_parse_message_level,
575 parse_messages_level_options,
582 DefineCustomEnumVariable("pg_hint_plan.message_level",
583 "Message level of debug messages.",
585 &pg_hint_plan_debug_message_level,
587 parse_messages_level_options,
594 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
595 "Force planner to not get hint by using table lookups.",
597 &pg_hint_plan_enable_hint_table,
606 prev_post_parse_analyze_hook = post_parse_analyze_hook;
607 post_parse_analyze_hook = pg_hint_plan_post_parse_analyze;
608 prev_planner = planner_hook;
609 planner_hook = pg_hint_plan_planner;
610 prev_get_relation_info = get_relation_info_hook;
611 get_relation_info_hook = pg_hint_plan_get_relation_info;
612 prev_join_search = join_search_hook;
613 join_search_hook = pg_hint_plan_join_search;
615 /* setup PL/pgSQL plugin hook */
616 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
617 *var_ptr = &plugin_funcs;
619 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
623 * Module unload callback
629 PLpgSQL_plugin **var_ptr;
631 /* Uninstall hooks. */
632 post_parse_analyze_hook = prev_post_parse_analyze_hook;
633 planner_hook = prev_planner;
634 get_relation_info_hook = prev_get_relation_info;
635 join_search_hook = prev_join_search;
637 /* uninstall PL/pgSQL plugin hook */
638 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
643 * create and delete functions the hint object
647 ScanMethodHintCreate(const char *hint_str, const char *keyword,
648 HintKeyword hint_keyword)
650 ScanMethodHint *hint;
652 hint = palloc(sizeof(ScanMethodHint));
653 hint->base.hint_str = hint_str;
654 hint->base.keyword = keyword;
655 hint->base.hint_keyword = hint_keyword;
656 hint->base.type = HINT_TYPE_SCAN_METHOD;
657 hint->base.state = HINT_STATE_NOTUSED;
658 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
659 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
660 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
661 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
662 hint->relname = NULL;
663 hint->indexnames = NIL;
664 hint->regexp = false;
665 hint->enforce_mask = 0;
667 return (Hint *) hint;
671 ScanMethodHintDelete(ScanMethodHint *hint)
677 pfree(hint->relname);
678 list_free_deep(hint->indexnames);
683 JoinMethodHintCreate(const char *hint_str, const char *keyword,
684 HintKeyword hint_keyword)
686 JoinMethodHint *hint;
688 hint = palloc(sizeof(JoinMethodHint));
689 hint->base.hint_str = hint_str;
690 hint->base.keyword = keyword;
691 hint->base.hint_keyword = hint_keyword;
692 hint->base.type = HINT_TYPE_JOIN_METHOD;
693 hint->base.state = HINT_STATE_NOTUSED;
694 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
695 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
696 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
697 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
699 hint->inner_nrels = 0;
700 hint->relnames = NULL;
701 hint->enforce_mask = 0;
702 hint->joinrelids = NULL;
703 hint->inner_joinrelids = NULL;
705 return (Hint *) hint;
709 JoinMethodHintDelete(JoinMethodHint *hint)
718 for (i = 0; i < hint->nrels; i++)
719 pfree(hint->relnames[i]);
720 pfree(hint->relnames);
723 bms_free(hint->joinrelids);
724 bms_free(hint->inner_joinrelids);
729 LeadingHintCreate(const char *hint_str, const char *keyword,
730 HintKeyword hint_keyword)
734 hint = palloc(sizeof(LeadingHint));
735 hint->base.hint_str = hint_str;
736 hint->base.keyword = keyword;
737 hint->base.hint_keyword = hint_keyword;
738 hint->base.type = HINT_TYPE_LEADING;
739 hint->base.state = HINT_STATE_NOTUSED;
740 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
741 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
742 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
743 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
744 hint->relations = NIL;
745 hint->outer_inner = NULL;
747 return (Hint *) hint;
751 LeadingHintDelete(LeadingHint *hint)
756 list_free_deep(hint->relations);
757 if (hint->outer_inner)
758 pfree(hint->outer_inner);
763 SetHintCreate(const char *hint_str, const char *keyword,
764 HintKeyword hint_keyword)
768 hint = palloc(sizeof(SetHint));
769 hint->base.hint_str = hint_str;
770 hint->base.keyword = keyword;
771 hint->base.hint_keyword = hint_keyword;
772 hint->base.type = HINT_TYPE_SET;
773 hint->base.state = HINT_STATE_NOTUSED;
774 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
775 hint->base.desc_func = (HintDescFunction) SetHintDesc;
776 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
777 hint->base.parse_func = (HintParseFunction) SetHintParse;
782 return (Hint *) hint;
786 SetHintDelete(SetHint *hint)
796 list_free(hint->words);
801 RowsHintCreate(const char *hint_str, const char *keyword,
802 HintKeyword hint_keyword)
806 hint = palloc(sizeof(RowsHint));
807 hint->base.hint_str = hint_str;
808 hint->base.keyword = keyword;
809 hint->base.hint_keyword = hint_keyword;
810 hint->base.type = HINT_TYPE_ROWS;
811 hint->base.state = HINT_STATE_NOTUSED;
812 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
813 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
814 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
815 hint->base.parse_func = (HintParseFunction) RowsHintParse;
817 hint->inner_nrels = 0;
818 hint->relnames = NULL;
819 hint->joinrelids = NULL;
820 hint->inner_joinrelids = NULL;
821 hint->rows_str = NULL;
822 hint->value_type = RVT_ABSOLUTE;
825 return (Hint *) hint;
829 RowsHintDelete(RowsHint *hint)
838 for (i = 0; i < hint->nrels; i++)
839 pfree(hint->relnames[i]);
840 pfree(hint->relnames);
843 bms_free(hint->joinrelids);
844 bms_free(hint->inner_joinrelids);
849 HintStateCreate(void)
853 hstate = palloc(sizeof(HintState));
854 hstate->hint_str = NULL;
855 hstate->nall_hints = 0;
856 hstate->max_all_hints = 0;
857 hstate->all_hints = NULL;
858 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
859 hstate->scan_hints = NULL;
860 hstate->init_scan_mask = 0;
861 hstate->parent_relid = 0;
862 hstate->parent_hint = NULL;
863 hstate->parent_index_infos = NIL;
864 hstate->join_hints = NULL;
865 hstate->init_join_mask = 0;
866 hstate->join_hint_level = NULL;
867 hstate->leading_hint = NULL;
868 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
869 hstate->set_hints = NULL;
870 hstate->rows_hints = NULL;
876 HintStateDelete(HintState *hstate)
883 if (hstate->hint_str)
884 pfree(hstate->hint_str);
886 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
887 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
888 if (hstate->all_hints)
889 pfree(hstate->all_hints);
890 if (hstate->parent_index_infos)
891 list_free(hstate->parent_index_infos);
895 * Copy given value into buf, with quoting with '"' if necessary.
898 quote_value(StringInfo buf, const char *value)
900 bool need_quote = false;
903 for (str = value; *str != '\0'; str++)
905 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
908 appendStringInfoCharMacro(buf, '"');
913 for (str = value; *str != '\0'; str++)
916 appendStringInfoCharMacro(buf, '"');
918 appendStringInfoCharMacro(buf, *str);
922 appendStringInfoCharMacro(buf, '"');
926 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
930 appendStringInfo(buf, "%s(", hint->base.keyword);
931 if (hint->relname != NULL)
933 quote_value(buf, hint->relname);
934 foreach(l, hint->indexnames)
936 appendStringInfoCharMacro(buf, ' ');
937 quote_value(buf, (char *) lfirst(l));
940 appendStringInfoString(buf, ")");
942 appendStringInfoChar(buf, '\n');
946 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
950 appendStringInfo(buf, "%s(", hint->base.keyword);
951 if (hint->relnames != NULL)
953 quote_value(buf, hint->relnames[0]);
954 for (i = 1; i < hint->nrels; i++)
956 appendStringInfoCharMacro(buf, ' ');
957 quote_value(buf, hint->relnames[i]);
960 appendStringInfoString(buf, ")");
962 appendStringInfoChar(buf, '\n');
966 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
968 if (outer_inner->relation == NULL)
975 appendStringInfoCharMacro(buf, '(');
976 foreach(l, outer_inner->outer_inner_pair)
981 appendStringInfoCharMacro(buf, ' ');
983 OuterInnerDesc(lfirst(l), buf);
986 appendStringInfoCharMacro(buf, ')');
989 quote_value(buf, outer_inner->relation);
993 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
995 appendStringInfo(buf, "%s(", HINT_LEADING);
996 if (hint->outer_inner == NULL)
1003 foreach(l, hint->relations)
1008 appendStringInfoCharMacro(buf, ' ');
1010 quote_value(buf, (char *) lfirst(l));
1014 OuterInnerDesc(hint->outer_inner, buf);
1016 appendStringInfoString(buf, ")");
1018 appendStringInfoChar(buf, '\n');
1022 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1024 bool is_first = true;
1027 appendStringInfo(buf, "%s(", HINT_SET);
1028 foreach(l, hint->words)
1033 appendStringInfoCharMacro(buf, ' ');
1035 quote_value(buf, (char *) lfirst(l));
1037 appendStringInfo(buf, ")");
1039 appendStringInfoChar(buf, '\n');
1043 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1047 appendStringInfo(buf, "%s(", hint->base.keyword);
1048 if (hint->relnames != NULL)
1050 quote_value(buf, hint->relnames[0]);
1051 for (i = 1; i < hint->nrels; i++)
1053 appendStringInfoCharMacro(buf, ' ');
1054 quote_value(buf, hint->relnames[i]);
1057 appendStringInfo(buf, " %s", hint->rows_str);
1058 appendStringInfoString(buf, ")");
1060 appendStringInfoChar(buf, '\n');
1064 * Append string which represents all hints in a given state to buf, with
1065 * preceding title with them.
1068 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1069 HintStatus state, bool nolf)
1073 appendStringInfo(buf, "%s:", title);
1075 appendStringInfoChar(buf, '\n');
1078 for (i = 0; i < hstate->nall_hints; i++)
1080 if (hstate->all_hints[i]->state != state)
1083 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1087 if (nolf && nshown == 0)
1088 appendStringInfoString(buf, "(none)");
1092 * Dump contents of given hstate to server log with log level LOG.
1095 HintStateDump(HintState *hstate)
1101 elog(pg_hint_plan_debug_message_level, "pg_hint_plan:\nno hint");
1105 initStringInfo(&buf);
1107 appendStringInfoString(&buf, "pg_hint_plan:\n");
1108 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1109 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1110 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1111 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1113 ereport(pg_hint_plan_debug_message_level,
1114 (errmsg ("%s", buf.data)));
1120 HintStateDump2(HintState *hstate)
1126 elog(pg_hint_plan_debug_message_level,
1127 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1131 initStringInfo(&buf);
1132 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1133 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1134 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1135 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1136 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1137 appendStringInfoChar(&buf, '}');
1139 ereport(pg_hint_plan_debug_message_level,
1140 (errmsg("%s", buf.data),
1142 errhidecontext(true)));
1152 RelnameCmp(const void *a, const void *b)
1154 const char *relnamea = *((const char **) a);
1155 const char *relnameb = *((const char **) b);
1157 return strcmp(relnamea, relnameb);
1161 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1163 return RelnameCmp(&a->relname, &b->relname);
1167 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1171 if (a->nrels != b->nrels)
1172 return a->nrels - b->nrels;
1174 for (i = 0; i < a->nrels; i++)
1177 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1185 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1191 SetHintCmp(const SetHint *a, const SetHint *b)
1193 return strcmp(a->name, b->name);
1197 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1201 if (a->nrels != b->nrels)
1202 return a->nrels - b->nrels;
1204 for (i = 0; i < a->nrels; i++)
1207 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1215 HintCmp(const void *a, const void *b)
1217 const Hint *hinta = *((const Hint **) a);
1218 const Hint *hintb = *((const Hint **) b);
1220 if (hinta->type != hintb->type)
1221 return hinta->type - hintb->type;
1222 if (hinta->state == HINT_STATE_ERROR)
1224 if (hintb->state == HINT_STATE_ERROR)
1226 return hinta->cmp_func(hinta, hintb);
1230 * Returns byte offset of hint b from hint a. If hint a was specified before
1231 * b, positive value is returned.
1234 HintCmpWithPos(const void *a, const void *b)
1236 const Hint *hinta = *((const Hint **) a);
1237 const Hint *hintb = *((const Hint **) b);
1240 result = HintCmp(a, b);
1242 result = hinta->hint_str - hintb->hint_str;
1251 parse_keyword(const char *str, StringInfo buf)
1255 while (!isspace(*str) && *str != '(' && *str != '\0')
1256 appendStringInfoCharMacro(buf, *str++);
1262 skip_parenthesis(const char *str, char parenthesis)
1266 if (*str != parenthesis)
1268 if (parenthesis == '(')
1269 hint_ereport(str, ("Opening parenthesis is necessary."));
1270 else if (parenthesis == ')')
1271 hint_ereport(str, ("Closing parenthesis is necessary."));
1282 * Parse a token from str, and store malloc'd copy into word. A token can be
1283 * quoted with '"'. Return value is pointer to unparsed portion of original
1284 * string, or NULL if an error occurred.
1286 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1289 parse_quoted_value(const char *str, char **word, bool truncate)
1294 /* Skip leading spaces. */
1297 initStringInfo(&buf);
1310 /* Double quotation must be closed. */
1314 hint_ereport(str, ("Unterminated quoted string."));
1319 * Skip escaped double quotation.
1321 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1322 * block comments) to be an object name, so users must specify
1323 * alias for such object names.
1325 * Those special names can be allowed if we care escaped slashes
1326 * and asterisks, but we don't.
1335 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1339 appendStringInfoCharMacro(&buf, *str++);
1344 hint_ereport(str, ("Zero-length delimited string."));
1351 /* Truncate name if it's too long */
1353 truncate_identifier(buf.data, strlen(buf.data), true);
1360 static OuterInnerRels *
1361 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1363 OuterInnerRels *outer_inner;
1365 outer_inner = palloc(sizeof(OuterInnerRels));
1366 outer_inner->relation = name;
1367 outer_inner->outer_inner_pair = outer_inner_list;
1373 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1375 List *outer_inner_pair = NIL;
1377 if ((str = skip_parenthesis(str, '(')) == NULL)
1382 /* Store words in parentheses into outer_inner_list. */
1383 while(*str != ')' && *str != '\0')
1385 OuterInnerRels *outer_inner_rels;
1389 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1397 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1400 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1403 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1408 (str = skip_parenthesis(str, ')')) == NULL)
1410 list_free(outer_inner_pair);
1414 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1420 parse_parentheses_Leading(const char *str, List **name_list,
1421 OuterInnerRels **outer_inner)
1424 bool truncate = true;
1426 if ((str = skip_parenthesis(str, '(')) == NULL)
1432 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1437 /* Store words in parentheses into name_list. */
1438 while(*str != ')' && *str != '\0')
1440 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1442 list_free(*name_list);
1446 *name_list = lappend(*name_list, name);
1451 if ((str = skip_parenthesis(str, ')')) == NULL)
1457 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1460 bool truncate = true;
1462 if ((str = skip_parenthesis(str, '(')) == NULL)
1467 /* Store words in parentheses into name_list. */
1468 while(*str != ')' && *str != '\0')
1470 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1472 list_free(*name_list);
1476 *name_list = lappend(*name_list, name);
1479 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1480 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1481 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1482 keyword == HINT_KEYWORD_SET)
1488 if ((str = skip_parenthesis(str, ')')) == NULL)
1494 parse_hints(HintState *hstate, Query *parse, const char *str)
1499 initStringInfo(&buf);
1500 while (*str != '\0')
1502 const HintParser *parser;
1504 /* in error message, we output the comment including the keyword. */
1505 head = (char *) str;
1507 /* parse only the keyword of the hint. */
1508 resetStringInfo(&buf);
1509 str = parse_keyword(str, &buf);
1511 for (parser = parsers; parser->keyword != NULL; parser++)
1513 char *keyword = parser->keyword;
1516 if (pg_strcasecmp(buf.data, keyword) != 0)
1519 hint = parser->create_func(head, keyword, parser->hint_keyword);
1521 /* parser of each hint does parse in a parenthesis. */
1522 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1524 hint->delete_func(hint);
1530 * Add hint information into all_hints array. If we don't have
1531 * enough space, double the array.
1533 if (hstate->nall_hints == 0)
1535 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1536 hstate->all_hints = (Hint **)
1537 palloc(sizeof(Hint *) * hstate->max_all_hints);
1539 else if (hstate->nall_hints == hstate->max_all_hints)
1541 hstate->max_all_hints *= 2;
1542 hstate->all_hints = (Hint **)
1543 repalloc(hstate->all_hints,
1544 sizeof(Hint *) * hstate->max_all_hints);
1547 hstate->all_hints[hstate->nall_hints] = hint;
1548 hstate->nall_hints++;
1555 if (parser->keyword == NULL)
1558 ("Unrecognized hint keyword \"%s\".", buf.data));
1569 * Get hints from table by client-supplied query string and application name.
1572 get_hints_from_table(const char *client_query, const char *client_application)
1574 const char *search_query =
1576 " FROM hint_plan.hints "
1577 " WHERE norm_query_string = $1 "
1578 " AND ( application_name = $2 "
1579 " OR application_name = '' ) "
1580 " ORDER BY application_name DESC";
1581 static SPIPlanPtr plan = NULL;
1583 Oid argtypes[2] = { TEXTOID, TEXTOID };
1585 bool nulls[2] = { false, false };
1591 bool snapshot_set = false;
1593 hint_inhibit_level++;
1595 if (!ActiveSnapshotSet())
1597 PushActiveSnapshot(GetTransactionSnapshot());
1598 snapshot_set = true;
1606 p = SPI_prepare(search_query, 2, argtypes);
1607 plan = SPI_saveplan(p);
1611 qry = cstring_to_text(client_query);
1612 app = cstring_to_text(client_application);
1613 values[0] = PointerGetDatum(qry);
1614 values[1] = PointerGetDatum(app);
1616 SPI_execute_plan(plan, values, nulls, true, 1);
1618 if (SPI_processed > 0)
1622 hints = SPI_getvalue(SPI_tuptable->vals[0],
1623 SPI_tuptable->tupdesc, 1);
1625 * Here we use SPI_palloc to ensure that hints string is valid even
1626 * after SPI_finish call. We can't use simple palloc because it
1627 * allocates memory in SPI's context and that context is deleted in
1630 buf = SPI_palloc(strlen(hints) + 1);
1638 PopActiveSnapshot();
1640 hint_inhibit_level--;
1644 hint_inhibit_level--;
1653 * Get client-supplied query string. Addtion to that the jumbled query is
1654 * supplied if the caller requested. From the restriction of JumbleQuery, some
1655 * kind of query needs special amendments. Reutrns NULL if this query doesn't
1656 * change the current hint. This function returns NULL also when something
1657 * wrong has happend and let the caller continue using the current hints.
1660 get_query_string(ParseState *pstate, Query *query, Query **jumblequery)
1662 const char *p = debug_query_string;
1665 * If debug_query_string is set, it is the top level statement. But in some
1666 * cases we reach here with debug_query_string set NULL for example in the
1667 * case of DESCRIBE message handling. We may still see a candidate
1668 * top-level query in pstate in the case.
1672 /* We don't see a query string, return NULL */
1673 if (!pstate->p_sourcetext)
1676 p = pstate->p_sourcetext;
1679 if (jumblequery != NULL)
1680 *jumblequery = query;
1682 /* Query for DeclareCursorStmt is CMD_SELECT and has query->utilityStmt */
1683 if (query->commandType == CMD_UTILITY || query->utilityStmt)
1685 Query *target_query = query;
1688 * Some utility statements have a subquery that we can hint on. Since
1689 * EXPLAIN can be placed before other kind of utility statements and
1690 * EXECUTE can be contained other kind of utility statements, these
1691 * conditions are not mutually exclusive and should be considered in
1694 if (IsA(target_query->utilityStmt, ExplainStmt))
1696 ExplainStmt *stmt = (ExplainStmt *)target_query->utilityStmt;
1698 Assert(IsA(stmt->query, Query));
1699 target_query = (Query *)stmt->query;
1701 /* strip out the top-level query for further processing */
1702 if (target_query->commandType == CMD_UTILITY &&
1703 target_query->utilityStmt != NULL)
1704 target_query = (Query *)target_query->utilityStmt;
1708 * JumbleQuery does not accept a Query that has utilityStmt. On the
1709 * other hand DeclareCursorStmt is in a bit strange shape that is
1710 * flipped upside down.
1712 if (IsA(target_query, Query) &&
1713 target_query->utilityStmt &&
1714 IsA(target_query->utilityStmt, DeclareCursorStmt))
1717 * The given Query cannot be modified so copy it and modify so that
1718 * JumbleQuery can accept it.
1720 Assert(IsA(target_query, Query) &&
1721 target_query->commandType == CMD_SELECT);
1722 target_query = copyObject(target_query);
1723 target_query->utilityStmt = NULL;
1726 if (IsA(target_query, CreateTableAsStmt))
1728 CreateTableAsStmt *stmt = (CreateTableAsStmt *) target_query;
1730 Assert(IsA(stmt->query, Query));
1731 target_query = (Query *) stmt->query;
1733 /* strip out the top-level query for further processing */
1734 if (target_query->commandType == CMD_UTILITY &&
1735 target_query->utilityStmt != NULL)
1736 target_query = (Query *)target_query->utilityStmt;
1739 if (IsA(target_query, ExecuteStmt))
1742 * Use the prepared query for EXECUTE. The Query for jumble
1743 * also replaced with the corresponding one.
1745 ExecuteStmt *stmt = (ExecuteStmt *)target_query;
1746 PreparedStatement *entry;
1748 entry = FetchPreparedStatement(stmt->name, true);
1749 p = entry->plansource->query_string;
1750 target_query = (Query *) linitial (entry->plansource->query_list);
1753 /* JumbleQuery accespts only a non-utility Query */
1754 if (!IsA(target_query, Query) ||
1755 target_query->utilityStmt != NULL)
1756 target_query = NULL;
1759 *jumblequery = target_query;
1762 /* Return NULL if the pstate is not identical to the top-level query */
1763 else if (strcmp(pstate->p_sourcetext, p) != 0)
1770 * Get hints from the head block comment in client-supplied query string.
1773 get_hints_from_comment(const char *p)
1775 const char *hint_head;
1783 /* extract query head comment. */
1784 hint_head = strstr(p, HINT_START);
1785 if (hint_head == NULL)
1787 for (;p < hint_head; p++)
1790 * Allow these characters precedes hint comment:
1792 * - alphabets which are in ASCII range
1793 * - space, tabs and new-lines
1794 * - underscores, for identifier
1795 * - commas, for SELECT clause, EXPLAIN and PREPARE
1796 * - parentheses, for EXPLAIN and PREPARE
1798 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1799 * avoid behavior which depends on locale setting.
1801 if (!(*p >= '0' && *p <= '9') &&
1802 !(*p >= 'A' && *p <= 'Z') &&
1803 !(*p >= 'a' && *p <= 'z') &&
1807 *p != '(' && *p != ')')
1811 len = strlen(HINT_START);
1816 /* find hint end keyword. */
1817 if ((tail = strstr(p, HINT_END)) == NULL)
1819 hint_ereport(head, ("Unterminated block comment."));
1823 /* We don't support nested block comments. */
1824 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1826 hint_ereport(head, ("Nested block comments are not supported."));
1830 /* Make a copy of hint. */
1832 head = palloc(len + 1);
1833 memcpy(head, p, len);
1841 * Parse hints that got, create hint struct from parse tree and parse hints.
1844 create_hintstate(Query *parse, const char *hints)
1854 hstate = HintStateCreate();
1855 hstate->hint_str = (char *) hints;
1857 /* parse each hint. */
1858 parse_hints(hstate, parse, p);
1860 /* When nothing specified a hint, we free HintState and returns NULL. */
1861 if (hstate->nall_hints == 0)
1863 HintStateDelete(hstate);
1867 /* Sort hints in order of original position. */
1868 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1871 /* Count number of hints per hint-type. */
1872 for (i = 0; i < hstate->nall_hints; i++)
1874 Hint *cur_hint = hstate->all_hints[i];
1875 hstate->num_hints[cur_hint->type]++;
1879 * If an object (or a set of objects) has multiple hints of same hint-type,
1880 * only the last hint is valid and others are ignored in planning.
1881 * Hints except the last are marked as 'duplicated' to remember the order.
1883 for (i = 0; i < hstate->nall_hints - 1; i++)
1885 Hint *cur_hint = hstate->all_hints[i];
1886 Hint *next_hint = hstate->all_hints[i + 1];
1889 * Leading hint is marked as 'duplicated' in transform_join_hints.
1891 if (cur_hint->type == HINT_TYPE_LEADING &&
1892 next_hint->type == HINT_TYPE_LEADING)
1896 * Note that we need to pass addresses of hint pointers, because
1897 * HintCmp is designed to sort array of Hint* by qsort.
1899 if (HintCmp(&cur_hint, &next_hint) == 0)
1901 hint_ereport(cur_hint->hint_str,
1902 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1903 cur_hint->state = HINT_STATE_DUPLICATION;
1908 * Make sure that per-type array pointers point proper position in the
1909 * array which consists of all hints.
1911 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1912 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1913 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1914 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1915 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1916 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1917 hstate->num_hints[HINT_TYPE_LEADING]);
1918 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
1919 hstate->num_hints[HINT_TYPE_SET]);
1925 * Parse inside of parentheses of scan-method hints.
1928 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1931 const char *keyword = hint->base.keyword;
1932 HintKeyword hint_keyword = hint->base.hint_keyword;
1933 List *name_list = NIL;
1936 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1939 /* Parse relation name and index name(s) if given hint accepts. */
1940 length = list_length(name_list);
1943 hint->relname = linitial(name_list);
1944 hint->indexnames = list_delete_first(name_list);
1946 /* check whether the hint accepts index name(s). */
1948 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1949 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1950 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1951 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1952 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1953 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1956 ("%s hint accepts only one relation.",
1957 hint->base.keyword));
1958 hint->base.state = HINT_STATE_ERROR;
1965 ("%s hint requires a relation.",
1966 hint->base.keyword));
1967 hint->base.state = HINT_STATE_ERROR;
1971 /* Set a bit for specified hint. */
1972 switch (hint_keyword)
1974 case HINT_KEYWORD_SEQSCAN:
1975 hint->enforce_mask = ENABLE_SEQSCAN;
1977 case HINT_KEYWORD_INDEXSCAN:
1978 hint->enforce_mask = ENABLE_INDEXSCAN;
1980 case HINT_KEYWORD_INDEXSCANREGEXP:
1981 hint->enforce_mask = ENABLE_INDEXSCAN;
1982 hint->regexp = true;
1984 case HINT_KEYWORD_BITMAPSCAN:
1985 hint->enforce_mask = ENABLE_BITMAPSCAN;
1987 case HINT_KEYWORD_BITMAPSCANREGEXP:
1988 hint->enforce_mask = ENABLE_BITMAPSCAN;
1989 hint->regexp = true;
1991 case HINT_KEYWORD_TIDSCAN:
1992 hint->enforce_mask = ENABLE_TIDSCAN;
1994 case HINT_KEYWORD_NOSEQSCAN:
1995 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1997 case HINT_KEYWORD_NOINDEXSCAN:
1998 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
2000 case HINT_KEYWORD_NOBITMAPSCAN:
2001 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
2003 case HINT_KEYWORD_NOTIDSCAN:
2004 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
2006 case HINT_KEYWORD_INDEXONLYSCAN:
2007 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2009 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
2010 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2011 hint->regexp = true;
2013 case HINT_KEYWORD_NOINDEXONLYSCAN:
2014 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
2017 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2026 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2029 const char *keyword = hint->base.keyword;
2030 HintKeyword hint_keyword = hint->base.hint_keyword;
2031 List *name_list = NIL;
2033 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2036 hint->nrels = list_length(name_list);
2038 if (hint->nrels > 0)
2044 * Transform relation names from list to array to sort them with qsort
2047 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2048 foreach (l, name_list)
2050 hint->relnames[i] = lfirst(l);
2055 list_free(name_list);
2057 /* A join hint requires at least two relations */
2058 if (hint->nrels < 2)
2061 ("%s hint requires at least two relations.",
2062 hint->base.keyword));
2063 hint->base.state = HINT_STATE_ERROR;
2067 /* Sort hints in alphabetical order of relation names. */
2068 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2070 switch (hint_keyword)
2072 case HINT_KEYWORD_NESTLOOP:
2073 hint->enforce_mask = ENABLE_NESTLOOP;
2075 case HINT_KEYWORD_MERGEJOIN:
2076 hint->enforce_mask = ENABLE_MERGEJOIN;
2078 case HINT_KEYWORD_HASHJOIN:
2079 hint->enforce_mask = ENABLE_HASHJOIN;
2081 case HINT_KEYWORD_NONESTLOOP:
2082 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2084 case HINT_KEYWORD_NOMERGEJOIN:
2085 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2087 case HINT_KEYWORD_NOHASHJOIN:
2088 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2091 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2100 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2103 if (outer_inner->outer_inner_pair == NIL)
2105 if (outer_inner->relation)
2111 if (list_length(outer_inner->outer_inner_pair) == 2)
2113 foreach(l, outer_inner->outer_inner_pair)
2115 if (!OuterInnerPairCheck(lfirst(l)))
2126 OuterInnerList(OuterInnerRels *outer_inner)
2128 List *outer_inner_list = NIL;
2130 OuterInnerRels *outer_inner_rels;
2132 foreach(l, outer_inner->outer_inner_pair)
2134 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2136 if (outer_inner_rels->relation != NULL)
2137 outer_inner_list = lappend(outer_inner_list,
2138 outer_inner_rels->relation);
2140 outer_inner_list = list_concat(outer_inner_list,
2141 OuterInnerList(outer_inner_rels));
2143 return outer_inner_list;
2147 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2150 List *name_list = NIL;
2151 OuterInnerRels *outer_inner = NULL;
2153 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2157 if (outer_inner != NULL)
2158 name_list = OuterInnerList(outer_inner);
2160 hint->relations = name_list;
2161 hint->outer_inner = outer_inner;
2163 /* A Leading hint requires at least two relations */
2164 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2166 hint_ereport(hint->base.hint_str,
2167 ("%s hint requires at least two relations.",
2169 hint->base.state = HINT_STATE_ERROR;
2171 else if (hint->outer_inner != NULL &&
2172 !OuterInnerPairCheck(hint->outer_inner))
2174 hint_ereport(hint->base.hint_str,
2175 ("%s hint requires two sets of relations when parentheses nests.",
2177 hint->base.state = HINT_STATE_ERROR;
2184 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2186 List *name_list = NIL;
2188 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2192 hint->words = name_list;
2194 /* We need both name and value to set GUC parameter. */
2195 if (list_length(name_list) == 2)
2197 hint->name = linitial(name_list);
2198 hint->value = lsecond(name_list);
2202 hint_ereport(hint->base.hint_str,
2203 ("%s hint requires name and value of GUC parameter.",
2205 hint->base.state = HINT_STATE_ERROR;
2212 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2215 HintKeyword hint_keyword = hint->base.hint_keyword;
2216 List *name_list = NIL;
2220 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2223 /* Last element must be rows specification */
2224 hint->nrels = list_length(name_list) - 1;
2226 if (hint->nrels > 0)
2232 * Transform relation names from list to array to sort them with qsort
2235 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2236 foreach (l, name_list)
2238 if (hint->nrels <= i)
2240 hint->relnames[i] = lfirst(l);
2245 /* Retieve rows estimation */
2246 rows_str = list_nth(name_list, hint->nrels);
2247 hint->rows_str = rows_str; /* store as-is for error logging */
2248 if (rows_str[0] == '#')
2250 hint->value_type = RVT_ABSOLUTE;
2253 else if (rows_str[0] == '+')
2255 hint->value_type = RVT_ADD;
2258 else if (rows_str[0] == '-')
2260 hint->value_type = RVT_SUB;
2263 else if (rows_str[0] == '*')
2265 hint->value_type = RVT_MULTI;
2270 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2271 hint->base.state = HINT_STATE_ERROR;
2274 hint->rows = strtod(rows_str, &end_ptr);
2277 hint_ereport(rows_str,
2278 ("%s hint requires valid number as rows estimation.",
2279 hint->base.keyword));
2280 hint->base.state = HINT_STATE_ERROR;
2284 /* A join hint requires at least two relations */
2285 if (hint->nrels < 2)
2288 ("%s hint requires at least two relations.",
2289 hint->base.keyword));
2290 hint->base.state = HINT_STATE_ERROR;
2294 list_free(name_list);
2296 /* Sort relnames in alphabetical order. */
2297 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2303 * set GUC parameter functions
2307 set_config_option_wrapper(const char *name, const char *value,
2308 GucContext context, GucSource source,
2309 GucAction action, bool changeVal, int elevel)
2312 MemoryContext ccxt = CurrentMemoryContext;
2316 result = set_config_option(name, value, context, source,
2317 action, changeVal, 0, false);
2323 /* Save error info */
2324 MemoryContextSwitchTo(ccxt);
2325 errdata = CopyErrorData();
2329 (errcode(errdata->sqlerrcode),
2330 errmsg("%s", errdata->message),
2331 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2332 errdata->hint ? errhint("%s", errdata->hint) : 0));
2334 FreeErrorData(errdata);
2342 set_config_options(SetHint **options, int noptions, GucContext context)
2347 save_nestlevel = NewGUCNestLevel();
2349 for (i = 0; i < noptions; i++)
2351 SetHint *hint = options[i];
2354 if (!hint_state_enabled(hint))
2357 result = set_config_option_wrapper(hint->name, hint->value, context,
2358 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2359 pg_hint_plan_parse_message_level);
2361 hint->base.state = HINT_STATE_USED;
2363 hint->base.state = HINT_STATE_ERROR;
2366 return save_nestlevel;
2369 #define SET_CONFIG_OPTION(name, type_bits) \
2370 set_config_option_wrapper((name), \
2371 (mask & (type_bits)) ? "true" : "false", \
2372 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2375 set_scan_config_options(unsigned char enforce_mask, GucContext context)
2379 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2380 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2381 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2383 mask = enforce_mask;
2385 mask = enforce_mask & current_hint->init_scan_mask;
2387 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2388 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2389 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2390 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2391 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2395 set_join_config_options(unsigned char enforce_mask, GucContext context)
2399 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2400 enforce_mask == ENABLE_HASHJOIN)
2401 mask = enforce_mask;
2403 mask = enforce_mask & current_hint->init_join_mask;
2405 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2406 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2407 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2411 * Push a hint into hint stack which is implemented with List struct. Head of
2412 * list is top of stack.
2415 push_hint(HintState *hstate)
2417 /* Prepend new hint to the list means pushing to stack. */
2418 HintStateStack = lcons(hstate, HintStateStack);
2420 /* Pushed hint is the one which should be used hereafter. */
2421 current_hint = hstate;
2424 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2428 /* Hint stack must not be empty. */
2429 if(HintStateStack == NIL)
2430 elog(ERROR, "hint stack is empty");
2433 * Take a hint at the head from the list, and free it. Switch current_hint
2434 * to point new head (NULL if the list is empty).
2436 HintStateStack = list_delete_first(HintStateStack);
2437 HintStateDelete(current_hint);
2438 if(HintStateStack == NIL)
2439 current_hint = NULL;
2441 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2445 * Retrieve and store a hint string from given query or from the hint table.
2446 * If we are using the hint table, the query string is needed to be normalized.
2447 * However, ParseState, which is not available in planner_hook, is required to
2448 * check if the query tree (Query) is surely corresponding to the target query.
2451 pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query)
2453 const char *query_str;
2454 MemoryContext oldcontext;
2456 if (prev_post_parse_analyze_hook)
2457 prev_post_parse_analyze_hook(pstate, query);
2459 /* do nothing under hint table search */
2460 if (hint_inhibit_level > 0)
2463 if (!pg_hint_plan_enable_hint)
2465 if (current_hint_str)
2467 pfree((void *)current_hint_str);
2468 current_hint_str = NULL;
2473 /* increment the query number */
2475 if (debug_level > 1)
2476 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2479 /* search the hint table for a hint if requested */
2480 if (pg_hint_plan_enable_hint_table)
2483 pgssJumbleState jstate;
2485 char *normalized_query = NULL;
2487 query_str = get_query_string(pstate, query, &jumblequery);
2489 /* If this query is not for hint, just return */
2493 /* clear the previous hint string */
2494 if (current_hint_str)
2496 pfree((void *)current_hint_str);
2497 current_hint_str = NULL;
2503 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2504 * careful to PostgreSQL's version up.
2506 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2507 jstate.jumble_len = 0;
2508 jstate.clocations_buf_size = 32;
2509 jstate.clocations = (pgssLocationLen *)
2510 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2511 jstate.clocations_count = 0;
2513 JumbleQuery(&jstate, jumblequery);
2516 * Normalize the query string by replacing constants with '?'
2519 * Search hint string which is stored keyed by query string
2520 * and application name. The query string is normalized to allow
2523 * Adding 1 byte to query_len ensures that the returned string has
2524 * a terminating NULL.
2526 query_len = strlen(query_str) + 1;
2528 generate_normalized_query(&jstate, query_str,
2530 GetDatabaseEncoding());
2533 * find a hint for the normalized query. the result should be in
2536 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2538 get_hints_from_table(normalized_query, application_name);
2539 MemoryContextSwitchTo(oldcontext);
2541 if (debug_level > 1)
2543 if (current_hint_str)
2544 ereport(pg_hint_plan_debug_message_level,
2545 (errmsg("pg_hint_plan[qno=0x%x]: "
2546 "post_parse_analyze_hook: "
2547 "hints from table: \"%s\": "
2548 "normalized_query=\"%s\", "
2549 "application name =\"%s\"",
2550 qno, current_hint_str,
2551 normalized_query, application_name),
2552 errhidestmt(msgqno != qno),
2553 errhidecontext(msgqno != qno)));
2555 ereport(pg_hint_plan_debug_message_level,
2556 (errmsg("pg_hint_plan[qno=0x%x]: "
2557 "no match found in table: "
2558 "application name = \"%s\", "
2559 "normalized_query=\"%s\"",
2560 qno, application_name,
2562 errhidestmt(msgqno != qno),
2563 errhidecontext(msgqno != qno)));
2569 /* retrun if we have hint here */
2570 if (current_hint_str)
2574 query_str = get_query_string(pstate, query, NULL);
2579 * get hints from the comment. However we may have the same query
2580 * string with the previous call, but just retrieving hints is expected
2581 * to be faster than checking for identicalness before retrieval.
2583 if (current_hint_str)
2584 pfree((void *)current_hint_str);
2586 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2587 current_hint_str = get_hints_from_comment(query_str);
2588 MemoryContextSwitchTo(oldcontext);
2591 if (debug_level > 1)
2593 if (debug_level == 1 &&
2594 (stmt_name || strcmp(query_str, debug_query_string)))
2595 ereport(pg_hint_plan_debug_message_level,
2596 (errmsg("hints in comment=\"%s\"",
2597 current_hint_str ? current_hint_str : "(none)"),
2598 errhidestmt(msgqno != qno),
2599 errhidecontext(msgqno != qno)));
2601 ereport(pg_hint_plan_debug_message_level,
2602 (errmsg("hints in comment=\"%s\", stmt=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2603 current_hint_str ? current_hint_str : "(none)",
2604 stmt_name, query_str, debug_query_string),
2605 errhidestmt(msgqno != qno),
2606 errhidecontext(msgqno != qno)));
2612 * Read and set up hint information
2614 static PlannedStmt *
2615 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2618 PlannedStmt *result;
2622 * Use standard planner if pg_hint_plan is disabled or current nesting
2623 * depth is nesting depth of SPI calls. Other hook functions try to change
2624 * plan with current_hint if any, so set it to NULL.
2626 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2628 if (debug_level > 1)
2629 ereport(pg_hint_plan_debug_message_level,
2630 (errmsg ("pg_hint_plan%s: planner: enable_hint=%d,"
2631 " hint_inhibit_level=%d",
2632 qnostr, pg_hint_plan_enable_hint,
2633 hint_inhibit_level),
2634 errhidestmt(msgqno != qno)));
2637 goto standard_planner_proc;
2641 * Support for nested plpgsql functions. This is quite ugly but this is the
2642 * only point I could find where I can get the query string.
2644 if (plpgsql_recurse_level > 0)
2646 MemoryContext oldcontext;
2648 if (current_hint_str)
2649 pfree((void *)current_hint_str);
2651 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2653 get_hints_from_comment((char *)error_context_stack->arg);
2654 MemoryContextSwitchTo(oldcontext);
2657 if (!current_hint_str)
2658 goto standard_planner_proc;
2660 /* parse the hint into hint state struct */
2661 hstate = create_hintstate(parse, pstrdup(current_hint_str));
2663 /* run standard planner if the statement has not valid hint */
2665 goto standard_planner_proc;
2668 * Push new hint struct to the hint stack to disable previous hint context.
2672 /* Set GUC parameters which are specified with Set hint. */
2673 save_nestlevel = set_config_options(current_hint->set_hints,
2674 current_hint->num_hints[HINT_TYPE_SET],
2675 current_hint->context);
2678 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2679 if (enable_indexscan)
2680 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2681 if (enable_bitmapscan)
2682 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2684 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2685 if (enable_indexonlyscan)
2686 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2687 if (enable_nestloop)
2688 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2689 if (enable_mergejoin)
2690 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2691 if (enable_hashjoin)
2692 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2694 if (debug_level > 1)
2696 ereport(pg_hint_plan_debug_message_level,
2697 (errhidestmt(msgqno != qno),
2698 errmsg("pg_hint_plan%s: planner", qnostr)));
2703 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2704 * state when this planner started when error occurred in planner.
2709 result = (*prev_planner) (parse, cursorOptions, boundParams);
2711 result = standard_planner(parse, cursorOptions, boundParams);
2716 * Rollback changes of GUC parameters, and pop current hint context
2717 * from hint stack to rewind the state.
2719 AtEOXact_GUC(true, save_nestlevel);
2725 /* Print hint in debug mode. */
2726 if (debug_level == 1)
2727 HintStateDump(current_hint);
2728 else if (debug_level > 1)
2729 HintStateDump2(current_hint);
2732 * Rollback changes of GUC parameters, and pop current hint context from
2733 * hint stack to rewind the state.
2735 AtEOXact_GUC(true, save_nestlevel);
2740 standard_planner_proc:
2741 if (debug_level > 1)
2743 ereport(pg_hint_plan_debug_message_level,
2744 (errhidestmt(msgqno != qno),
2745 errmsg("pg_hint_plan%s: planner: no valid hint",
2749 current_hint = NULL;
2751 return (*prev_planner) (parse, cursorOptions, boundParams);
2753 return standard_planner(parse, cursorOptions, boundParams);
2757 * Return scan method hint which matches given aliasname.
2759 static ScanMethodHint *
2760 find_scan_hint(PlannerInfo *root, Index relid, RelOptInfo *rel)
2766 * We can't apply scan method hint if the relation is:
2767 * - not a base relation
2768 * - not an ordinary relation (such as join and subquery)
2770 if (rel && (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION))
2773 rte = root->simple_rte_array[relid];
2775 /* We can't force scan method of foreign tables */
2776 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2779 /* Find scan method hint, which matches given names, from the list. */
2780 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2782 ScanMethodHint *hint = current_hint->scan_hints[i];
2784 /* We ignore disabled hints. */
2785 if (!hint_state_enabled(hint))
2788 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2798 * Returns TRUE on match, FALSE on no match.
2800 * s1 --- the data to match against
2801 * s2 --- the pattern
2803 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2806 regexpeq(const char *s1, const char *s2)
2812 strcpy(name.data, s1);
2813 regexp = cstring_to_text(s2);
2815 result = DirectFunctionCall2Coll(nameregexeq,
2816 DEFAULT_COLLATION_OID,
2817 NameGetDatum(&name),
2818 PointerGetDatum(regexp));
2819 return DatumGetBool(result);
2823 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2831 * We delete all the IndexOptInfo list and prevent you from being usable by
2834 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2835 hint->enforce_mask == ENABLE_TIDSCAN)
2837 list_free_deep(rel->indexlist);
2838 rel->indexlist = NIL;
2839 hint->base.state = HINT_STATE_USED;
2845 * When a list of indexes is not specified, we just use all indexes.
2847 if (hint->indexnames == NIL)
2851 * Leaving only an specified index, we delete it from a IndexOptInfo list
2855 if (debug_level > 0)
2856 initStringInfo(&buf);
2858 for (cell = list_head(rel->indexlist); cell; cell = next)
2860 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2861 char *indexname = get_rel_name(info->indexoid);
2863 bool use_index = false;
2867 foreach(l, hint->indexnames)
2869 char *hintname = (char *) lfirst(l);
2873 result = regexpeq(indexname, hintname);
2875 result = RelnameCmp(&indexname, &hintname) == 0;
2880 if (debug_level > 0)
2882 appendStringInfoCharMacro(&buf, ' ');
2883 quote_value(&buf, indexname);
2891 * to make the index a candidate when definition of this index is
2892 * matched with the index's definition of current_hint.
2894 if (OidIsValid(relationObjectId) && !use_index)
2896 foreach(l, current_hint->parent_index_infos)
2900 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2902 /* check to match the parameter of unique */
2903 if (p_info->indisunique != info->unique)
2906 /* check to match the parameter of index's method */
2907 if (p_info->method != info->relam)
2910 /* to check to match the indexkey's configuration */
2911 if ((list_length(p_info->column_names)) !=
2915 /* check to match the indexkey's configuration */
2916 for (i = 0; i < info->ncolumns; i++)
2918 char *c_attname = NULL;
2919 char *p_attname = NULL;
2922 list_nth(p_info->column_names, i);
2924 /* both are expressions */
2925 if (info->indexkeys[i] == 0 && !p_attname)
2928 /* one's column is expression, the other is not */
2929 if (info->indexkeys[i] == 0 || !p_attname)
2932 c_attname = get_attname(relationObjectId,
2933 info->indexkeys[i]);
2935 if (strcmp(p_attname, c_attname) != 0)
2938 if (p_info->indcollation[i] != info->indexcollations[i])
2941 if (p_info->opclass[i] != info->opcintype[i])
2944 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2945 info->reverse_sort[i])
2948 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2949 info->nulls_first[i])
2954 if (i != info->ncolumns)
2957 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2958 (p_info->indpred_str && (info->indpred != NIL)))
2961 * Fetch the pg_index tuple by the Oid of the index
2963 ht_idx = SearchSysCache1(INDEXRELID,
2964 ObjectIdGetDatum(info->indexoid));
2966 /* check to match the expression's parameter of index */
2967 if (p_info->expression_str &&
2968 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2975 * to change the expression's parameter of child's
2978 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2979 Anum_pg_index_indexprs,
2982 result = DirectFunctionCall2(pg_get_expr,
2987 if (strcmp(p_info->expression_str,
2988 text_to_cstring(DatumGetTextP(result))) != 0)
2991 ReleaseSysCache(ht_idx);
2997 /* Check to match the predicate's parameter of index */
2998 if (p_info->indpred_str &&
2999 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
3006 * to change the predicate's parameter of child's
3009 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3010 Anum_pg_index_indpred,
3013 result = DirectFunctionCall2(pg_get_expr,
3018 if (strcmp(p_info->indpred_str,
3019 text_to_cstring(DatumGetTextP(result))) != 0)
3022 ReleaseSysCache(ht_idx);
3029 ReleaseSysCache(ht_idx);
3031 else if (p_info->expression_str || (info->indexprs != NIL))
3033 else if (p_info->indpred_str || (info->indpred != NIL))
3038 /* to log the candidate of index */
3039 if (debug_level > 0)
3041 appendStringInfoCharMacro(&buf, ' ');
3042 quote_value(&buf, indexname);
3050 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
3057 if (debug_level == 1)
3060 StringInfoData rel_buf;
3062 if (OidIsValid(relationObjectId))
3063 relname = get_rel_name(relationObjectId);
3065 relname = hint->relname;
3067 initStringInfo(&rel_buf);
3068 quote_value(&rel_buf, relname);
3070 ereport(pg_hint_plan_debug_message_level,
3071 (errmsg("available indexes for %s(%s):%s",
3076 pfree(rel_buf.data);
3081 * Return information of index definition.
3083 static ParentIndexInfo *
3084 get_parent_index_info(Oid indexoid, Oid relid)
3086 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3087 Relation indexRelation;
3088 Form_pg_index index;
3092 indexRelation = index_open(indexoid, RowExclusiveLock);
3094 index = indexRelation->rd_index;
3096 p_info->indisunique = index->indisunique;
3097 p_info->method = indexRelation->rd_rel->relam;
3099 p_info->column_names = NIL;
3100 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3101 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3102 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3104 for (i = 0; i < index->indnatts; i++)
3106 attname = get_attname(relid, index->indkey.values[i]);
3107 p_info->column_names = lappend(p_info->column_names, attname);
3109 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3110 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3111 p_info->indoption[i] = indexRelation->rd_indoption[i];
3115 * to check to match the expression's parameter of index with child indexes
3117 p_info->expression_str = NULL;
3118 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
3124 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3125 Anum_pg_index_indexprs, &isnull);
3127 result = DirectFunctionCall2(pg_get_expr,
3129 ObjectIdGetDatum(relid));
3131 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3135 * to check to match the predicate's parameter of index with child indexes
3137 p_info->indpred_str = NULL;
3138 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
3144 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3145 Anum_pg_index_indpred, &isnull);
3147 result = DirectFunctionCall2(pg_get_expr,
3149 ObjectIdGetDatum(relid));
3151 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3154 index_close(indexRelation, NoLock);
3160 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
3161 bool inhparent, RelOptInfo *rel)
3163 ScanMethodHint *hint = NULL;
3165 Index new_parent_relid = 0;
3167 if (prev_get_relation_info)
3168 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
3171 * Do nothing if we don't have a valid hint in this context or current
3172 * nesting depth is at SPI calls.
3174 if (!current_hint || hint_inhibit_level > 0)
3176 if (debug_level > 1)
3177 ereport(pg_hint_plan_debug_message_level,
3179 errmsg ("pg_hint_plan%s: get_relation_info"
3180 " no hint to apply: relation=%u(%s), inhparent=%d,"
3181 " current_hint=%p, hint_inhibit_level=%d",
3182 qnostr, relationObjectId,
3183 get_rel_name(relationObjectId),
3184 inhparent, current_hint, hint_inhibit_level)));
3189 * We could register the parent relation of the following children here
3190 * when inhparent == true but inheritnce planner doesn't request
3191 * information for inheritance parents. We also cannot distinguish the
3192 * caller so we should always find the parents without this function being
3197 if (debug_level > 1)
3198 ereport(pg_hint_plan_debug_message_level,
3200 errmsg ("pg_hint_plan%s: get_relation_info"
3201 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3202 " current_hint=%p, hint_inhibit_level=%d",
3203 qnostr, relationObjectId,
3204 get_rel_name(relationObjectId),
3205 inhparent, current_hint, hint_inhibit_level)));
3209 /* Find the parent for this relation */
3210 foreach (l, root->append_rel_list)
3212 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3214 if (appinfo->child_relid == rel->relid)
3216 if (current_hint->parent_relid != appinfo->parent_relid)
3217 new_parent_relid = appinfo->parent_relid;
3224 /* This relation doesn't have a parent. Cancel current_hint. */
3225 current_hint->parent_relid = 0;
3226 current_hint->parent_hint = NULL;
3229 if (new_parent_relid > 0)
3232 * Here we found a parent relation different from the remembered one.
3233 * Remember it, apply the scan mask of it and then resolve the index
3234 * restriction in order to be used by its children.
3236 int scanmask = current_hint->init_scan_mask;
3237 ScanMethodHint *parent_hint;
3239 current_hint->parent_relid = new_parent_relid;
3242 * Get and apply the hint for the new parent relation. It should be an
3243 * ordinary relation so calling find_scan_hint with rel == NULL is
3246 current_hint->parent_hint = parent_hint =
3247 find_scan_hint(root, current_hint->parent_relid, NULL);
3251 scanmask = current_hint->parent_hint->enforce_mask;
3252 parent_hint->base.state = HINT_STATE_USED;
3254 /* Resolve index name mask (if any) using the parent. */
3255 if (parent_hint->indexnames)
3258 Relation parent_rel;
3261 root->simple_rte_array[current_hint->parent_relid]->relid;
3262 parent_rel = heap_open(parentrel_oid, NoLock);
3264 /* Search the parent relation for indexes match the hint spec */
3265 foreach(l, RelationGetIndexList(parent_rel))
3267 Oid indexoid = lfirst_oid(l);
3268 char *indexname = get_rel_name(indexoid);
3270 ParentIndexInfo *parent_index_info;
3272 foreach(lc, parent_hint->indexnames)
3274 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3281 get_parent_index_info(indexoid, parentrel_oid);
3282 current_hint->parent_index_infos =
3283 lappend(current_hint->parent_index_infos, parent_index_info);
3285 heap_close(parent_rel, NoLock);
3289 set_scan_config_options(scanmask, current_hint->context);
3292 if (current_hint->parent_hint != 0)
3294 delete_indexes(current_hint->parent_hint, rel,
3297 /* Scan fixation status is the same to the parent. */
3298 if (debug_level > 1)
3299 ereport(pg_hint_plan_debug_message_level,
3301 errmsg("pg_hint_plan%s: get_relation_info:"
3302 " index deletion by parent hint: "
3303 "relation=%u(%s), inhparent=%d, current_hint=%p,"
3304 " hint_inhibit_level=%d",
3305 qnostr, relationObjectId,
3306 get_rel_name(relationObjectId),
3307 inhparent, current_hint, hint_inhibit_level)));
3311 /* This table doesn't have a parent hint. Apply its own hint if any. */
3312 if ((hint = find_scan_hint(root, rel->relid, rel)) != NULL)
3314 set_scan_config_options(hint->enforce_mask, current_hint->context);
3315 hint->base.state = HINT_STATE_USED;
3317 delete_indexes(hint, rel, InvalidOid);
3319 if (debug_level > 1)
3320 ereport(pg_hint_plan_debug_message_level,
3322 errmsg ("pg_hint_plan%s: get_relation_info"
3324 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3325 " hint_inhibit_level=%d, scanmask=0x%x",
3326 qnostr, relationObjectId,
3327 get_rel_name(relationObjectId),
3328 inhparent, current_hint, hint_inhibit_level,
3329 hint->enforce_mask)));
3333 if (debug_level > 1)
3334 ereport(pg_hint_plan_debug_message_level,
3335 (errhidestmt (true),
3336 errmsg ("pg_hint_plan%s: get_relation_info"
3338 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3339 " hint_inhibit_level=%d, scanmask=0x%x",
3340 qnostr, relationObjectId,
3341 get_rel_name(relationObjectId),
3342 inhparent, current_hint, hint_inhibit_level,
3343 current_hint->init_scan_mask)));
3344 set_scan_config_options(current_hint->init_scan_mask,
3345 current_hint->context);
3351 * Return index of relation which matches given aliasname, or 0 if not found.
3352 * If same aliasname was used multiple times in a query, return -1.
3355 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3361 for (i = 1; i < root->simple_rel_array_size; i++)
3365 if (root->simple_rel_array[i] == NULL)
3368 Assert(i == root->simple_rel_array[i]->relid);
3370 if (RelnameCmp(&aliasname,
3371 &root->simple_rte_array[i]->eref->aliasname) != 0)
3374 foreach(l, initial_rels)
3376 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3378 if (rel->reloptkind == RELOPT_BASEREL)
3380 if (rel->relid != i)
3385 Assert(rel->reloptkind == RELOPT_JOINREL);
3387 if (!bms_is_member(i, rel->relids))
3394 ("Relation name \"%s\" is ambiguous.",
3409 * Return join hint which matches given joinrelids.
3411 static JoinMethodHint *
3412 find_join_hint(Relids joinrelids)
3417 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
3419 foreach(l, join_hint)
3421 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3423 if (bms_equal(joinrelids, hint->joinrelids))
3431 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3432 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3434 OuterInnerRels *outer_rels;
3435 OuterInnerRels *inner_rels;
3436 Relids outer_relids;
3437 Relids inner_relids;
3439 JoinMethodHint *hint;
3441 if (outer_inner->relation != NULL)
3443 return bms_make_singleton(
3444 find_relid_aliasname(root, outer_inner->relation,
3446 leading_hint->base.hint_str));
3449 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3450 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3452 outer_relids = OuterInnerJoinCreate(outer_rels,
3458 inner_relids = OuterInnerJoinCreate(inner_rels,
3465 join_relids = bms_add_members(outer_relids, inner_relids);
3467 if (bms_num_members(join_relids) > nbaserel)
3471 * If we don't have join method hint, create new one for the
3472 * join combination with all join methods are enabled.
3474 hint = find_join_hint(join_relids);
3478 * Here relnames is not set, since Relids bitmap is sufficient to
3479 * control paths of this query afterward.
3481 hint = (JoinMethodHint *) JoinMethodHintCreate(
3482 leading_hint->base.hint_str,
3484 HINT_KEYWORD_LEADING);
3485 hint->base.state = HINT_STATE_USED;
3486 hint->nrels = bms_num_members(join_relids);
3487 hint->enforce_mask = ENABLE_ALL_JOIN;
3488 hint->joinrelids = bms_copy(join_relids);
3489 hint->inner_nrels = bms_num_members(inner_relids);
3490 hint->inner_joinrelids = bms_copy(inner_relids);
3492 hstate->join_hint_level[hint->nrels] =
3493 lappend(hstate->join_hint_level[hint->nrels], hint);
3497 hint->inner_nrels = bms_num_members(inner_relids);
3498 hint->inner_joinrelids = bms_copy(inner_relids);
3505 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3506 int nrels, char **relnames)
3509 Relids relids = NULL;
3513 for (j = 0; j < nrels; j++)
3515 relname = relnames[j];
3517 relid = find_relid_aliasname(root, relname, initial_rels,
3521 base->state = HINT_STATE_ERROR;
3524 * the aliasname is not found(relid == 0) or same aliasname was used
3525 * multiple times in a query(relid == -1)
3532 if (bms_is_member(relid, relids))
3534 hint_ereport(base->hint_str,
3535 ("Relation name \"%s\" is duplicated.", relname));
3536 base->state = HINT_STATE_ERROR;
3540 relids = bms_add_member(relids, relid);
3545 * Transform join method hint into handy form.
3547 * - create bitmap of relids from alias names, to make it easier to check
3548 * whether a join path matches a join method hint.
3549 * - add join method hints which are necessary to enforce join order
3550 * specified by Leading hint
3553 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
3554 List *initial_rels, JoinMethodHint **join_method_hints)
3562 LeadingHint *lhint = NULL;
3565 * Create bitmap of relids from alias names for each join method hint.
3566 * Bitmaps are more handy than strings in join searching.
3568 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
3570 JoinMethodHint *hint = hstate->join_hints[i];
3572 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3575 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3576 initial_rels, hint->nrels, hint->relnames);
3578 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
3581 hstate->join_hint_level[hint->nrels] =
3582 lappend(hstate->join_hint_level[hint->nrels], hint);
3586 * Create bitmap of relids from alias names for each rows hint.
3587 * Bitmaps are more handy than strings in join searching.
3589 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
3591 RowsHint *hint = hstate->rows_hints[i];
3593 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3596 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3597 initial_rels, hint->nrels, hint->relnames);
3600 /* Do nothing if no Leading hint was supplied. */
3601 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
3605 * Decide whether to use Leading hint
3607 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
3609 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
3612 if (leading_hint->base.state == HINT_STATE_ERROR)
3618 foreach(l, leading_hint->relations)
3620 relname = (char *)lfirst(l);;
3622 relid = find_relid_aliasname(root, relname, initial_rels,
3623 leading_hint->base.hint_str);
3625 leading_hint->base.state = HINT_STATE_ERROR;
3630 if (bms_is_member(relid, relids))
3632 hint_ereport(leading_hint->base.hint_str,
3633 ("Relation name \"%s\" is duplicated.", relname));
3634 leading_hint->base.state = HINT_STATE_ERROR;
3638 relids = bms_add_member(relids, relid);
3641 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3646 hint_ereport(lhint->base.hint_str,
3647 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3648 lhint->base.state = HINT_STATE_DUPLICATION;
3650 leading_hint->base.state = HINT_STATE_USED;
3651 lhint = leading_hint;
3654 /* check to exist Leading hint marked with 'used'. */
3659 * We need join method hints which fit specified join order in every join
3660 * level. For example, Leading(A B C) virtually requires following join
3661 * method hints, if no join method hint supplied:
3663 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3664 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3666 * If we already have join method hint which fits specified join order in
3667 * that join level, we leave it as-is and don't add new hints.
3671 if (lhint->outer_inner == NULL)
3673 foreach(l, lhint->relations)
3675 JoinMethodHint *hint;
3677 relname = (char *)lfirst(l);
3680 * Find relid of the relation which has given name. If we have the
3681 * name given in Leading hint multiple times in the join, nothing to
3684 relid = find_relid_aliasname(root, relname, initial_rels,
3687 /* Create bitmap of relids for current join level. */
3688 joinrelids = bms_add_member(joinrelids, relid);
3691 /* We never have join method hint for single relation. */
3696 * If we don't have join method hint, create new one for the
3697 * join combination with all join methods are enabled.
3699 hint = find_join_hint(joinrelids);
3703 * Here relnames is not set, since Relids bitmap is sufficient
3704 * to control paths of this query afterward.
3706 hint = (JoinMethodHint *) JoinMethodHintCreate(
3707 lhint->base.hint_str,
3709 HINT_KEYWORD_LEADING);
3710 hint->base.state = HINT_STATE_USED;
3711 hint->nrels = njoinrels;
3712 hint->enforce_mask = ENABLE_ALL_JOIN;
3713 hint->joinrelids = bms_copy(joinrelids);
3716 join_method_hints[njoinrels] = hint;
3718 if (njoinrels >= nbaserel)
3721 bms_free(joinrelids);
3727 * Delete all join hints which have different combination from Leading
3730 for (i = 2; i <= njoinrels; i++)
3732 list_free(hstate->join_hint_level[i]);
3734 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3739 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3746 njoinrels = bms_num_members(joinrelids);
3747 Assert(njoinrels >= 2);
3750 * Delete all join hints which have different combination from Leading
3753 for (i = 2;i <= njoinrels; i++)
3755 if (hstate->join_hint_level[i] != NIL)
3757 ListCell *prev = NULL;
3758 ListCell *next = NULL;
3759 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3762 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3766 if (hint->inner_nrels == 0 &&
3767 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3768 bms_equal(bms_union(hint->joinrelids, joinrelids),
3771 hstate->join_hint_level[i] =
3772 list_delete_cell(hstate->join_hint_level[i], l,
3781 bms_free(joinrelids);
3784 if (hint_state_enabled(lhint))
3786 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3793 * set_plain_rel_pathlist
3794 * Build access paths for a plain relation (no subquery, no inheritance)
3796 * This function was copied and edited from set_plain_rel_pathlist() in
3797 * src/backend/optimizer/path/allpaths.c
3800 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3802 /* Consider sequential scan */
3803 add_path(rel, create_seqscan_path(root, rel, NULL));
3805 /* Consider index scans */
3806 create_index_paths(root, rel);
3808 /* Consider TID scans */
3809 create_tidscan_paths(root, rel);
3811 /* Now find the cheapest of the paths for this rel */
3816 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3821 foreach(l, initial_rels)
3823 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3825 ScanMethodHint *hint;
3827 /* Skip relations which we can't choose scan method. */
3828 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3831 rte = root->simple_rte_array[rel->relid];
3833 /* We can't force scan method of foreign tables */
3834 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3838 * Create scan paths with GUC parameters which are at the beginning of
3839 * planner if scan method hint is not specified, otherwise use
3840 * specified hints and mark the hint as used.
3842 if ((hint = find_scan_hint(root, rel->relid, rel)) == NULL)
3843 set_scan_config_options(hstate->init_scan_mask,
3847 set_scan_config_options(hint->enforce_mask, hstate->context);
3848 hint->base.state = HINT_STATE_USED;
3851 list_free_deep(rel->pathlist);
3852 rel->pathlist = NIL;
3855 /* It's an "append relation", process accordingly */
3856 set_append_rel_pathlist(root, rel, rel->relid, rte);
3860 set_plain_rel_pathlist(root, rel, rte);
3867 * Restore the GUC variables we set above.
3869 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3873 * wrapper of make_join_rel()
3875 * call make_join_rel() after changing enable_* parameters according to given
3879 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3882 JoinMethodHint *hint;
3886 joinrelids = bms_union(rel1->relids, rel2->relids);
3887 hint = find_join_hint(joinrelids);
3888 bms_free(joinrelids);
3891 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3893 if (hint->inner_nrels == 0)
3895 save_nestlevel = NewGUCNestLevel();
3897 set_join_config_options(hint->enforce_mask, current_hint->context);
3899 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3900 hint->base.state = HINT_STATE_USED;
3903 * Restore the GUC variables we set above.
3905 AtEOXact_GUC(true, save_nestlevel);
3908 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3917 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3918 RelOptInfo *joinrel,
3919 RelOptInfo *outerrel,
3920 RelOptInfo *innerrel,
3922 SpecialJoinInfo *sjinfo,
3925 ScanMethodHint *scan_hint = NULL;
3927 JoinMethodHint *join_hint;
3930 if ((scan_hint = find_scan_hint(root, innerrel->relid, innerrel)) != NULL)
3932 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3933 scan_hint->base.state = HINT_STATE_USED;
3936 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3937 join_hint = find_join_hint(joinrelids);
3938 bms_free(joinrelids);
3940 if (join_hint && join_hint->inner_nrels != 0)
3942 save_nestlevel = NewGUCNestLevel();
3944 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3947 set_join_config_options(join_hint->enforce_mask,
3948 current_hint->context);
3950 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3951 sjinfo, restrictlist);
3952 join_hint->base.state = HINT_STATE_USED;
3956 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3957 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3958 sjinfo, restrictlist);
3962 * Restore the GUC variables we set above.
3964 AtEOXact_GUC(true, save_nestlevel);
3967 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3968 sjinfo, restrictlist);
3970 if (scan_hint != NULL)
3971 set_scan_config_options(current_hint->init_scan_mask,
3972 current_hint->context);
3976 get_num_baserels(List *initial_rels)
3981 foreach(l, initial_rels)
3983 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3985 if (rel->reloptkind == RELOPT_BASEREL)
3987 else if (rel->reloptkind ==RELOPT_JOINREL)
3988 nbaserel+= bms_num_members(rel->relids);
3991 /* other values not expected here */
3992 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
4000 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
4003 JoinMethodHint **join_method_hints;
4007 bool leading_hint_enable;
4010 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
4011 * valid hint is supplied or current nesting depth is nesting depth of SPI
4014 if (!current_hint || hint_inhibit_level > 0)
4016 if (prev_join_search)
4017 return (*prev_join_search) (root, levels_needed, initial_rels);
4018 else if (enable_geqo && levels_needed >= geqo_threshold)
4019 return geqo(root, levels_needed, initial_rels);
4021 return standard_join_search(root, levels_needed, initial_rels);
4024 /* We apply scan method hint rebuild scan path. */
4025 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
4028 * In the case using GEQO, only scan method hints and Set hints have
4029 * effect. Join method and join order is not controllable by hints.
4031 if (enable_geqo && levels_needed >= geqo_threshold)
4032 return geqo(root, levels_needed, initial_rels);
4034 nbaserel = get_num_baserels(initial_rels);
4035 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
4036 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4038 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
4039 initial_rels, join_method_hints);
4041 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4043 for (i = 2; i <= nbaserel; i++)
4045 list_free(current_hint->join_hint_level[i]);
4047 /* free Leading hint only */
4048 if (join_method_hints[i] != NULL &&
4049 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4050 JoinMethodHintDelete(join_method_hints[i]);
4052 pfree(current_hint->join_hint_level);
4053 pfree(join_method_hints);
4055 if (leading_hint_enable)
4056 set_join_config_options(current_hint->init_join_mask,
4057 current_hint->context);
4064 * Build access paths for a base relation
4066 * This function was copied and edited from set_rel_pathlist() in
4067 * src/backend/optimizer/path/allpaths.c
4070 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4071 Index rti, RangeTblEntry *rte)
4073 if (IS_DUMMY_REL(rel))
4075 /* We already proved the relation empty, so nothing more to do */
4079 /* It's an "append relation", process accordingly */
4080 set_append_rel_pathlist(root, rel, rti, rte);
4084 if (rel->rtekind == RTE_RELATION)
4086 if (rte->relkind == RELKIND_RELATION)
4088 /* Plain relation */
4089 set_plain_rel_pathlist(root, rel, rte);
4092 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4095 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4100 * stmt_beg callback is called when each query in PL/pgSQL function is about
4101 * to be executed. At that timing, we save query string in the global variable
4102 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4103 * variable for the purpose, because its content is only necessary until
4104 * planner hook is called for the query, so recursive PL/pgSQL function calls
4105 * don't harm this mechanism.
4108 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4110 plpgsql_recurse_level++;
4114 * stmt_end callback is called then each query in PL/pgSQL function has
4115 * finished. At that timing, we clear plpgsql_query_string to tell planner
4116 * hook that next call is not for a query written in PL/pgSQL block.
4119 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4121 plpgsql_recurse_level--;
4124 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4129 if (!isTopLevel || phase != RESOURCE_RELEASE_AFTER_LOCKS)
4131 /* Cancel plpgsql nest level*/
4132 plpgsql_recurse_level = 0;
4135 #define standard_join_search pg_hint_plan_standard_join_search
4136 #define join_search_one_level pg_hint_plan_join_search_one_level
4137 #define make_join_rel make_join_rel_wrapper
4140 #undef make_join_rel
4141 #define make_join_rel pg_hint_plan_make_join_rel
4142 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4143 #include "make_join_rel.c"
4145 #include "pg_stat_statements.c"