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 "optimizer/clauses.h"
19 #include "optimizer/cost.h"
20 #include "optimizer/geqo.h"
21 #include "optimizer/joininfo.h"
22 #include "optimizer/pathnode.h"
23 #include "optimizer/paths.h"
24 #include "optimizer/plancat.h"
25 #include "optimizer/planner.h"
26 #include "optimizer/prep.h"
27 #include "optimizer/restrictinfo.h"
28 #include "parser/scansup.h"
29 #include "tcop/utility.h"
30 #include "utils/builtins.h"
31 #include "utils/lsyscache.h"
32 #include "utils/memutils.h"
33 #include "utils/rel.h"
34 #include "utils/syscache.h"
35 #include "utils/resowner.h"
37 #include "catalog/pg_class.h"
39 #include "executor/spi.h"
40 #include "catalog/pg_type.h"
43 * We have our own header file "plpgsql-9.1", which is necessary to support
44 * hints for queries in PL/pgSQL blocks, in pg_hint_plan source package,
45 * because PostgreSQL 9.1 doesn't provide the header file as a part of
46 * installation. This header file is a copy of src/pl/plpgsql/src/plpgsql.h in
47 * PostgreSQL 9.1.9 source tree,
49 * On the other hand, 9.2 installation provides that header file for external
50 * modules, so we include the header in ordinary place.
54 /* partially copied from pg_stat_statements */
55 #include "normalize_query.h"
57 #ifdef PG_MODULE_MAGIC
61 #define BLOCK_COMMENT_START "/*"
62 #define BLOCK_COMMENT_END "*/"
63 #define HINT_COMMENT_KEYWORD "+"
64 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
65 #define HINT_END BLOCK_COMMENT_END
68 #define HINT_SEQSCAN "SeqScan"
69 #define HINT_INDEXSCAN "IndexScan"
70 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
71 #define HINT_BITMAPSCAN "BitmapScan"
72 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
73 #define HINT_TIDSCAN "TidScan"
74 #define HINT_NOSEQSCAN "NoSeqScan"
75 #define HINT_NOINDEXSCAN "NoIndexScan"
76 #define HINT_NOBITMAPSCAN "NoBitmapScan"
77 #define HINT_NOTIDSCAN "NoTidScan"
78 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
79 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
80 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
81 #define HINT_NESTLOOP "NestLoop"
82 #define HINT_MERGEJOIN "MergeJoin"
83 #define HINT_HASHJOIN "HashJoin"
84 #define HINT_NONESTLOOP "NoNestLoop"
85 #define HINT_NOMERGEJOIN "NoMergeJoin"
86 #define HINT_NOHASHJOIN "NoHashJoin"
87 #define HINT_LEADING "Leading"
88 #define HINT_SET "Set"
89 #define HINT_ROWS "Rows"
91 #define HINT_ARRAY_DEFAULT_INITSIZE 8
93 #define hint_ereport(str, detail) \
94 ereport(pg_hint_plan_message_level, \
95 (errhidestmt(hidestmt), \
96 errmsg("pg_hint_plan%s: hint syntax error at or near \"%s\"", qnostr, (str)), \
99 #define skip_space(str) \
100 while (isspace(*str)) \
105 ENABLE_SEQSCAN = 0x01,
106 ENABLE_INDEXSCAN = 0x02,
107 ENABLE_BITMAPSCAN = 0x04,
108 ENABLE_TIDSCAN = 0x08,
109 ENABLE_INDEXONLYSCAN = 0x10
114 ENABLE_NESTLOOP = 0x01,
115 ENABLE_MERGEJOIN = 0x02,
116 ENABLE_HASHJOIN = 0x04
119 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
120 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
121 ENABLE_INDEXONLYSCAN)
122 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
123 #define DISABLE_ALL_SCAN 0
124 #define DISABLE_ALL_JOIN 0
126 /* hint keyword of enum type*/
127 typedef enum HintKeyword
129 HINT_KEYWORD_SEQSCAN,
130 HINT_KEYWORD_INDEXSCAN,
131 HINT_KEYWORD_INDEXSCANREGEXP,
132 HINT_KEYWORD_BITMAPSCAN,
133 HINT_KEYWORD_BITMAPSCANREGEXP,
134 HINT_KEYWORD_TIDSCAN,
135 HINT_KEYWORD_NOSEQSCAN,
136 HINT_KEYWORD_NOINDEXSCAN,
137 HINT_KEYWORD_NOBITMAPSCAN,
138 HINT_KEYWORD_NOTIDSCAN,
139 HINT_KEYWORD_INDEXONLYSCAN,
140 HINT_KEYWORD_INDEXONLYSCANREGEXP,
141 HINT_KEYWORD_NOINDEXONLYSCAN,
142 HINT_KEYWORD_NESTLOOP,
143 HINT_KEYWORD_MERGEJOIN,
144 HINT_KEYWORD_HASHJOIN,
145 HINT_KEYWORD_NONESTLOOP,
146 HINT_KEYWORD_NOMERGEJOIN,
147 HINT_KEYWORD_NOHASHJOIN,
148 HINT_KEYWORD_LEADING,
151 HINT_KEYWORD_UNRECOGNIZED
154 typedef struct Hint Hint;
155 typedef struct HintState HintState;
157 typedef Hint *(*HintCreateFunction) (const char *hint_str,
159 HintKeyword hint_keyword);
160 typedef void (*HintDeleteFunction) (Hint *hint);
161 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf, bool nolf);
162 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
163 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
164 Query *parse, const char *str);
167 #define NUM_HINT_TYPE 5
168 typedef enum HintType
170 HINT_TYPE_SCAN_METHOD,
171 HINT_TYPE_JOIN_METHOD,
177 static const char *HintTypeName[] = {
186 typedef enum HintStatus
188 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
189 HINT_STATE_USED, /* hint is used */
190 HINT_STATE_DUPLICATION, /* specified hint duplication */
191 HINT_STATE_ERROR /* execute error (parse error does not include
195 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
196 (hint)->base.state == HINT_STATE_USED)
198 static unsigned int qno = 0;
199 static char qnostr[32];
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_ProcessUtility(Node *parsetree,
349 const char *queryString,
350 ParamListInfo params, bool isTopLevel,
352 char *completionTag);
353 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
354 ParamListInfo boundParams);
355 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
356 Oid relationObjectId,
357 bool inhparent, RelOptInfo *rel);
358 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
362 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
363 HintKeyword hint_keyword);
364 static void ScanMethodHintDelete(ScanMethodHint *hint);
365 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
366 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
367 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
368 Query *parse, const char *str);
369 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
370 HintKeyword hint_keyword);
371 static void JoinMethodHintDelete(JoinMethodHint *hint);
372 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
373 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
374 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
375 Query *parse, const char *str);
376 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
377 HintKeyword hint_keyword);
378 static void LeadingHintDelete(LeadingHint *hint);
379 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
380 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
381 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
382 Query *parse, const char *str);
383 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
384 HintKeyword hint_keyword);
385 static void SetHintDelete(SetHint *hint);
386 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
387 static int SetHintCmp(const SetHint *a, const SetHint *b);
388 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
390 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
391 HintKeyword hint_keyword);
392 static void RowsHintDelete(RowsHint *hint);
393 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
394 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
395 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
396 Query *parse, const char *str);
397 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
398 HintKeyword hint_keyword);
400 static void quote_value(StringInfo buf, const char *value);
402 static const char *parse_quoted_value(const char *str, char **word,
405 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
408 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
409 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
410 ListCell *other_rels);
411 static void make_rels_by_clauseless_joins(PlannerInfo *root,
413 ListCell *other_rels);
414 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
415 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
416 Index rti, RangeTblEntry *rte);
417 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
418 List *live_childrels,
419 List *all_child_pathkeys);
420 static Path *get_cheapest_parameterized_child_path(PlannerInfo *root,
422 Relids required_outer);
423 static List *accumulate_append_subpath(List *subpaths, Path *path);
424 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
427 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
429 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
431 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
437 static bool pg_hint_plan_enable_hint = true;
438 static int debug_level = 0;
439 static int pg_hint_plan_message_level = INFO;
440 /* Default is off, to keep backward compatibility. */
441 static bool pg_hint_plan_enable_hint_table = false;
443 /* Internal static variables. */
444 static bool hidestmt = false; /* Allow or inhibit STATEMENT: output */
446 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
447 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
448 /* (This could not be above 1) */
450 static const struct config_enum_entry parse_messages_level_options[] = {
451 {"debug", DEBUG2, true},
452 {"debug5", DEBUG5, false},
453 {"debug4", DEBUG4, false},
454 {"debug3", DEBUG3, false},
455 {"debug2", DEBUG2, false},
456 {"debug1", DEBUG1, false},
458 {"info", INFO, false},
459 {"notice", NOTICE, false},
460 {"warning", WARNING, false},
461 {"error", ERROR, false},
463 * {"fatal", FATAL, true},
464 * {"panic", PANIC, true},
469 static const struct config_enum_entry parse_debug_level_options[] = {
472 {"detailed", 2, false},
473 {"verbose", 3, false},
485 /* Saved hook values in case of unload */
486 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
487 static planner_hook_type prev_planner = NULL;
488 static get_relation_info_hook_type prev_get_relation_info = NULL;
489 static join_search_hook_type prev_join_search = NULL;
491 /* Hold reference to currently active hint */
492 static HintState *current_hint = NULL;
495 * List of hint contexts. We treat the head of the list as the Top of the
496 * context stack, so current_hint always points the first element of this list.
498 static List *HintStateStack = NIL;
501 * Holds statement name during executing EXECUTE command. NULL for other
504 static char *stmt_name = NULL;
506 static const HintParser parsers[] = {
507 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
508 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
509 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
510 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
511 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
512 HINT_KEYWORD_BITMAPSCANREGEXP},
513 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
514 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
515 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
516 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
517 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
518 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
519 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
520 HINT_KEYWORD_INDEXONLYSCANREGEXP},
521 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
522 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
523 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
524 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
525 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
526 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
527 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
528 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
529 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
530 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
531 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
534 PLpgSQL_plugin plugin_funcs = {
538 pg_hint_plan_plpgsql_stmt_beg,
539 pg_hint_plan_plpgsql_stmt_end,
545 * Module load callbacks
550 PLpgSQL_plugin **var_ptr;
552 /* Define custom GUC variables. */
553 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
554 "Force planner to use plans specified in the hint comment preceding to the query.",
556 &pg_hint_plan_enable_hint,
564 DefineCustomEnumVariable("pg_hint_plan.debug_print",
565 "Logs results of hint parsing.",
569 parse_debug_level_options,
576 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
577 "Message level of parse errors.",
579 &pg_hint_plan_message_level,
581 parse_messages_level_options,
588 DefineCustomEnumVariable("pg_hint_plan.message_level",
589 "Message level of debug messages.",
591 &pg_hint_plan_message_level,
593 parse_messages_level_options,
600 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
601 "Force planner to not get hint by using table lookups.",
603 &pg_hint_plan_enable_hint_table,
612 prev_ProcessUtility = ProcessUtility_hook;
613 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
614 prev_planner = planner_hook;
615 planner_hook = pg_hint_plan_planner;
616 prev_get_relation_info = get_relation_info_hook;
617 get_relation_info_hook = pg_hint_plan_get_relation_info;
618 prev_join_search = join_search_hook;
619 join_search_hook = pg_hint_plan_join_search;
621 /* setup PL/pgSQL plugin hook */
622 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
623 *var_ptr = &plugin_funcs;
625 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
629 * Module unload callback
635 PLpgSQL_plugin **var_ptr;
637 /* Uninstall hooks. */
638 ProcessUtility_hook = prev_ProcessUtility;
639 planner_hook = prev_planner;
640 get_relation_info_hook = prev_get_relation_info;
641 join_search_hook = prev_join_search;
643 /* uninstall PL/pgSQL plugin hook */
644 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
649 * create and delete functions the hint object
653 ScanMethodHintCreate(const char *hint_str, const char *keyword,
654 HintKeyword hint_keyword)
656 ScanMethodHint *hint;
658 hint = palloc(sizeof(ScanMethodHint));
659 hint->base.hint_str = hint_str;
660 hint->base.keyword = keyword;
661 hint->base.hint_keyword = hint_keyword;
662 hint->base.type = HINT_TYPE_SCAN_METHOD;
663 hint->base.state = HINT_STATE_NOTUSED;
664 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
665 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
666 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
667 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
668 hint->relname = NULL;
669 hint->indexnames = NIL;
670 hint->regexp = false;
671 hint->enforce_mask = 0;
673 return (Hint *) hint;
677 ScanMethodHintDelete(ScanMethodHint *hint)
683 pfree(hint->relname);
684 list_free_deep(hint->indexnames);
689 JoinMethodHintCreate(const char *hint_str, const char *keyword,
690 HintKeyword hint_keyword)
692 JoinMethodHint *hint;
694 hint = palloc(sizeof(JoinMethodHint));
695 hint->base.hint_str = hint_str;
696 hint->base.keyword = keyword;
697 hint->base.hint_keyword = hint_keyword;
698 hint->base.type = HINT_TYPE_JOIN_METHOD;
699 hint->base.state = HINT_STATE_NOTUSED;
700 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
701 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
702 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
703 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
705 hint->inner_nrels = 0;
706 hint->relnames = NULL;
707 hint->enforce_mask = 0;
708 hint->joinrelids = NULL;
709 hint->inner_joinrelids = NULL;
711 return (Hint *) hint;
715 JoinMethodHintDelete(JoinMethodHint *hint)
724 for (i = 0; i < hint->nrels; i++)
725 pfree(hint->relnames[i]);
726 pfree(hint->relnames);
729 bms_free(hint->joinrelids);
730 bms_free(hint->inner_joinrelids);
735 LeadingHintCreate(const char *hint_str, const char *keyword,
736 HintKeyword hint_keyword)
740 hint = palloc(sizeof(LeadingHint));
741 hint->base.hint_str = hint_str;
742 hint->base.keyword = keyword;
743 hint->base.hint_keyword = hint_keyword;
744 hint->base.type = HINT_TYPE_LEADING;
745 hint->base.state = HINT_STATE_NOTUSED;
746 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
747 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
748 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
749 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
750 hint->relations = NIL;
751 hint->outer_inner = NULL;
753 return (Hint *) hint;
757 LeadingHintDelete(LeadingHint *hint)
762 list_free_deep(hint->relations);
763 if (hint->outer_inner)
764 pfree(hint->outer_inner);
769 SetHintCreate(const char *hint_str, const char *keyword,
770 HintKeyword hint_keyword)
774 hint = palloc(sizeof(SetHint));
775 hint->base.hint_str = hint_str;
776 hint->base.keyword = keyword;
777 hint->base.hint_keyword = hint_keyword;
778 hint->base.type = HINT_TYPE_SET;
779 hint->base.state = HINT_STATE_NOTUSED;
780 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
781 hint->base.desc_func = (HintDescFunction) SetHintDesc;
782 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
783 hint->base.parse_func = (HintParseFunction) SetHintParse;
788 return (Hint *) hint;
792 SetHintDelete(SetHint *hint)
802 list_free(hint->words);
807 RowsHintCreate(const char *hint_str, const char *keyword,
808 HintKeyword hint_keyword)
812 hint = palloc(sizeof(RowsHint));
813 hint->base.hint_str = hint_str;
814 hint->base.keyword = keyword;
815 hint->base.hint_keyword = hint_keyword;
816 hint->base.type = HINT_TYPE_ROWS;
817 hint->base.state = HINT_STATE_NOTUSED;
818 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
819 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
820 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
821 hint->base.parse_func = (HintParseFunction) RowsHintParse;
823 hint->inner_nrels = 0;
824 hint->relnames = NULL;
825 hint->joinrelids = NULL;
826 hint->inner_joinrelids = NULL;
827 hint->rows_str = NULL;
828 hint->value_type = RVT_ABSOLUTE;
831 return (Hint *) hint;
835 RowsHintDelete(RowsHint *hint)
844 for (i = 0; i < hint->nrels; i++)
845 pfree(hint->relnames[i]);
846 pfree(hint->relnames);
849 bms_free(hint->joinrelids);
850 bms_free(hint->inner_joinrelids);
855 HintStateCreate(void)
859 hstate = palloc(sizeof(HintState));
860 hstate->hint_str = NULL;
861 hstate->nall_hints = 0;
862 hstate->max_all_hints = 0;
863 hstate->all_hints = NULL;
864 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
865 hstate->scan_hints = NULL;
866 hstate->init_scan_mask = 0;
867 hstate->parent_relid = 0;
868 hstate->parent_hint = NULL;
869 hstate->parent_index_infos = NIL;
870 hstate->join_hints = NULL;
871 hstate->init_join_mask = 0;
872 hstate->join_hint_level = NULL;
873 hstate->leading_hint = NULL;
874 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
875 hstate->set_hints = NULL;
876 hstate->rows_hints = NULL;
882 HintStateDelete(HintState *hstate)
889 if (hstate->hint_str)
890 pfree(hstate->hint_str);
892 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
893 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
894 if (hstate->all_hints)
895 pfree(hstate->all_hints);
896 if (hstate->parent_index_infos)
897 list_free(hstate->parent_index_infos);
901 * Copy given value into buf, with quoting with '"' if necessary.
904 quote_value(StringInfo buf, const char *value)
906 bool need_quote = false;
909 for (str = value; *str != '\0'; str++)
911 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
914 appendStringInfoCharMacro(buf, '"');
919 for (str = value; *str != '\0'; str++)
922 appendStringInfoCharMacro(buf, '"');
924 appendStringInfoCharMacro(buf, *str);
928 appendStringInfoCharMacro(buf, '"');
932 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
936 appendStringInfo(buf, "%s(", hint->base.keyword);
937 if (hint->relname != NULL)
939 quote_value(buf, hint->relname);
940 foreach(l, hint->indexnames)
942 appendStringInfoCharMacro(buf, ' ');
943 quote_value(buf, (char *) lfirst(l));
946 appendStringInfoString(buf, ")");
948 appendStringInfoChar(buf, '\n');
952 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
956 appendStringInfo(buf, "%s(", hint->base.keyword);
957 if (hint->relnames != NULL)
959 quote_value(buf, hint->relnames[0]);
960 for (i = 1; i < hint->nrels; i++)
962 appendStringInfoCharMacro(buf, ' ');
963 quote_value(buf, hint->relnames[i]);
966 appendStringInfoString(buf, ")");
968 appendStringInfoChar(buf, '\n');
973 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
975 if (outer_inner->relation == NULL)
982 appendStringInfoCharMacro(buf, '(');
983 foreach(l, outer_inner->outer_inner_pair)
988 appendStringInfoCharMacro(buf, ' ');
990 OuterInnerDesc(lfirst(l), buf);
993 appendStringInfoCharMacro(buf, ')');
996 quote_value(buf, outer_inner->relation);
1000 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
1002 appendStringInfo(buf, "%s(", HINT_LEADING);
1003 if (hint->outer_inner == NULL)
1010 foreach(l, hint->relations)
1015 appendStringInfoCharMacro(buf, ' ');
1017 quote_value(buf, (char *) lfirst(l));
1021 OuterInnerDesc(hint->outer_inner, buf);
1023 appendStringInfoString(buf, ")");
1025 appendStringInfoChar(buf, '\n');
1029 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1031 bool is_first = true;
1034 appendStringInfo(buf, "%s(", HINT_SET);
1035 foreach(l, hint->words)
1040 appendStringInfoCharMacro(buf, ' ');
1042 quote_value(buf, (char *) lfirst(l));
1044 appendStringInfo(buf, ")");
1046 appendStringInfoChar(buf, '\n');
1050 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1054 appendStringInfo(buf, "%s(", hint->base.keyword);
1055 if (hint->relnames != NULL)
1057 quote_value(buf, hint->relnames[0]);
1058 for (i = 1; i < hint->nrels; i++)
1060 appendStringInfoCharMacro(buf, ' ');
1061 quote_value(buf, hint->relnames[i]);
1064 appendStringInfo(buf, " %s", hint->rows_str);
1065 appendStringInfoString(buf, ")");
1067 appendStringInfoChar(buf, '\n');
1071 * Append string which represents all hints in a given state to buf, with
1072 * preceding title with them.
1075 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1076 HintStatus state, bool nolf)
1080 appendStringInfo(buf, "%s:", title);
1082 appendStringInfoChar(buf, '\n');
1085 for (i = 0; i < hstate->nall_hints; i++)
1087 if (hstate->all_hints[i]->state != state)
1090 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1094 if (nolf && nshown == 0)
1095 appendStringInfoString(buf, "(none)");
1099 * Dump contents of given hstate to server log with log level LOG.
1102 HintStateDump(HintState *hstate)
1108 elog(LOG, "pg_hint_plan:\nno hint");
1112 initStringInfo(&buf);
1114 appendStringInfoString(&buf, "pg_hint_plan:\n");
1115 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1116 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1117 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1118 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1120 elog(LOG, "%s", buf.data);
1126 HintStateDump2(HintState *hstate)
1132 elog(pg_hint_plan_message_level,
1133 "pg_hint_plan%s: HintStateDump:\nno hint", qnostr);
1137 initStringInfo(&buf);
1138 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1139 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1140 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1141 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1142 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1143 appendStringInfoChar(&buf, '}');
1145 ereport(pg_hint_plan_message_level,
1147 errmsg("%s", buf.data)));
1157 RelnameCmp(const void *a, const void *b)
1159 const char *relnamea = *((const char **) a);
1160 const char *relnameb = *((const char **) b);
1162 return strcmp(relnamea, relnameb);
1166 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1168 return RelnameCmp(&a->relname, &b->relname);
1172 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1176 if (a->nrels != b->nrels)
1177 return a->nrels - b->nrels;
1179 for (i = 0; i < a->nrels; i++)
1182 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1190 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1196 SetHintCmp(const SetHint *a, const SetHint *b)
1198 return strcmp(a->name, b->name);
1202 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1206 if (a->nrels != b->nrels)
1207 return a->nrels - b->nrels;
1209 for (i = 0; i < a->nrels; i++)
1212 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1220 HintCmp(const void *a, const void *b)
1222 const Hint *hinta = *((const Hint **) a);
1223 const Hint *hintb = *((const Hint **) b);
1225 if (hinta->type != hintb->type)
1226 return hinta->type - hintb->type;
1227 if (hinta->state == HINT_STATE_ERROR)
1229 if (hintb->state == HINT_STATE_ERROR)
1231 return hinta->cmp_func(hinta, hintb);
1235 * Returns byte offset of hint b from hint a. If hint a was specified before
1236 * b, positive value is returned.
1239 HintCmpWithPos(const void *a, const void *b)
1241 const Hint *hinta = *((const Hint **) a);
1242 const Hint *hintb = *((const Hint **) b);
1245 result = HintCmp(a, b);
1247 result = hinta->hint_str - hintb->hint_str;
1256 parse_keyword(const char *str, StringInfo buf)
1260 while (!isspace(*str) && *str != '(' && *str != '\0')
1261 appendStringInfoCharMacro(buf, *str++);
1267 skip_parenthesis(const char *str, char parenthesis)
1271 if (*str != parenthesis)
1273 if (parenthesis == '(')
1274 hint_ereport(str, ("Opening parenthesis is necessary."));
1275 else if (parenthesis == ')')
1276 hint_ereport(str, ("Closing parenthesis is necessary."));
1287 * Parse a token from str, and store malloc'd copy into word. A token can be
1288 * quoted with '"'. Return value is pointer to unparsed portion of original
1289 * string, or NULL if an error occurred.
1291 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1294 parse_quoted_value(const char *str, char **word, bool truncate)
1299 /* Skip leading spaces. */
1302 initStringInfo(&buf);
1315 /* Double quotation must be closed. */
1319 hint_ereport(str, ("Unterminated quoted string."));
1324 * Skip escaped double quotation.
1326 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1327 * block comments) to be an object name, so users must specify
1328 * alias for such object names.
1330 * Those special names can be allowed if we care escaped slashes
1331 * and asterisks, but we don't.
1340 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1344 appendStringInfoCharMacro(&buf, *str++);
1349 hint_ereport(str, ("Zero-length delimited string."));
1356 /* Truncate name if it's too long */
1358 truncate_identifier(buf.data, strlen(buf.data), true);
1365 static OuterInnerRels *
1366 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1368 OuterInnerRels *outer_inner;
1370 outer_inner = palloc(sizeof(OuterInnerRels));
1371 outer_inner->relation = name;
1372 outer_inner->outer_inner_pair = outer_inner_list;
1378 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1380 List *outer_inner_pair = NIL;
1382 if ((str = skip_parenthesis(str, '(')) == NULL)
1387 /* Store words in parentheses into outer_inner_list. */
1388 while(*str != ')' && *str != '\0')
1390 OuterInnerRels *outer_inner_rels;
1394 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1402 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1405 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1408 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1413 (str = skip_parenthesis(str, ')')) == NULL)
1415 list_free(outer_inner_pair);
1419 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1425 parse_parentheses_Leading(const char *str, List **name_list,
1426 OuterInnerRels **outer_inner)
1429 bool truncate = true;
1431 if ((str = skip_parenthesis(str, '(')) == NULL)
1437 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1442 /* Store words in parentheses into name_list. */
1443 while(*str != ')' && *str != '\0')
1445 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1447 list_free(*name_list);
1451 *name_list = lappend(*name_list, name);
1456 if ((str = skip_parenthesis(str, ')')) == NULL)
1462 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1465 bool truncate = true;
1467 if ((str = skip_parenthesis(str, '(')) == NULL)
1472 /* Store words in parentheses into name_list. */
1473 while(*str != ')' && *str != '\0')
1475 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1477 list_free(*name_list);
1481 *name_list = lappend(*name_list, name);
1484 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1485 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1486 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1487 keyword == HINT_KEYWORD_SET)
1493 if ((str = skip_parenthesis(str, ')')) == NULL)
1499 parse_hints(HintState *hstate, Query *parse, const char *str)
1504 initStringInfo(&buf);
1505 while (*str != '\0')
1507 const HintParser *parser;
1509 /* in error message, we output the comment including the keyword. */
1510 head = (char *) str;
1512 /* parse only the keyword of the hint. */
1513 resetStringInfo(&buf);
1514 str = parse_keyword(str, &buf);
1516 for (parser = parsers; parser->keyword != NULL; parser++)
1518 char *keyword = parser->keyword;
1521 if (strcasecmp(buf.data, keyword) != 0)
1524 hint = parser->create_func(head, keyword, parser->hint_keyword);
1526 /* parser of each hint does parse in a parenthesis. */
1527 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1529 hint->delete_func(hint);
1535 * Add hint information into all_hints array. If we don't have
1536 * enough space, double the array.
1538 if (hstate->nall_hints == 0)
1540 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1541 hstate->all_hints = (Hint **)
1542 palloc(sizeof(Hint *) * hstate->max_all_hints);
1544 else if (hstate->nall_hints == hstate->max_all_hints)
1546 hstate->max_all_hints *= 2;
1547 hstate->all_hints = (Hint **)
1548 repalloc(hstate->all_hints,
1549 sizeof(Hint *) * hstate->max_all_hints);
1552 hstate->all_hints[hstate->nall_hints] = hint;
1553 hstate->nall_hints++;
1560 if (parser->keyword == NULL)
1563 ("Unrecognized hint keyword \"%s\".", buf.data));
1574 * Get hints from table by client-supplied query string and application name.
1577 get_hints_from_table(const char *client_query, const char *client_application)
1579 const char *search_query =
1581 " FROM hint_plan.hints "
1582 " WHERE norm_query_string = $1 "
1583 " AND ( application_name = $2 "
1584 " OR application_name = '' ) "
1585 " ORDER BY application_name DESC";
1586 static SPIPlanPtr plan = NULL;
1588 Oid argtypes[2] = { TEXTOID, TEXTOID };
1590 bool nulls[2] = { false, false };
1596 hint_inhibit_level++;
1603 p = SPI_prepare(search_query, 2, argtypes);
1604 plan = SPI_saveplan(p);
1608 qry = cstring_to_text(client_query);
1609 app = cstring_to_text(client_application);
1610 values[0] = PointerGetDatum(qry);
1611 values[1] = PointerGetDatum(app);
1613 SPI_execute_plan(plan, values, nulls, true, 1);
1615 if (SPI_processed > 0)
1619 hints = SPI_getvalue(SPI_tuptable->vals[0],
1620 SPI_tuptable->tupdesc, 1);
1622 * Here we use SPI_palloc to ensure that hints string is valid even
1623 * after SPI_finish call. We can't use simple palloc because it
1624 * allocates memory in SPI's context and that context is deleted in
1627 buf = SPI_palloc(strlen(hints) + 1);
1634 hint_inhibit_level--;
1638 hint_inhibit_level--;
1647 * Get client-supplied query string.
1650 get_query_string(void)
1654 if (plpgsql_recurse_level > 0)
1657 * This is quite ugly but this is the only point I could find where
1658 * we can get the query string.
1660 p = (char*)error_context_stack->arg;
1664 PreparedStatement *entry;
1666 entry = FetchPreparedStatement(stmt_name, true);
1667 p = entry->plansource->query_string;
1670 p = debug_query_string;
1676 * Get hints from the head block comment in client-supplied query string.
1679 get_hints_from_comment(const char *p)
1681 const char *hint_head;
1689 /* extract query head comment. */
1690 hint_head = strstr(p, HINT_START);
1691 if (hint_head == NULL)
1693 for (;p < hint_head; p++)
1696 * Allow these characters precedes hint comment:
1698 * - alphabets which are in ASCII range
1699 * - space, tabs and new-lines
1700 * - underscores, for identifier
1701 * - commas, for SELECT clause, EXPLAIN and PREPARE
1702 * - parentheses, for EXPLAIN and PREPARE
1704 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1705 * avoid behavior which depends on locale setting.
1707 if (!(*p >= '0' && *p <= '9') &&
1708 !(*p >= 'A' && *p <= 'Z') &&
1709 !(*p >= 'a' && *p <= 'z') &&
1713 *p != '(' && *p != ')')
1717 len = strlen(HINT_START);
1722 /* find hint end keyword. */
1723 if ((tail = strstr(p, HINT_END)) == NULL)
1725 hint_ereport(head, ("Unterminated block comment."));
1729 /* We don't support nested block comments. */
1730 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1732 hint_ereport(head, ("Nested block comments are not supported."));
1736 /* Make a copy of hint. */
1738 head = palloc(len + 1);
1739 memcpy(head, p, len);
1747 * Parse hints that got, create hint struct from parse tree and parse hints.
1750 create_hintstate(Query *parse, const char *hints)
1760 hstate = HintStateCreate();
1761 hstate->hint_str = (char *) hints;
1763 /* parse each hint. */
1764 parse_hints(hstate, parse, p);
1766 /* When nothing specified a hint, we free HintState and returns NULL. */
1767 if (hstate->nall_hints == 0)
1769 HintStateDelete(hstate);
1773 /* Sort hints in order of original position. */
1774 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1777 /* Count number of hints per hint-type. */
1778 for (i = 0; i < hstate->nall_hints; i++)
1780 Hint *cur_hint = hstate->all_hints[i];
1781 hstate->num_hints[cur_hint->type]++;
1785 * If an object (or a set of objects) has multiple hints of same hint-type,
1786 * only the last hint is valid and others are ignored in planning.
1787 * Hints except the last are marked as 'duplicated' to remember the order.
1789 for (i = 0; i < hstate->nall_hints - 1; i++)
1791 Hint *cur_hint = hstate->all_hints[i];
1792 Hint *next_hint = hstate->all_hints[i + 1];
1795 * Leading hint is marked as 'duplicated' in transform_join_hints.
1797 if (cur_hint->type == HINT_TYPE_LEADING &&
1798 next_hint->type == HINT_TYPE_LEADING)
1802 * Note that we need to pass addresses of hint pointers, because
1803 * HintCmp is designed to sort array of Hint* by qsort.
1805 if (HintCmp(&cur_hint, &next_hint) == 0)
1807 hint_ereport(cur_hint->hint_str,
1808 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1809 cur_hint->state = HINT_STATE_DUPLICATION;
1814 * Make sure that per-type array pointers point proper position in the
1815 * array which consists of all hints.
1817 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1818 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1819 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1820 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1821 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1822 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1823 hstate->num_hints[HINT_TYPE_LEADING]);
1824 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
1825 hstate->num_hints[HINT_TYPE_SET]);
1831 * Parse inside of parentheses of scan-method hints.
1834 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1837 const char *keyword = hint->base.keyword;
1838 HintKeyword hint_keyword = hint->base.hint_keyword;
1839 List *name_list = NIL;
1842 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1845 /* Parse relation name and index name(s) if given hint accepts. */
1846 length = list_length(name_list);
1849 hint->relname = linitial(name_list);
1850 hint->indexnames = list_delete_first(name_list);
1852 /* check whether the hint accepts index name(s). */
1854 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1855 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1856 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1857 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1858 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1859 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1862 ("%s hint accepts only one relation.",
1863 hint->base.keyword));
1864 hint->base.state = HINT_STATE_ERROR;
1871 ("%s hint requires a relation.",
1872 hint->base.keyword));
1873 hint->base.state = HINT_STATE_ERROR;
1877 /* Set a bit for specified hint. */
1878 switch (hint_keyword)
1880 case HINT_KEYWORD_SEQSCAN:
1881 hint->enforce_mask = ENABLE_SEQSCAN;
1883 case HINT_KEYWORD_INDEXSCAN:
1884 hint->enforce_mask = ENABLE_INDEXSCAN;
1886 case HINT_KEYWORD_INDEXSCANREGEXP:
1887 hint->enforce_mask = ENABLE_INDEXSCAN;
1888 hint->regexp = true;
1890 case HINT_KEYWORD_BITMAPSCAN:
1891 hint->enforce_mask = ENABLE_BITMAPSCAN;
1893 case HINT_KEYWORD_BITMAPSCANREGEXP:
1894 hint->enforce_mask = ENABLE_BITMAPSCAN;
1895 hint->regexp = true;
1897 case HINT_KEYWORD_TIDSCAN:
1898 hint->enforce_mask = ENABLE_TIDSCAN;
1900 case HINT_KEYWORD_NOSEQSCAN:
1901 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1903 case HINT_KEYWORD_NOINDEXSCAN:
1904 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1906 case HINT_KEYWORD_NOBITMAPSCAN:
1907 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1909 case HINT_KEYWORD_NOTIDSCAN:
1910 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1912 case HINT_KEYWORD_INDEXONLYSCAN:
1913 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1915 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1916 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1917 hint->regexp = true;
1919 case HINT_KEYWORD_NOINDEXONLYSCAN:
1920 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1923 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1932 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1935 const char *keyword = hint->base.keyword;
1936 HintKeyword hint_keyword = hint->base.hint_keyword;
1937 List *name_list = NIL;
1939 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1942 hint->nrels = list_length(name_list);
1944 if (hint->nrels > 0)
1950 * Transform relation names from list to array to sort them with qsort
1953 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1954 foreach (l, name_list)
1956 hint->relnames[i] = lfirst(l);
1961 list_free(name_list);
1963 /* A join hint requires at least two relations */
1964 if (hint->nrels < 2)
1967 ("%s hint requires at least two relations.",
1968 hint->base.keyword));
1969 hint->base.state = HINT_STATE_ERROR;
1973 /* Sort hints in alphabetical order of relation names. */
1974 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1976 switch (hint_keyword)
1978 case HINT_KEYWORD_NESTLOOP:
1979 hint->enforce_mask = ENABLE_NESTLOOP;
1981 case HINT_KEYWORD_MERGEJOIN:
1982 hint->enforce_mask = ENABLE_MERGEJOIN;
1984 case HINT_KEYWORD_HASHJOIN:
1985 hint->enforce_mask = ENABLE_HASHJOIN;
1987 case HINT_KEYWORD_NONESTLOOP:
1988 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1990 case HINT_KEYWORD_NOMERGEJOIN:
1991 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1993 case HINT_KEYWORD_NOHASHJOIN:
1994 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1997 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2006 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2009 if (outer_inner->outer_inner_pair == NIL)
2011 if (outer_inner->relation)
2017 if (list_length(outer_inner->outer_inner_pair) == 2)
2019 foreach(l, outer_inner->outer_inner_pair)
2021 if (!OuterInnerPairCheck(lfirst(l)))
2032 OuterInnerList(OuterInnerRels *outer_inner)
2034 List *outer_inner_list = NIL;
2036 OuterInnerRels *outer_inner_rels;
2038 foreach(l, outer_inner->outer_inner_pair)
2040 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2042 if (outer_inner_rels->relation != NULL)
2043 outer_inner_list = lappend(outer_inner_list,
2044 outer_inner_rels->relation);
2046 outer_inner_list = list_concat(outer_inner_list,
2047 OuterInnerList(outer_inner_rels));
2049 return outer_inner_list;
2053 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2056 List *name_list = NIL;
2057 OuterInnerRels *outer_inner = NULL;
2059 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2063 if (outer_inner != NULL)
2064 name_list = OuterInnerList(outer_inner);
2066 hint->relations = name_list;
2067 hint->outer_inner = outer_inner;
2069 /* A Leading hint requires at least two relations */
2070 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2072 hint_ereport(hint->base.hint_str,
2073 ("%s hint requires at least two relations.",
2075 hint->base.state = HINT_STATE_ERROR;
2077 else if (hint->outer_inner != NULL &&
2078 !OuterInnerPairCheck(hint->outer_inner))
2080 hint_ereport(hint->base.hint_str,
2081 ("%s hint requires two sets of relations when parentheses nests.",
2083 hint->base.state = HINT_STATE_ERROR;
2090 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2092 List *name_list = NIL;
2094 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2098 hint->words = name_list;
2100 /* We need both name and value to set GUC parameter. */
2101 if (list_length(name_list) == 2)
2103 hint->name = linitial(name_list);
2104 hint->value = lsecond(name_list);
2108 hint_ereport(hint->base.hint_str,
2109 ("%s hint requires name and value of GUC parameter.",
2111 hint->base.state = HINT_STATE_ERROR;
2118 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2121 HintKeyword hint_keyword = hint->base.hint_keyword;
2122 List *name_list = NIL;
2126 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2129 /* Last element must be rows specification */
2130 hint->nrels = list_length(name_list) - 1;
2132 if (hint->nrels > 0)
2138 * Transform relation names from list to array to sort them with qsort
2141 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2142 foreach (l, name_list)
2144 if (hint->nrels <= i)
2146 hint->relnames[i] = lfirst(l);
2151 /* Retieve rows estimation */
2152 rows_str = list_nth(name_list, hint->nrels);
2153 hint->rows_str = rows_str; /* store as-is for error logging */
2154 if (rows_str[0] == '#')
2156 hint->value_type = RVT_ABSOLUTE;
2159 else if (rows_str[0] == '+')
2161 hint->value_type = RVT_ADD;
2164 else if (rows_str[0] == '-')
2166 hint->value_type = RVT_SUB;
2169 else if (rows_str[0] == '*')
2171 hint->value_type = RVT_MULTI;
2176 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2177 hint->base.state = HINT_STATE_ERROR;
2180 hint->rows = strtod(rows_str, &end_ptr);
2183 hint_ereport(rows_str,
2184 ("%s hint requires valid number as rows estimation.",
2185 hint->base.keyword));
2186 hint->base.state = HINT_STATE_ERROR;
2190 /* A join hint requires at least two relations */
2191 if (hint->nrels < 2)
2194 ("%s hint requires at least two relations.",
2195 hint->base.keyword));
2196 hint->base.state = HINT_STATE_ERROR;
2200 list_free(name_list);
2202 /* Sort relnames in alphabetical order. */
2203 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2209 * set GUC parameter functions
2213 set_config_option_wrapper(const char *name, const char *value,
2214 GucContext context, GucSource source,
2215 GucAction action, bool changeVal, int elevel)
2218 MemoryContext ccxt = CurrentMemoryContext;
2222 result = set_config_option(name, value, context, source,
2223 action, changeVal, 0);
2229 /* Save error info */
2230 MemoryContextSwitchTo(ccxt);
2231 errdata = CopyErrorData();
2235 (errcode(errdata->sqlerrcode),
2236 errhidestmt(hidestmt),
2237 errmsg("%s", errdata->message),
2238 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2239 errdata->hint ? errhint("%s", errdata->hint) : 0));
2240 FreeErrorData(errdata);
2248 set_config_options(SetHint **options, int noptions, GucContext context)
2253 save_nestlevel = NewGUCNestLevel();
2255 for (i = 0; i < noptions; i++)
2257 SetHint *hint = options[i];
2260 if (!hint_state_enabled(hint))
2263 result = set_config_option_wrapper(hint->name, hint->value, context,
2264 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2265 pg_hint_plan_message_level);
2267 hint->base.state = HINT_STATE_USED;
2269 hint->base.state = HINT_STATE_ERROR;
2272 return save_nestlevel;
2275 #define SET_CONFIG_OPTION(name, type_bits) \
2276 set_config_option_wrapper((name), \
2277 (mask & (type_bits)) ? "true" : "false", \
2278 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2281 set_scan_config_options(unsigned char enforce_mask, GucContext context)
2285 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2286 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2287 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2289 mask = enforce_mask;
2291 mask = enforce_mask & current_hint->init_scan_mask;
2293 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2294 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2295 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2296 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2297 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2301 set_join_config_options(unsigned char enforce_mask, GucContext context)
2305 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2306 enforce_mask == ENABLE_HASHJOIN)
2307 mask = enforce_mask;
2309 mask = enforce_mask & current_hint->init_join_mask;
2311 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2312 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2313 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2317 * pg_hint_plan hook functions
2321 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
2322 ParamListInfo params, bool isTopLevel,
2323 DestReceiver *dest, char *completionTag)
2328 * Use standard planner if pg_hint_plan is disabled or current nesting
2329 * depth is nesting depth of SPI calls.
2331 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2333 if (debug_level > 1)
2334 ereport(pg_hint_plan_message_level,
2335 (errmsg ("pg_hint_plan: ProcessUtility:"
2336 " pg_hint_plan.enable_hint = off")));
2337 if (prev_ProcessUtility)
2338 (*prev_ProcessUtility) (parsetree, queryString, params,
2339 isTopLevel, dest, completionTag);
2341 standard_ProcessUtility(parsetree, queryString, params,
2342 isTopLevel, dest, completionTag);
2348 if (IsA(node, ExplainStmt))
2351 * Draw out parse tree of actual query from Query struct of EXPLAIN
2357 stmt = (ExplainStmt *) node;
2359 Assert(IsA(stmt->query, Query));
2360 query = (Query *) stmt->query;
2362 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2363 node = query->utilityStmt;
2367 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2368 * specified to preceding PREPARE command to use it as source of hints.
2370 if (IsA(node, ExecuteStmt))
2374 stmt = (ExecuteStmt *) node;
2375 stmt_name = stmt->name;
2379 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2382 if (IsA(node, CreateTableAsStmt))
2384 CreateTableAsStmt *stmt;
2387 stmt = (CreateTableAsStmt *) node;
2388 Assert(IsA(stmt->query, Query));
2389 query = (Query *) stmt->query;
2391 if (query->commandType == CMD_UTILITY &&
2392 IsA(query->utilityStmt, ExecuteStmt))
2394 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2395 stmt_name = estmt->name;
2401 if (debug_level > 1)
2402 ereport(pg_hint_plan_message_level,
2403 (errmsg ("pg_hint_plan: ProcessUtility:"
2404 " stmt_name = \"%s\", statement=\"%s\"",
2405 stmt_name, queryString)));
2408 if (prev_ProcessUtility)
2409 (*prev_ProcessUtility) (parsetree, queryString, params,
2410 isTopLevel, dest, completionTag);
2412 standard_ProcessUtility(parsetree, queryString, params,
2413 isTopLevel, dest, completionTag);
2427 if (prev_ProcessUtility)
2428 (*prev_ProcessUtility) (parsetree, queryString, params,
2429 isTopLevel, dest, completionTag);
2431 standard_ProcessUtility(parsetree, queryString, params,
2432 isTopLevel, dest, completionTag);
2436 * Push a hint into hint stack which is implemented with List struct. Head of
2437 * list is top of stack.
2440 push_hint(HintState *hstate)
2442 /* Prepend new hint to the list means pushing to stack. */
2443 HintStateStack = lcons(hstate, HintStateStack);
2445 /* Pushed hint is the one which should be used hereafter. */
2446 current_hint = hstate;
2449 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2453 /* Hint stack must not be empty. */
2454 if(HintStateStack == NIL)
2455 elog(ERROR, "hint stack is empty");
2458 * Take a hint at the head from the list, and free it. Switch current_hint
2459 * to point new head (NULL if the list is empty).
2461 HintStateStack = list_delete_first(HintStateStack);
2462 HintStateDelete(current_hint);
2463 if(HintStateStack == NIL)
2464 current_hint = NULL;
2466 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2469 static PlannedStmt *
2470 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2472 const char *hints = NULL;
2475 pgssJumbleState jstate;
2478 PlannedStmt *result;
2484 if (debug_level > 1)
2485 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2489 * Use standard planner if pg_hint_plan is disabled or current nesting
2490 * depth is nesting depth of SPI calls. Other hook functions try to change
2491 * plan with current_hint if any, so set it to NULL.
2493 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2495 if (debug_level > 1)
2496 elog(pg_hint_plan_message_level,
2497 "pg_hint_plan%s: planner: enable_hint=%d,"
2498 " hint_inhibit_level=%d",
2499 qnostr, pg_hint_plan_enable_hint, hint_inhibit_level);
2502 goto standard_planner_proc;
2505 /* Create hint struct from client-supplied query string. */
2506 query = get_query_string();
2509 * Create hintstate from hint specified for the query, if any.
2511 * First we lookup hint in pg_hint.hints table by normalized query string,
2512 * unless pg_hint_plan.enable_hint_table is OFF.
2513 * This parameter provides option to avoid overhead of table lookup during
2516 * If no hint was found, then we try to get hint from special query comment.
2518 if (pg_hint_plan_enable_hint_table)
2521 * Search hint information which is stored for the query and the
2522 * application. Query string is normalized before using in condition
2523 * in order to allow fuzzy matching.
2525 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2526 * careful when supporting PostgreSQL's version up.
2528 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2529 jstate.jumble_len = 0;
2530 jstate.clocations_buf_size = 32;
2531 jstate.clocations = (pgssLocationLen *)
2532 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2533 jstate.clocations_count = 0;
2534 JumbleQuery(&jstate, parse);
2536 * generate_normalized_query() copies exact given query_len bytes, so we
2537 * add 1 byte for null-termination here. As comments on
2538 * generate_normalized_query says, generate_normalized_query doesn't
2539 * take care of null-terminate, but additional 1 byte ensures that '\0'
2540 * byte in the source buffer to be copied into norm_query.
2542 query_len = strlen(query) + 1;
2543 norm_query = generate_normalized_query(&jstate,
2546 GetDatabaseEncoding());
2547 hints = get_hints_from_table(norm_query, application_name);
2548 if (debug_level > 1)
2551 snprintf(msgstr, 1024, "hints from table: \"%s\":"
2552 " normalzed_query=\"%s\", application name =\"%s\"",
2553 hints, norm_query, application_name);
2556 ereport(pg_hint_plan_message_level,
2557 (errhidestmt(hidestmt),
2558 errmsg("pg_hint_plan%s:"
2559 " no match found in table:"
2560 " application name = \"%s\","
2561 " normalzed_query=\"%s\"",
2562 qnostr, application_name, norm_query)));
2569 hints = get_hints_from_comment(query);
2571 if (debug_level > 1)
2573 snprintf(msgstr, 1024, "hints in comment=\"%s\"",
2574 hints ? hints : "(none)");
2575 if (debug_level > 2 ||
2576 stmt_name || strcmp(query, debug_query_string))
2577 snprintf(msgstr + strlen(msgstr), 1024- strlen(msgstr),
2578 ", stmt=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2579 stmt_name, query, debug_query_string);
2583 hstate = create_hintstate(parse, hints);
2586 * Use standard planner if the statement has not valid hint. Other hook
2587 * functions try to change plan with current_hint if any, so set it to
2591 goto standard_planner_proc;
2594 * Push new hint struct to the hint stack to disable previous hint context.
2598 /* Set GUC parameters which are specified with Set hint. */
2599 save_nestlevel = set_config_options(current_hint->set_hints,
2600 current_hint->num_hints[HINT_TYPE_SET],
2601 current_hint->context);
2604 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2605 if (enable_indexscan)
2606 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2607 if (enable_bitmapscan)
2608 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2610 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2611 if (enable_indexonlyscan)
2612 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2613 if (enable_nestloop)
2614 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2615 if (enable_mergejoin)
2616 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2617 if (enable_hashjoin)
2618 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2620 if (debug_level > 1)
2622 ereport(pg_hint_plan_message_level,
2623 (errhidestmt(hidestmt),
2624 errmsg("pg_hint_plan%s: planner: %s",
2629 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2630 * state when this planner started when error occurred in planner.
2635 result = (*prev_planner) (parse, cursorOptions, boundParams);
2637 result = standard_planner(parse, cursorOptions, boundParams);
2642 * Rollback changes of GUC parameters, and pop current hint context
2643 * from hint stack to rewind the state.
2645 AtEOXact_GUC(true, save_nestlevel);
2651 /* Print hint in debug mode. */
2652 if (debug_level == 1)
2653 HintStateDump(current_hint);
2654 else if (debug_level == 2)
2655 HintStateDump2(current_hint);
2658 * Rollback changes of GUC parameters, and pop current hint context from
2659 * hint stack to rewind the state.
2661 AtEOXact_GUC(true, save_nestlevel);
2666 standard_planner_proc:
2667 if (debug_level > 1)
2669 ereport(pg_hint_plan_message_level,
2670 (errhidestmt(hidestmt),
2671 errmsg("pg_hint_plan%s: planner: no valid hint (%s)",
2675 current_hint = NULL;
2677 return (*prev_planner) (parse, cursorOptions, boundParams);
2679 return standard_planner(parse, cursorOptions, boundParams);
2683 * Return scan method hint which matches given aliasname.
2685 static ScanMethodHint *
2686 find_scan_hint(PlannerInfo *root, Index relid, RelOptInfo *rel)
2692 * We can't apply scan method hint if the relation is:
2693 * - not a base relation
2694 * - not an ordinary relation (such as join and subquery)
2696 if (rel && (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION))
2699 rte = root->simple_rte_array[relid];
2701 /* We can't force scan method of foreign tables */
2702 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2705 /* Find scan method hint, which matches given names, from the list. */
2706 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2708 ScanMethodHint *hint = current_hint->scan_hints[i];
2710 /* We ignore disabled hints. */
2711 if (!hint_state_enabled(hint))
2714 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2724 * Returns TRUE on match, FALSE on no match.
2726 * s1 --- the data to match against
2727 * s2 --- the pattern
2729 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2732 regexpeq(const char *s1, const char *s2)
2738 strcpy(name.data, s1);
2739 regexp = cstring_to_text(s2);
2741 result = DirectFunctionCall2Coll(nameregexeq,
2742 DEFAULT_COLLATION_OID,
2743 NameGetDatum(&name),
2744 PointerGetDatum(regexp));
2745 return DatumGetBool(result);
2749 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2757 * We delete all the IndexOptInfo list and prevent you from being usable by
2760 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2761 hint->enforce_mask == ENABLE_TIDSCAN)
2763 list_free_deep(rel->indexlist);
2764 rel->indexlist = NIL;
2765 hint->base.state = HINT_STATE_USED;
2771 * When a list of indexes is not specified, we just use all indexes.
2773 if (hint->indexnames == NIL)
2777 * Leaving only an specified index, we delete it from a IndexOptInfo list
2781 if (debug_level > 0)
2782 initStringInfo(&buf);
2784 for (cell = list_head(rel->indexlist); cell; cell = next)
2786 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2787 char *indexname = get_rel_name(info->indexoid);
2789 bool use_index = false;
2793 foreach(l, hint->indexnames)
2795 char *hintname = (char *) lfirst(l);
2799 result = regexpeq(indexname, hintname);
2801 result = RelnameCmp(&indexname, &hintname) == 0;
2806 if (debug_level > 0)
2808 appendStringInfoCharMacro(&buf, ' ');
2809 quote_value(&buf, indexname);
2817 * to make the index a candidate when definition of this index is
2818 * matched with the index's definition of current_hint.
2820 if (OidIsValid(relationObjectId) && !use_index)
2822 foreach(l, current_hint->parent_index_infos)
2826 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2828 /* check to match the parameter of unique */
2829 if (p_info->indisunique != info->unique)
2832 /* check to match the parameter of index's method */
2833 if (p_info->method != info->relam)
2836 /* to check to match the indexkey's configuration */
2837 if ((list_length(p_info->column_names)) !=
2841 /* check to match the indexkey's configuration */
2842 for (i = 0; i < info->ncolumns; i++)
2844 char *c_attname = NULL;
2845 char *p_attname = NULL;
2848 list_nth(p_info->column_names, i);
2850 /* both are expressions */
2851 if (info->indexkeys[i] == 0 && !p_attname)
2854 /* one's column is expression, the other is not */
2855 if (info->indexkeys[i] == 0 || !p_attname)
2858 c_attname = get_attname(relationObjectId,
2859 info->indexkeys[i]);
2861 if (strcmp(p_attname, c_attname) != 0)
2864 if (p_info->indcollation[i] != info->indexcollations[i])
2867 if (p_info->opclass[i] != info->opcintype[i])
2870 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2871 info->reverse_sort[i])
2874 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2875 info->nulls_first[i])
2880 if (i != info->ncolumns)
2883 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2884 (p_info->indpred_str && (info->indpred != NIL)))
2887 * Fetch the pg_index tuple by the Oid of the index
2889 ht_idx = SearchSysCache1(INDEXRELID,
2890 ObjectIdGetDatum(info->indexoid));
2892 /* check to match the expression's parameter of index */
2893 if (p_info->expression_str &&
2894 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2901 * to change the expression's parameter of child's
2904 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2905 Anum_pg_index_indexprs,
2908 result = DirectFunctionCall2(pg_get_expr,
2913 if (strcmp(p_info->expression_str,
2914 text_to_cstring(DatumGetTextP(result))) != 0)
2917 ReleaseSysCache(ht_idx);
2923 /* Check to match the predicate's parameter of index */
2924 if (p_info->indpred_str &&
2925 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2932 * to change the predicate's parameter of child's
2935 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2936 Anum_pg_index_indpred,
2939 result = DirectFunctionCall2(pg_get_expr,
2944 if (strcmp(p_info->indpred_str,
2945 text_to_cstring(DatumGetTextP(result))) != 0)
2948 ReleaseSysCache(ht_idx);
2955 ReleaseSysCache(ht_idx);
2957 else if (p_info->expression_str || (info->indexprs != NIL))
2959 else if (p_info->indpred_str || (info->indpred != NIL))
2964 /* to log the candidate of index */
2965 if (debug_level > 0)
2967 appendStringInfoCharMacro(&buf, ' ');
2968 quote_value(&buf, indexname);
2976 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2983 if (debug_level == 1)
2986 StringInfoData rel_buf;
2988 if (OidIsValid(relationObjectId))
2989 relname = get_rel_name(relationObjectId);
2991 relname = hint->relname;
2993 initStringInfo(&rel_buf);
2994 quote_value(&rel_buf, relname);
2997 (errmsg("available indexes for %s(%s):%s",
3002 pfree(rel_buf.data);
3007 * Return information of index definition.
3009 static ParentIndexInfo *
3010 get_parent_index_info(Oid indexoid, Oid relid)
3012 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3013 Relation indexRelation;
3014 Form_pg_index index;
3018 indexRelation = index_open(indexoid, RowExclusiveLock);
3020 index = indexRelation->rd_index;
3022 p_info->indisunique = index->indisunique;
3023 p_info->method = indexRelation->rd_rel->relam;
3025 p_info->column_names = NIL;
3026 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3027 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3028 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3030 for (i = 0; i < index->indnatts; i++)
3032 attname = get_attname(relid, index->indkey.values[i]);
3033 p_info->column_names = lappend(p_info->column_names, attname);
3035 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3036 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3037 p_info->indoption[i] = indexRelation->rd_indoption[i];
3041 * to check to match the expression's parameter of index with child indexes
3043 p_info->expression_str = NULL;
3044 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
3050 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3051 Anum_pg_index_indexprs, &isnull);
3053 result = DirectFunctionCall2(pg_get_expr,
3055 ObjectIdGetDatum(relid));
3057 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3061 * to check to match the predicate's parameter of index with child indexes
3063 p_info->indpred_str = NULL;
3064 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
3070 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3071 Anum_pg_index_indpred, &isnull);
3073 result = DirectFunctionCall2(pg_get_expr,
3075 ObjectIdGetDatum(relid));
3077 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3080 index_close(indexRelation, NoLock);
3086 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
3087 bool inhparent, RelOptInfo *rel)
3089 ScanMethodHint *hint = NULL;
3091 Index new_parent_relid = 0;
3093 if (prev_get_relation_info)
3094 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
3097 * Do nothing if we don't have a valid hint in this context or current
3098 * nesting depth is at SPI calls.
3100 if (!current_hint || hint_inhibit_level > 0)
3102 if (debug_level > 1)
3103 ereport(pg_hint_plan_message_level,
3105 errmsg ("pg_hint_plan%s: get_relation_info"
3106 " no hint to apply: relation=%u(%s), inhparent=%d,"
3107 " current_hint=%p, hint_inhibit_level=%d",
3108 qnostr, relationObjectId,
3109 get_rel_name(relationObjectId),
3110 inhparent, current_hint, hint_inhibit_level)));
3115 * We could register the parent relation of the following children here
3116 * when inhparent == true but inheritnce planner doesn't request
3117 * information for inheritance parents. We also cannot distinguish the
3118 * caller so we should always find the parents without this function being
3123 if (debug_level > 1)
3124 ereport(pg_hint_plan_message_level,
3126 errmsg ("pg_hint_plan%s: get_relation_info"
3127 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3128 " current_hint=%p, hint_inhibit_level=%d",
3129 qnostr, relationObjectId,
3130 get_rel_name(relationObjectId),
3131 inhparent, current_hint, hint_inhibit_level)));
3135 /* Find the parent for this relation */
3136 foreach (l, root->append_rel_list)
3138 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3140 if (appinfo->child_relid == rel->relid)
3142 if (current_hint->parent_relid != appinfo->parent_relid)
3143 new_parent_relid = appinfo->parent_relid;
3150 /* This relation doesn't have a parent. Cancel current_hint. */
3151 current_hint->parent_relid = 0;
3152 current_hint->parent_hint = NULL;
3155 if (new_parent_relid > 0)
3158 * Here we found a parent relation different from the remembered one.
3159 * Remember it, apply the scan mask of it and then resolve the index
3160 * restriction in order to be used by its children.
3162 int scanmask = current_hint->init_scan_mask;
3163 ScanMethodHint *parent_hint;
3165 current_hint->parent_relid = new_parent_relid;
3168 * Get and apply the hint for the new parent relation. It should be an
3169 * ordinary relation so calling find_scan_hint with rel == NULL is
3172 current_hint->parent_hint = parent_hint =
3173 find_scan_hint(root, current_hint->parent_relid, NULL);
3177 scanmask = current_hint->parent_hint->enforce_mask;
3178 parent_hint->base.state = HINT_STATE_USED;
3180 /* Resolve index name mask (if any) using the parent. */
3181 if (parent_hint->indexnames)
3184 Relation parent_rel;
3187 root->simple_rte_array[current_hint->parent_relid]->relid;
3188 parent_rel = heap_open(parentrel_oid, NoLock);
3190 /* Search the parent relation for indexes match the hint spec */
3191 foreach(l, RelationGetIndexList(parent_rel))
3193 Oid indexoid = lfirst_oid(l);
3194 char *indexname = get_rel_name(indexoid);
3196 ParentIndexInfo *parent_index_info;
3198 foreach(lc, parent_hint->indexnames)
3200 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3207 get_parent_index_info(indexoid, parentrel_oid);
3208 current_hint->parent_index_infos =
3209 lappend(current_hint->parent_index_infos, parent_index_info);
3211 heap_close(parent_rel, NoLock);
3215 set_scan_config_options(scanmask, current_hint->context);
3218 if (current_hint->parent_hint != 0)
3220 delete_indexes(current_hint->parent_hint, rel,
3223 /* Scan fixation status is the same to the parent. */
3224 if (debug_level > 1)
3225 ereport(pg_hint_plan_message_level,
3227 errmsg("pg_hint_plan%s: get_relation_info:"
3228 " index deletion by parent hint: "
3229 "relation=%u(%s), inhparent=%d, current_hint=%p,"
3230 " hint_inhibit_level=%d",
3231 qnostr, relationObjectId,
3232 get_rel_name(relationObjectId),
3233 inhparent, current_hint, hint_inhibit_level)));
3237 /* This table doesn't have a parent hint. Apply its own hint if any. */
3238 if ((hint = find_scan_hint(root, rel->relid, rel)) != NULL)
3240 set_scan_config_options(hint->enforce_mask, current_hint->context);
3241 hint->base.state = HINT_STATE_USED;
3243 delete_indexes(hint, rel, InvalidOid);
3245 if (debug_level > 1)
3246 ereport(pg_hint_plan_message_level,
3248 errmsg ("pg_hint_plan%s: get_relation_info"
3250 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3251 " hint_inhibit_level=%d, scanmask=0x%x",
3252 qnostr, relationObjectId,
3253 get_rel_name(relationObjectId),
3254 inhparent, current_hint, hint_inhibit_level,
3255 hint->enforce_mask)));
3259 if (debug_level > 1)
3260 ereport(pg_hint_plan_message_level,
3261 (errhidestmt (true),
3262 errmsg ("pg_hint_plan%s: get_relation_info"
3264 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3265 " hint_inhibit_level=%d, scanmask=0x%x",
3266 qnostr, relationObjectId,
3267 get_rel_name(relationObjectId),
3268 inhparent, current_hint, hint_inhibit_level,
3269 current_hint->init_scan_mask)));
3270 set_scan_config_options(current_hint->init_scan_mask,
3271 current_hint->context);
3277 * Return index of relation which matches given aliasname, or 0 if not found.
3278 * If same aliasname was used multiple times in a query, return -1.
3281 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3287 for (i = 1; i < root->simple_rel_array_size; i++)
3291 if (root->simple_rel_array[i] == NULL)
3294 Assert(i == root->simple_rel_array[i]->relid);
3296 if (RelnameCmp(&aliasname,
3297 &root->simple_rte_array[i]->eref->aliasname) != 0)
3300 foreach(l, initial_rels)
3302 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3304 if (rel->reloptkind == RELOPT_BASEREL)
3306 if (rel->relid != i)
3311 Assert(rel->reloptkind == RELOPT_JOINREL);
3313 if (!bms_is_member(i, rel->relids))
3320 ("Relation name \"%s\" is ambiguous.",
3335 * Return join hint which matches given joinrelids.
3337 static JoinMethodHint *
3338 find_join_hint(Relids joinrelids)
3343 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
3345 foreach(l, join_hint)
3347 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3349 if (bms_equal(joinrelids, hint->joinrelids))
3357 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3358 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3360 OuterInnerRels *outer_rels;
3361 OuterInnerRels *inner_rels;
3362 Relids outer_relids;
3363 Relids inner_relids;
3365 JoinMethodHint *hint;
3367 if (outer_inner->relation != NULL)
3369 return bms_make_singleton(
3370 find_relid_aliasname(root, outer_inner->relation,
3372 leading_hint->base.hint_str));
3375 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3376 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3378 outer_relids = OuterInnerJoinCreate(outer_rels,
3384 inner_relids = OuterInnerJoinCreate(inner_rels,
3391 join_relids = bms_add_members(outer_relids, inner_relids);
3393 if (bms_num_members(join_relids) > nbaserel)
3397 * If we don't have join method hint, create new one for the
3398 * join combination with all join methods are enabled.
3400 hint = find_join_hint(join_relids);
3404 * Here relnames is not set, since Relids bitmap is sufficient to
3405 * control paths of this query afterward.
3407 hint = (JoinMethodHint *) JoinMethodHintCreate(
3408 leading_hint->base.hint_str,
3410 HINT_KEYWORD_LEADING);
3411 hint->base.state = HINT_STATE_USED;
3412 hint->nrels = bms_num_members(join_relids);
3413 hint->enforce_mask = ENABLE_ALL_JOIN;
3414 hint->joinrelids = bms_copy(join_relids);
3415 hint->inner_nrels = bms_num_members(inner_relids);
3416 hint->inner_joinrelids = bms_copy(inner_relids);
3418 hstate->join_hint_level[hint->nrels] =
3419 lappend(hstate->join_hint_level[hint->nrels], hint);
3423 hint->inner_nrels = bms_num_members(inner_relids);
3424 hint->inner_joinrelids = bms_copy(inner_relids);
3431 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3432 int nrels, char **relnames)
3435 Relids relids = NULL;
3439 for (j = 0; j < nrels; j++)
3441 relname = relnames[j];
3443 relid = find_relid_aliasname(root, relname, initial_rels,
3447 base->state = HINT_STATE_ERROR;
3450 * the aliasname is not found(relid == 0) or same aliasname was used
3451 * multiple times in a query(relid == -1)
3458 if (bms_is_member(relid, relids))
3460 hint_ereport(base->hint_str,
3461 ("Relation name \"%s\" is duplicated.", relname));
3462 base->state = HINT_STATE_ERROR;
3466 relids = bms_add_member(relids, relid);
3471 * Transform join method hint into handy form.
3473 * - create bitmap of relids from alias names, to make it easier to check
3474 * whether a join path matches a join method hint.
3475 * - add join method hints which are necessary to enforce join order
3476 * specified by Leading hint
3479 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
3480 List *initial_rels, JoinMethodHint **join_method_hints)
3488 LeadingHint *lhint = NULL;
3491 * Create bitmap of relids from alias names for each join method hint.
3492 * Bitmaps are more handy than strings in join searching.
3494 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
3496 JoinMethodHint *hint = hstate->join_hints[i];
3498 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3501 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3502 initial_rels, hint->nrels, hint->relnames);
3504 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
3507 hstate->join_hint_level[hint->nrels] =
3508 lappend(hstate->join_hint_level[hint->nrels], hint);
3512 * Create bitmap of relids from alias names for each rows hint.
3513 * Bitmaps are more handy than strings in join searching.
3515 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
3517 RowsHint *hint = hstate->rows_hints[i];
3519 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3522 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3523 initial_rels, hint->nrels, hint->relnames);
3526 /* Do nothing if no Leading hint was supplied. */
3527 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
3531 * Decide to use Leading hint。
3533 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
3535 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
3538 if (leading_hint->base.state == HINT_STATE_ERROR)
3544 foreach(l, leading_hint->relations)
3546 relname = (char *)lfirst(l);;
3548 relid = find_relid_aliasname(root, relname, initial_rels,
3549 leading_hint->base.hint_str);
3551 leading_hint->base.state = HINT_STATE_ERROR;
3556 if (bms_is_member(relid, relids))
3558 hint_ereport(leading_hint->base.hint_str,
3559 ("Relation name \"%s\" is duplicated.", relname));
3560 leading_hint->base.state = HINT_STATE_ERROR;
3564 relids = bms_add_member(relids, relid);
3567 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3572 hint_ereport(lhint->base.hint_str,
3573 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3574 lhint->base.state = HINT_STATE_DUPLICATION;
3576 leading_hint->base.state = HINT_STATE_USED;
3577 lhint = leading_hint;
3580 /* check to exist Leading hint marked with 'used'. */
3585 * We need join method hints which fit specified join order in every join
3586 * level. For example, Leading(A B C) virtually requires following join
3587 * method hints, if no join method hint supplied:
3589 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3590 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3592 * If we already have join method hint which fits specified join order in
3593 * that join level, we leave it as-is and don't add new hints.
3597 if (lhint->outer_inner == NULL)
3599 foreach(l, lhint->relations)
3601 JoinMethodHint *hint;
3603 relname = (char *)lfirst(l);
3606 * Find relid of the relation which has given name. If we have the
3607 * name given in Leading hint multiple times in the join, nothing to
3610 relid = find_relid_aliasname(root, relname, initial_rels,
3613 /* Create bitmap of relids for current join level. */
3614 joinrelids = bms_add_member(joinrelids, relid);
3617 /* We never have join method hint for single relation. */
3622 * If we don't have join method hint, create new one for the
3623 * join combination with all join methods are enabled.
3625 hint = find_join_hint(joinrelids);
3629 * Here relnames is not set, since Relids bitmap is sufficient
3630 * to control paths of this query afterward.
3632 hint = (JoinMethodHint *) JoinMethodHintCreate(
3633 lhint->base.hint_str,
3635 HINT_KEYWORD_LEADING);
3636 hint->base.state = HINT_STATE_USED;
3637 hint->nrels = njoinrels;
3638 hint->enforce_mask = ENABLE_ALL_JOIN;
3639 hint->joinrelids = bms_copy(joinrelids);
3642 join_method_hints[njoinrels] = hint;
3644 if (njoinrels >= nbaserel)
3647 bms_free(joinrelids);
3653 * Delete all join hints which have different combination from Leading
3656 for (i = 2; i <= njoinrels; i++)
3658 list_free(hstate->join_hint_level[i]);
3660 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3665 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3672 njoinrels = bms_num_members(joinrelids);
3673 Assert(njoinrels >= 2);
3676 * Delete all join hints which have different combination from Leading
3679 for (i = 2;i <= njoinrels; i++)
3681 if (hstate->join_hint_level[i] != NIL)
3683 ListCell *prev = NULL;
3684 ListCell *next = NULL;
3685 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3687 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3691 if (hint->inner_nrels == 0 &&
3692 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3693 bms_equal(bms_union(hint->joinrelids, joinrelids),
3696 hstate->join_hint_level[i] =
3697 list_delete_cell(hstate->join_hint_level[i], l,
3706 bms_free(joinrelids);
3709 if (hint_state_enabled(lhint))
3711 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3718 * set_plain_rel_pathlist
3719 * Build access paths for a plain relation (no subquery, no inheritance)
3721 * This function was copied and edited from set_plain_rel_pathlist() in
3722 * src/backend/optimizer/path/allpaths.c
3725 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3727 /* Consider sequential scan */
3728 add_path(rel, create_seqscan_path(root, rel, NULL));
3730 /* Consider index scans */
3731 create_index_paths(root, rel);
3733 /* Consider TID scans */
3734 create_tidscan_paths(root, rel);
3736 /* Now find the cheapest of the paths for this rel */
3741 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3746 foreach(l, initial_rels)
3748 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3750 ScanMethodHint *hint;
3752 /* Skip relations which we can't choose scan method. */
3753 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3756 rte = root->simple_rte_array[rel->relid];
3758 /* We can't force scan method of foreign tables */
3759 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3763 * Create scan paths with GUC parameters which are at the beginning of
3764 * planner if scan method hint is not specified, otherwise use
3765 * specified hints and mark the hint as used.
3767 if ((hint = find_scan_hint(root, rel->relid, rel)) == NULL)
3768 set_scan_config_options(hstate->init_scan_mask,
3772 set_scan_config_options(hint->enforce_mask, hstate->context);
3773 hint->base.state = HINT_STATE_USED;
3776 list_free_deep(rel->pathlist);
3777 rel->pathlist = NIL;
3780 /* It's an "append relation", process accordingly */
3781 set_append_rel_pathlist(root, rel, rel->relid, rte);
3785 set_plain_rel_pathlist(root, rel, rte);
3790 * Restore the GUC variables we set above.
3792 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3796 * wrapper of make_join_rel()
3798 * call make_join_rel() after changing enable_* parameters according to given
3802 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3805 JoinMethodHint *hint;
3809 joinrelids = bms_union(rel1->relids, rel2->relids);
3810 hint = find_join_hint(joinrelids);
3811 bms_free(joinrelids);
3814 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3816 if (hint->inner_nrels == 0)
3818 save_nestlevel = NewGUCNestLevel();
3820 set_join_config_options(hint->enforce_mask, current_hint->context);
3822 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3823 hint->base.state = HINT_STATE_USED;
3826 * Restore the GUC variables we set above.
3828 AtEOXact_GUC(true, save_nestlevel);
3831 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3840 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3841 RelOptInfo *joinrel,
3842 RelOptInfo *outerrel,
3843 RelOptInfo *innerrel,
3845 SpecialJoinInfo *sjinfo,
3848 ScanMethodHint *scan_hint = NULL;
3850 JoinMethodHint *join_hint;
3853 if ((scan_hint = find_scan_hint(root, innerrel->relid, innerrel)) != NULL)
3855 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3856 scan_hint->base.state = HINT_STATE_USED;
3859 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3861 join_hint = find_join_hint(joinrelids);
3862 bms_free(joinrelids);
3864 if (join_hint && join_hint->inner_nrels != 0)
3866 save_nestlevel = NewGUCNestLevel();
3868 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3871 set_join_config_options(join_hint->enforce_mask,
3872 current_hint->context);
3874 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3875 sjinfo, restrictlist);
3876 join_hint->base.state = HINT_STATE_USED;
3880 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3881 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3882 sjinfo, restrictlist);
3886 * Restore the GUC variables we set above.
3888 AtEOXact_GUC(true, save_nestlevel);
3891 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3892 sjinfo, restrictlist);
3894 if (scan_hint != NULL)
3895 set_scan_config_options(current_hint->init_scan_mask,
3896 current_hint->context);
3900 get_num_baserels(List *initial_rels)
3905 foreach(l, initial_rels)
3907 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3909 if (rel->reloptkind == RELOPT_BASEREL)
3911 else if (rel->reloptkind ==RELOPT_JOINREL)
3912 nbaserel+= bms_num_members(rel->relids);
3915 /* other values not expected here */
3916 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3924 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3927 JoinMethodHint **join_method_hints;
3931 bool leading_hint_enable;
3934 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3935 * valid hint is supplied or current nesting depth is nesting depth of SPI
3938 if (!current_hint || hint_inhibit_level > 0)
3940 if (prev_join_search)
3941 return (*prev_join_search) (root, levels_needed, initial_rels);
3942 else if (enable_geqo && levels_needed >= geqo_threshold)
3943 return geqo(root, levels_needed, initial_rels);
3945 return standard_join_search(root, levels_needed, initial_rels);
3948 /* We apply scan method hint rebuild scan path. */
3949 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3952 * In the case using GEQO, only scan method hints and Set hints have
3953 * effect. Join method and join order is not controllable by hints.
3955 if (enable_geqo && levels_needed >= geqo_threshold)
3956 return geqo(root, levels_needed, initial_rels);
3958 nbaserel = get_num_baserels(initial_rels);
3959 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3960 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3962 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3963 initial_rels, join_method_hints);
3965 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3967 for (i = 2; i <= nbaserel; i++)
3969 list_free(current_hint->join_hint_level[i]);
3971 /* free Leading hint only */
3972 if (join_method_hints[i] != NULL &&
3973 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3974 JoinMethodHintDelete(join_method_hints[i]);
3976 pfree(current_hint->join_hint_level);
3977 pfree(join_method_hints);
3979 if (leading_hint_enable)
3980 set_join_config_options(current_hint->init_join_mask,
3981 current_hint->context);
3988 * Build access paths for a base relation
3990 * This function was copied and edited from set_rel_pathlist() in
3991 * src/backend/optimizer/path/allpaths.c
3994 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3995 Index rti, RangeTblEntry *rte)
3997 if (IS_DUMMY_REL(rel))
3999 /* We already proved the relation empty, so nothing more to do */
4003 /* It's an "append relation", process accordingly */
4004 set_append_rel_pathlist(root, rel, rti, rte);
4008 if (rel->rtekind == RTE_RELATION)
4010 if (rte->relkind == RELKIND_RELATION)
4012 /* Plain relation */
4013 set_plain_rel_pathlist(root, rel, rte);
4016 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4019 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4024 * stmt_beg callback is called when each query in PL/pgSQL function is about
4025 * to be executed. At that timing, we save query string in the global variable
4026 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4027 * variable for the purpose, because its content is only necessary until
4028 * planner hook is called for the query, so recursive PL/pgSQL function calls
4029 * don't harm this mechanism.
4032 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4034 plpgsql_recurse_level++;
4038 * stmt_end callback is called then each query in PL/pgSQL function has
4039 * finished. At that timing, we clear plpgsql_query_string to tell planner
4040 * hook that next call is not for a query written in PL/pgSQL block.
4043 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4045 plpgsql_recurse_level--;
4048 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4053 if (phase != RESOURCE_RELEASE_AFTER_LOCKS)
4055 /* Cancel plpgsql nest level*/
4056 plpgsql_recurse_level = 0;
4059 #define standard_join_search pg_hint_plan_standard_join_search
4060 #define join_search_one_level pg_hint_plan_join_search_one_level
4061 #define make_join_rel make_join_rel_wrapper
4064 #undef make_join_rel
4065 #define make_join_rel pg_hint_plan_make_join_rel
4066 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4067 #include "make_join_rel.c"
4069 #include "pg_stat_statements.c"