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"
46 * We have our own header file "plpgsql-9.1", which is necessary to support
47 * hints for queries in PL/pgSQL blocks, in pg_hint_plan source package,
48 * because PostgreSQL 9.1 doesn't provide the header file as a part of
49 * installation. This header file is a copy of src/pl/plpgsql/src/plpgsql.h in
50 * PostgreSQL 9.1.9 source tree,
52 * On the other hand, 9.2 installation provides that header file for external
53 * modules, so we include the header in ordinary place.
57 /* partially copied from pg_stat_statements */
58 #include "normalize_query.h"
61 #include "access/htup_details.h"
63 #ifdef PG_MODULE_MAGIC
67 #define BLOCK_COMMENT_START "/*"
68 #define BLOCK_COMMENT_END "*/"
69 #define HINT_COMMENT_KEYWORD "+"
70 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
71 #define HINT_END BLOCK_COMMENT_END
74 #define HINT_SEQSCAN "SeqScan"
75 #define HINT_INDEXSCAN "IndexScan"
76 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
77 #define HINT_BITMAPSCAN "BitmapScan"
78 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
79 #define HINT_TIDSCAN "TidScan"
80 #define HINT_NOSEQSCAN "NoSeqScan"
81 #define HINT_NOINDEXSCAN "NoIndexScan"
82 #define HINT_NOBITMAPSCAN "NoBitmapScan"
83 #define HINT_NOTIDSCAN "NoTidScan"
84 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
85 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
86 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
87 #define HINT_NESTLOOP "NestLoop"
88 #define HINT_MERGEJOIN "MergeJoin"
89 #define HINT_HASHJOIN "HashJoin"
90 #define HINT_NONESTLOOP "NoNestLoop"
91 #define HINT_NOMERGEJOIN "NoMergeJoin"
92 #define HINT_NOHASHJOIN "NoHashJoin"
93 #define HINT_LEADING "Leading"
94 #define HINT_SET "Set"
95 #define HINT_ROWS "Rows"
97 #define HINT_ARRAY_DEFAULT_INITSIZE 8
99 #define hint_ereport(str, detail) \
101 ereport(pg_hint_plan_message_level, \
102 (errmsg("pg_hint_plan%s: hint syntax error at or near \"%s\"", qnostr, (str)), \
103 errdetail detail)); \
107 #define skip_space(str) \
108 while (isspace(*str)) \
113 ENABLE_SEQSCAN = 0x01,
114 ENABLE_INDEXSCAN = 0x02,
115 ENABLE_BITMAPSCAN = 0x04,
116 ENABLE_TIDSCAN = 0x08,
117 ENABLE_INDEXONLYSCAN = 0x10
122 ENABLE_NESTLOOP = 0x01,
123 ENABLE_MERGEJOIN = 0x02,
124 ENABLE_HASHJOIN = 0x04
127 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
128 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
129 ENABLE_INDEXONLYSCAN)
130 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
131 #define DISABLE_ALL_SCAN 0
132 #define DISABLE_ALL_JOIN 0
134 /* hint keyword of enum type*/
135 typedef enum HintKeyword
137 HINT_KEYWORD_SEQSCAN,
138 HINT_KEYWORD_INDEXSCAN,
139 HINT_KEYWORD_INDEXSCANREGEXP,
140 HINT_KEYWORD_BITMAPSCAN,
141 HINT_KEYWORD_BITMAPSCANREGEXP,
142 HINT_KEYWORD_TIDSCAN,
143 HINT_KEYWORD_NOSEQSCAN,
144 HINT_KEYWORD_NOINDEXSCAN,
145 HINT_KEYWORD_NOBITMAPSCAN,
146 HINT_KEYWORD_NOTIDSCAN,
147 HINT_KEYWORD_INDEXONLYSCAN,
148 HINT_KEYWORD_INDEXONLYSCANREGEXP,
149 HINT_KEYWORD_NOINDEXONLYSCAN,
150 HINT_KEYWORD_NESTLOOP,
151 HINT_KEYWORD_MERGEJOIN,
152 HINT_KEYWORD_HASHJOIN,
153 HINT_KEYWORD_NONESTLOOP,
154 HINT_KEYWORD_NOMERGEJOIN,
155 HINT_KEYWORD_NOHASHJOIN,
156 HINT_KEYWORD_LEADING,
159 HINT_KEYWORD_UNRECOGNIZED
162 typedef struct Hint Hint;
163 typedef struct HintState HintState;
165 typedef Hint *(*HintCreateFunction) (const char *hint_str,
167 HintKeyword hint_keyword);
168 typedef void (*HintDeleteFunction) (Hint *hint);
169 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf, bool nolf);
170 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
171 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
172 Query *parse, const char *str);
175 #define NUM_HINT_TYPE 5
176 typedef enum HintType
178 HINT_TYPE_SCAN_METHOD,
179 HINT_TYPE_JOIN_METHOD,
185 static const char *HintTypeName[] = {
194 typedef enum HintStatus
196 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
197 HINT_STATE_USED, /* hint is used */
198 HINT_STATE_DUPLICATION, /* specified hint duplication */
199 HINT_STATE_ERROR /* execute error (parse error does not include
203 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
204 (hint)->base.state == HINT_STATE_USED)
206 static unsigned int qno = 0;
207 static unsigned int msgqno = 0;
208 static char qnostr[32];
209 static const char *current_hint_str = NULL;
211 /* common data for all hints. */
214 const char *hint_str; /* must not do pfree */
215 const char *keyword; /* must not do pfree */
216 HintKeyword hint_keyword;
219 HintDeleteFunction delete_func;
220 HintDescFunction desc_func;
221 HintCmpFunction cmp_func;
222 HintParseFunction parse_func;
225 /* scan method hints */
226 typedef struct ScanMethodHint
232 unsigned char enforce_mask;
235 typedef struct ParentIndexInfo
240 char *expression_str;
247 /* join method hints */
248 typedef struct JoinMethodHint
254 unsigned char enforce_mask;
256 Relids inner_joinrelids;
259 /* join order hints */
260 typedef struct OuterInnerRels
263 List *outer_inner_pair;
266 typedef struct LeadingHint
269 List *relations; /* relation names specified in Leading hint */
270 OuterInnerRels *outer_inner;
273 /* change a run-time parameter hints */
274 typedef struct SetHint
277 char *name; /* name of variable */
283 typedef enum RowsValueType {
284 RVT_ABSOLUTE, /* Rows(... #1000) */
285 RVT_ADD, /* Rows(... +1000) */
286 RVT_SUB, /* Rows(... -1000) */
287 RVT_MULTI, /* Rows(... *1.2) */
289 typedef struct RowsHint
296 Relids inner_joinrelids;
298 RowsValueType value_type;
303 * Describes a context of hint processing.
307 char *hint_str; /* original hint string */
310 int nall_hints; /* # of valid all hints */
311 int max_all_hints; /* # of slots for all hints */
312 Hint **all_hints; /* parsed all hints */
314 /* # of each hints */
315 int num_hints[NUM_HINT_TYPE];
317 /* for scan method hints */
318 ScanMethodHint **scan_hints; /* parsed scan hints */
319 int init_scan_mask; /* initial value scan parameter */
320 Index parent_relid; /* inherit parent table relid */
321 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
322 List *parent_index_infos; /* information of inherit parent table's
325 /* for join method hints */
326 JoinMethodHint **join_hints; /* parsed join hints */
327 int init_join_mask; /* initial value join parameter */
328 List **join_hint_level;
330 /* for Leading hint */
331 LeadingHint **leading_hint; /* parsed Leading hints */
334 SetHint **set_hints; /* parsed Set hints */
335 GucContext context; /* which GUC parameters can we set? */
338 RowsHint **rows_hints; /* parsed Rows hints */
342 * Describes a hint parser module which is bound with particular hint keyword.
344 typedef struct HintParser
347 HintCreateFunction create_func;
348 HintKeyword hint_keyword;
351 /* Module callbacks */
355 static void push_hint(HintState *hstate);
356 static void pop_hint(void);
358 static void pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query);
359 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
360 ParamListInfo boundParams);
361 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
362 Oid relationObjectId,
363 bool inhparent, RelOptInfo *rel);
364 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
368 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
369 HintKeyword hint_keyword);
370 static void ScanMethodHintDelete(ScanMethodHint *hint);
371 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
372 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
373 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
374 Query *parse, const char *str);
375 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
376 HintKeyword hint_keyword);
377 static void JoinMethodHintDelete(JoinMethodHint *hint);
378 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
379 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
380 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
381 Query *parse, const char *str);
382 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
383 HintKeyword hint_keyword);
384 static void LeadingHintDelete(LeadingHint *hint);
385 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
386 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
387 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
388 Query *parse, const char *str);
389 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
390 HintKeyword hint_keyword);
391 static void SetHintDelete(SetHint *hint);
392 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
393 static int SetHintCmp(const SetHint *a, const SetHint *b);
394 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
396 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
397 HintKeyword hint_keyword);
398 static void RowsHintDelete(RowsHint *hint);
399 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
400 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
401 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
402 Query *parse, const char *str);
403 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
404 HintKeyword hint_keyword);
406 static void quote_value(StringInfo buf, const char *value);
408 static const char *parse_quoted_value(const char *str, char **word,
411 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
414 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
415 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
416 ListCell *other_rels);
417 static void make_rels_by_clauseless_joins(PlannerInfo *root,
419 ListCell *other_rels);
420 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
421 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
422 Index rti, RangeTblEntry *rte);
423 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
424 List *live_childrels,
425 List *all_child_pathkeys);
426 static Path *get_cheapest_parameterized_child_path(PlannerInfo *root,
428 Relids required_outer);
429 static List *accumulate_append_subpath(List *subpaths, Path *path);
430 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
433 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
435 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
437 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
443 static bool pg_hint_plan_enable_hint = true;
444 static int debug_level = 0;
445 static int pg_hint_plan_message_level = INFO;
446 /* Default is off, to keep backward compatibility. */
447 static bool pg_hint_plan_enable_hint_table = false;
449 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
450 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
451 /* (This could not be above 1) */
453 static const struct config_enum_entry parse_messages_level_options[] = {
454 {"debug", DEBUG2, true},
455 {"debug5", DEBUG5, false},
456 {"debug4", DEBUG4, false},
457 {"debug3", DEBUG3, false},
458 {"debug2", DEBUG2, false},
459 {"debug1", DEBUG1, false},
461 {"info", INFO, false},
462 {"notice", NOTICE, false},
463 {"warning", WARNING, false},
464 {"error", ERROR, false},
466 * {"fatal", FATAL, true},
467 * {"panic", PANIC, true},
472 static const struct config_enum_entry parse_debug_level_options[] = {
475 {"detailed", 2, false},
476 {"verbose", 3, false},
488 /* Saved hook values in case of unload */
489 static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
490 static planner_hook_type prev_planner = NULL;
491 static get_relation_info_hook_type prev_get_relation_info = NULL;
492 static join_search_hook_type prev_join_search = NULL;
494 /* Hold reference to currently active hint */
495 static HintState *current_hint = NULL;
498 * List of hint contexts. We treat the head of the list as the Top of the
499 * context stack, so current_hint always points the first element of this list.
501 static List *HintStateStack = NIL;
504 * Holds statement name during executing EXECUTE command. NULL for other
507 static char *stmt_name = NULL;
509 static const HintParser parsers[] = {
510 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
511 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
512 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
513 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
514 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
515 HINT_KEYWORD_BITMAPSCANREGEXP},
516 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
517 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
518 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
519 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
520 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
521 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
522 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
523 HINT_KEYWORD_INDEXONLYSCANREGEXP},
524 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
525 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
526 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
527 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
528 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
529 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
530 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
531 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
532 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
533 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
534 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
537 PLpgSQL_plugin plugin_funcs = {
541 pg_hint_plan_plpgsql_stmt_beg,
542 pg_hint_plan_plpgsql_stmt_end,
548 * Module load callbacks
553 PLpgSQL_plugin **var_ptr;
555 /* Define custom GUC variables. */
556 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
557 "Force planner to use plans specified in the hint comment preceding to the query.",
559 &pg_hint_plan_enable_hint,
567 DefineCustomEnumVariable("pg_hint_plan.debug_print",
568 "Logs results of hint parsing.",
572 parse_debug_level_options,
579 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
580 "Message level of parse errors.",
582 &pg_hint_plan_message_level,
584 parse_messages_level_options,
591 DefineCustomEnumVariable("pg_hint_plan.message_level",
592 "Message level of debug messages.",
594 &pg_hint_plan_message_level,
596 parse_messages_level_options,
603 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
604 "Force planner to not get hint by using table lookups.",
606 &pg_hint_plan_enable_hint_table,
615 prev_post_parse_analyze_hook = post_parse_analyze_hook;
616 post_parse_analyze_hook = pg_hint_plan_post_parse_analyze;
617 prev_planner = planner_hook;
618 planner_hook = pg_hint_plan_planner;
619 prev_get_relation_info = get_relation_info_hook;
620 get_relation_info_hook = pg_hint_plan_get_relation_info;
621 prev_join_search = join_search_hook;
622 join_search_hook = pg_hint_plan_join_search;
624 /* setup PL/pgSQL plugin hook */
625 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
626 *var_ptr = &plugin_funcs;
628 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
632 * Module unload callback
638 PLpgSQL_plugin **var_ptr;
640 /* Uninstall hooks. */
641 post_parse_analyze_hook = prev_post_parse_analyze_hook;
642 planner_hook = prev_planner;
643 get_relation_info_hook = prev_get_relation_info;
644 join_search_hook = prev_join_search;
646 /* uninstall PL/pgSQL plugin hook */
647 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
652 * create and delete functions the hint object
656 ScanMethodHintCreate(const char *hint_str, const char *keyword,
657 HintKeyword hint_keyword)
659 ScanMethodHint *hint;
661 hint = palloc(sizeof(ScanMethodHint));
662 hint->base.hint_str = hint_str;
663 hint->base.keyword = keyword;
664 hint->base.hint_keyword = hint_keyword;
665 hint->base.type = HINT_TYPE_SCAN_METHOD;
666 hint->base.state = HINT_STATE_NOTUSED;
667 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
668 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
669 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
670 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
671 hint->relname = NULL;
672 hint->indexnames = NIL;
673 hint->regexp = false;
674 hint->enforce_mask = 0;
676 return (Hint *) hint;
680 ScanMethodHintDelete(ScanMethodHint *hint)
686 pfree(hint->relname);
687 list_free_deep(hint->indexnames);
692 JoinMethodHintCreate(const char *hint_str, const char *keyword,
693 HintKeyword hint_keyword)
695 JoinMethodHint *hint;
697 hint = palloc(sizeof(JoinMethodHint));
698 hint->base.hint_str = hint_str;
699 hint->base.keyword = keyword;
700 hint->base.hint_keyword = hint_keyword;
701 hint->base.type = HINT_TYPE_JOIN_METHOD;
702 hint->base.state = HINT_STATE_NOTUSED;
703 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
704 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
705 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
706 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
708 hint->inner_nrels = 0;
709 hint->relnames = NULL;
710 hint->enforce_mask = 0;
711 hint->joinrelids = NULL;
712 hint->inner_joinrelids = NULL;
714 return (Hint *) hint;
718 JoinMethodHintDelete(JoinMethodHint *hint)
727 for (i = 0; i < hint->nrels; i++)
728 pfree(hint->relnames[i]);
729 pfree(hint->relnames);
732 bms_free(hint->joinrelids);
733 bms_free(hint->inner_joinrelids);
738 LeadingHintCreate(const char *hint_str, const char *keyword,
739 HintKeyword hint_keyword)
743 hint = palloc(sizeof(LeadingHint));
744 hint->base.hint_str = hint_str;
745 hint->base.keyword = keyword;
746 hint->base.hint_keyword = hint_keyword;
747 hint->base.type = HINT_TYPE_LEADING;
748 hint->base.state = HINT_STATE_NOTUSED;
749 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
750 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
751 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
752 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
753 hint->relations = NIL;
754 hint->outer_inner = NULL;
756 return (Hint *) hint;
760 LeadingHintDelete(LeadingHint *hint)
765 list_free_deep(hint->relations);
766 if (hint->outer_inner)
767 pfree(hint->outer_inner);
772 SetHintCreate(const char *hint_str, const char *keyword,
773 HintKeyword hint_keyword)
777 hint = palloc(sizeof(SetHint));
778 hint->base.hint_str = hint_str;
779 hint->base.keyword = keyword;
780 hint->base.hint_keyword = hint_keyword;
781 hint->base.type = HINT_TYPE_SET;
782 hint->base.state = HINT_STATE_NOTUSED;
783 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
784 hint->base.desc_func = (HintDescFunction) SetHintDesc;
785 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
786 hint->base.parse_func = (HintParseFunction) SetHintParse;
791 return (Hint *) hint;
795 SetHintDelete(SetHint *hint)
805 list_free(hint->words);
810 RowsHintCreate(const char *hint_str, const char *keyword,
811 HintKeyword hint_keyword)
815 hint = palloc(sizeof(RowsHint));
816 hint->base.hint_str = hint_str;
817 hint->base.keyword = keyword;
818 hint->base.hint_keyword = hint_keyword;
819 hint->base.type = HINT_TYPE_ROWS;
820 hint->base.state = HINT_STATE_NOTUSED;
821 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
822 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
823 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
824 hint->base.parse_func = (HintParseFunction) RowsHintParse;
826 hint->inner_nrels = 0;
827 hint->relnames = NULL;
828 hint->joinrelids = NULL;
829 hint->inner_joinrelids = NULL;
830 hint->rows_str = NULL;
831 hint->value_type = RVT_ABSOLUTE;
834 return (Hint *) hint;
838 RowsHintDelete(RowsHint *hint)
847 for (i = 0; i < hint->nrels; i++)
848 pfree(hint->relnames[i]);
849 pfree(hint->relnames);
852 bms_free(hint->joinrelids);
853 bms_free(hint->inner_joinrelids);
858 HintStateCreate(void)
862 hstate = palloc(sizeof(HintState));
863 hstate->hint_str = NULL;
864 hstate->nall_hints = 0;
865 hstate->max_all_hints = 0;
866 hstate->all_hints = NULL;
867 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
868 hstate->scan_hints = NULL;
869 hstate->init_scan_mask = 0;
870 hstate->parent_relid = 0;
871 hstate->parent_hint = NULL;
872 hstate->parent_index_infos = NIL;
873 hstate->join_hints = NULL;
874 hstate->init_join_mask = 0;
875 hstate->join_hint_level = NULL;
876 hstate->leading_hint = NULL;
877 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
878 hstate->set_hints = NULL;
879 hstate->rows_hints = NULL;
885 HintStateDelete(HintState *hstate)
892 if (hstate->hint_str)
893 pfree(hstate->hint_str);
895 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
896 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
897 if (hstate->all_hints)
898 pfree(hstate->all_hints);
899 if (hstate->parent_index_infos)
900 list_free(hstate->parent_index_infos);
904 * Copy given value into buf, with quoting with '"' if necessary.
907 quote_value(StringInfo buf, const char *value)
909 bool need_quote = false;
912 for (str = value; *str != '\0'; str++)
914 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
917 appendStringInfoCharMacro(buf, '"');
922 for (str = value; *str != '\0'; str++)
925 appendStringInfoCharMacro(buf, '"');
927 appendStringInfoCharMacro(buf, *str);
931 appendStringInfoCharMacro(buf, '"');
935 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
939 appendStringInfo(buf, "%s(", hint->base.keyword);
940 if (hint->relname != NULL)
942 quote_value(buf, hint->relname);
943 foreach(l, hint->indexnames)
945 appendStringInfoCharMacro(buf, ' ');
946 quote_value(buf, (char *) lfirst(l));
949 appendStringInfoString(buf, ")");
951 appendStringInfoChar(buf, '\n');
955 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
959 appendStringInfo(buf, "%s(", hint->base.keyword);
960 if (hint->relnames != NULL)
962 quote_value(buf, hint->relnames[0]);
963 for (i = 1; i < hint->nrels; i++)
965 appendStringInfoCharMacro(buf, ' ');
966 quote_value(buf, hint->relnames[i]);
969 appendStringInfoString(buf, ")");
971 appendStringInfoChar(buf, '\n');
975 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
977 if (outer_inner->relation == NULL)
984 appendStringInfoCharMacro(buf, '(');
985 foreach(l, outer_inner->outer_inner_pair)
990 appendStringInfoCharMacro(buf, ' ');
992 OuterInnerDesc(lfirst(l), buf);
995 appendStringInfoCharMacro(buf, ')');
998 quote_value(buf, outer_inner->relation);
1002 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
1004 appendStringInfo(buf, "%s(", HINT_LEADING);
1005 if (hint->outer_inner == NULL)
1012 foreach(l, hint->relations)
1017 appendStringInfoCharMacro(buf, ' ');
1019 quote_value(buf, (char *) lfirst(l));
1023 OuterInnerDesc(hint->outer_inner, buf);
1025 appendStringInfoString(buf, ")");
1027 appendStringInfoChar(buf, '\n');
1031 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1033 bool is_first = true;
1036 appendStringInfo(buf, "%s(", HINT_SET);
1037 foreach(l, hint->words)
1042 appendStringInfoCharMacro(buf, ' ');
1044 quote_value(buf, (char *) lfirst(l));
1046 appendStringInfo(buf, ")");
1048 appendStringInfoChar(buf, '\n');
1052 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1056 appendStringInfo(buf, "%s(", hint->base.keyword);
1057 if (hint->relnames != NULL)
1059 quote_value(buf, hint->relnames[0]);
1060 for (i = 1; i < hint->nrels; i++)
1062 appendStringInfoCharMacro(buf, ' ');
1063 quote_value(buf, hint->relnames[i]);
1066 appendStringInfo(buf, " %s", hint->rows_str);
1067 appendStringInfoString(buf, ")");
1069 appendStringInfoChar(buf, '\n');
1073 * Append string which represents all hints in a given state to buf, with
1074 * preceding title with them.
1077 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1078 HintStatus state, bool nolf)
1082 appendStringInfo(buf, "%s:", title);
1084 appendStringInfoChar(buf, '\n');
1087 for (i = 0; i < hstate->nall_hints; i++)
1089 if (hstate->all_hints[i]->state != state)
1092 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1096 if (nolf && nshown == 0)
1097 appendStringInfoString(buf, "(none)");
1101 * Dump contents of given hstate to server log with log level LOG.
1104 HintStateDump(HintState *hstate)
1110 elog(LOG, "pg_hint_plan:\nno hint");
1114 initStringInfo(&buf);
1116 appendStringInfoString(&buf, "pg_hint_plan:\n");
1117 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1118 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1119 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1120 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1122 elog(LOG, "%s", buf.data);
1128 HintStateDump2(HintState *hstate)
1134 elog(pg_hint_plan_message_level,
1135 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1139 initStringInfo(&buf);
1140 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1141 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1142 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1143 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1144 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1145 appendStringInfoChar(&buf, '}');
1147 ereport(pg_hint_plan_message_level,
1148 (errmsg("%s", buf.data),
1149 errhidestmt(true)));
1159 RelnameCmp(const void *a, const void *b)
1161 const char *relnamea = *((const char **) a);
1162 const char *relnameb = *((const char **) b);
1164 return strcmp(relnamea, relnameb);
1168 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1170 return RelnameCmp(&a->relname, &b->relname);
1174 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1178 if (a->nrels != b->nrels)
1179 return a->nrels - b->nrels;
1181 for (i = 0; i < a->nrels; i++)
1184 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1192 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1198 SetHintCmp(const SetHint *a, const SetHint *b)
1200 return strcmp(a->name, b->name);
1204 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1208 if (a->nrels != b->nrels)
1209 return a->nrels - b->nrels;
1211 for (i = 0; i < a->nrels; i++)
1214 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1222 HintCmp(const void *a, const void *b)
1224 const Hint *hinta = *((const Hint **) a);
1225 const Hint *hintb = *((const Hint **) b);
1227 if (hinta->type != hintb->type)
1228 return hinta->type - hintb->type;
1229 if (hinta->state == HINT_STATE_ERROR)
1231 if (hintb->state == HINT_STATE_ERROR)
1233 return hinta->cmp_func(hinta, hintb);
1237 * Returns byte offset of hint b from hint a. If hint a was specified before
1238 * b, positive value is returned.
1241 HintCmpWithPos(const void *a, const void *b)
1243 const Hint *hinta = *((const Hint **) a);
1244 const Hint *hintb = *((const Hint **) b);
1247 result = HintCmp(a, b);
1249 result = hinta->hint_str - hintb->hint_str;
1258 parse_keyword(const char *str, StringInfo buf)
1262 while (!isspace(*str) && *str != '(' && *str != '\0')
1263 appendStringInfoCharMacro(buf, *str++);
1269 skip_parenthesis(const char *str, char parenthesis)
1273 if (*str != parenthesis)
1275 if (parenthesis == '(')
1276 hint_ereport(str, ("Opening parenthesis is necessary."));
1277 else if (parenthesis == ')')
1278 hint_ereport(str, ("Closing parenthesis is necessary."));
1289 * Parse a token from str, and store malloc'd copy into word. A token can be
1290 * quoted with '"'. Return value is pointer to unparsed portion of original
1291 * string, or NULL if an error occurred.
1293 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1296 parse_quoted_value(const char *str, char **word, bool truncate)
1301 /* Skip leading spaces. */
1304 initStringInfo(&buf);
1317 /* Double quotation must be closed. */
1321 hint_ereport(str, ("Unterminated quoted string."));
1326 * Skip escaped double quotation.
1328 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1329 * block comments) to be an object name, so users must specify
1330 * alias for such object names.
1332 * Those special names can be allowed if we care escaped slashes
1333 * and asterisks, but we don't.
1342 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1346 appendStringInfoCharMacro(&buf, *str++);
1351 hint_ereport(str, ("Zero-length delimited string."));
1358 /* Truncate name if it's too long */
1360 truncate_identifier(buf.data, strlen(buf.data), true);
1367 static OuterInnerRels *
1368 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1370 OuterInnerRels *outer_inner;
1372 outer_inner = palloc(sizeof(OuterInnerRels));
1373 outer_inner->relation = name;
1374 outer_inner->outer_inner_pair = outer_inner_list;
1380 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1382 List *outer_inner_pair = NIL;
1384 if ((str = skip_parenthesis(str, '(')) == NULL)
1389 /* Store words in parentheses into outer_inner_list. */
1390 while(*str != ')' && *str != '\0')
1392 OuterInnerRels *outer_inner_rels;
1396 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1404 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1407 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1410 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1415 (str = skip_parenthesis(str, ')')) == NULL)
1417 list_free(outer_inner_pair);
1421 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1427 parse_parentheses_Leading(const char *str, List **name_list,
1428 OuterInnerRels **outer_inner)
1431 bool truncate = true;
1433 if ((str = skip_parenthesis(str, '(')) == NULL)
1439 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1444 /* Store words in parentheses into name_list. */
1445 while(*str != ')' && *str != '\0')
1447 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1449 list_free(*name_list);
1453 *name_list = lappend(*name_list, name);
1458 if ((str = skip_parenthesis(str, ')')) == NULL)
1464 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1467 bool truncate = true;
1469 if ((str = skip_parenthesis(str, '(')) == NULL)
1474 /* Store words in parentheses into name_list. */
1475 while(*str != ')' && *str != '\0')
1477 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1479 list_free(*name_list);
1483 *name_list = lappend(*name_list, name);
1486 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1487 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1488 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1489 keyword == HINT_KEYWORD_SET)
1495 if ((str = skip_parenthesis(str, ')')) == NULL)
1501 parse_hints(HintState *hstate, Query *parse, const char *str)
1506 initStringInfo(&buf);
1507 while (*str != '\0')
1509 const HintParser *parser;
1511 /* in error message, we output the comment including the keyword. */
1512 head = (char *) str;
1514 /* parse only the keyword of the hint. */
1515 resetStringInfo(&buf);
1516 str = parse_keyword(str, &buf);
1518 for (parser = parsers; parser->keyword != NULL; parser++)
1520 char *keyword = parser->keyword;
1523 if (strcasecmp(buf.data, keyword) != 0)
1526 hint = parser->create_func(head, keyword, parser->hint_keyword);
1528 /* parser of each hint does parse in a parenthesis. */
1529 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1531 hint->delete_func(hint);
1537 * Add hint information into all_hints array. If we don't have
1538 * enough space, double the array.
1540 if (hstate->nall_hints == 0)
1542 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1543 hstate->all_hints = (Hint **)
1544 palloc(sizeof(Hint *) * hstate->max_all_hints);
1546 else if (hstate->nall_hints == hstate->max_all_hints)
1548 hstate->max_all_hints *= 2;
1549 hstate->all_hints = (Hint **)
1550 repalloc(hstate->all_hints,
1551 sizeof(Hint *) * hstate->max_all_hints);
1554 hstate->all_hints[hstate->nall_hints] = hint;
1555 hstate->nall_hints++;
1562 if (parser->keyword == NULL)
1565 ("Unrecognized hint keyword \"%s\".", buf.data));
1576 * Get hints from table by client-supplied query string and application name.
1579 get_hints_from_table(const char *client_query, const char *client_application)
1581 const char *search_query =
1583 " FROM hint_plan.hints "
1584 " WHERE norm_query_string = $1 "
1585 " AND ( application_name = $2 "
1586 " OR application_name = '' ) "
1587 " ORDER BY application_name DESC";
1588 static SPIPlanPtr plan = NULL;
1590 Oid argtypes[2] = { TEXTOID, TEXTOID };
1592 bool nulls[2] = { false, false };
1598 bool snapshot_set = false;
1600 hint_inhibit_level++;
1602 if (!ActiveSnapshotSet())
1604 PushActiveSnapshot(GetTransactionSnapshot());
1605 snapshot_set = true;
1613 p = SPI_prepare(search_query, 2, argtypes);
1614 plan = SPI_saveplan(p);
1618 qry = cstring_to_text(client_query);
1619 app = cstring_to_text(client_application);
1620 values[0] = PointerGetDatum(qry);
1621 values[1] = PointerGetDatum(app);
1623 SPI_execute_plan(plan, values, nulls, true, 1);
1625 if (SPI_processed > 0)
1629 hints = SPI_getvalue(SPI_tuptable->vals[0],
1630 SPI_tuptable->tupdesc, 1);
1632 * Here we use SPI_palloc to ensure that hints string is valid even
1633 * after SPI_finish call. We can't use simple palloc because it
1634 * allocates memory in SPI's context and that context is deleted in
1637 buf = SPI_palloc(strlen(hints) + 1);
1645 PopActiveSnapshot();
1647 hint_inhibit_level--;
1651 hint_inhibit_level--;
1660 * Get client-supplied query string. Addtion to that the jumbled query is
1661 * supplied if the caller requested. From the restriction of JumbleQuery, some
1662 * kind of query needs special amendments. Reutrns NULL if the current hint
1663 * string is still valid.
1666 get_query_string(ParseState *pstate, Query *query, Query **jumblequery)
1668 const char *p = debug_query_string;
1670 if (jumblequery != NULL)
1671 *jumblequery = query;
1673 if (query->commandType == CMD_UTILITY)
1675 Query *target_query = query;
1677 /* Use the target query if EXPLAIN */
1678 if (IsA(query->utilityStmt, ExplainStmt))
1680 ExplainStmt *stmt = (ExplainStmt *)(query->utilityStmt);
1682 Assert(IsA(stmt->query, Query));
1683 target_query = (Query *)stmt->query;
1685 /* strip out the top-level query for further processing */
1686 if (target_query->commandType == CMD_UTILITY &&
1687 target_query->utilityStmt != NULL)
1688 target_query = (Query *)target_query->utilityStmt;
1691 if (IsA(target_query, CreateTableAsStmt))
1694 * Use the the body query for CREATE AS. The Query for jumble also
1695 * replaced with the corresponding one.
1697 CreateTableAsStmt *stmt = (CreateTableAsStmt *) target_query;
1698 PreparedStatement *entry;
1701 Assert(IsA(stmt->query, Query));
1702 tmp_query = (Query *) stmt->query;
1704 if (tmp_query->commandType == CMD_UTILITY &&
1705 IsA(tmp_query->utilityStmt, ExecuteStmt))
1707 ExecuteStmt *estmt = (ExecuteStmt *) tmp_query->utilityStmt;
1708 entry = FetchPreparedStatement(estmt->name, true);
1709 p = entry->plansource->query_string;
1710 target_query = (Query *) linitial (entry->plansource->query_list);
1714 if (IsA(target_query, ExecuteStmt))
1717 * Use the prepared query for EXECUTE. The Query for jumble also
1718 * replaced with the corresponding one.
1720 ExecuteStmt *stmt = (ExecuteStmt *)target_query;
1721 PreparedStatement *entry;
1723 entry = FetchPreparedStatement(stmt->name, true);
1724 p = entry->plansource->query_string;
1725 target_query = (Query *) linitial (entry->plansource->query_list);
1728 /* We don't accept other than a Query other than a CMD_UTILITY */
1729 if (!IsA(target_query, Query) ||
1730 target_query->commandType == CMD_UTILITY)
1731 target_query = NULL;
1734 *jumblequery = target_query;
1736 /* Return NULL if the pstate is not identical to the top-level query */
1737 else if (strcmp(pstate->p_sourcetext, p) != 0)
1744 * Get hints from the head block comment in client-supplied query string.
1747 get_hints_from_comment(const char *p)
1749 const char *hint_head;
1757 /* extract query head comment. */
1758 hint_head = strstr(p, HINT_START);
1759 if (hint_head == NULL)
1761 for (;p < hint_head; p++)
1764 * Allow these characters precedes hint comment:
1766 * - alphabets which are in ASCII range
1767 * - space, tabs and new-lines
1768 * - underscores, for identifier
1769 * - commas, for SELECT clause, EXPLAIN and PREPARE
1770 * - parentheses, for EXPLAIN and PREPARE
1772 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1773 * avoid behavior which depends on locale setting.
1775 if (!(*p >= '0' && *p <= '9') &&
1776 !(*p >= 'A' && *p <= 'Z') &&
1777 !(*p >= 'a' && *p <= 'z') &&
1781 *p != '(' && *p != ')')
1785 len = strlen(HINT_START);
1790 /* find hint end keyword. */
1791 if ((tail = strstr(p, HINT_END)) == NULL)
1793 hint_ereport(head, ("Unterminated block comment."));
1797 /* We don't support nested block comments. */
1798 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1800 hint_ereport(head, ("Nested block comments are not supported."));
1804 /* Make a copy of hint. */
1806 head = palloc(len + 1);
1807 memcpy(head, p, len);
1815 * Parse hints that got, create hint struct from parse tree and parse hints.
1818 create_hintstate(Query *parse, const char *hints)
1828 hstate = HintStateCreate();
1829 hstate->hint_str = (char *) hints;
1831 /* parse each hint. */
1832 parse_hints(hstate, parse, p);
1834 /* When nothing specified a hint, we free HintState and returns NULL. */
1835 if (hstate->nall_hints == 0)
1837 HintStateDelete(hstate);
1841 /* Sort hints in order of original position. */
1842 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1845 /* Count number of hints per hint-type. */
1846 for (i = 0; i < hstate->nall_hints; i++)
1848 Hint *cur_hint = hstate->all_hints[i];
1849 hstate->num_hints[cur_hint->type]++;
1853 * If an object (or a set of objects) has multiple hints of same hint-type,
1854 * only the last hint is valid and others are ignored in planning.
1855 * Hints except the last are marked as 'duplicated' to remember the order.
1857 for (i = 0; i < hstate->nall_hints - 1; i++)
1859 Hint *cur_hint = hstate->all_hints[i];
1860 Hint *next_hint = hstate->all_hints[i + 1];
1863 * Leading hint is marked as 'duplicated' in transform_join_hints.
1865 if (cur_hint->type == HINT_TYPE_LEADING &&
1866 next_hint->type == HINT_TYPE_LEADING)
1870 * Note that we need to pass addresses of hint pointers, because
1871 * HintCmp is designed to sort array of Hint* by qsort.
1873 if (HintCmp(&cur_hint, &next_hint) == 0)
1875 hint_ereport(cur_hint->hint_str,
1876 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1877 cur_hint->state = HINT_STATE_DUPLICATION;
1882 * Make sure that per-type array pointers point proper position in the
1883 * array which consists of all hints.
1885 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1886 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1887 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1888 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1889 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1890 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1891 hstate->num_hints[HINT_TYPE_LEADING]);
1892 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
1893 hstate->num_hints[HINT_TYPE_SET]);
1899 * Parse inside of parentheses of scan-method hints.
1902 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1905 const char *keyword = hint->base.keyword;
1906 HintKeyword hint_keyword = hint->base.hint_keyword;
1907 List *name_list = NIL;
1910 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1913 /* Parse relation name and index name(s) if given hint accepts. */
1914 length = list_length(name_list);
1917 hint->relname = linitial(name_list);
1918 hint->indexnames = list_delete_first(name_list);
1920 /* check whether the hint accepts index name(s). */
1922 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1923 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1924 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1925 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1926 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1927 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1930 ("%s hint accepts only one relation.",
1931 hint->base.keyword));
1932 hint->base.state = HINT_STATE_ERROR;
1939 ("%s hint requires a relation.",
1940 hint->base.keyword));
1941 hint->base.state = HINT_STATE_ERROR;
1945 /* Set a bit for specified hint. */
1946 switch (hint_keyword)
1948 case HINT_KEYWORD_SEQSCAN:
1949 hint->enforce_mask = ENABLE_SEQSCAN;
1951 case HINT_KEYWORD_INDEXSCAN:
1952 hint->enforce_mask = ENABLE_INDEXSCAN;
1954 case HINT_KEYWORD_INDEXSCANREGEXP:
1955 hint->enforce_mask = ENABLE_INDEXSCAN;
1956 hint->regexp = true;
1958 case HINT_KEYWORD_BITMAPSCAN:
1959 hint->enforce_mask = ENABLE_BITMAPSCAN;
1961 case HINT_KEYWORD_BITMAPSCANREGEXP:
1962 hint->enforce_mask = ENABLE_BITMAPSCAN;
1963 hint->regexp = true;
1965 case HINT_KEYWORD_TIDSCAN:
1966 hint->enforce_mask = ENABLE_TIDSCAN;
1968 case HINT_KEYWORD_NOSEQSCAN:
1969 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1971 case HINT_KEYWORD_NOINDEXSCAN:
1972 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1974 case HINT_KEYWORD_NOBITMAPSCAN:
1975 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1977 case HINT_KEYWORD_NOTIDSCAN:
1978 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1980 case HINT_KEYWORD_INDEXONLYSCAN:
1981 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1983 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1984 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1985 hint->regexp = true;
1987 case HINT_KEYWORD_NOINDEXONLYSCAN:
1988 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1991 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2000 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2003 const char *keyword = hint->base.keyword;
2004 HintKeyword hint_keyword = hint->base.hint_keyword;
2005 List *name_list = NIL;
2007 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2010 hint->nrels = list_length(name_list);
2012 if (hint->nrels > 0)
2018 * Transform relation names from list to array to sort them with qsort
2021 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2022 foreach (l, name_list)
2024 hint->relnames[i] = lfirst(l);
2029 list_free(name_list);
2031 /* A join hint requires at least two relations */
2032 if (hint->nrels < 2)
2035 ("%s hint requires at least two relations.",
2036 hint->base.keyword));
2037 hint->base.state = HINT_STATE_ERROR;
2041 /* Sort hints in alphabetical order of relation names. */
2042 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2044 switch (hint_keyword)
2046 case HINT_KEYWORD_NESTLOOP:
2047 hint->enforce_mask = ENABLE_NESTLOOP;
2049 case HINT_KEYWORD_MERGEJOIN:
2050 hint->enforce_mask = ENABLE_MERGEJOIN;
2052 case HINT_KEYWORD_HASHJOIN:
2053 hint->enforce_mask = ENABLE_HASHJOIN;
2055 case HINT_KEYWORD_NONESTLOOP:
2056 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2058 case HINT_KEYWORD_NOMERGEJOIN:
2059 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2061 case HINT_KEYWORD_NOHASHJOIN:
2062 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2065 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2074 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2077 if (outer_inner->outer_inner_pair == NIL)
2079 if (outer_inner->relation)
2085 if (list_length(outer_inner->outer_inner_pair) == 2)
2087 foreach(l, outer_inner->outer_inner_pair)
2089 if (!OuterInnerPairCheck(lfirst(l)))
2100 OuterInnerList(OuterInnerRels *outer_inner)
2102 List *outer_inner_list = NIL;
2104 OuterInnerRels *outer_inner_rels;
2106 foreach(l, outer_inner->outer_inner_pair)
2108 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2110 if (outer_inner_rels->relation != NULL)
2111 outer_inner_list = lappend(outer_inner_list,
2112 outer_inner_rels->relation);
2114 outer_inner_list = list_concat(outer_inner_list,
2115 OuterInnerList(outer_inner_rels));
2117 return outer_inner_list;
2121 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2124 List *name_list = NIL;
2125 OuterInnerRels *outer_inner = NULL;
2127 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2131 if (outer_inner != NULL)
2132 name_list = OuterInnerList(outer_inner);
2134 hint->relations = name_list;
2135 hint->outer_inner = outer_inner;
2137 /* A Leading hint requires at least two relations */
2138 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2140 hint_ereport(hint->base.hint_str,
2141 ("%s hint requires at least two relations.",
2143 hint->base.state = HINT_STATE_ERROR;
2145 else if (hint->outer_inner != NULL &&
2146 !OuterInnerPairCheck(hint->outer_inner))
2148 hint_ereport(hint->base.hint_str,
2149 ("%s hint requires two sets of relations when parentheses nests.",
2151 hint->base.state = HINT_STATE_ERROR;
2158 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2160 List *name_list = NIL;
2162 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2166 hint->words = name_list;
2168 /* We need both name and value to set GUC parameter. */
2169 if (list_length(name_list) == 2)
2171 hint->name = linitial(name_list);
2172 hint->value = lsecond(name_list);
2176 hint_ereport(hint->base.hint_str,
2177 ("%s hint requires name and value of GUC parameter.",
2179 hint->base.state = HINT_STATE_ERROR;
2186 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2189 HintKeyword hint_keyword = hint->base.hint_keyword;
2190 List *name_list = NIL;
2194 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2197 /* Last element must be rows specification */
2198 hint->nrels = list_length(name_list) - 1;
2200 if (hint->nrels > 0)
2206 * Transform relation names from list to array to sort them with qsort
2209 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2210 foreach (l, name_list)
2212 if (hint->nrels <= i)
2214 hint->relnames[i] = lfirst(l);
2219 /* Retieve rows estimation */
2220 rows_str = list_nth(name_list, hint->nrels);
2221 hint->rows_str = rows_str; /* store as-is for error logging */
2222 if (rows_str[0] == '#')
2224 hint->value_type = RVT_ABSOLUTE;
2227 else if (rows_str[0] == '+')
2229 hint->value_type = RVT_ADD;
2232 else if (rows_str[0] == '-')
2234 hint->value_type = RVT_SUB;
2237 else if (rows_str[0] == '*')
2239 hint->value_type = RVT_MULTI;
2244 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2245 hint->base.state = HINT_STATE_ERROR;
2248 hint->rows = strtod(rows_str, &end_ptr);
2251 hint_ereport(rows_str,
2252 ("%s hint requires valid number as rows estimation.",
2253 hint->base.keyword));
2254 hint->base.state = HINT_STATE_ERROR;
2258 /* A join hint requires at least two relations */
2259 if (hint->nrels < 2)
2262 ("%s hint requires at least two relations.",
2263 hint->base.keyword));
2264 hint->base.state = HINT_STATE_ERROR;
2268 list_free(name_list);
2270 /* Sort relnames in alphabetical order. */
2271 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2277 * set GUC parameter functions
2281 set_config_option_wrapper(const char *name, const char *value,
2282 GucContext context, GucSource source,
2283 GucAction action, bool changeVal, int elevel)
2286 MemoryContext ccxt = CurrentMemoryContext;
2290 result = set_config_option(name, value, context, source,
2291 action, changeVal, 0);
2297 /* Save error info */
2298 MemoryContextSwitchTo(ccxt);
2299 errdata = CopyErrorData();
2303 (errcode(errdata->sqlerrcode),
2304 errmsg("%s", errdata->message),
2305 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2306 errdata->hint ? errhint("%s", errdata->hint) : 0));
2308 FreeErrorData(errdata);
2316 set_config_options(SetHint **options, int noptions, GucContext context)
2321 save_nestlevel = NewGUCNestLevel();
2323 for (i = 0; i < noptions; i++)
2325 SetHint *hint = options[i];
2328 if (!hint_state_enabled(hint))
2331 result = set_config_option_wrapper(hint->name, hint->value, context,
2332 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2333 pg_hint_plan_message_level);
2335 hint->base.state = HINT_STATE_USED;
2337 hint->base.state = HINT_STATE_ERROR;
2340 return save_nestlevel;
2343 #define SET_CONFIG_OPTION(name, type_bits) \
2344 set_config_option_wrapper((name), \
2345 (mask & (type_bits)) ? "true" : "false", \
2346 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2349 set_scan_config_options(unsigned char enforce_mask, GucContext context)
2353 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2354 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2355 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2357 mask = enforce_mask;
2359 mask = enforce_mask & current_hint->init_scan_mask;
2361 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2362 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2363 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2364 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2365 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2369 set_join_config_options(unsigned char enforce_mask, GucContext context)
2373 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2374 enforce_mask == ENABLE_HASHJOIN)
2375 mask = enforce_mask;
2377 mask = enforce_mask & current_hint->init_join_mask;
2379 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2380 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2381 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2385 * Push a hint into hint stack which is implemented with List struct. Head of
2386 * list is top of stack.
2389 push_hint(HintState *hstate)
2391 /* Prepend new hint to the list means pushing to stack. */
2392 HintStateStack = lcons(hstate, HintStateStack);
2394 /* Pushed hint is the one which should be used hereafter. */
2395 current_hint = hstate;
2398 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2402 /* Hint stack must not be empty. */
2403 if(HintStateStack == NIL)
2404 elog(ERROR, "hint stack is empty");
2407 * Take a hint at the head from the list, and free it. Switch current_hint
2408 * to point new head (NULL if the list is empty).
2410 HintStateStack = list_delete_first(HintStateStack);
2411 HintStateDelete(current_hint);
2412 if(HintStateStack == NIL)
2413 current_hint = NULL;
2415 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2419 * Retrieve and store a hint string from given query or from the hint table.
2420 * If we are using the hint table, the query string is needed to be normalized.
2421 * However, ParseState, which is not available in planner_hook, is required to
2422 * check if the query tree (Query) is surely corresponding to the target query.
2425 pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query)
2427 const char *query_str;
2428 MemoryContext oldcontext;
2430 if (prev_post_parse_analyze_hook)
2431 prev_post_parse_analyze_hook(pstate, query);
2433 /* do nothing under hint table search */
2434 if (hint_inhibit_level > 0)
2437 if (!pg_hint_plan_enable_hint)
2439 if (current_hint_str)
2441 pfree((void *)current_hint_str);
2442 current_hint_str = NULL;
2447 /* increment the query number */
2449 if (debug_level > 1)
2450 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2453 /* search the hint table for a hint if requested */
2454 if (pg_hint_plan_enable_hint_table)
2457 pgssJumbleState jstate;
2459 char *normalized_query = NULL;
2461 query_str = get_query_string(pstate, query, &jumblequery);
2463 /* If this query is not for hint, just return */
2467 /* clear the previous hint string */
2468 if (current_hint_str)
2470 pfree((void *)current_hint_str);
2471 current_hint_str = NULL;
2477 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2478 * careful to PostgreSQL's version up.
2480 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2481 jstate.jumble_len = 0;
2482 jstate.clocations_buf_size = 32;
2483 jstate.clocations = (pgssLocationLen *)
2484 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2485 jstate.clocations_count = 0;
2487 JumbleQuery(&jstate, jumblequery);
2490 * Normalize the query string by replacing constants with '?'
2493 * Search hint string which is stored keyed by query string
2494 * and application name. The query string is normalized to allow
2497 * Adding 1 byte to query_len ensures that the returned string has
2498 * a terminating NULL.
2500 query_len = strlen(query_str) + 1;
2502 generate_normalized_query(&jstate, query_str,
2504 GetDatabaseEncoding());
2507 * find a hint for the normalized query. the result should be in
2510 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2512 get_hints_from_table(normalized_query, application_name);
2513 MemoryContextSwitchTo(oldcontext);
2515 if (debug_level > 1)
2517 if (current_hint_str)
2518 ereport(pg_hint_plan_message_level,
2519 (errmsg("pg_hint_plan[qno=0x%x]: "
2520 "post_parse_analyze_hook: "
2521 "hints from table: \"%s\": "
2522 "normalized_query=\"%s\", "
2523 "application name =\"%s\"",
2524 qno, current_hint_str,
2525 normalized_query, application_name),
2526 errhidestmt(msgqno != qno)));
2528 ereport(pg_hint_plan_message_level,
2529 (errmsg("pg_hint_plan[qno=0x%x]: "
2530 "no match found in table: "
2531 "application name = \"%s\", "
2532 "normalized_query=\"%s\"",
2533 qno, application_name,
2535 errhidestmt(msgqno != qno)));
2541 /* retrun if we have hint here*/
2542 if (current_hint_str)
2546 query_str = get_query_string(pstate, query, NULL);
2551 * get hints from the comment. However we may have the same query
2552 * string with the previous call, but just retrieving hints is expected
2553 * to be faster than checking for identicalness before retrieval.
2555 if (current_hint_str)
2556 pfree((void *)current_hint_str);
2558 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2559 current_hint_str = get_hints_from_comment(query_str);
2560 MemoryContextSwitchTo(oldcontext);
2563 if (debug_level > 1)
2565 if (debug_level == 1 &&
2566 (stmt_name || strcmp(query_str, debug_query_string)))
2567 ereport(pg_hint_plan_message_level,
2568 (errmsg("hints in comment=\"%s\"",
2569 current_hint_str ? current_hint_str : "(none)"),
2570 errhidestmt(msgqno != qno)));
2572 ereport(pg_hint_plan_message_level,
2573 (errmsg("hints in comment=\"%s\", stmt=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2574 current_hint_str ? current_hint_str : "(none)",
2575 stmt_name, query_str, debug_query_string),
2576 errhidestmt(msgqno != qno)));
2582 * Read and set up hint information
2584 static PlannedStmt *
2585 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2588 PlannedStmt *result;
2592 * Use standard planner if pg_hint_plan is disabled or current nesting
2593 * depth is nesting depth of SPI calls. Other hook functions try to change
2594 * plan with current_hint if any, so set it to NULL.
2596 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2598 if (debug_level > 1)
2599 ereport(pg_hint_plan_message_level,
2600 (errmsg ("pg_hint_plan%s: planner: enable_hint=%d,"
2601 " hint_inhibit_level=%d",
2602 qnostr, pg_hint_plan_enable_hint,
2603 hint_inhibit_level),
2604 errhidestmt(msgqno != qno)));
2607 goto standard_planner_proc;
2611 * Support for nested plpgsql functions. This is quite ugly but this is the
2612 * only point I could find where I can get the query string.
2614 if (plpgsql_recurse_level > 0)
2616 MemoryContext oldcontext;
2618 if (current_hint_str)
2619 pfree((void *)current_hint_str);
2621 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2623 get_hints_from_comment((char *)error_context_stack->arg);
2624 MemoryContextSwitchTo(oldcontext);
2627 if (!current_hint_str)
2628 goto standard_planner_proc;
2630 /* parse the hint into hint state struct */
2631 hstate = create_hintstate(parse, pstrdup(current_hint_str));
2633 /* run standard planner if the statement has not valid hint */
2635 goto standard_planner_proc;
2638 * Push new hint struct to the hint stack to disable previous hint context.
2642 /* Set GUC parameters which are specified with Set hint. */
2643 save_nestlevel = set_config_options(current_hint->set_hints,
2644 current_hint->num_hints[HINT_TYPE_SET],
2645 current_hint->context);
2648 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2649 if (enable_indexscan)
2650 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2651 if (enable_bitmapscan)
2652 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2654 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2655 if (enable_indexonlyscan)
2656 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2657 if (enable_nestloop)
2658 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2659 if (enable_mergejoin)
2660 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2661 if (enable_hashjoin)
2662 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2664 if (debug_level > 1)
2666 ereport(pg_hint_plan_message_level,
2667 (errhidestmt(msgqno != qno),
2668 errmsg("pg_hint_plan%s: planner", qnostr)));
2673 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2674 * state when this planner started when error occurred in planner.
2679 result = (*prev_planner) (parse, cursorOptions, boundParams);
2681 result = standard_planner(parse, cursorOptions, boundParams);
2686 * Rollback changes of GUC parameters, and pop current hint context
2687 * from hint stack to rewind the state.
2689 AtEOXact_GUC(true, save_nestlevel);
2695 /* Print hint in debug mode. */
2696 if (debug_level == 1)
2697 HintStateDump(current_hint);
2698 else if (debug_level > 1)
2699 HintStateDump2(current_hint);
2702 * Rollback changes of GUC parameters, and pop current hint context from
2703 * hint stack to rewind the state.
2705 AtEOXact_GUC(true, save_nestlevel);
2710 standard_planner_proc:
2711 if (debug_level > 1)
2713 ereport(pg_hint_plan_message_level,
2714 (errhidestmt(msgqno != qno),
2715 errmsg("pg_hint_plan%s: planner: no valid hint",
2719 current_hint = NULL;
2721 return (*prev_planner) (parse, cursorOptions, boundParams);
2723 return standard_planner(parse, cursorOptions, boundParams);
2727 * Return scan method hint which matches given aliasname.
2729 static ScanMethodHint *
2730 find_scan_hint(PlannerInfo *root, Index relid, RelOptInfo *rel)
2736 * We can't apply scan method hint if the relation is:
2737 * - not a base relation
2738 * - not an ordinary relation (such as join and subquery)
2740 if (rel && (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION))
2743 rte = root->simple_rte_array[relid];
2745 /* We can't force scan method of foreign tables */
2746 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2749 /* Find scan method hint, which matches given names, from the list. */
2750 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2752 ScanMethodHint *hint = current_hint->scan_hints[i];
2754 /* We ignore disabled hints. */
2755 if (!hint_state_enabled(hint))
2758 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2768 * Returns TRUE on match, FALSE on no match.
2770 * s1 --- the data to match against
2771 * s2 --- the pattern
2773 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2776 regexpeq(const char *s1, const char *s2)
2782 strcpy(name.data, s1);
2783 regexp = cstring_to_text(s2);
2785 result = DirectFunctionCall2Coll(nameregexeq,
2786 DEFAULT_COLLATION_OID,
2787 NameGetDatum(&name),
2788 PointerGetDatum(regexp));
2789 return DatumGetBool(result);
2793 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2801 * We delete all the IndexOptInfo list and prevent you from being usable by
2804 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2805 hint->enforce_mask == ENABLE_TIDSCAN)
2807 list_free_deep(rel->indexlist);
2808 rel->indexlist = NIL;
2809 hint->base.state = HINT_STATE_USED;
2815 * When a list of indexes is not specified, we just use all indexes.
2817 if (hint->indexnames == NIL)
2821 * Leaving only an specified index, we delete it from a IndexOptInfo list
2825 if (debug_level > 0)
2826 initStringInfo(&buf);
2828 for (cell = list_head(rel->indexlist); cell; cell = next)
2830 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2831 char *indexname = get_rel_name(info->indexoid);
2833 bool use_index = false;
2837 foreach(l, hint->indexnames)
2839 char *hintname = (char *) lfirst(l);
2843 result = regexpeq(indexname, hintname);
2845 result = RelnameCmp(&indexname, &hintname) == 0;
2850 if (debug_level > 0)
2852 appendStringInfoCharMacro(&buf, ' ');
2853 quote_value(&buf, indexname);
2861 * to make the index a candidate when definition of this index is
2862 * matched with the index's definition of current_hint.
2864 if (OidIsValid(relationObjectId) && !use_index)
2866 foreach(l, current_hint->parent_index_infos)
2870 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2872 /* check to match the parameter of unique */
2873 if (p_info->indisunique != info->unique)
2876 /* check to match the parameter of index's method */
2877 if (p_info->method != info->relam)
2880 /* to check to match the indexkey's configuration */
2881 if ((list_length(p_info->column_names)) !=
2885 /* check to match the indexkey's configuration */
2886 for (i = 0; i < info->ncolumns; i++)
2888 char *c_attname = NULL;
2889 char *p_attname = NULL;
2892 list_nth(p_info->column_names, i);
2894 /* both are expressions */
2895 if (info->indexkeys[i] == 0 && !p_attname)
2898 /* one's column is expression, the other is not */
2899 if (info->indexkeys[i] == 0 || !p_attname)
2902 c_attname = get_attname(relationObjectId,
2903 info->indexkeys[i]);
2905 if (strcmp(p_attname, c_attname) != 0)
2908 if (p_info->indcollation[i] != info->indexcollations[i])
2911 if (p_info->opclass[i] != info->opcintype[i])
2914 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2915 info->reverse_sort[i])
2918 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2919 info->nulls_first[i])
2924 if (i != info->ncolumns)
2927 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2928 (p_info->indpred_str && (info->indpred != NIL)))
2931 * Fetch the pg_index tuple by the Oid of the index
2933 ht_idx = SearchSysCache1(INDEXRELID,
2934 ObjectIdGetDatum(info->indexoid));
2936 /* check to match the expression's parameter of index */
2937 if (p_info->expression_str &&
2938 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2945 * to change the expression's parameter of child's
2948 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2949 Anum_pg_index_indexprs,
2952 result = DirectFunctionCall2(pg_get_expr,
2957 if (strcmp(p_info->expression_str,
2958 text_to_cstring(DatumGetTextP(result))) != 0)
2961 ReleaseSysCache(ht_idx);
2967 /* Check to match the predicate's parameter of index */
2968 if (p_info->indpred_str &&
2969 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2976 * to change the predicate's parameter of child's
2979 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2980 Anum_pg_index_indpred,
2983 result = DirectFunctionCall2(pg_get_expr,
2988 if (strcmp(p_info->indpred_str,
2989 text_to_cstring(DatumGetTextP(result))) != 0)
2992 ReleaseSysCache(ht_idx);
2999 ReleaseSysCache(ht_idx);
3001 else if (p_info->expression_str || (info->indexprs != NIL))
3003 else if (p_info->indpred_str || (info->indpred != NIL))
3008 /* to log the candidate of index */
3009 if (debug_level > 0)
3011 appendStringInfoCharMacro(&buf, ' ');
3012 quote_value(&buf, indexname);
3020 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
3027 if (debug_level == 1)
3030 StringInfoData rel_buf;
3032 if (OidIsValid(relationObjectId))
3033 relname = get_rel_name(relationObjectId);
3035 relname = hint->relname;
3037 initStringInfo(&rel_buf);
3038 quote_value(&rel_buf, relname);
3041 (errmsg("available indexes for %s(%s):%s",
3046 pfree(rel_buf.data);
3051 * Return information of index definition.
3053 static ParentIndexInfo *
3054 get_parent_index_info(Oid indexoid, Oid relid)
3056 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3057 Relation indexRelation;
3058 Form_pg_index index;
3062 indexRelation = index_open(indexoid, RowExclusiveLock);
3064 index = indexRelation->rd_index;
3066 p_info->indisunique = index->indisunique;
3067 p_info->method = indexRelation->rd_rel->relam;
3069 p_info->column_names = NIL;
3070 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3071 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3072 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3074 for (i = 0; i < index->indnatts; i++)
3076 attname = get_attname(relid, index->indkey.values[i]);
3077 p_info->column_names = lappend(p_info->column_names, attname);
3079 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3080 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3081 p_info->indoption[i] = indexRelation->rd_indoption[i];
3085 * to check to match the expression's parameter of index with child indexes
3087 p_info->expression_str = NULL;
3088 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
3094 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3095 Anum_pg_index_indexprs, &isnull);
3097 result = DirectFunctionCall2(pg_get_expr,
3099 ObjectIdGetDatum(relid));
3101 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3105 * to check to match the predicate's parameter of index with child indexes
3107 p_info->indpred_str = NULL;
3108 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
3114 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3115 Anum_pg_index_indpred, &isnull);
3117 result = DirectFunctionCall2(pg_get_expr,
3119 ObjectIdGetDatum(relid));
3121 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3124 index_close(indexRelation, NoLock);
3130 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
3131 bool inhparent, RelOptInfo *rel)
3133 ScanMethodHint *hint = NULL;
3135 Index new_parent_relid = 0;
3137 if (prev_get_relation_info)
3138 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
3141 * Do nothing if we don't have a valid hint in this context or current
3142 * nesting depth is at SPI calls.
3144 if (!current_hint || hint_inhibit_level > 0)
3146 if (debug_level > 1)
3147 ereport(pg_hint_plan_message_level,
3149 errmsg ("pg_hint_plan%s: get_relation_info"
3150 " no hint to apply: relation=%u(%s), inhparent=%d,"
3151 " current_hint=%p, hint_inhibit_level=%d",
3152 qnostr, relationObjectId,
3153 get_rel_name(relationObjectId),
3154 inhparent, current_hint, hint_inhibit_level)));
3159 * We could register the parent relation of the following children here
3160 * when inhparent == true but inheritnce planner doesn't request
3161 * information for inheritance parents. We also cannot distinguish the
3162 * caller so we should always find the parents without this function being
3167 if (debug_level > 1)
3168 ereport(pg_hint_plan_message_level,
3170 errmsg ("pg_hint_plan%s: get_relation_info"
3171 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3172 " current_hint=%p, hint_inhibit_level=%d",
3173 qnostr, relationObjectId,
3174 get_rel_name(relationObjectId),
3175 inhparent, current_hint, hint_inhibit_level)));
3179 /* Find the parent for this relation */
3180 foreach (l, root->append_rel_list)
3182 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3184 if (appinfo->child_relid == rel->relid)
3186 if (current_hint->parent_relid != appinfo->parent_relid)
3187 new_parent_relid = appinfo->parent_relid;
3194 /* This relation doesn't have a parent. Cancel current_hint. */
3195 current_hint->parent_relid = 0;
3196 current_hint->parent_hint = NULL;
3199 if (new_parent_relid > 0)
3202 * Here we found a parent relation different from the remembered one.
3203 * Remember it, apply the scan mask of it and then resolve the index
3204 * restriction in order to be used by its children.
3206 int scanmask = current_hint->init_scan_mask;
3207 ScanMethodHint *parent_hint;
3209 current_hint->parent_relid = new_parent_relid;
3212 * Get and apply the hint for the new parent relation. It should be an
3213 * ordinary relation so calling find_scan_hint with rel == NULL is
3216 current_hint->parent_hint = parent_hint =
3217 find_scan_hint(root, current_hint->parent_relid, NULL);
3221 scanmask = current_hint->parent_hint->enforce_mask;
3222 parent_hint->base.state = HINT_STATE_USED;
3224 /* Resolve index name mask (if any) using the parent. */
3225 if (parent_hint->indexnames)
3228 Relation parent_rel;
3231 root->simple_rte_array[current_hint->parent_relid]->relid;
3232 parent_rel = heap_open(parentrel_oid, NoLock);
3234 /* Search the parent relation for indexes match the hint spec */
3235 foreach(l, RelationGetIndexList(parent_rel))
3237 Oid indexoid = lfirst_oid(l);
3238 char *indexname = get_rel_name(indexoid);
3240 ParentIndexInfo *parent_index_info;
3242 foreach(lc, parent_hint->indexnames)
3244 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3251 get_parent_index_info(indexoid, parentrel_oid);
3252 current_hint->parent_index_infos =
3253 lappend(current_hint->parent_index_infos, parent_index_info);
3255 heap_close(parent_rel, NoLock);
3259 set_scan_config_options(scanmask, current_hint->context);
3262 if (current_hint->parent_hint != 0)
3264 delete_indexes(current_hint->parent_hint, rel,
3267 /* Scan fixation status is the same to the parent. */
3268 if (debug_level > 1)
3269 ereport(pg_hint_plan_message_level,
3271 errmsg("pg_hint_plan%s: get_relation_info:"
3272 " index deletion by parent hint: "
3273 "relation=%u(%s), inhparent=%d, current_hint=%p,"
3274 " hint_inhibit_level=%d",
3275 qnostr, relationObjectId,
3276 get_rel_name(relationObjectId),
3277 inhparent, current_hint, hint_inhibit_level)));
3281 /* This table doesn't have a parent hint. Apply its own hint if any. */
3282 if ((hint = find_scan_hint(root, rel->relid, rel)) != NULL)
3284 set_scan_config_options(hint->enforce_mask, current_hint->context);
3285 hint->base.state = HINT_STATE_USED;
3287 delete_indexes(hint, rel, InvalidOid);
3289 if (debug_level > 1)
3290 ereport(pg_hint_plan_message_level,
3292 errmsg ("pg_hint_plan%s: get_relation_info"
3294 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3295 " hint_inhibit_level=%d, scanmask=0x%x",
3296 qnostr, relationObjectId,
3297 get_rel_name(relationObjectId),
3298 inhparent, current_hint, hint_inhibit_level,
3299 hint->enforce_mask)));
3303 if (debug_level > 1)
3304 ereport(pg_hint_plan_message_level,
3305 (errhidestmt (true),
3306 errmsg ("pg_hint_plan%s: get_relation_info"
3308 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3309 " hint_inhibit_level=%d, scanmask=0x%x",
3310 qnostr, relationObjectId,
3311 get_rel_name(relationObjectId),
3312 inhparent, current_hint, hint_inhibit_level,
3313 current_hint->init_scan_mask)));
3314 set_scan_config_options(current_hint->init_scan_mask,
3315 current_hint->context);
3321 * Return index of relation which matches given aliasname, or 0 if not found.
3322 * If same aliasname was used multiple times in a query, return -1.
3325 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3331 for (i = 1; i < root->simple_rel_array_size; i++)
3335 if (root->simple_rel_array[i] == NULL)
3338 Assert(i == root->simple_rel_array[i]->relid);
3340 if (RelnameCmp(&aliasname,
3341 &root->simple_rte_array[i]->eref->aliasname) != 0)
3344 foreach(l, initial_rels)
3346 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3348 if (rel->reloptkind == RELOPT_BASEREL)
3350 if (rel->relid != i)
3355 Assert(rel->reloptkind == RELOPT_JOINREL);
3357 if (!bms_is_member(i, rel->relids))
3364 ("Relation name \"%s\" is ambiguous.",
3379 * Return join hint which matches given joinrelids.
3381 static JoinMethodHint *
3382 find_join_hint(Relids joinrelids)
3387 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
3389 foreach(l, join_hint)
3391 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3393 if (bms_equal(joinrelids, hint->joinrelids))
3401 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3402 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3404 OuterInnerRels *outer_rels;
3405 OuterInnerRels *inner_rels;
3406 Relids outer_relids;
3407 Relids inner_relids;
3409 JoinMethodHint *hint;
3411 if (outer_inner->relation != NULL)
3413 return bms_make_singleton(
3414 find_relid_aliasname(root, outer_inner->relation,
3416 leading_hint->base.hint_str));
3419 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3420 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3422 outer_relids = OuterInnerJoinCreate(outer_rels,
3428 inner_relids = OuterInnerJoinCreate(inner_rels,
3435 join_relids = bms_add_members(outer_relids, inner_relids);
3437 if (bms_num_members(join_relids) > nbaserel)
3441 * If we don't have join method hint, create new one for the
3442 * join combination with all join methods are enabled.
3444 hint = find_join_hint(join_relids);
3448 * Here relnames is not set, since Relids bitmap is sufficient to
3449 * control paths of this query afterward.
3451 hint = (JoinMethodHint *) JoinMethodHintCreate(
3452 leading_hint->base.hint_str,
3454 HINT_KEYWORD_LEADING);
3455 hint->base.state = HINT_STATE_USED;
3456 hint->nrels = bms_num_members(join_relids);
3457 hint->enforce_mask = ENABLE_ALL_JOIN;
3458 hint->joinrelids = bms_copy(join_relids);
3459 hint->inner_nrels = bms_num_members(inner_relids);
3460 hint->inner_joinrelids = bms_copy(inner_relids);
3462 hstate->join_hint_level[hint->nrels] =
3463 lappend(hstate->join_hint_level[hint->nrels], hint);
3467 hint->inner_nrels = bms_num_members(inner_relids);
3468 hint->inner_joinrelids = bms_copy(inner_relids);
3475 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3476 int nrels, char **relnames)
3479 Relids relids = NULL;
3483 for (j = 0; j < nrels; j++)
3485 relname = relnames[j];
3487 relid = find_relid_aliasname(root, relname, initial_rels,
3491 base->state = HINT_STATE_ERROR;
3494 * the aliasname is not found(relid == 0) or same aliasname was used
3495 * multiple times in a query(relid == -1)
3502 if (bms_is_member(relid, relids))
3504 hint_ereport(base->hint_str,
3505 ("Relation name \"%s\" is duplicated.", relname));
3506 base->state = HINT_STATE_ERROR;
3510 relids = bms_add_member(relids, relid);
3515 * Transform join method hint into handy form.
3517 * - create bitmap of relids from alias names, to make it easier to check
3518 * whether a join path matches a join method hint.
3519 * - add join method hints which are necessary to enforce join order
3520 * specified by Leading hint
3523 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
3524 List *initial_rels, JoinMethodHint **join_method_hints)
3532 LeadingHint *lhint = NULL;
3535 * Create bitmap of relids from alias names for each join method hint.
3536 * Bitmaps are more handy than strings in join searching.
3538 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
3540 JoinMethodHint *hint = hstate->join_hints[i];
3542 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3545 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3546 initial_rels, hint->nrels, hint->relnames);
3548 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
3551 hstate->join_hint_level[hint->nrels] =
3552 lappend(hstate->join_hint_level[hint->nrels], hint);
3556 * Create bitmap of relids from alias names for each rows hint.
3557 * Bitmaps are more handy than strings in join searching.
3559 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
3561 RowsHint *hint = hstate->rows_hints[i];
3563 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3566 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3567 initial_rels, hint->nrels, hint->relnames);
3570 /* Do nothing if no Leading hint was supplied. */
3571 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
3575 * Decide to use Leading hint。
3577 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
3579 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
3582 if (leading_hint->base.state == HINT_STATE_ERROR)
3588 foreach(l, leading_hint->relations)
3590 relname = (char *)lfirst(l);;
3592 relid = find_relid_aliasname(root, relname, initial_rels,
3593 leading_hint->base.hint_str);
3595 leading_hint->base.state = HINT_STATE_ERROR;
3600 if (bms_is_member(relid, relids))
3602 hint_ereport(leading_hint->base.hint_str,
3603 ("Relation name \"%s\" is duplicated.", relname));
3604 leading_hint->base.state = HINT_STATE_ERROR;
3608 relids = bms_add_member(relids, relid);
3611 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3616 hint_ereport(lhint->base.hint_str,
3617 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3618 lhint->base.state = HINT_STATE_DUPLICATION;
3620 leading_hint->base.state = HINT_STATE_USED;
3621 lhint = leading_hint;
3624 /* check to exist Leading hint marked with 'used'. */
3629 * We need join method hints which fit specified join order in every join
3630 * level. For example, Leading(A B C) virtually requires following join
3631 * method hints, if no join method hint supplied:
3633 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3634 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3636 * If we already have join method hint which fits specified join order in
3637 * that join level, we leave it as-is and don't add new hints.
3641 if (lhint->outer_inner == NULL)
3643 foreach(l, lhint->relations)
3645 JoinMethodHint *hint;
3647 relname = (char *)lfirst(l);
3650 * Find relid of the relation which has given name. If we have the
3651 * name given in Leading hint multiple times in the join, nothing to
3654 relid = find_relid_aliasname(root, relname, initial_rels,
3657 /* Create bitmap of relids for current join level. */
3658 joinrelids = bms_add_member(joinrelids, relid);
3661 /* We never have join method hint for single relation. */
3666 * If we don't have join method hint, create new one for the
3667 * join combination with all join methods are enabled.
3669 hint = find_join_hint(joinrelids);
3673 * Here relnames is not set, since Relids bitmap is sufficient
3674 * to control paths of this query afterward.
3676 hint = (JoinMethodHint *) JoinMethodHintCreate(
3677 lhint->base.hint_str,
3679 HINT_KEYWORD_LEADING);
3680 hint->base.state = HINT_STATE_USED;
3681 hint->nrels = njoinrels;
3682 hint->enforce_mask = ENABLE_ALL_JOIN;
3683 hint->joinrelids = bms_copy(joinrelids);
3686 join_method_hints[njoinrels] = hint;
3688 if (njoinrels >= nbaserel)
3691 bms_free(joinrelids);
3697 * Delete all join hints which have different combination from Leading
3700 for (i = 2; i <= njoinrels; i++)
3702 list_free(hstate->join_hint_level[i]);
3704 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3709 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3716 njoinrels = bms_num_members(joinrelids);
3717 Assert(njoinrels >= 2);
3720 * Delete all join hints which have different combination from Leading
3723 for (i = 2;i <= njoinrels; i++)
3725 if (hstate->join_hint_level[i] != NIL)
3727 ListCell *prev = NULL;
3728 ListCell *next = NULL;
3729 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3732 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3736 if (hint->inner_nrels == 0 &&
3737 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3738 bms_equal(bms_union(hint->joinrelids, joinrelids),
3741 hstate->join_hint_level[i] =
3742 list_delete_cell(hstate->join_hint_level[i], l,
3751 bms_free(joinrelids);
3754 if (hint_state_enabled(lhint))
3756 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3763 * set_plain_rel_pathlist
3764 * Build access paths for a plain relation (no subquery, no inheritance)
3766 * This function was copied and edited from set_plain_rel_pathlist() in
3767 * src/backend/optimizer/path/allpaths.c
3770 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3772 /* Consider sequential scan */
3773 add_path(rel, create_seqscan_path(root, rel, NULL));
3775 /* Consider index scans */
3776 create_index_paths(root, rel);
3778 /* Consider TID scans */
3779 create_tidscan_paths(root, rel);
3781 /* Now find the cheapest of the paths for this rel */
3786 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3791 foreach(l, initial_rels)
3793 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3795 ScanMethodHint *hint;
3797 /* Skip relations which we can't choose scan method. */
3798 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3801 rte = root->simple_rte_array[rel->relid];
3803 /* We can't force scan method of foreign tables */
3804 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3808 * Create scan paths with GUC parameters which are at the beginning of
3809 * planner if scan method hint is not specified, otherwise use
3810 * specified hints and mark the hint as used.
3812 if ((hint = find_scan_hint(root, rel->relid, rel)) == NULL)
3813 set_scan_config_options(hstate->init_scan_mask,
3817 set_scan_config_options(hint->enforce_mask, hstate->context);
3818 hint->base.state = HINT_STATE_USED;
3821 list_free_deep(rel->pathlist);
3822 rel->pathlist = NIL;
3825 /* It's an "append relation", process accordingly */
3826 set_append_rel_pathlist(root, rel, rel->relid, rte);
3830 set_plain_rel_pathlist(root, rel, rte);
3835 * Restore the GUC variables we set above.
3837 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3841 * wrapper of make_join_rel()
3843 * call make_join_rel() after changing enable_* parameters according to given
3847 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3850 JoinMethodHint *hint;
3854 joinrelids = bms_union(rel1->relids, rel2->relids);
3855 hint = find_join_hint(joinrelids);
3856 bms_free(joinrelids);
3859 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3861 if (hint->inner_nrels == 0)
3863 save_nestlevel = NewGUCNestLevel();
3865 set_join_config_options(hint->enforce_mask, current_hint->context);
3867 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3868 hint->base.state = HINT_STATE_USED;
3871 * Restore the GUC variables we set above.
3873 AtEOXact_GUC(true, save_nestlevel);
3876 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3885 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3886 RelOptInfo *joinrel,
3887 RelOptInfo *outerrel,
3888 RelOptInfo *innerrel,
3890 SpecialJoinInfo *sjinfo,
3893 ScanMethodHint *scan_hint = NULL;
3895 JoinMethodHint *join_hint;
3898 if ((scan_hint = find_scan_hint(root, innerrel->relid, innerrel)) != NULL)
3900 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3901 scan_hint->base.state = HINT_STATE_USED;
3904 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3905 join_hint = find_join_hint(joinrelids);
3906 bms_free(joinrelids);
3908 if (join_hint && join_hint->inner_nrels != 0)
3910 save_nestlevel = NewGUCNestLevel();
3912 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3915 set_join_config_options(join_hint->enforce_mask,
3916 current_hint->context);
3918 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3919 sjinfo, restrictlist);
3920 join_hint->base.state = HINT_STATE_USED;
3924 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3925 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3926 sjinfo, restrictlist);
3930 * Restore the GUC variables we set above.
3932 AtEOXact_GUC(true, save_nestlevel);
3935 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3936 sjinfo, restrictlist);
3938 if (scan_hint != NULL)
3939 set_scan_config_options(current_hint->init_scan_mask,
3940 current_hint->context);
3944 get_num_baserels(List *initial_rels)
3949 foreach(l, initial_rels)
3951 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3953 if (rel->reloptkind == RELOPT_BASEREL)
3955 else if (rel->reloptkind ==RELOPT_JOINREL)
3956 nbaserel+= bms_num_members(rel->relids);
3959 /* other values not expected here */
3960 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3968 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3971 JoinMethodHint **join_method_hints;
3975 bool leading_hint_enable;
3978 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3979 * valid hint is supplied or current nesting depth is nesting depth of SPI
3982 if (!current_hint || hint_inhibit_level > 0)
3984 if (prev_join_search)
3985 return (*prev_join_search) (root, levels_needed, initial_rels);
3986 else if (enable_geqo && levels_needed >= geqo_threshold)
3987 return geqo(root, levels_needed, initial_rels);
3989 return standard_join_search(root, levels_needed, initial_rels);
3992 /* We apply scan method hint rebuild scan path. */
3993 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3996 * In the case using GEQO, only scan method hints and Set hints have
3997 * effect. Join method and join order is not controllable by hints.
3999 if (enable_geqo && levels_needed >= geqo_threshold)
4000 return geqo(root, levels_needed, initial_rels);
4002 nbaserel = get_num_baserels(initial_rels);
4003 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
4004 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4006 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
4007 initial_rels, join_method_hints);
4009 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4011 for (i = 2; i <= nbaserel; i++)
4013 list_free(current_hint->join_hint_level[i]);
4015 /* free Leading hint only */
4016 if (join_method_hints[i] != NULL &&
4017 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4018 JoinMethodHintDelete(join_method_hints[i]);
4020 pfree(current_hint->join_hint_level);
4021 pfree(join_method_hints);
4023 if (leading_hint_enable)
4024 set_join_config_options(current_hint->init_join_mask,
4025 current_hint->context);
4032 * Build access paths for a base relation
4034 * This function was copied and edited from set_rel_pathlist() in
4035 * src/backend/optimizer/path/allpaths.c
4038 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4039 Index rti, RangeTblEntry *rte)
4041 if (IS_DUMMY_REL(rel))
4043 /* We already proved the relation empty, so nothing more to do */
4047 /* It's an "append relation", process accordingly */
4048 set_append_rel_pathlist(root, rel, rti, rte);
4052 if (rel->rtekind == RTE_RELATION)
4054 if (rte->relkind == RELKIND_RELATION)
4056 /* Plain relation */
4057 set_plain_rel_pathlist(root, rel, rte);
4060 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4063 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4068 * stmt_beg callback is called when each query in PL/pgSQL function is about
4069 * to be executed. At that timing, we save query string in the global variable
4070 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4071 * variable for the purpose, because its content is only necessary until
4072 * planner hook is called for the query, so recursive PL/pgSQL function calls
4073 * don't harm this mechanism.
4076 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4078 plpgsql_recurse_level++;
4082 * stmt_end callback is called then each query in PL/pgSQL function has
4083 * finished. At that timing, we clear plpgsql_query_string to tell planner
4084 * hook that next call is not for a query written in PL/pgSQL block.
4087 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4089 plpgsql_recurse_level--;
4092 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4097 if (phase != RESOURCE_RELEASE_AFTER_LOCKS)
4099 /* Cancel plpgsql nest level*/
4100 plpgsql_recurse_level = 0;
4103 #define standard_join_search pg_hint_plan_standard_join_search
4104 #define join_search_one_level pg_hint_plan_join_search_one_level
4105 #define make_join_rel make_join_rel_wrapper
4108 #undef make_join_rel
4109 #define make_join_rel pg_hint_plan_make_join_rel
4110 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4111 #include "make_join_rel.c"
4113 #include "pg_stat_statements.c"