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"
44 /* partially copied from pg_stat_statements */
45 #include "normalize_query.h"
48 #include "access/htup_details.h"
50 #ifdef PG_MODULE_MAGIC
54 #define BLOCK_COMMENT_START "/*"
55 #define BLOCK_COMMENT_END "*/"
56 #define HINT_COMMENT_KEYWORD "+"
57 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
58 #define HINT_END BLOCK_COMMENT_END
61 #define HINT_SEQSCAN "SeqScan"
62 #define HINT_INDEXSCAN "IndexScan"
63 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
64 #define HINT_BITMAPSCAN "BitmapScan"
65 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
66 #define HINT_TIDSCAN "TidScan"
67 #define HINT_NOSEQSCAN "NoSeqScan"
68 #define HINT_NOINDEXSCAN "NoIndexScan"
69 #define HINT_NOBITMAPSCAN "NoBitmapScan"
70 #define HINT_NOTIDSCAN "NoTidScan"
71 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
72 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
73 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
74 #define HINT_NESTLOOP "NestLoop"
75 #define HINT_MERGEJOIN "MergeJoin"
76 #define HINT_HASHJOIN "HashJoin"
77 #define HINT_NONESTLOOP "NoNestLoop"
78 #define HINT_NOMERGEJOIN "NoMergeJoin"
79 #define HINT_NOHASHJOIN "NoHashJoin"
80 #define HINT_LEADING "Leading"
81 #define HINT_SET "Set"
82 #define HINT_ROWS "Rows"
84 #define HINT_ARRAY_DEFAULT_INITSIZE 8
86 #define hint_ereport(str, detail) \
87 ereport(pg_hint_plan_message_level, \
88 (errhidestmt(hidestmt), \
89 errmsg("pg_hint_plan%s: hint syntax error at or near \"%s\"", qnostr, (str)), \
92 #define skip_space(str) \
93 while (isspace(*str)) \
98 ENABLE_SEQSCAN = 0x01,
99 ENABLE_INDEXSCAN = 0x02,
100 ENABLE_BITMAPSCAN = 0x04,
101 ENABLE_TIDSCAN = 0x08,
102 ENABLE_INDEXONLYSCAN = 0x10
107 ENABLE_NESTLOOP = 0x01,
108 ENABLE_MERGEJOIN = 0x02,
109 ENABLE_HASHJOIN = 0x04
112 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
113 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
114 ENABLE_INDEXONLYSCAN)
115 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
116 #define DISABLE_ALL_SCAN 0
117 #define DISABLE_ALL_JOIN 0
119 /* hint keyword of enum type*/
120 typedef enum HintKeyword
122 HINT_KEYWORD_SEQSCAN,
123 HINT_KEYWORD_INDEXSCAN,
124 HINT_KEYWORD_INDEXSCANREGEXP,
125 HINT_KEYWORD_BITMAPSCAN,
126 HINT_KEYWORD_BITMAPSCANREGEXP,
127 HINT_KEYWORD_TIDSCAN,
128 HINT_KEYWORD_NOSEQSCAN,
129 HINT_KEYWORD_NOINDEXSCAN,
130 HINT_KEYWORD_NOBITMAPSCAN,
131 HINT_KEYWORD_NOTIDSCAN,
132 HINT_KEYWORD_INDEXONLYSCAN,
133 HINT_KEYWORD_INDEXONLYSCANREGEXP,
134 HINT_KEYWORD_NOINDEXONLYSCAN,
135 HINT_KEYWORD_NESTLOOP,
136 HINT_KEYWORD_MERGEJOIN,
137 HINT_KEYWORD_HASHJOIN,
138 HINT_KEYWORD_NONESTLOOP,
139 HINT_KEYWORD_NOMERGEJOIN,
140 HINT_KEYWORD_NOHASHJOIN,
141 HINT_KEYWORD_LEADING,
144 HINT_KEYWORD_UNRECOGNIZED
147 typedef struct Hint Hint;
148 typedef struct HintState HintState;
150 typedef Hint *(*HintCreateFunction) (const char *hint_str,
152 HintKeyword hint_keyword);
153 typedef void (*HintDeleteFunction) (Hint *hint);
154 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf, bool nolf);
155 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
156 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
157 Query *parse, const char *str);
160 #define NUM_HINT_TYPE 5
161 typedef enum HintType
163 HINT_TYPE_SCAN_METHOD,
164 HINT_TYPE_JOIN_METHOD,
170 static const char *HintTypeName[] = {
179 typedef enum HintStatus
181 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
182 HINT_STATE_USED, /* hint is used */
183 HINT_STATE_DUPLICATION, /* specified hint duplication */
184 HINT_STATE_ERROR /* execute error (parse error does not include
188 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
189 (hint)->base.state == HINT_STATE_USED)
191 static unsigned int qno = 0;
192 static char qnostr[32];
194 /* common data for all hints. */
197 const char *hint_str; /* must not do pfree */
198 const char *keyword; /* must not do pfree */
199 HintKeyword hint_keyword;
202 HintDeleteFunction delete_func;
203 HintDescFunction desc_func;
204 HintCmpFunction cmp_func;
205 HintParseFunction parse_func;
208 /* scan method hints */
209 typedef struct ScanMethodHint
215 unsigned char enforce_mask;
218 typedef struct ParentIndexInfo
223 char *expression_str;
230 /* join method hints */
231 typedef struct JoinMethodHint
237 unsigned char enforce_mask;
239 Relids inner_joinrelids;
242 /* join order hints */
243 typedef struct OuterInnerRels
246 List *outer_inner_pair;
249 typedef struct LeadingHint
252 List *relations; /* relation names specified in Leading hint */
253 OuterInnerRels *outer_inner;
256 /* change a run-time parameter hints */
257 typedef struct SetHint
260 char *name; /* name of variable */
266 typedef enum RowsValueType {
267 RVT_ABSOLUTE, /* Rows(... #1000) */
268 RVT_ADD, /* Rows(... +1000) */
269 RVT_SUB, /* Rows(... -1000) */
270 RVT_MULTI, /* Rows(... *1.2) */
272 typedef struct RowsHint
279 Relids inner_joinrelids;
281 RowsValueType value_type;
286 * Describes a context of hint processing.
290 char *hint_str; /* original hint string */
293 int nall_hints; /* # of valid all hints */
294 int max_all_hints; /* # of slots for all hints */
295 Hint **all_hints; /* parsed all hints */
297 /* # of each hints */
298 int num_hints[NUM_HINT_TYPE];
300 /* for scan method hints */
301 ScanMethodHint **scan_hints; /* parsed scan hints */
302 int init_scan_mask; /* initial value scan parameter */
303 Index parent_relid; /* inherit parent table relid */
304 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
305 List *parent_index_infos; /* information of inherit parent table's
308 /* for join method hints */
309 JoinMethodHint **join_hints; /* parsed join hints */
310 int init_join_mask; /* initial value join parameter */
311 List **join_hint_level;
313 /* for Leading hint */
314 LeadingHint **leading_hint; /* parsed Leading hints */
317 SetHint **set_hints; /* parsed Set hints */
318 GucContext context; /* which GUC parameters can we set? */
321 RowsHint **rows_hints; /* parsed Rows hints */
325 * Describes a hint parser module which is bound with particular hint keyword.
327 typedef struct HintParser
330 HintCreateFunction create_func;
331 HintKeyword hint_keyword;
334 /* Module callbacks */
338 static void push_hint(HintState *hstate);
339 static void pop_hint(void);
341 static void pg_hint_plan_ProcessUtility(Node *parsetree,
342 const char *queryString,
343 ProcessUtilityContext context,
344 ParamListInfo params,
345 DestReceiver *dest, char *completionTag);
346 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
347 ParamListInfo boundParams);
348 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
349 Oid relationObjectId,
350 bool inhparent, RelOptInfo *rel);
351 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
355 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
356 HintKeyword hint_keyword);
357 static void ScanMethodHintDelete(ScanMethodHint *hint);
358 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
359 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
360 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
361 Query *parse, const char *str);
362 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
363 HintKeyword hint_keyword);
364 static void JoinMethodHintDelete(JoinMethodHint *hint);
365 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
366 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
367 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
368 Query *parse, const char *str);
369 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
370 HintKeyword hint_keyword);
371 static void LeadingHintDelete(LeadingHint *hint);
372 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
373 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
374 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
375 Query *parse, const char *str);
376 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
377 HintKeyword hint_keyword);
378 static void SetHintDelete(SetHint *hint);
379 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
380 static int SetHintCmp(const SetHint *a, const SetHint *b);
381 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
383 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
384 HintKeyword hint_keyword);
385 static void RowsHintDelete(RowsHint *hint);
386 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
387 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
388 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
389 Query *parse, const char *str);
390 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
391 HintKeyword hint_keyword);
393 static void quote_value(StringInfo buf, const char *value);
395 static const char *parse_quoted_value(const char *str, char **word,
398 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
401 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
402 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
403 ListCell *other_rels);
404 static void make_rels_by_clauseless_joins(PlannerInfo *root,
406 ListCell *other_rels);
407 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
408 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
409 Index rti, RangeTblEntry *rte);
410 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
411 List *live_childrels,
412 List *all_child_pathkeys);
413 static Path *get_cheapest_parameterized_child_path(PlannerInfo *root,
415 Relids required_outer);
416 static List *accumulate_append_subpath(List *subpaths, Path *path);
417 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
420 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
422 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
424 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
430 static bool pg_hint_plan_enable_hint = true;
431 static int debug_level = 0;
432 static int pg_hint_plan_message_level = INFO;
433 /* Default is off, to keep backward compatibility. */
434 static bool pg_hint_plan_enable_hint_table = false;
436 /* Internal static variables. */
437 static bool hidestmt = false; /* Allow or inhibit STATEMENT: output */
439 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
440 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
441 /* (This could not be above 1) */
443 static const struct config_enum_entry parse_messages_level_options[] = {
444 {"debug", DEBUG2, true},
445 {"debug5", DEBUG5, false},
446 {"debug4", DEBUG4, false},
447 {"debug3", DEBUG3, false},
448 {"debug2", DEBUG2, false},
449 {"debug1", DEBUG1, false},
451 {"info", INFO, false},
452 {"notice", NOTICE, false},
453 {"warning", WARNING, false},
454 {"error", ERROR, false},
456 * {"fatal", FATAL, true},
457 * {"panic", PANIC, true},
462 static const struct config_enum_entry parse_debug_level_options[] = {
465 {"detailed", 2, false},
466 {"verbose", 3, false},
478 /* Saved hook values in case of unload */
479 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
480 static planner_hook_type prev_planner = NULL;
481 static get_relation_info_hook_type prev_get_relation_info = NULL;
482 static join_search_hook_type prev_join_search = NULL;
484 /* Hold reference to currently active hint */
485 static HintState *current_hint = NULL;
488 * List of hint contexts. We treat the head of the list as the Top of the
489 * context stack, so current_hint always points the first element of this list.
491 static List *HintStateStack = NIL;
494 * Holds statement name during executing EXECUTE command. NULL for other
497 static char *stmt_name = NULL;
499 static const HintParser parsers[] = {
500 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
501 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
502 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
503 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
504 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
505 HINT_KEYWORD_BITMAPSCANREGEXP},
506 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
507 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
508 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
509 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
510 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
511 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
512 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
513 HINT_KEYWORD_INDEXONLYSCANREGEXP},
514 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
515 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
516 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
517 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
518 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
519 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
520 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
521 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
522 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
523 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
524 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
527 PLpgSQL_plugin plugin_funcs = {
531 pg_hint_plan_plpgsql_stmt_beg,
532 pg_hint_plan_plpgsql_stmt_end,
538 * Module load callbacks
543 PLpgSQL_plugin **var_ptr;
545 /* Define custom GUC variables. */
546 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
547 "Force planner to use plans specified in the hint comment preceding to the query.",
549 &pg_hint_plan_enable_hint,
557 DefineCustomEnumVariable("pg_hint_plan.debug_print",
558 "Logs results of hint parsing.",
562 parse_debug_level_options,
569 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
570 "Message level of parse errors.",
572 &pg_hint_plan_message_level,
574 parse_messages_level_options,
581 DefineCustomEnumVariable("pg_hint_plan.message_level",
582 "Message level of debug messages.",
584 &pg_hint_plan_message_level,
586 parse_messages_level_options,
593 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
594 "Force planner to not get hint by using table lookups.",
596 &pg_hint_plan_enable_hint_table,
605 prev_ProcessUtility = ProcessUtility_hook;
606 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
607 prev_planner = planner_hook;
608 planner_hook = pg_hint_plan_planner;
609 prev_get_relation_info = get_relation_info_hook;
610 get_relation_info_hook = pg_hint_plan_get_relation_info;
611 prev_join_search = join_search_hook;
612 join_search_hook = pg_hint_plan_join_search;
614 /* setup PL/pgSQL plugin hook */
615 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
616 *var_ptr = &plugin_funcs;
618 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
622 * Module unload callback
628 PLpgSQL_plugin **var_ptr;
630 /* Uninstall hooks. */
631 ProcessUtility_hook = prev_ProcessUtility;
632 planner_hook = prev_planner;
633 get_relation_info_hook = prev_get_relation_info;
634 join_search_hook = prev_join_search;
636 /* uninstall PL/pgSQL plugin hook */
637 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
642 * create and delete functions the hint object
646 ScanMethodHintCreate(const char *hint_str, const char *keyword,
647 HintKeyword hint_keyword)
649 ScanMethodHint *hint;
651 hint = palloc(sizeof(ScanMethodHint));
652 hint->base.hint_str = hint_str;
653 hint->base.keyword = keyword;
654 hint->base.hint_keyword = hint_keyword;
655 hint->base.type = HINT_TYPE_SCAN_METHOD;
656 hint->base.state = HINT_STATE_NOTUSED;
657 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
658 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
659 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
660 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
661 hint->relname = NULL;
662 hint->indexnames = NIL;
663 hint->regexp = false;
664 hint->enforce_mask = 0;
666 return (Hint *) hint;
670 ScanMethodHintDelete(ScanMethodHint *hint)
676 pfree(hint->relname);
677 list_free_deep(hint->indexnames);
682 JoinMethodHintCreate(const char *hint_str, const char *keyword,
683 HintKeyword hint_keyword)
685 JoinMethodHint *hint;
687 hint = palloc(sizeof(JoinMethodHint));
688 hint->base.hint_str = hint_str;
689 hint->base.keyword = keyword;
690 hint->base.hint_keyword = hint_keyword;
691 hint->base.type = HINT_TYPE_JOIN_METHOD;
692 hint->base.state = HINT_STATE_NOTUSED;
693 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
694 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
695 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
696 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
698 hint->inner_nrels = 0;
699 hint->relnames = NULL;
700 hint->enforce_mask = 0;
701 hint->joinrelids = NULL;
702 hint->inner_joinrelids = NULL;
704 return (Hint *) hint;
708 JoinMethodHintDelete(JoinMethodHint *hint)
717 for (i = 0; i < hint->nrels; i++)
718 pfree(hint->relnames[i]);
719 pfree(hint->relnames);
722 bms_free(hint->joinrelids);
723 bms_free(hint->inner_joinrelids);
728 LeadingHintCreate(const char *hint_str, const char *keyword,
729 HintKeyword hint_keyword)
733 hint = palloc(sizeof(LeadingHint));
734 hint->base.hint_str = hint_str;
735 hint->base.keyword = keyword;
736 hint->base.hint_keyword = hint_keyword;
737 hint->base.type = HINT_TYPE_LEADING;
738 hint->base.state = HINT_STATE_NOTUSED;
739 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
740 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
741 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
742 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
743 hint->relations = NIL;
744 hint->outer_inner = NULL;
746 return (Hint *) hint;
750 LeadingHintDelete(LeadingHint *hint)
755 list_free_deep(hint->relations);
756 if (hint->outer_inner)
757 pfree(hint->outer_inner);
762 SetHintCreate(const char *hint_str, const char *keyword,
763 HintKeyword hint_keyword)
767 hint = palloc(sizeof(SetHint));
768 hint->base.hint_str = hint_str;
769 hint->base.keyword = keyword;
770 hint->base.hint_keyword = hint_keyword;
771 hint->base.type = HINT_TYPE_SET;
772 hint->base.state = HINT_STATE_NOTUSED;
773 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
774 hint->base.desc_func = (HintDescFunction) SetHintDesc;
775 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
776 hint->base.parse_func = (HintParseFunction) SetHintParse;
781 return (Hint *) hint;
785 SetHintDelete(SetHint *hint)
795 list_free(hint->words);
800 RowsHintCreate(const char *hint_str, const char *keyword,
801 HintKeyword hint_keyword)
805 hint = palloc(sizeof(RowsHint));
806 hint->base.hint_str = hint_str;
807 hint->base.keyword = keyword;
808 hint->base.hint_keyword = hint_keyword;
809 hint->base.type = HINT_TYPE_ROWS;
810 hint->base.state = HINT_STATE_NOTUSED;
811 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
812 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
813 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
814 hint->base.parse_func = (HintParseFunction) RowsHintParse;
816 hint->inner_nrels = 0;
817 hint->relnames = NULL;
818 hint->joinrelids = NULL;
819 hint->inner_joinrelids = NULL;
820 hint->rows_str = NULL;
821 hint->value_type = RVT_ABSOLUTE;
824 return (Hint *) hint;
828 RowsHintDelete(RowsHint *hint)
837 for (i = 0; i < hint->nrels; i++)
838 pfree(hint->relnames[i]);
839 pfree(hint->relnames);
842 bms_free(hint->joinrelids);
843 bms_free(hint->inner_joinrelids);
848 HintStateCreate(void)
852 hstate = palloc(sizeof(HintState));
853 hstate->hint_str = NULL;
854 hstate->nall_hints = 0;
855 hstate->max_all_hints = 0;
856 hstate->all_hints = NULL;
857 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
858 hstate->scan_hints = NULL;
859 hstate->init_scan_mask = 0;
860 hstate->parent_relid = 0;
861 hstate->parent_hint = NULL;
862 hstate->parent_index_infos = NIL;
863 hstate->join_hints = NULL;
864 hstate->init_join_mask = 0;
865 hstate->join_hint_level = NULL;
866 hstate->leading_hint = NULL;
867 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
868 hstate->set_hints = NULL;
869 hstate->rows_hints = NULL;
875 HintStateDelete(HintState *hstate)
882 if (hstate->hint_str)
883 pfree(hstate->hint_str);
885 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
886 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
887 if (hstate->all_hints)
888 pfree(hstate->all_hints);
889 if (hstate->parent_index_infos)
890 list_free(hstate->parent_index_infos);
894 * Copy given value into buf, with quoting with '"' if necessary.
897 quote_value(StringInfo buf, const char *value)
899 bool need_quote = false;
902 for (str = value; *str != '\0'; str++)
904 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
907 appendStringInfoCharMacro(buf, '"');
912 for (str = value; *str != '\0'; str++)
915 appendStringInfoCharMacro(buf, '"');
917 appendStringInfoCharMacro(buf, *str);
921 appendStringInfoCharMacro(buf, '"');
925 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
929 appendStringInfo(buf, "%s(", hint->base.keyword);
930 if (hint->relname != NULL)
932 quote_value(buf, hint->relname);
933 foreach(l, hint->indexnames)
935 appendStringInfoCharMacro(buf, ' ');
936 quote_value(buf, (char *) lfirst(l));
939 appendStringInfoString(buf, ")");
941 appendStringInfoChar(buf, '\n');
945 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
949 appendStringInfo(buf, "%s(", hint->base.keyword);
950 if (hint->relnames != NULL)
952 quote_value(buf, hint->relnames[0]);
953 for (i = 1; i < hint->nrels; i++)
955 appendStringInfoCharMacro(buf, ' ');
956 quote_value(buf, hint->relnames[i]);
959 appendStringInfoString(buf, ")");
961 appendStringInfoChar(buf, '\n');
965 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
967 if (outer_inner->relation == NULL)
974 appendStringInfoCharMacro(buf, '(');
975 foreach(l, outer_inner->outer_inner_pair)
980 appendStringInfoCharMacro(buf, ' ');
982 OuterInnerDesc(lfirst(l), buf);
985 appendStringInfoCharMacro(buf, ')');
988 quote_value(buf, outer_inner->relation);
992 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
994 appendStringInfo(buf, "%s(", HINT_LEADING);
995 if (hint->outer_inner == NULL)
1002 foreach(l, hint->relations)
1007 appendStringInfoCharMacro(buf, ' ');
1009 quote_value(buf, (char *) lfirst(l));
1013 OuterInnerDesc(hint->outer_inner, buf);
1015 appendStringInfoString(buf, ")");
1017 appendStringInfoChar(buf, '\n');
1021 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1023 bool is_first = true;
1026 appendStringInfo(buf, "%s(", HINT_SET);
1027 foreach(l, hint->words)
1032 appendStringInfoCharMacro(buf, ' ');
1034 quote_value(buf, (char *) lfirst(l));
1036 appendStringInfo(buf, ")");
1038 appendStringInfoChar(buf, '\n');
1042 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1046 appendStringInfo(buf, "%s(", hint->base.keyword);
1047 if (hint->relnames != NULL)
1049 quote_value(buf, hint->relnames[0]);
1050 for (i = 1; i < hint->nrels; i++)
1052 appendStringInfoCharMacro(buf, ' ');
1053 quote_value(buf, hint->relnames[i]);
1056 appendStringInfo(buf, " %s", hint->rows_str);
1057 appendStringInfoString(buf, ")");
1059 appendStringInfoChar(buf, '\n');
1063 * Append string which represents all hints in a given state to buf, with
1064 * preceding title with them.
1067 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1068 HintStatus state, bool nolf)
1072 appendStringInfo(buf, "%s:", title);
1074 appendStringInfoChar(buf, '\n');
1077 for (i = 0; i < hstate->nall_hints; i++)
1079 if (hstate->all_hints[i]->state != state)
1082 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1086 if (nolf && nshown == 0)
1087 appendStringInfoString(buf, "(none)");
1091 * Dump contents of given hstate to server log with log level LOG.
1094 HintStateDump(HintState *hstate)
1100 elog(LOG, "pg_hint_plan:\nno hint");
1104 initStringInfo(&buf);
1106 appendStringInfoString(&buf, "pg_hint_plan:\n");
1107 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1108 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1109 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1110 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1112 elog(LOG, "%s", buf.data);
1118 HintStateDump2(HintState *hstate)
1124 elog(pg_hint_plan_message_level,
1125 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1129 initStringInfo(&buf);
1130 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1131 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1132 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1133 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1134 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1135 appendStringInfoChar(&buf, '}');
1137 ereport(pg_hint_plan_message_level,
1139 errmsg("%s", buf.data)));
1149 RelnameCmp(const void *a, const void *b)
1151 const char *relnamea = *((const char **) a);
1152 const char *relnameb = *((const char **) b);
1154 return strcmp(relnamea, relnameb);
1158 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1160 return RelnameCmp(&a->relname, &b->relname);
1164 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1168 if (a->nrels != b->nrels)
1169 return a->nrels - b->nrels;
1171 for (i = 0; i < a->nrels; i++)
1174 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1182 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1188 SetHintCmp(const SetHint *a, const SetHint *b)
1190 return strcmp(a->name, b->name);
1194 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1198 if (a->nrels != b->nrels)
1199 return a->nrels - b->nrels;
1201 for (i = 0; i < a->nrels; i++)
1204 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1212 HintCmp(const void *a, const void *b)
1214 const Hint *hinta = *((const Hint **) a);
1215 const Hint *hintb = *((const Hint **) b);
1217 if (hinta->type != hintb->type)
1218 return hinta->type - hintb->type;
1219 if (hinta->state == HINT_STATE_ERROR)
1221 if (hintb->state == HINT_STATE_ERROR)
1223 return hinta->cmp_func(hinta, hintb);
1227 * Returns byte offset of hint b from hint a. If hint a was specified before
1228 * b, positive value is returned.
1231 HintCmpWithPos(const void *a, const void *b)
1233 const Hint *hinta = *((const Hint **) a);
1234 const Hint *hintb = *((const Hint **) b);
1237 result = HintCmp(a, b);
1239 result = hinta->hint_str - hintb->hint_str;
1248 parse_keyword(const char *str, StringInfo buf)
1252 while (!isspace(*str) && *str != '(' && *str != '\0')
1253 appendStringInfoCharMacro(buf, *str++);
1259 skip_parenthesis(const char *str, char parenthesis)
1263 if (*str != parenthesis)
1265 if (parenthesis == '(')
1266 hint_ereport(str, ("Opening parenthesis is necessary."));
1267 else if (parenthesis == ')')
1268 hint_ereport(str, ("Closing parenthesis is necessary."));
1279 * Parse a token from str, and store malloc'd copy into word. A token can be
1280 * quoted with '"'. Return value is pointer to unparsed portion of original
1281 * string, or NULL if an error occurred.
1283 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1286 parse_quoted_value(const char *str, char **word, bool truncate)
1291 /* Skip leading spaces. */
1294 initStringInfo(&buf);
1307 /* Double quotation must be closed. */
1311 hint_ereport(str, ("Unterminated quoted string."));
1316 * Skip escaped double quotation.
1318 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1319 * block comments) to be an object name, so users must specify
1320 * alias for such object names.
1322 * Those special names can be allowed if we care escaped slashes
1323 * and asterisks, but we don't.
1332 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1336 appendStringInfoCharMacro(&buf, *str++);
1341 hint_ereport(str, ("Zero-length delimited string."));
1348 /* Truncate name if it's too long */
1350 truncate_identifier(buf.data, strlen(buf.data), true);
1357 static OuterInnerRels *
1358 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1360 OuterInnerRels *outer_inner;
1362 outer_inner = palloc(sizeof(OuterInnerRels));
1363 outer_inner->relation = name;
1364 outer_inner->outer_inner_pair = outer_inner_list;
1370 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1372 List *outer_inner_pair = NIL;
1374 if ((str = skip_parenthesis(str, '(')) == NULL)
1379 /* Store words in parentheses into outer_inner_list. */
1380 while(*str != ')' && *str != '\0')
1382 OuterInnerRels *outer_inner_rels;
1386 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1394 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1397 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1400 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1405 (str = skip_parenthesis(str, ')')) == NULL)
1407 list_free(outer_inner_pair);
1411 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1417 parse_parentheses_Leading(const char *str, List **name_list,
1418 OuterInnerRels **outer_inner)
1421 bool truncate = true;
1423 if ((str = skip_parenthesis(str, '(')) == NULL)
1429 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1434 /* Store words in parentheses into name_list. */
1435 while(*str != ')' && *str != '\0')
1437 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1439 list_free(*name_list);
1443 *name_list = lappend(*name_list, name);
1448 if ((str = skip_parenthesis(str, ')')) == NULL)
1454 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1457 bool truncate = true;
1459 if ((str = skip_parenthesis(str, '(')) == NULL)
1464 /* Store words in parentheses into name_list. */
1465 while(*str != ')' && *str != '\0')
1467 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1469 list_free(*name_list);
1473 *name_list = lappend(*name_list, name);
1476 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1477 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1478 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1479 keyword == HINT_KEYWORD_SET)
1485 if ((str = skip_parenthesis(str, ')')) == NULL)
1491 parse_hints(HintState *hstate, Query *parse, const char *str)
1496 initStringInfo(&buf);
1497 while (*str != '\0')
1499 const HintParser *parser;
1501 /* in error message, we output the comment including the keyword. */
1502 head = (char *) str;
1504 /* parse only the keyword of the hint. */
1505 resetStringInfo(&buf);
1506 str = parse_keyword(str, &buf);
1508 for (parser = parsers; parser->keyword != NULL; parser++)
1510 char *keyword = parser->keyword;
1513 if (strcasecmp(buf.data, keyword) != 0)
1516 hint = parser->create_func(head, keyword, parser->hint_keyword);
1518 /* parser of each hint does parse in a parenthesis. */
1519 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1521 hint->delete_func(hint);
1527 * Add hint information into all_hints array. If we don't have
1528 * enough space, double the array.
1530 if (hstate->nall_hints == 0)
1532 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1533 hstate->all_hints = (Hint **)
1534 palloc(sizeof(Hint *) * hstate->max_all_hints);
1536 else if (hstate->nall_hints == hstate->max_all_hints)
1538 hstate->max_all_hints *= 2;
1539 hstate->all_hints = (Hint **)
1540 repalloc(hstate->all_hints,
1541 sizeof(Hint *) * hstate->max_all_hints);
1544 hstate->all_hints[hstate->nall_hints] = hint;
1545 hstate->nall_hints++;
1552 if (parser->keyword == NULL)
1555 ("Unrecognized hint keyword \"%s\".", buf.data));
1566 * Get hints from table by client-supplied query string and application name.
1569 get_hints_from_table(const char *client_query, const char *client_application)
1571 const char *search_query =
1573 " FROM hint_plan.hints "
1574 " WHERE norm_query_string = $1 "
1575 " AND ( application_name = $2 "
1576 " OR application_name = '' ) "
1577 " ORDER BY application_name DESC";
1578 static SPIPlanPtr plan = NULL;
1580 Oid argtypes[2] = { TEXTOID, TEXTOID };
1582 bool nulls[2] = { false, false };
1588 hint_inhibit_level++;
1595 p = SPI_prepare(search_query, 2, argtypes);
1596 plan = SPI_saveplan(p);
1600 qry = cstring_to_text(client_query);
1601 app = cstring_to_text(client_application);
1602 values[0] = PointerGetDatum(qry);
1603 values[1] = PointerGetDatum(app);
1605 SPI_execute_plan(plan, values, nulls, true, 1);
1607 if (SPI_processed > 0)
1611 hints = SPI_getvalue(SPI_tuptable->vals[0],
1612 SPI_tuptable->tupdesc, 1);
1614 * Here we use SPI_palloc to ensure that hints string is valid even
1615 * after SPI_finish call. We can't use simple palloc because it
1616 * allocates memory in SPI's context and that context is deleted in
1619 buf = SPI_palloc(strlen(hints) + 1);
1626 hint_inhibit_level--;
1630 hint_inhibit_level--;
1639 * Get client-supplied query string.
1642 get_query_string(void)
1646 if (plpgsql_recurse_level > 0)
1649 * This is quite ugly but this is the only point I could find where
1650 * we can get the query string.
1652 p = (char*)error_context_stack->arg;
1656 PreparedStatement *entry;
1658 entry = FetchPreparedStatement(stmt_name, true);
1659 p = entry->plansource->query_string;
1662 p = debug_query_string;
1668 * Get hints from the head block comment in client-supplied query string.
1671 get_hints_from_comment(const char *p)
1673 const char *hint_head;
1681 /* extract query head comment. */
1682 hint_head = strstr(p, HINT_START);
1683 if (hint_head == NULL)
1685 for (;p < hint_head; p++)
1688 * Allow these characters precedes hint comment:
1690 * - alphabets which are in ASCII range
1691 * - space, tabs and new-lines
1692 * - underscores, for identifier
1693 * - commas, for SELECT clause, EXPLAIN and PREPARE
1694 * - parentheses, for EXPLAIN and PREPARE
1696 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1697 * avoid behavior which depends on locale setting.
1699 if (!(*p >= '0' && *p <= '9') &&
1700 !(*p >= 'A' && *p <= 'Z') &&
1701 !(*p >= 'a' && *p <= 'z') &&
1705 *p != '(' && *p != ')')
1709 len = strlen(HINT_START);
1714 /* find hint end keyword. */
1715 if ((tail = strstr(p, HINT_END)) == NULL)
1717 hint_ereport(head, ("Unterminated block comment."));
1721 /* We don't support nested block comments. */
1722 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1724 hint_ereport(head, ("Nested block comments are not supported."));
1728 /* Make a copy of hint. */
1730 head = palloc(len + 1);
1731 memcpy(head, p, len);
1739 * Parse hints that got, create hint struct from parse tree and parse hints.
1742 create_hintstate(Query *parse, const char *hints)
1752 hstate = HintStateCreate();
1753 hstate->hint_str = (char *) hints;
1755 /* parse each hint. */
1756 parse_hints(hstate, parse, p);
1758 /* When nothing specified a hint, we free HintState and returns NULL. */
1759 if (hstate->nall_hints == 0)
1761 HintStateDelete(hstate);
1765 /* Sort hints in order of original position. */
1766 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1769 /* Count number of hints per hint-type. */
1770 for (i = 0; i < hstate->nall_hints; i++)
1772 Hint *cur_hint = hstate->all_hints[i];
1773 hstate->num_hints[cur_hint->type]++;
1777 * If an object (or a set of objects) has multiple hints of same hint-type,
1778 * only the last hint is valid and others are ignored in planning.
1779 * Hints except the last are marked as 'duplicated' to remember the order.
1781 for (i = 0; i < hstate->nall_hints - 1; i++)
1783 Hint *cur_hint = hstate->all_hints[i];
1784 Hint *next_hint = hstate->all_hints[i + 1];
1787 * Leading hint is marked as 'duplicated' in transform_join_hints.
1789 if (cur_hint->type == HINT_TYPE_LEADING &&
1790 next_hint->type == HINT_TYPE_LEADING)
1794 * Note that we need to pass addresses of hint pointers, because
1795 * HintCmp is designed to sort array of Hint* by qsort.
1797 if (HintCmp(&cur_hint, &next_hint) == 0)
1799 hint_ereport(cur_hint->hint_str,
1800 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1801 cur_hint->state = HINT_STATE_DUPLICATION;
1806 * Make sure that per-type array pointers point proper position in the
1807 * array which consists of all hints.
1809 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1810 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1811 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1812 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1813 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1814 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1815 hstate->num_hints[HINT_TYPE_LEADING]);
1816 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
1817 hstate->num_hints[HINT_TYPE_SET]);
1823 * Parse inside of parentheses of scan-method hints.
1826 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1829 const char *keyword = hint->base.keyword;
1830 HintKeyword hint_keyword = hint->base.hint_keyword;
1831 List *name_list = NIL;
1834 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1837 /* Parse relation name and index name(s) if given hint accepts. */
1838 length = list_length(name_list);
1841 hint->relname = linitial(name_list);
1842 hint->indexnames = list_delete_first(name_list);
1844 /* check whether the hint accepts index name(s). */
1846 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1847 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1848 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1849 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1850 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1851 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1854 ("%s hint accepts only one relation.",
1855 hint->base.keyword));
1856 hint->base.state = HINT_STATE_ERROR;
1863 ("%s hint requires a relation.",
1864 hint->base.keyword));
1865 hint->base.state = HINT_STATE_ERROR;
1869 /* Set a bit for specified hint. */
1870 switch (hint_keyword)
1872 case HINT_KEYWORD_SEQSCAN:
1873 hint->enforce_mask = ENABLE_SEQSCAN;
1875 case HINT_KEYWORD_INDEXSCAN:
1876 hint->enforce_mask = ENABLE_INDEXSCAN;
1878 case HINT_KEYWORD_INDEXSCANREGEXP:
1879 hint->enforce_mask = ENABLE_INDEXSCAN;
1880 hint->regexp = true;
1882 case HINT_KEYWORD_BITMAPSCAN:
1883 hint->enforce_mask = ENABLE_BITMAPSCAN;
1885 case HINT_KEYWORD_BITMAPSCANREGEXP:
1886 hint->enforce_mask = ENABLE_BITMAPSCAN;
1887 hint->regexp = true;
1889 case HINT_KEYWORD_TIDSCAN:
1890 hint->enforce_mask = ENABLE_TIDSCAN;
1892 case HINT_KEYWORD_NOSEQSCAN:
1893 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1895 case HINT_KEYWORD_NOINDEXSCAN:
1896 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1898 case HINT_KEYWORD_NOBITMAPSCAN:
1899 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1901 case HINT_KEYWORD_NOTIDSCAN:
1902 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1904 case HINT_KEYWORD_INDEXONLYSCAN:
1905 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1907 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1908 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1909 hint->regexp = true;
1911 case HINT_KEYWORD_NOINDEXONLYSCAN:
1912 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1915 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1924 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1927 const char *keyword = hint->base.keyword;
1928 HintKeyword hint_keyword = hint->base.hint_keyword;
1929 List *name_list = NIL;
1931 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1934 hint->nrels = list_length(name_list);
1936 if (hint->nrels > 0)
1942 * Transform relation names from list to array to sort them with qsort
1945 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1946 foreach (l, name_list)
1948 hint->relnames[i] = lfirst(l);
1953 list_free(name_list);
1955 /* A join hint requires at least two relations */
1956 if (hint->nrels < 2)
1959 ("%s hint requires at least two relations.",
1960 hint->base.keyword));
1961 hint->base.state = HINT_STATE_ERROR;
1965 /* Sort hints in alphabetical order of relation names. */
1966 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1968 switch (hint_keyword)
1970 case HINT_KEYWORD_NESTLOOP:
1971 hint->enforce_mask = ENABLE_NESTLOOP;
1973 case HINT_KEYWORD_MERGEJOIN:
1974 hint->enforce_mask = ENABLE_MERGEJOIN;
1976 case HINT_KEYWORD_HASHJOIN:
1977 hint->enforce_mask = ENABLE_HASHJOIN;
1979 case HINT_KEYWORD_NONESTLOOP:
1980 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1982 case HINT_KEYWORD_NOMERGEJOIN:
1983 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1985 case HINT_KEYWORD_NOHASHJOIN:
1986 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1989 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1998 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2001 if (outer_inner->outer_inner_pair == NIL)
2003 if (outer_inner->relation)
2009 if (list_length(outer_inner->outer_inner_pair) == 2)
2011 foreach(l, outer_inner->outer_inner_pair)
2013 if (!OuterInnerPairCheck(lfirst(l)))
2024 OuterInnerList(OuterInnerRels *outer_inner)
2026 List *outer_inner_list = NIL;
2028 OuterInnerRels *outer_inner_rels;
2030 foreach(l, outer_inner->outer_inner_pair)
2032 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2034 if (outer_inner_rels->relation != NULL)
2035 outer_inner_list = lappend(outer_inner_list,
2036 outer_inner_rels->relation);
2038 outer_inner_list = list_concat(outer_inner_list,
2039 OuterInnerList(outer_inner_rels));
2041 return outer_inner_list;
2045 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2048 List *name_list = NIL;
2049 OuterInnerRels *outer_inner = NULL;
2051 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2055 if (outer_inner != NULL)
2056 name_list = OuterInnerList(outer_inner);
2058 hint->relations = name_list;
2059 hint->outer_inner = outer_inner;
2061 /* A Leading hint requires at least two relations */
2062 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2064 hint_ereport(hint->base.hint_str,
2065 ("%s hint requires at least two relations.",
2067 hint->base.state = HINT_STATE_ERROR;
2069 else if (hint->outer_inner != NULL &&
2070 !OuterInnerPairCheck(hint->outer_inner))
2072 hint_ereport(hint->base.hint_str,
2073 ("%s hint requires two sets of relations when parentheses nests.",
2075 hint->base.state = HINT_STATE_ERROR;
2082 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2084 List *name_list = NIL;
2086 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2090 hint->words = name_list;
2092 /* We need both name and value to set GUC parameter. */
2093 if (list_length(name_list) == 2)
2095 hint->name = linitial(name_list);
2096 hint->value = lsecond(name_list);
2100 hint_ereport(hint->base.hint_str,
2101 ("%s hint requires name and value of GUC parameter.",
2103 hint->base.state = HINT_STATE_ERROR;
2110 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2113 HintKeyword hint_keyword = hint->base.hint_keyword;
2114 List *name_list = NIL;
2118 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2121 /* Last element must be rows specification */
2122 hint->nrels = list_length(name_list) - 1;
2124 if (hint->nrels > 0)
2130 * Transform relation names from list to array to sort them with qsort
2133 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2134 foreach (l, name_list)
2136 if (hint->nrels <= i)
2138 hint->relnames[i] = lfirst(l);
2143 /* Retieve rows estimation */
2144 rows_str = list_nth(name_list, hint->nrels);
2145 hint->rows_str = rows_str; /* store as-is for error logging */
2146 if (rows_str[0] == '#')
2148 hint->value_type = RVT_ABSOLUTE;
2151 else if (rows_str[0] == '+')
2153 hint->value_type = RVT_ADD;
2156 else if (rows_str[0] == '-')
2158 hint->value_type = RVT_SUB;
2161 else if (rows_str[0] == '*')
2163 hint->value_type = RVT_MULTI;
2168 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2169 hint->base.state = HINT_STATE_ERROR;
2172 hint->rows = strtod(rows_str, &end_ptr);
2175 hint_ereport(rows_str,
2176 ("%s hint requires valid number as rows estimation.",
2177 hint->base.keyword));
2178 hint->base.state = HINT_STATE_ERROR;
2182 /* A join hint requires at least two relations */
2183 if (hint->nrels < 2)
2186 ("%s hint requires at least two relations.",
2187 hint->base.keyword));
2188 hint->base.state = HINT_STATE_ERROR;
2192 list_free(name_list);
2194 /* Sort relnames in alphabetical order. */
2195 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2201 * set GUC parameter functions
2205 set_config_option_wrapper(const char *name, const char *value,
2206 GucContext context, GucSource source,
2207 GucAction action, bool changeVal, int elevel)
2210 MemoryContext ccxt = CurrentMemoryContext;
2214 result = set_config_option(name, value, context, source,
2215 action, changeVal, 0, false);
2221 /* Save error info */
2222 MemoryContextSwitchTo(ccxt);
2223 errdata = CopyErrorData();
2227 (errcode(errdata->sqlerrcode),
2228 errhidestmt(hidestmt),
2229 errmsg("%s", errdata->message),
2230 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2231 errdata->hint ? errhint("%s", errdata->hint) : 0));
2232 FreeErrorData(errdata);
2240 set_config_options(SetHint **options, int noptions, GucContext context)
2245 save_nestlevel = NewGUCNestLevel();
2247 for (i = 0; i < noptions; i++)
2249 SetHint *hint = options[i];
2252 if (!hint_state_enabled(hint))
2255 result = set_config_option_wrapper(hint->name, hint->value, context,
2256 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2257 pg_hint_plan_message_level);
2259 hint->base.state = HINT_STATE_USED;
2261 hint->base.state = HINT_STATE_ERROR;
2264 return save_nestlevel;
2267 #define SET_CONFIG_OPTION(name, type_bits) \
2268 set_config_option_wrapper((name), \
2269 (mask & (type_bits)) ? "true" : "false", \
2270 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2273 set_scan_config_options(unsigned char enforce_mask, GucContext context)
2277 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2278 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2279 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2281 mask = enforce_mask;
2283 mask = enforce_mask & current_hint->init_scan_mask;
2285 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2286 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2287 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2288 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2289 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2293 set_join_config_options(unsigned char enforce_mask, GucContext context)
2297 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2298 enforce_mask == ENABLE_HASHJOIN)
2299 mask = enforce_mask;
2301 mask = enforce_mask & current_hint->init_join_mask;
2303 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2304 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2305 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2309 * pg_hint_plan hook functions
2313 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
2314 ProcessUtilityContext context,
2315 ParamListInfo params,
2316 DestReceiver *dest, char *completionTag)
2321 * Use standard planner if pg_hint_plan is disabled or current nesting
2322 * depth is nesting depth of SPI calls.
2324 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2326 if (debug_level > 1)
2327 ereport(pg_hint_plan_message_level,
2328 (errmsg ("pg_hint_plan: ProcessUtility:"
2329 " pg_hint_plan.enable_hint = off")));
2330 if (prev_ProcessUtility)
2331 (*prev_ProcessUtility) (parsetree, queryString,
2333 dest, completionTag);
2335 standard_ProcessUtility(parsetree, queryString,
2337 dest, completionTag);
2342 if (IsA(node, ExplainStmt))
2345 * Draw out parse tree of actual query from Query struct of EXPLAIN
2351 stmt = (ExplainStmt *) node;
2353 Assert(IsA(stmt->query, Query));
2354 query = (Query *) stmt->query;
2356 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2357 node = query->utilityStmt;
2361 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2362 * specified to preceding PREPARE command to use it as source of hints.
2364 if (IsA(node, ExecuteStmt))
2368 stmt = (ExecuteStmt *) node;
2369 stmt_name = stmt->name;
2373 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2376 if (IsA(node, CreateTableAsStmt))
2378 CreateTableAsStmt *stmt;
2381 stmt = (CreateTableAsStmt *) node;
2382 Assert(IsA(stmt->query, Query));
2383 query = (Query *) stmt->query;
2385 if (query->commandType == CMD_UTILITY &&
2386 IsA(query->utilityStmt, ExecuteStmt))
2388 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2389 stmt_name = estmt->name;
2395 if (debug_level > 1)
2396 ereport(pg_hint_plan_message_level,
2397 (errmsg ("pg_hint_plan: ProcessUtility:"
2398 " stmt_name = \"%s\", statement=\"%s\"",
2399 stmt_name, queryString)));
2403 if (prev_ProcessUtility)
2404 (*prev_ProcessUtility) (parsetree, queryString,
2406 dest, completionTag);
2408 standard_ProcessUtility(parsetree, queryString,
2410 dest, completionTag);
2424 if (prev_ProcessUtility)
2425 (*prev_ProcessUtility) (parsetree, queryString,
2427 dest, completionTag);
2429 standard_ProcessUtility(parsetree, queryString,
2431 dest, completionTag);
2435 * Push a hint into hint stack which is implemented with List struct. Head of
2436 * list is top of stack.
2439 push_hint(HintState *hstate)
2441 /* Prepend new hint to the list means pushing to stack. */
2442 HintStateStack = lcons(hstate, HintStateStack);
2444 /* Pushed hint is the one which should be used hereafter. */
2445 current_hint = hstate;
2448 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2452 /* Hint stack must not be empty. */
2453 if(HintStateStack == NIL)
2454 elog(ERROR, "hint stack is empty");
2457 * Take a hint at the head from the list, and free it. Switch current_hint
2458 * to point new head (NULL if the list is empty).
2460 HintStateStack = list_delete_first(HintStateStack);
2461 HintStateDelete(current_hint);
2462 if(HintStateStack == NIL)
2463 current_hint = NULL;
2465 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2468 static PlannedStmt *
2469 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2471 const char *hints = NULL;
2474 pgssJumbleState jstate;
2477 PlannedStmt *result;
2483 if (debug_level > 1)
2484 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2488 * Use standard planner if pg_hint_plan is disabled or current nesting
2489 * depth is nesting depth of SPI calls. Other hook functions try to change
2490 * plan with current_hint if any, so set it to NULL.
2492 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2494 if (debug_level > 1)
2495 elog(pg_hint_plan_message_level,
2496 "pg_hint_plan%s: planner: enable_hint=%d,"
2497 " hint_inhibit_level=%d",
2498 qnostr, pg_hint_plan_enable_hint, hint_inhibit_level);
2501 goto standard_planner_proc;
2504 /* Create hint struct from client-supplied query string. */
2505 query = get_query_string();
2508 * Create hintstate from hint specified for the query, if any.
2510 * First we lookup hint in pg_hint.hints table by normalized query string,
2511 * unless pg_hint_plan.enable_hint_table is OFF.
2512 * This parameter provides option to avoid overhead of table lookup during
2515 * If no hint was found, then we try to get hint from special query comment.
2517 if (pg_hint_plan_enable_hint_table)
2520 * Search hint information which is stored for the query and the
2521 * application. Query string is normalized before using in condition
2522 * in order to allow fuzzy matching.
2524 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2525 * careful when supporting PostgreSQL's version up.
2527 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2528 jstate.jumble_len = 0;
2529 jstate.clocations_buf_size = 32;
2530 jstate.clocations = (pgssLocationLen *)
2531 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2532 jstate.clocations_count = 0;
2533 JumbleQuery(&jstate, parse);
2535 * generate_normalized_query() copies exact given query_len bytes, so we
2536 * add 1 byte for null-termination here. As comments on
2537 * generate_normalized_query says, generate_normalized_query doesn't
2538 * take care of null-terminate, but additional 1 byte ensures that '\0'
2539 * byte in the source buffer to be copied into norm_query.
2541 query_len = strlen(query) + 1;
2542 norm_query = generate_normalized_query(&jstate,
2545 GetDatabaseEncoding());
2546 hints = get_hints_from_table(norm_query, application_name);
2547 if (debug_level > 1)
2550 snprintf(msgstr, 1024, "hints from table: \"%s\":"
2551 " normalzed_query=\"%s\", application name =\"%s\"",
2552 hints, norm_query, application_name);
2555 ereport(pg_hint_plan_message_level,
2556 (errhidestmt(hidestmt),
2557 errmsg("pg_hint_plan%s:"
2558 " no match found in table:"
2559 " application name = \"%s\","
2560 " normalzed_query=\"%s\"",
2561 qnostr, application_name, norm_query)));
2568 hints = get_hints_from_comment(query);
2570 if (debug_level > 1)
2572 snprintf(msgstr, 1024, "hints in comment=\"%s\"",
2573 hints ? hints : "(none)");
2574 if (debug_level > 2 ||
2575 stmt_name || strcmp(query, debug_query_string))
2576 snprintf(msgstr + strlen(msgstr), 1024- strlen(msgstr),
2577 ", stmt=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2578 stmt_name, query, debug_query_string);
2582 hstate = create_hintstate(parse, hints);
2585 * Use standard planner if the statement has not valid hint. Other hook
2586 * functions try to change plan with current_hint if any, so set it to
2590 goto standard_planner_proc;
2593 * Push new hint struct to the hint stack to disable previous hint context.
2597 /* Set GUC parameters which are specified with Set hint. */
2598 save_nestlevel = set_config_options(current_hint->set_hints,
2599 current_hint->num_hints[HINT_TYPE_SET],
2600 current_hint->context);
2603 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2604 if (enable_indexscan)
2605 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2606 if (enable_bitmapscan)
2607 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2609 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2610 if (enable_indexonlyscan)
2611 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2612 if (enable_nestloop)
2613 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2614 if (enable_mergejoin)
2615 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2616 if (enable_hashjoin)
2617 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2619 if (debug_level > 1)
2621 ereport(pg_hint_plan_message_level,
2622 (errhidestmt(hidestmt),
2623 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 > 1)
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 whether 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)
3688 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3692 if (hint->inner_nrels == 0 &&
3693 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3694 bms_equal(bms_union(hint->joinrelids, joinrelids),
3697 hstate->join_hint_level[i] =
3698 list_delete_cell(hstate->join_hint_level[i], l,
3707 bms_free(joinrelids);
3710 if (hint_state_enabled(lhint))
3712 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3719 * set_plain_rel_pathlist
3720 * Build access paths for a plain relation (no subquery, no inheritance)
3722 * This function was copied and edited from set_plain_rel_pathlist() in
3723 * src/backend/optimizer/path/allpaths.c
3726 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3728 /* Consider sequential scan */
3729 add_path(rel, create_seqscan_path(root, rel, NULL));
3731 /* Consider index scans */
3732 create_index_paths(root, rel);
3734 /* Consider TID scans */
3735 create_tidscan_paths(root, rel);
3737 /* Now find the cheapest of the paths for this rel */
3742 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3747 foreach(l, initial_rels)
3749 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3751 ScanMethodHint *hint;
3753 /* Skip relations which we can't choose scan method. */
3754 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3757 rte = root->simple_rte_array[rel->relid];
3759 /* We can't force scan method of foreign tables */
3760 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3764 * Create scan paths with GUC parameters which are at the beginning of
3765 * planner if scan method hint is not specified, otherwise use
3766 * specified hints and mark the hint as used.
3768 if ((hint = find_scan_hint(root, rel->relid, rel)) == NULL)
3769 set_scan_config_options(hstate->init_scan_mask,
3773 set_scan_config_options(hint->enforce_mask, hstate->context);
3774 hint->base.state = HINT_STATE_USED;
3777 list_free_deep(rel->pathlist);
3778 rel->pathlist = NIL;
3781 /* It's an "append relation", process accordingly */
3782 set_append_rel_pathlist(root, rel, rel->relid, rte);
3786 set_plain_rel_pathlist(root, rel, rte);
3791 * Restore the GUC variables we set above.
3793 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3797 * wrapper of make_join_rel()
3799 * call make_join_rel() after changing enable_* parameters according to given
3803 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3806 JoinMethodHint *hint;
3810 joinrelids = bms_union(rel1->relids, rel2->relids);
3811 hint = find_join_hint(joinrelids);
3812 bms_free(joinrelids);
3815 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3817 if (hint->inner_nrels == 0)
3819 save_nestlevel = NewGUCNestLevel();
3821 set_join_config_options(hint->enforce_mask, current_hint->context);
3823 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3824 hint->base.state = HINT_STATE_USED;
3827 * Restore the GUC variables we set above.
3829 AtEOXact_GUC(true, save_nestlevel);
3832 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3841 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3842 RelOptInfo *joinrel,
3843 RelOptInfo *outerrel,
3844 RelOptInfo *innerrel,
3846 SpecialJoinInfo *sjinfo,
3849 ScanMethodHint *scan_hint = NULL;
3851 JoinMethodHint *join_hint;
3854 if ((scan_hint = find_scan_hint(root, innerrel->relid, innerrel)) != NULL)
3856 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3857 scan_hint->base.state = HINT_STATE_USED;
3860 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"