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;
435 static bool hidestmt = false;
437 static const struct config_enum_entry parse_messages_level_options[] = {
438 {"debug", DEBUG2, true},
439 {"debug5", DEBUG5, false},
440 {"debug4", DEBUG4, false},
441 {"debug3", DEBUG3, false},
442 {"debug2", DEBUG2, false},
443 {"debug1", DEBUG1, false},
445 {"info", INFO, false},
446 {"notice", NOTICE, false},
447 {"warning", WARNING, false},
448 {"error", ERROR, false},
450 * {"fatal", FATAL, true},
451 * {"panic", PANIC, true},
456 static const struct config_enum_entry parse_debug_level_options[] = {
459 {"detailed", 2, false},
460 {"verbose", 3, false},
472 /* Saved hook values in case of unload */
473 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
474 static planner_hook_type prev_planner = NULL;
475 static get_relation_info_hook_type prev_get_relation_info = NULL;
476 static join_search_hook_type prev_join_search = NULL;
478 /* Hold reference to currently active hint */
479 static HintState *current_hint = NULL;
482 * List of hint contexts. We treat the head of the list as the Top of the
483 * context stack, so current_hint always points the first element of this list.
485 static List *HintStateStack = NIL;
488 * Holds statement name during executing EXECUTE command. NULL for other
491 static char *stmt_name = NULL;
493 static const HintParser parsers[] = {
494 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
495 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
496 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
497 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
498 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
499 HINT_KEYWORD_BITMAPSCANREGEXP},
500 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
501 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
502 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
503 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
504 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
505 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
506 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
507 HINT_KEYWORD_INDEXONLYSCANREGEXP},
508 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
509 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
510 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
511 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
512 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
513 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
514 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
515 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
516 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
517 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
518 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
522 * PL/pgSQL plugin for retrieving string representation of each query during
523 * function execution.
525 static const char *plpgsql_query_string = NULL;
526 static enum PLpgSQL_stmt_types plpgsql_query_string_src;
528 PLpgSQL_plugin plugin_funcs = {
532 pg_hint_plan_plpgsql_stmt_beg,
533 pg_hint_plan_plpgsql_stmt_end,
538 /* Current nesting depth of SPI calls, used to prevent recursive calls */
539 static int nested_level = 0;
542 * Module load callbacks
547 PLpgSQL_plugin **var_ptr;
549 /* Define custom GUC variables. */
550 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
551 "Force planner to use plans specified in the hint comment preceding to the query.",
553 &pg_hint_plan_enable_hint,
561 DefineCustomEnumVariable("pg_hint_plan.debug_print",
562 "Logs results of hint parsing.",
566 parse_debug_level_options,
573 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
574 "Message level of parse errors.",
576 &pg_hint_plan_message_level,
578 parse_messages_level_options,
585 DefineCustomEnumVariable("pg_hint_plan.message_level",
586 "Message level of debug messages.",
588 &pg_hint_plan_message_level,
590 parse_messages_level_options,
597 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
598 "Force planner to not get hint by using table lookups.",
600 &pg_hint_plan_enable_hint_table,
609 prev_ProcessUtility = ProcessUtility_hook;
610 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
611 prev_planner = planner_hook;
612 planner_hook = pg_hint_plan_planner;
613 prev_get_relation_info = get_relation_info_hook;
614 get_relation_info_hook = pg_hint_plan_get_relation_info;
615 prev_join_search = join_search_hook;
616 join_search_hook = pg_hint_plan_join_search;
618 /* setup PL/pgSQL plugin hook */
619 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
620 *var_ptr = &plugin_funcs;
622 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
626 * Module unload callback
632 PLpgSQL_plugin **var_ptr;
634 /* Uninstall hooks. */
635 ProcessUtility_hook = prev_ProcessUtility;
636 planner_hook = prev_planner;
637 get_relation_info_hook = prev_get_relation_info;
638 join_search_hook = prev_join_search;
640 /* uninstall PL/pgSQL plugin hook */
641 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
646 * create and delete functions the hint object
650 ScanMethodHintCreate(const char *hint_str, const char *keyword,
651 HintKeyword hint_keyword)
653 ScanMethodHint *hint;
655 hint = palloc(sizeof(ScanMethodHint));
656 hint->base.hint_str = hint_str;
657 hint->base.keyword = keyword;
658 hint->base.hint_keyword = hint_keyword;
659 hint->base.type = HINT_TYPE_SCAN_METHOD;
660 hint->base.state = HINT_STATE_NOTUSED;
661 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
662 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
663 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
664 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
665 hint->relname = NULL;
666 hint->indexnames = NIL;
667 hint->regexp = false;
668 hint->enforce_mask = 0;
670 return (Hint *) hint;
674 ScanMethodHintDelete(ScanMethodHint *hint)
680 pfree(hint->relname);
681 list_free_deep(hint->indexnames);
686 JoinMethodHintCreate(const char *hint_str, const char *keyword,
687 HintKeyword hint_keyword)
689 JoinMethodHint *hint;
691 hint = palloc(sizeof(JoinMethodHint));
692 hint->base.hint_str = hint_str;
693 hint->base.keyword = keyword;
694 hint->base.hint_keyword = hint_keyword;
695 hint->base.type = HINT_TYPE_JOIN_METHOD;
696 hint->base.state = HINT_STATE_NOTUSED;
697 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
698 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
699 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
700 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
702 hint->inner_nrels = 0;
703 hint->relnames = NULL;
704 hint->enforce_mask = 0;
705 hint->joinrelids = NULL;
706 hint->inner_joinrelids = NULL;
708 return (Hint *) hint;
712 JoinMethodHintDelete(JoinMethodHint *hint)
721 for (i = 0; i < hint->nrels; i++)
722 pfree(hint->relnames[i]);
723 pfree(hint->relnames);
726 bms_free(hint->joinrelids);
727 bms_free(hint->inner_joinrelids);
732 LeadingHintCreate(const char *hint_str, const char *keyword,
733 HintKeyword hint_keyword)
737 hint = palloc(sizeof(LeadingHint));
738 hint->base.hint_str = hint_str;
739 hint->base.keyword = keyword;
740 hint->base.hint_keyword = hint_keyword;
741 hint->base.type = HINT_TYPE_LEADING;
742 hint->base.state = HINT_STATE_NOTUSED;
743 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
744 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
745 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
746 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
747 hint->relations = NIL;
748 hint->outer_inner = NULL;
750 return (Hint *) hint;
754 LeadingHintDelete(LeadingHint *hint)
759 list_free_deep(hint->relations);
760 if (hint->outer_inner)
761 pfree(hint->outer_inner);
766 SetHintCreate(const char *hint_str, const char *keyword,
767 HintKeyword hint_keyword)
771 hint = palloc(sizeof(SetHint));
772 hint->base.hint_str = hint_str;
773 hint->base.keyword = keyword;
774 hint->base.hint_keyword = hint_keyword;
775 hint->base.type = HINT_TYPE_SET;
776 hint->base.state = HINT_STATE_NOTUSED;
777 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
778 hint->base.desc_func = (HintDescFunction) SetHintDesc;
779 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
780 hint->base.parse_func = (HintParseFunction) SetHintParse;
785 return (Hint *) hint;
789 SetHintDelete(SetHint *hint)
799 list_free(hint->words);
804 RowsHintCreate(const char *hint_str, const char *keyword,
805 HintKeyword hint_keyword)
809 hint = palloc(sizeof(RowsHint));
810 hint->base.hint_str = hint_str;
811 hint->base.keyword = keyword;
812 hint->base.hint_keyword = hint_keyword;
813 hint->base.type = HINT_TYPE_ROWS;
814 hint->base.state = HINT_STATE_NOTUSED;
815 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
816 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
817 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
818 hint->base.parse_func = (HintParseFunction) RowsHintParse;
820 hint->inner_nrels = 0;
821 hint->relnames = NULL;
822 hint->joinrelids = NULL;
823 hint->inner_joinrelids = NULL;
824 hint->rows_str = NULL;
825 hint->value_type = RVT_ABSOLUTE;
828 return (Hint *) hint;
832 RowsHintDelete(RowsHint *hint)
841 for (i = 0; i < hint->nrels; i++)
842 pfree(hint->relnames[i]);
843 pfree(hint->relnames);
846 bms_free(hint->joinrelids);
847 bms_free(hint->inner_joinrelids);
852 HintStateCreate(void)
856 hstate = palloc(sizeof(HintState));
857 hstate->hint_str = NULL;
858 hstate->nall_hints = 0;
859 hstate->max_all_hints = 0;
860 hstate->all_hints = NULL;
861 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
862 hstate->scan_hints = NULL;
863 hstate->init_scan_mask = 0;
864 hstate->parent_relid = 0;
865 hstate->parent_hint = NULL;
866 hstate->parent_index_infos = NIL;
867 hstate->join_hints = NULL;
868 hstate->init_join_mask = 0;
869 hstate->join_hint_level = NULL;
870 hstate->leading_hint = NULL;
871 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
872 hstate->set_hints = NULL;
873 hstate->rows_hints = NULL;
879 HintStateDelete(HintState *hstate)
886 if (hstate->hint_str)
887 pfree(hstate->hint_str);
889 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
890 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
891 if (hstate->all_hints)
892 pfree(hstate->all_hints);
893 if (hstate->parent_index_infos)
894 list_free(hstate->parent_index_infos);
898 * Copy given value into buf, with quoting with '"' if necessary.
901 quote_value(StringInfo buf, const char *value)
903 bool need_quote = false;
906 for (str = value; *str != '\0'; str++)
908 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
911 appendStringInfoCharMacro(buf, '"');
916 for (str = value; *str != '\0'; str++)
919 appendStringInfoCharMacro(buf, '"');
921 appendStringInfoCharMacro(buf, *str);
925 appendStringInfoCharMacro(buf, '"');
929 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
933 appendStringInfo(buf, "%s(", hint->base.keyword);
934 if (hint->relname != NULL)
936 quote_value(buf, hint->relname);
937 foreach(l, hint->indexnames)
939 appendStringInfoCharMacro(buf, ' ');
940 quote_value(buf, (char *) lfirst(l));
943 appendStringInfoString(buf, ")");
945 appendStringInfoChar(buf, '\n');
949 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
953 appendStringInfo(buf, "%s(", hint->base.keyword);
954 if (hint->relnames != NULL)
956 quote_value(buf, hint->relnames[0]);
957 for (i = 1; i < hint->nrels; i++)
959 appendStringInfoCharMacro(buf, ' ');
960 quote_value(buf, hint->relnames[i]);
963 appendStringInfoString(buf, ")");
965 appendStringInfoChar(buf, '\n');
969 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
971 if (outer_inner->relation == NULL)
978 appendStringInfoCharMacro(buf, '(');
979 foreach(l, outer_inner->outer_inner_pair)
984 appendStringInfoCharMacro(buf, ' ');
986 OuterInnerDesc(lfirst(l), buf);
989 appendStringInfoCharMacro(buf, ')');
992 quote_value(buf, outer_inner->relation);
996 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
998 appendStringInfo(buf, "%s(", HINT_LEADING);
999 if (hint->outer_inner == NULL)
1006 foreach(l, hint->relations)
1011 appendStringInfoCharMacro(buf, ' ');
1013 quote_value(buf, (char *) lfirst(l));
1017 OuterInnerDesc(hint->outer_inner, buf);
1019 appendStringInfoString(buf, ")");
1021 appendStringInfoChar(buf, '\n');
1025 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1027 bool is_first = true;
1030 appendStringInfo(buf, "%s(", HINT_SET);
1031 foreach(l, hint->words)
1036 appendStringInfoCharMacro(buf, ' ');
1038 quote_value(buf, (char *) lfirst(l));
1040 appendStringInfo(buf, ")");
1042 appendStringInfoChar(buf, '\n');
1046 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1050 appendStringInfo(buf, "%s(", hint->base.keyword);
1051 if (hint->relnames != NULL)
1053 quote_value(buf, hint->relnames[0]);
1054 for (i = 1; i < hint->nrels; i++)
1056 appendStringInfoCharMacro(buf, ' ');
1057 quote_value(buf, hint->relnames[i]);
1060 appendStringInfo(buf, " %s", hint->rows_str);
1061 appendStringInfoString(buf, ")");
1063 appendStringInfoChar(buf, '\n');
1067 * Append string which represents all hints in a given state to buf, with
1068 * preceding title with them.
1071 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1072 HintStatus state, bool nolf)
1076 appendStringInfo(buf, "%s:", title);
1078 appendStringInfoChar(buf, '\n');
1081 for (i = 0; i < hstate->nall_hints; i++)
1083 if (hstate->all_hints[i]->state != state)
1086 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1090 if (nolf && nshown == 0)
1091 appendStringInfoString(buf, "(none)");
1095 * Dump contents of given hstate to server log with log level LOG.
1098 HintStateDump(HintState *hstate)
1104 elog(LOG, "pg_hint_plan:\nno hint");
1108 initStringInfo(&buf);
1110 appendStringInfoString(&buf, "pg_hint_plan:\n");
1111 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1112 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1113 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1114 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1116 elog(LOG, "%s", buf.data);
1122 HintStateDump2(HintState *hstate)
1128 elog(pg_hint_plan_message_level,
1129 "pg_hint_plan%s: HintStateDump:\nno hint", qnostr);
1133 initStringInfo(&buf);
1134 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1135 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1136 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1137 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1138 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1139 appendStringInfoChar(&buf, '}');
1141 ereport(pg_hint_plan_message_level,
1143 errmsg("%s", buf.data)));
1153 RelnameCmp(const void *a, const void *b)
1155 const char *relnamea = *((const char **) a);
1156 const char *relnameb = *((const char **) b);
1158 return strcmp(relnamea, relnameb);
1162 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1164 return RelnameCmp(&a->relname, &b->relname);
1168 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1172 if (a->nrels != b->nrels)
1173 return a->nrels - b->nrels;
1175 for (i = 0; i < a->nrels; i++)
1178 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1186 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1192 SetHintCmp(const SetHint *a, const SetHint *b)
1194 return strcmp(a->name, b->name);
1198 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1202 if (a->nrels != b->nrels)
1203 return a->nrels - b->nrels;
1205 for (i = 0; i < a->nrels; i++)
1208 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1216 HintCmp(const void *a, const void *b)
1218 const Hint *hinta = *((const Hint **) a);
1219 const Hint *hintb = *((const Hint **) b);
1221 if (hinta->type != hintb->type)
1222 return hinta->type - hintb->type;
1223 if (hinta->state == HINT_STATE_ERROR)
1225 if (hintb->state == HINT_STATE_ERROR)
1227 return hinta->cmp_func(hinta, hintb);
1231 * Returns byte offset of hint b from hint a. If hint a was specified before
1232 * b, positive value is returned.
1235 HintCmpWithPos(const void *a, const void *b)
1237 const Hint *hinta = *((const Hint **) a);
1238 const Hint *hintb = *((const Hint **) b);
1241 result = HintCmp(a, b);
1243 result = hinta->hint_str - hintb->hint_str;
1252 parse_keyword(const char *str, StringInfo buf)
1256 while (!isspace(*str) && *str != '(' && *str != '\0')
1257 appendStringInfoCharMacro(buf, *str++);
1263 skip_parenthesis(const char *str, char parenthesis)
1267 if (*str != parenthesis)
1269 if (parenthesis == '(')
1270 hint_ereport(str, ("Opening parenthesis is necessary."));
1271 else if (parenthesis == ')')
1272 hint_ereport(str, ("Closing parenthesis is necessary."));
1283 * Parse a token from str, and store malloc'd copy into word. A token can be
1284 * quoted with '"'. Return value is pointer to unparsed portion of original
1285 * string, or NULL if an error occurred.
1287 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1290 parse_quoted_value(const char *str, char **word, bool truncate)
1295 /* Skip leading spaces. */
1298 initStringInfo(&buf);
1311 /* Double quotation must be closed. */
1315 hint_ereport(str, ("Unterminated quoted string."));
1320 * Skip escaped double quotation.
1322 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1323 * block comments) to be an object name, so users must specify
1324 * alias for such object names.
1326 * Those special names can be allowed if we care escaped slashes
1327 * and asterisks, but we don't.
1336 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1340 appendStringInfoCharMacro(&buf, *str++);
1345 hint_ereport(str, ("Zero-length delimited string."));
1352 /* Truncate name if it's too long */
1354 truncate_identifier(buf.data, strlen(buf.data), true);
1361 static OuterInnerRels *
1362 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1364 OuterInnerRels *outer_inner;
1366 outer_inner = palloc(sizeof(OuterInnerRels));
1367 outer_inner->relation = name;
1368 outer_inner->outer_inner_pair = outer_inner_list;
1374 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1376 List *outer_inner_pair = NIL;
1378 if ((str = skip_parenthesis(str, '(')) == NULL)
1383 /* Store words in parentheses into outer_inner_list. */
1384 while(*str != ')' && *str != '\0')
1386 OuterInnerRels *outer_inner_rels;
1390 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1398 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1401 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1404 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1409 (str = skip_parenthesis(str, ')')) == NULL)
1411 list_free(outer_inner_pair);
1415 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1421 parse_parentheses_Leading(const char *str, List **name_list,
1422 OuterInnerRels **outer_inner)
1425 bool truncate = true;
1427 if ((str = skip_parenthesis(str, '(')) == NULL)
1433 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1438 /* Store words in parentheses into name_list. */
1439 while(*str != ')' && *str != '\0')
1441 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1443 list_free(*name_list);
1447 *name_list = lappend(*name_list, name);
1452 if ((str = skip_parenthesis(str, ')')) == NULL)
1458 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1461 bool truncate = true;
1463 if ((str = skip_parenthesis(str, '(')) == NULL)
1468 /* Store words in parentheses into name_list. */
1469 while(*str != ')' && *str != '\0')
1471 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1473 list_free(*name_list);
1477 *name_list = lappend(*name_list, name);
1480 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1481 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1482 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1483 keyword == HINT_KEYWORD_SET)
1489 if ((str = skip_parenthesis(str, ')')) == NULL)
1495 parse_hints(HintState *hstate, Query *parse, const char *str)
1500 initStringInfo(&buf);
1501 while (*str != '\0')
1503 const HintParser *parser;
1505 /* in error message, we output the comment including the keyword. */
1506 head = (char *) str;
1508 /* parse only the keyword of the hint. */
1509 resetStringInfo(&buf);
1510 str = parse_keyword(str, &buf);
1512 for (parser = parsers; parser->keyword != NULL; parser++)
1514 char *keyword = parser->keyword;
1517 if (strcasecmp(buf.data, keyword) != 0)
1520 hint = parser->create_func(head, keyword, parser->hint_keyword);
1522 /* parser of each hint does parse in a parenthesis. */
1523 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1525 hint->delete_func(hint);
1531 * Add hint information into all_hints array. If we don't have
1532 * enough space, double the array.
1534 if (hstate->nall_hints == 0)
1536 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1537 hstate->all_hints = (Hint **)
1538 palloc(sizeof(Hint *) * hstate->max_all_hints);
1540 else if (hstate->nall_hints == hstate->max_all_hints)
1542 hstate->max_all_hints *= 2;
1543 hstate->all_hints = (Hint **)
1544 repalloc(hstate->all_hints,
1545 sizeof(Hint *) * hstate->max_all_hints);
1548 hstate->all_hints[hstate->nall_hints] = hint;
1549 hstate->nall_hints++;
1556 if (parser->keyword == NULL)
1559 ("Unrecognized hint keyword \"%s\".", buf.data));
1570 * Get hints from table by client-supplied query string and application name.
1573 get_hints_from_table(const char *client_query, const char *client_application)
1575 const char *search_query =
1577 " FROM hint_plan.hints "
1578 " WHERE norm_query_string = $1 "
1579 " AND ( application_name = $2 "
1580 " OR application_name = '' ) "
1581 " ORDER BY application_name DESC";
1582 static SPIPlanPtr plan = NULL;
1584 Oid argtypes[2] = { TEXTOID, TEXTOID };
1586 bool nulls[2] = { false, false };
1599 p = SPI_prepare(search_query, 2, argtypes);
1600 plan = SPI_saveplan(p);
1604 qry = cstring_to_text(client_query);
1605 app = cstring_to_text(client_application);
1606 values[0] = PointerGetDatum(qry);
1607 values[1] = PointerGetDatum(app);
1609 SPI_execute_plan(plan, values, nulls, true, 1);
1611 if (SPI_processed > 0)
1615 hints = SPI_getvalue(SPI_tuptable->vals[0],
1616 SPI_tuptable->tupdesc, 1);
1618 * Here we use SPI_palloc to ensure that hints string is valid even
1619 * after SPI_finish call. We can't use simple palloc because it
1620 * allocates memory in SPI's context and that context is deleted in
1623 buf = SPI_palloc(strlen(hints) + 1);
1643 * Get client-supplied query string.
1646 get_query_string(void)
1652 PreparedStatement *entry;
1654 entry = FetchPreparedStatement(stmt_name, true);
1655 p = entry->plansource->query_string;
1657 else if (plpgsql_query_string)
1658 p = plpgsql_query_string;
1660 p = debug_query_string;
1666 * Get hints from the head block comment in client-supplied query string.
1669 get_hints_from_comment(const char *p)
1671 const char *hint_head;
1679 /* extract query head comment. */
1680 hint_head = strstr(p, HINT_START);
1681 if (hint_head == NULL)
1683 for (;p < hint_head; p++)
1686 * Allow these characters precedes hint comment:
1688 * - alphabets which are in ASCII range
1689 * - space, tabs and new-lines
1690 * - underscores, for identifier
1691 * - commas, for SELECT clause, EXPLAIN and PREPARE
1692 * - parentheses, for EXPLAIN and PREPARE
1694 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1695 * avoid behavior which depends on locale setting.
1697 if (!(*p >= '0' && *p <= '9') &&
1698 !(*p >= 'A' && *p <= 'Z') &&
1699 !(*p >= 'a' && *p <= 'z') &&
1703 *p != '(' && *p != ')')
1707 len = strlen(HINT_START);
1712 /* find hint end keyword. */
1713 if ((tail = strstr(p, HINT_END)) == NULL)
1715 hint_ereport(head, ("Unterminated block comment."));
1719 /* We don't support nested block comments. */
1720 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1722 hint_ereport(head, ("Nested block comments are not supported."));
1726 /* Make a copy of hint. */
1728 head = palloc(len + 1);
1729 memcpy(head, p, len);
1737 * Parse hints that got, create hint struct from parse tree and parse hints.
1740 create_hintstate(Query *parse, const char *hints)
1750 hstate = HintStateCreate();
1751 hstate->hint_str = (char *) hints;
1753 /* parse each hint. */
1754 parse_hints(hstate, parse, p);
1756 /* When nothing specified a hint, we free HintState and returns NULL. */
1757 if (hstate->nall_hints == 0)
1759 HintStateDelete(hstate);
1763 /* Sort hints in order of original position. */
1764 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1767 /* Count number of hints per hint-type. */
1768 for (i = 0; i < hstate->nall_hints; i++)
1770 Hint *cur_hint = hstate->all_hints[i];
1771 hstate->num_hints[cur_hint->type]++;
1775 * If an object (or a set of objects) has multiple hints of same hint-type,
1776 * only the last hint is valid and others are ignored in planning.
1777 * Hints except the last are marked as 'duplicated' to remember the order.
1779 for (i = 0; i < hstate->nall_hints - 1; i++)
1781 Hint *cur_hint = hstate->all_hints[i];
1782 Hint *next_hint = hstate->all_hints[i + 1];
1785 * Leading hint is marked as 'duplicated' in transform_join_hints.
1787 if (cur_hint->type == HINT_TYPE_LEADING &&
1788 next_hint->type == HINT_TYPE_LEADING)
1792 * Note that we need to pass addresses of hint pointers, because
1793 * HintCmp is designed to sort array of Hint* by qsort.
1795 if (HintCmp(&cur_hint, &next_hint) == 0)
1797 hint_ereport(cur_hint->hint_str,
1798 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1799 cur_hint->state = HINT_STATE_DUPLICATION;
1804 * Make sure that per-type array pointers point proper position in the
1805 * array which consists of all hints.
1807 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1808 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1809 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1810 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1811 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1812 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1813 hstate->num_hints[HINT_TYPE_LEADING]);
1814 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
1815 hstate->num_hints[HINT_TYPE_SET]);
1821 * Parse inside of parentheses of scan-method hints.
1824 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1827 const char *keyword = hint->base.keyword;
1828 HintKeyword hint_keyword = hint->base.hint_keyword;
1829 List *name_list = NIL;
1832 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1835 /* Parse relation name and index name(s) if given hint accepts. */
1836 length = list_length(name_list);
1839 hint->relname = linitial(name_list);
1840 hint->indexnames = list_delete_first(name_list);
1842 /* check whether the hint accepts index name(s). */
1844 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1845 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1846 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1847 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1848 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1849 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1852 ("%s hint accepts only one relation.",
1853 hint->base.keyword));
1854 hint->base.state = HINT_STATE_ERROR;
1861 ("%s hint requires a relation.",
1862 hint->base.keyword));
1863 hint->base.state = HINT_STATE_ERROR;
1867 /* Set a bit for specified hint. */
1868 switch (hint_keyword)
1870 case HINT_KEYWORD_SEQSCAN:
1871 hint->enforce_mask = ENABLE_SEQSCAN;
1873 case HINT_KEYWORD_INDEXSCAN:
1874 hint->enforce_mask = ENABLE_INDEXSCAN;
1876 case HINT_KEYWORD_INDEXSCANREGEXP:
1877 hint->enforce_mask = ENABLE_INDEXSCAN;
1878 hint->regexp = true;
1880 case HINT_KEYWORD_BITMAPSCAN:
1881 hint->enforce_mask = ENABLE_BITMAPSCAN;
1883 case HINT_KEYWORD_BITMAPSCANREGEXP:
1884 hint->enforce_mask = ENABLE_BITMAPSCAN;
1885 hint->regexp = true;
1887 case HINT_KEYWORD_TIDSCAN:
1888 hint->enforce_mask = ENABLE_TIDSCAN;
1890 case HINT_KEYWORD_NOSEQSCAN:
1891 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1893 case HINT_KEYWORD_NOINDEXSCAN:
1894 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1896 case HINT_KEYWORD_NOBITMAPSCAN:
1897 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1899 case HINT_KEYWORD_NOTIDSCAN:
1900 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1902 case HINT_KEYWORD_INDEXONLYSCAN:
1903 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1905 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1906 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1907 hint->regexp = true;
1909 case HINT_KEYWORD_NOINDEXONLYSCAN:
1910 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1913 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1922 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1925 const char *keyword = hint->base.keyword;
1926 HintKeyword hint_keyword = hint->base.hint_keyword;
1927 List *name_list = NIL;
1929 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1932 hint->nrels = list_length(name_list);
1934 if (hint->nrels > 0)
1940 * Transform relation names from list to array to sort them with qsort
1943 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1944 foreach (l, name_list)
1946 hint->relnames[i] = lfirst(l);
1951 list_free(name_list);
1953 /* A join hint requires at least two relations */
1954 if (hint->nrels < 2)
1957 ("%s hint requires at least two relations.",
1958 hint->base.keyword));
1959 hint->base.state = HINT_STATE_ERROR;
1963 /* Sort hints in alphabetical order of relation names. */
1964 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1966 switch (hint_keyword)
1968 case HINT_KEYWORD_NESTLOOP:
1969 hint->enforce_mask = ENABLE_NESTLOOP;
1971 case HINT_KEYWORD_MERGEJOIN:
1972 hint->enforce_mask = ENABLE_MERGEJOIN;
1974 case HINT_KEYWORD_HASHJOIN:
1975 hint->enforce_mask = ENABLE_HASHJOIN;
1977 case HINT_KEYWORD_NONESTLOOP:
1978 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1980 case HINT_KEYWORD_NOMERGEJOIN:
1981 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1983 case HINT_KEYWORD_NOHASHJOIN:
1984 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1987 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1996 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1999 if (outer_inner->outer_inner_pair == NIL)
2001 if (outer_inner->relation)
2007 if (list_length(outer_inner->outer_inner_pair) == 2)
2009 foreach(l, outer_inner->outer_inner_pair)
2011 if (!OuterInnerPairCheck(lfirst(l)))
2022 OuterInnerList(OuterInnerRels *outer_inner)
2024 List *outer_inner_list = NIL;
2026 OuterInnerRels *outer_inner_rels;
2028 foreach(l, outer_inner->outer_inner_pair)
2030 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2032 if (outer_inner_rels->relation != NULL)
2033 outer_inner_list = lappend(outer_inner_list,
2034 outer_inner_rels->relation);
2036 outer_inner_list = list_concat(outer_inner_list,
2037 OuterInnerList(outer_inner_rels));
2039 return outer_inner_list;
2043 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2046 List *name_list = NIL;
2047 OuterInnerRels *outer_inner = NULL;
2049 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2053 if (outer_inner != NULL)
2054 name_list = OuterInnerList(outer_inner);
2056 hint->relations = name_list;
2057 hint->outer_inner = outer_inner;
2059 /* A Leading hint requires at least two relations */
2060 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2062 hint_ereport(hint->base.hint_str,
2063 ("%s hint requires at least two relations.",
2065 hint->base.state = HINT_STATE_ERROR;
2067 else if (hint->outer_inner != NULL &&
2068 !OuterInnerPairCheck(hint->outer_inner))
2070 hint_ereport(hint->base.hint_str,
2071 ("%s hint requires two sets of relations when parentheses nests.",
2073 hint->base.state = HINT_STATE_ERROR;
2080 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2082 List *name_list = NIL;
2084 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2088 hint->words = name_list;
2090 /* We need both name and value to set GUC parameter. */
2091 if (list_length(name_list) == 2)
2093 hint->name = linitial(name_list);
2094 hint->value = lsecond(name_list);
2098 hint_ereport(hint->base.hint_str,
2099 ("%s hint requires name and value of GUC parameter.",
2101 hint->base.state = HINT_STATE_ERROR;
2108 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2111 HintKeyword hint_keyword = hint->base.hint_keyword;
2112 List *name_list = NIL;
2116 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2119 /* Last element must be rows specification */
2120 hint->nrels = list_length(name_list) - 1;
2122 if (hint->nrels > 0)
2128 * Transform relation names from list to array to sort them with qsort
2131 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2132 foreach (l, name_list)
2134 if (hint->nrels <= i)
2136 hint->relnames[i] = lfirst(l);
2141 /* Retieve rows estimation */
2142 rows_str = list_nth(name_list, hint->nrels);
2143 hint->rows_str = rows_str; /* store as-is for error logging */
2144 if (rows_str[0] == '#')
2146 hint->value_type = RVT_ABSOLUTE;
2149 else if (rows_str[0] == '+')
2151 hint->value_type = RVT_ADD;
2154 else if (rows_str[0] == '-')
2156 hint->value_type = RVT_SUB;
2159 else if (rows_str[0] == '*')
2161 hint->value_type = RVT_MULTI;
2166 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2167 hint->base.state = HINT_STATE_ERROR;
2170 hint->rows = strtod(rows_str, &end_ptr);
2173 hint_ereport(rows_str,
2174 ("%s hint requires valid number as rows estimation.",
2175 hint->base.keyword));
2176 hint->base.state = HINT_STATE_ERROR;
2180 /* A join hint requires at least two relations */
2181 if (hint->nrels < 2)
2184 ("%s hint requires at least two relations.",
2185 hint->base.keyword));
2186 hint->base.state = HINT_STATE_ERROR;
2190 list_free(name_list);
2192 /* Sort relnames in alphabetical order. */
2193 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2199 * set GUC parameter functions
2203 set_config_option_wrapper(const char *name, const char *value,
2204 GucContext context, GucSource source,
2205 GucAction action, bool changeVal, int elevel)
2208 MemoryContext ccxt = CurrentMemoryContext;
2212 result = set_config_option(name, value, context, source,
2213 action, changeVal, 0);
2219 /* Save error info */
2220 MemoryContextSwitchTo(ccxt);
2221 errdata = CopyErrorData();
2225 (errcode(errdata->sqlerrcode),
2226 errhidestmt(hidestmt),
2227 errmsg("%s", errdata->message),
2228 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2229 errdata->hint ? errhint("%s", errdata->hint) : 0));
2230 FreeErrorData(errdata);
2238 set_config_options(SetHint **options, int noptions, GucContext context)
2243 save_nestlevel = NewGUCNestLevel();
2245 for (i = 0; i < noptions; i++)
2247 SetHint *hint = options[i];
2250 if (!hint_state_enabled(hint))
2253 result = set_config_option_wrapper(hint->name, hint->value, context,
2254 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2255 pg_hint_plan_message_level);
2257 hint->base.state = HINT_STATE_USED;
2259 hint->base.state = HINT_STATE_ERROR;
2262 return save_nestlevel;
2265 #define SET_CONFIG_OPTION(name, type_bits) \
2266 set_config_option_wrapper((name), \
2267 (mask & (type_bits)) ? "true" : "false", \
2268 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2271 set_scan_config_options(unsigned char enforce_mask, GucContext context)
2275 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2276 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2277 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2279 mask = enforce_mask;
2281 mask = enforce_mask & current_hint->init_scan_mask;
2283 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2284 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2285 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2286 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2287 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2291 set_join_config_options(unsigned char enforce_mask, GucContext context)
2295 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2296 enforce_mask == ENABLE_HASHJOIN)
2297 mask = enforce_mask;
2299 mask = enforce_mask & current_hint->init_join_mask;
2301 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2302 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2303 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2307 * pg_hint_plan hook functions
2311 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
2312 ProcessUtilityContext context,
2313 ParamListInfo params,
2314 DestReceiver *dest, char *completionTag)
2319 * Use standard planner if pg_hint_plan is disabled or current nesting
2320 * depth is nesting depth of SPI calls.
2322 if (!pg_hint_plan_enable_hint || nested_level > 0)
2324 if (debug_level > 1)
2325 ereport(pg_hint_plan_message_level,
2326 (errmsg ("pg_hint_plan: ProcessUtility:"
2327 " pg_hint_plan.enable_hint = off")));
2328 if (prev_ProcessUtility)
2329 (*prev_ProcessUtility) (parsetree, queryString,
2331 dest, completionTag);
2333 standard_ProcessUtility(parsetree, queryString,
2335 dest, completionTag);
2340 if (IsA(node, ExplainStmt))
2343 * Draw out parse tree of actual query from Query struct of EXPLAIN
2349 stmt = (ExplainStmt *) node;
2351 Assert(IsA(stmt->query, Query));
2352 query = (Query *) stmt->query;
2354 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2355 node = query->utilityStmt;
2359 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2360 * specified to preceding PREPARE command to use it as source of hints.
2362 if (IsA(node, ExecuteStmt))
2366 stmt = (ExecuteStmt *) node;
2367 stmt_name = stmt->name;
2371 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2374 if (IsA(node, CreateTableAsStmt))
2376 CreateTableAsStmt *stmt;
2379 stmt = (CreateTableAsStmt *) node;
2380 Assert(IsA(stmt->query, Query));
2381 query = (Query *) stmt->query;
2383 if (query->commandType == CMD_UTILITY &&
2384 IsA(query->utilityStmt, ExecuteStmt))
2386 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2387 stmt_name = estmt->name;
2393 if (debug_level > 1)
2394 ereport(pg_hint_plan_message_level,
2395 (errmsg ("pg_hint_plan: ProcessUtility:"
2396 " stmt_name = \"%s\", statement=\"%s\"",
2397 stmt_name, queryString)));
2401 if (prev_ProcessUtility)
2402 (*prev_ProcessUtility) (parsetree, queryString,
2404 dest, completionTag);
2406 standard_ProcessUtility(parsetree, queryString,
2408 dest, completionTag);
2422 if (prev_ProcessUtility)
2423 (*prev_ProcessUtility) (parsetree, queryString,
2425 dest, completionTag);
2427 standard_ProcessUtility(parsetree, queryString,
2429 dest, completionTag);
2433 * Push a hint into hint stack which is implemented with List struct. Head of
2434 * list is top of stack.
2437 push_hint(HintState *hstate)
2439 /* Prepend new hint to the list means pushing to stack. */
2440 HintStateStack = lcons(hstate, HintStateStack);
2442 /* Pushed hint is the one which should be used hereafter. */
2443 current_hint = hstate;
2446 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2450 /* Hint stack must not be empty. */
2451 if(HintStateStack == NIL)
2452 elog(ERROR, "hint stack is empty");
2455 * Take a hint at the head from the list, and free it. Switch current_hint
2456 * to point new head (NULL if the list is empty).
2458 HintStateStack = list_delete_first(HintStateStack);
2459 HintStateDelete(current_hint);
2460 if(HintStateStack == NIL)
2461 current_hint = NULL;
2463 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2466 static PlannedStmt *
2467 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2469 const char *hints = NULL;
2472 pgssJumbleState jstate;
2475 PlannedStmt *result;
2481 if (debug_level > 1)
2482 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2486 * Use standard planner if pg_hint_plan is disabled or current nesting
2487 * depth is nesting depth of SPI calls. Other hook functions try to change
2488 * plan with current_hint if any, so set it to NULL.
2490 if (!pg_hint_plan_enable_hint || nested_level > 0)
2492 if (debug_level > 1)
2493 elog(pg_hint_plan_message_level,
2494 "pg_hint_plan%s: planner: enable_hint=%d,"
2496 qnostr, pg_hint_plan_enable_hint, nested_level);
2499 goto standard_planner_proc;
2502 /* Create hint struct from client-supplied query string. */
2503 query = get_query_string();
2506 * Create hintstate from hint specified for the query, if any.
2508 * First we lookup hint in pg_hint.hints table by normalized query string,
2509 * unless pg_hint_plan.enable_hint_table is OFF.
2510 * This parameter provides option to avoid overhead of table lookup during
2513 * If no hint was found, then we try to get hint from special query comment.
2515 if (pg_hint_plan_enable_hint_table)
2518 * Search hint information which is stored for the query and the
2519 * application. Query string is normalized before using in condition
2520 * in order to allow fuzzy matching.
2522 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2523 * careful when supporting PostgreSQL's version up.
2525 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2526 jstate.jumble_len = 0;
2527 jstate.clocations_buf_size = 32;
2528 jstate.clocations = (pgssLocationLen *)
2529 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2530 jstate.clocations_count = 0;
2531 JumbleQuery(&jstate, parse);
2533 * generate_normalized_query() copies exact given query_len bytes, so we
2534 * add 1 byte for null-termination here. As comments on
2535 * generate_normalized_query says, generate_normalized_query doesn't
2536 * take care of null-terminate, but additional 1 byte ensures that '\0'
2537 * byte in the source buffer to be copied into norm_query.
2539 query_len = strlen(query) + 1;
2540 norm_query = generate_normalized_query(&jstate,
2543 GetDatabaseEncoding());
2544 hints = get_hints_from_table(norm_query, application_name);
2545 if (debug_level > 1)
2548 snprintf(msgstr, 1024, "hints from table: \"%s\":"
2549 " normalzed_query=\"%s\", application name =\"%s\"",
2550 hints, norm_query, application_name);
2553 ereport(pg_hint_plan_message_level,
2554 (errhidestmt(hidestmt),
2555 errmsg("pg_hint_plan%s:"
2556 " no match found in table:"
2557 " application name = \"%s\","
2558 " normalzed_query=\"%s\"",
2559 qnostr, application_name, norm_query)));
2566 hints = get_hints_from_comment(query);
2568 if (debug_level > 1)
2570 snprintf(msgstr, 1024, "hints in comment=\"%s\"",
2571 hints ? hints : "(none)");
2572 if (debug_level > 2 ||
2573 stmt_name || strcmp(query, debug_query_string))
2574 snprintf(msgstr + strlen(msgstr), 1024- strlen(msgstr),
2575 ", stmt=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2576 stmt_name, query, debug_query_string);
2580 hstate = create_hintstate(parse, hints);
2583 * Use standard planner if the statement has not valid hint. Other hook
2584 * functions try to change plan with current_hint if any, so set it to
2588 goto standard_planner_proc;
2591 * Push new hint struct to the hint stack to disable previous hint context.
2595 /* Set GUC parameters which are specified with Set hint. */
2596 save_nestlevel = set_config_options(current_hint->set_hints,
2597 current_hint->num_hints[HINT_TYPE_SET],
2598 current_hint->context);
2601 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2602 if (enable_indexscan)
2603 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2604 if (enable_bitmapscan)
2605 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2607 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2608 if (enable_indexonlyscan)
2609 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2610 if (enable_nestloop)
2611 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2612 if (enable_mergejoin)
2613 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2614 if (enable_hashjoin)
2615 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2617 if (debug_level > 1)
2619 ereport(pg_hint_plan_message_level,
2620 (errhidestmt(hidestmt),
2621 errmsg("pg_hint_plan%s: planner: %s",
2627 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2628 * state when this planner started when error occurred in planner.
2633 result = (*prev_planner) (parse, cursorOptions, boundParams);
2635 result = standard_planner(parse, cursorOptions, boundParams);
2640 * Rollback changes of GUC parameters, and pop current hint context
2641 * from hint stack to rewind the state.
2643 AtEOXact_GUC(true, save_nestlevel);
2649 /* Print hint in debug mode. */
2650 if (debug_level == 1)
2651 HintStateDump(current_hint);
2652 else if (debug_level > 1)
2653 HintStateDump2(current_hint);
2656 * Rollback changes of GUC parameters, and pop current hint context from
2657 * hint stack to rewind the state.
2659 AtEOXact_GUC(true, save_nestlevel);
2664 standard_planner_proc:
2665 if (debug_level > 1)
2667 ereport(pg_hint_plan_message_level,
2668 (errhidestmt(hidestmt),
2669 errmsg("pg_hint_plan%s: planner: no valid hint (%s)",
2673 current_hint = NULL;
2675 return (*prev_planner) (parse, cursorOptions, boundParams);
2677 return standard_planner(parse, cursorOptions, boundParams);
2681 * Return scan method hint which matches given aliasname.
2683 static ScanMethodHint *
2684 find_scan_hint(PlannerInfo *root, Index relid, RelOptInfo *rel)
2690 * We can't apply scan method hint if the relation is:
2691 * - not a base relation
2692 * - not an ordinary relation (such as join and subquery)
2694 if (rel && (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION))
2697 rte = root->simple_rte_array[relid];
2699 /* We can't force scan method of foreign tables */
2700 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2703 /* Find scan method hint, which matches given names, from the list. */
2704 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2706 ScanMethodHint *hint = current_hint->scan_hints[i];
2708 /* We ignore disabled hints. */
2709 if (!hint_state_enabled(hint))
2712 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2722 * Returns TRUE on match, FALSE on no match.
2724 * s1 --- the data to match against
2725 * s2 --- the pattern
2727 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2730 regexpeq(const char *s1, const char *s2)
2736 strcpy(name.data, s1);
2737 regexp = cstring_to_text(s2);
2739 result = DirectFunctionCall2Coll(nameregexeq,
2740 DEFAULT_COLLATION_OID,
2741 NameGetDatum(&name),
2742 PointerGetDatum(regexp));
2743 return DatumGetBool(result);
2747 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2755 * We delete all the IndexOptInfo list and prevent you from being usable by
2758 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2759 hint->enforce_mask == ENABLE_TIDSCAN)
2761 list_free_deep(rel->indexlist);
2762 rel->indexlist = NIL;
2763 hint->base.state = HINT_STATE_USED;
2769 * When a list of indexes is not specified, we just use all indexes.
2771 if (hint->indexnames == NIL)
2775 * Leaving only an specified index, we delete it from a IndexOptInfo list
2779 if (debug_level > 0)
2780 initStringInfo(&buf);
2782 for (cell = list_head(rel->indexlist); cell; cell = next)
2784 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2785 char *indexname = get_rel_name(info->indexoid);
2787 bool use_index = false;
2791 foreach(l, hint->indexnames)
2793 char *hintname = (char *) lfirst(l);
2797 result = regexpeq(indexname, hintname);
2799 result = RelnameCmp(&indexname, &hintname) == 0;
2804 if (debug_level > 0)
2806 appendStringInfoCharMacro(&buf, ' ');
2807 quote_value(&buf, indexname);
2815 * to make the index a candidate when definition of this index is
2816 * matched with the index's definition of current_hint.
2818 if (OidIsValid(relationObjectId) && !use_index)
2820 foreach(l, current_hint->parent_index_infos)
2824 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2826 /* check to match the parameter of unique */
2827 if (p_info->indisunique != info->unique)
2830 /* check to match the parameter of index's method */
2831 if (p_info->method != info->relam)
2834 /* to check to match the indexkey's configuration */
2835 if ((list_length(p_info->column_names)) !=
2839 /* check to match the indexkey's configuration */
2840 for (i = 0; i < info->ncolumns; i++)
2842 char *c_attname = NULL;
2843 char *p_attname = NULL;
2846 list_nth(p_info->column_names, i);
2848 /* both are expressions */
2849 if (info->indexkeys[i] == 0 && !p_attname)
2852 /* one's column is expression, the other is not */
2853 if (info->indexkeys[i] == 0 || !p_attname)
2856 c_attname = get_attname(relationObjectId,
2857 info->indexkeys[i]);
2859 if (strcmp(p_attname, c_attname) != 0)
2862 if (p_info->indcollation[i] != info->indexcollations[i])
2865 if (p_info->opclass[i] != info->opcintype[i])
2868 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2869 info->reverse_sort[i])
2872 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2873 info->nulls_first[i])
2878 if (i != info->ncolumns)
2881 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2882 (p_info->indpred_str && (info->indpred != NIL)))
2885 * Fetch the pg_index tuple by the Oid of the index
2887 ht_idx = SearchSysCache1(INDEXRELID,
2888 ObjectIdGetDatum(info->indexoid));
2890 /* check to match the expression's parameter of index */
2891 if (p_info->expression_str &&
2892 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2899 * to change the expression's parameter of child's
2902 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2903 Anum_pg_index_indexprs,
2906 result = DirectFunctionCall2(pg_get_expr,
2911 if (strcmp(p_info->expression_str,
2912 text_to_cstring(DatumGetTextP(result))) != 0)
2915 ReleaseSysCache(ht_idx);
2921 /* Check to match the predicate's parameter of index */
2922 if (p_info->indpred_str &&
2923 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2930 * to change the predicate's parameter of child's
2933 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2934 Anum_pg_index_indpred,
2937 result = DirectFunctionCall2(pg_get_expr,
2942 if (strcmp(p_info->indpred_str,
2943 text_to_cstring(DatumGetTextP(result))) != 0)
2946 ReleaseSysCache(ht_idx);
2953 ReleaseSysCache(ht_idx);
2955 else if (p_info->expression_str || (info->indexprs != NIL))
2957 else if (p_info->indpred_str || (info->indpred != NIL))
2962 /* to log the candidate of index */
2963 if (debug_level > 0)
2965 appendStringInfoCharMacro(&buf, ' ');
2966 quote_value(&buf, indexname);
2974 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2981 if (debug_level == 1)
2984 StringInfoData rel_buf;
2986 if (OidIsValid(relationObjectId))
2987 relname = get_rel_name(relationObjectId);
2989 relname = hint->relname;
2991 initStringInfo(&rel_buf);
2992 quote_value(&rel_buf, relname);
2995 (errmsg("available indexes for %s(%s):%s",
3000 pfree(rel_buf.data);
3005 * Return information of index definition.
3007 static ParentIndexInfo *
3008 get_parent_index_info(Oid indexoid, Oid relid)
3010 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3011 Relation indexRelation;
3012 Form_pg_index index;
3016 indexRelation = index_open(indexoid, RowExclusiveLock);
3018 index = indexRelation->rd_index;
3020 p_info->indisunique = index->indisunique;
3021 p_info->method = indexRelation->rd_rel->relam;
3023 p_info->column_names = NIL;
3024 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3025 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3026 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3028 for (i = 0; i < index->indnatts; i++)
3030 attname = get_attname(relid, index->indkey.values[i]);
3031 p_info->column_names = lappend(p_info->column_names, attname);
3033 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3034 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3035 p_info->indoption[i] = indexRelation->rd_indoption[i];
3039 * to check to match the expression's parameter of index with child indexes
3041 p_info->expression_str = NULL;
3042 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
3048 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3049 Anum_pg_index_indexprs, &isnull);
3051 result = DirectFunctionCall2(pg_get_expr,
3053 ObjectIdGetDatum(relid));
3055 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3059 * to check to match the predicate's parameter of index with child indexes
3061 p_info->indpred_str = NULL;
3062 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
3068 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3069 Anum_pg_index_indpred, &isnull);
3071 result = DirectFunctionCall2(pg_get_expr,
3073 ObjectIdGetDatum(relid));
3075 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3078 index_close(indexRelation, NoLock);
3084 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
3085 bool inhparent, RelOptInfo *rel)
3087 ScanMethodHint *hint = NULL;
3089 Index new_parent_relid = 0;
3091 if (prev_get_relation_info)
3092 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
3095 * Do nothing if we don't have a valid hint in this context or current
3096 * nesting depth is at SPI calls.
3098 if (!current_hint || nested_level > 0)
3100 if (debug_level > 1)
3101 ereport(pg_hint_plan_message_level,
3103 errmsg ("pg_hint_plan%s: get_relation_info"
3104 " no hint to apply: relation=%u(%s), inhparent=%d,"
3105 " current_hint=%p, nested_level=%d",
3106 qnostr, relationObjectId,
3107 get_rel_name(relationObjectId),
3108 inhparent, current_hint, nested_level)));
3113 * We could register the parent relation of the following children here
3114 * when inhparent == true but inheritnce planner doesn't request
3115 * information for inheritance parents. We also cannot distinguish the
3116 * caller so we should always find the parents without this function being
3121 if (debug_level > 1)
3122 ereport(pg_hint_plan_message_level,
3124 errmsg ("pg_hint_plan%s: get_relation_info"
3125 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3126 " current_hint=%p, nested_level=%d",
3127 qnostr, relationObjectId,
3128 get_rel_name(relationObjectId),
3129 inhparent, current_hint, nested_level)));
3133 /* Find the parent for this relation */
3134 foreach (l, root->append_rel_list)
3136 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3138 if (appinfo->child_relid == rel->relid)
3140 if (current_hint->parent_relid != appinfo->parent_relid)
3141 new_parent_relid = appinfo->parent_relid;
3148 /* This relation doesn't have a parent. Cancel current_hint. */
3149 current_hint->parent_relid = 0;
3150 current_hint->parent_hint = NULL;
3153 if (new_parent_relid > 0)
3156 * Here we found a parent relation different from the remembered one.
3157 * Remember it, apply the scan mask of it and then resolve the index
3158 * restriction in order to be used by its children.
3160 int scanmask = current_hint->init_scan_mask;
3161 ScanMethodHint *parent_hint;
3163 current_hint->parent_relid = new_parent_relid;
3166 * Get and apply the hint for the new parent relation. It should be an
3167 * ordinary relation so calling find_scan_hint with rel == NULL is
3170 current_hint->parent_hint = parent_hint =
3171 find_scan_hint(root, current_hint->parent_relid, NULL);
3175 scanmask = current_hint->parent_hint->enforce_mask;
3176 parent_hint->base.state = HINT_STATE_USED;
3178 /* Resolve index name mask (if any) using the parent. */
3179 if (parent_hint->indexnames)
3182 Relation parent_rel;
3185 root->simple_rte_array[current_hint->parent_relid]->relid;
3186 parent_rel = heap_open(parentrel_oid, NoLock);
3188 /* Search the parent relation for indexes match the hint spec */
3189 foreach(l, RelationGetIndexList(parent_rel))
3191 Oid indexoid = lfirst_oid(l);
3192 char *indexname = get_rel_name(indexoid);
3194 ParentIndexInfo *parent_index_info;
3196 foreach(lc, parent_hint->indexnames)
3198 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3205 get_parent_index_info(indexoid, parentrel_oid);
3206 current_hint->parent_index_infos =
3207 lappend(current_hint->parent_index_infos, parent_index_info);
3209 heap_close(parent_rel, NoLock);
3213 set_scan_config_options(scanmask, current_hint->context);
3216 if (current_hint->parent_hint != 0)
3218 delete_indexes(current_hint->parent_hint, rel,
3221 /* Scan fixation status is the same to the parent. */
3222 if (debug_level > 1)
3223 ereport(pg_hint_plan_message_level,
3225 errmsg("pg_hint_plan%s: get_relation_info:"
3226 " index deletion by parent hint: "
3227 "relation=%u(%s), inhparent=%d, current_hint=%p,"
3229 qnostr, relationObjectId,
3230 get_rel_name(relationObjectId),
3231 inhparent, current_hint, nested_level)));
3235 /* This table doesn't have a parent hint. Apply its own hint if any. */
3236 if ((hint = find_scan_hint(root, rel->relid, rel)) != NULL)
3238 set_scan_config_options(hint->enforce_mask, current_hint->context);
3239 hint->base.state = HINT_STATE_USED;
3241 delete_indexes(hint, rel, InvalidOid);
3243 if (debug_level > 1)
3244 ereport(pg_hint_plan_message_level,
3246 errmsg ("pg_hint_plan%s: get_relation_info"
3248 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3249 " nested_level=%d, scanmask=0x%x",
3250 qnostr, relationObjectId,
3251 get_rel_name(relationObjectId),
3252 inhparent, current_hint, nested_level,
3253 hint->enforce_mask)));
3257 if (debug_level > 1)
3258 ereport(pg_hint_plan_message_level,
3259 (errhidestmt (true),
3260 errmsg ("pg_hint_plan%s: get_relation_info"
3262 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3263 " nested_level=%d, scanmask=0x%x",
3264 qnostr, relationObjectId,
3265 get_rel_name(relationObjectId),
3266 inhparent, current_hint, nested_level,
3267 current_hint->init_scan_mask)));
3268 set_scan_config_options(current_hint->init_scan_mask,
3269 current_hint->context);
3275 * Return index of relation which matches given aliasname, or 0 if not found.
3276 * If same aliasname was used multiple times in a query, return -1.
3279 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3285 for (i = 1; i < root->simple_rel_array_size; i++)
3289 if (root->simple_rel_array[i] == NULL)
3292 Assert(i == root->simple_rel_array[i]->relid);
3294 if (RelnameCmp(&aliasname,
3295 &root->simple_rte_array[i]->eref->aliasname) != 0)
3298 foreach(l, initial_rels)
3300 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3302 if (rel->reloptkind == RELOPT_BASEREL)
3304 if (rel->relid != i)
3309 Assert(rel->reloptkind == RELOPT_JOINREL);
3311 if (!bms_is_member(i, rel->relids))
3318 ("Relation name \"%s\" is ambiguous.",
3333 * Return join hint which matches given joinrelids.
3335 static JoinMethodHint *
3336 find_join_hint(Relids joinrelids)
3341 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
3343 foreach(l, join_hint)
3345 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3347 if (bms_equal(joinrelids, hint->joinrelids))
3355 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3356 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3358 OuterInnerRels *outer_rels;
3359 OuterInnerRels *inner_rels;
3360 Relids outer_relids;
3361 Relids inner_relids;
3363 JoinMethodHint *hint;
3365 if (outer_inner->relation != NULL)
3367 return bms_make_singleton(
3368 find_relid_aliasname(root, outer_inner->relation,
3370 leading_hint->base.hint_str));
3373 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3374 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3376 outer_relids = OuterInnerJoinCreate(outer_rels,
3382 inner_relids = OuterInnerJoinCreate(inner_rels,
3389 join_relids = bms_add_members(outer_relids, inner_relids);
3391 if (bms_num_members(join_relids) > nbaserel)
3395 * If we don't have join method hint, create new one for the
3396 * join combination with all join methods are enabled.
3398 hint = find_join_hint(join_relids);
3402 * Here relnames is not set, since Relids bitmap is sufficient to
3403 * control paths of this query afterward.
3405 hint = (JoinMethodHint *) JoinMethodHintCreate(
3406 leading_hint->base.hint_str,
3408 HINT_KEYWORD_LEADING);
3409 hint->base.state = HINT_STATE_USED;
3410 hint->nrels = bms_num_members(join_relids);
3411 hint->enforce_mask = ENABLE_ALL_JOIN;
3412 hint->joinrelids = bms_copy(join_relids);
3413 hint->inner_nrels = bms_num_members(inner_relids);
3414 hint->inner_joinrelids = bms_copy(inner_relids);
3416 hstate->join_hint_level[hint->nrels] =
3417 lappend(hstate->join_hint_level[hint->nrels], hint);
3421 hint->inner_nrels = bms_num_members(inner_relids);
3422 hint->inner_joinrelids = bms_copy(inner_relids);
3429 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3430 int nrels, char **relnames)
3433 Relids relids = NULL;
3437 for (j = 0; j < nrels; j++)
3439 relname = relnames[j];
3441 relid = find_relid_aliasname(root, relname, initial_rels,
3445 base->state = HINT_STATE_ERROR;
3448 * the aliasname is not found(relid == 0) or same aliasname was used
3449 * multiple times in a query(relid == -1)
3456 if (bms_is_member(relid, relids))
3458 hint_ereport(base->hint_str,
3459 ("Relation name \"%s\" is duplicated.", relname));
3460 base->state = HINT_STATE_ERROR;
3464 relids = bms_add_member(relids, relid);
3469 * Transform join method hint into handy form.
3471 * - create bitmap of relids from alias names, to make it easier to check
3472 * whether a join path matches a join method hint.
3473 * - add join method hints which are necessary to enforce join order
3474 * specified by Leading hint
3477 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
3478 List *initial_rels, JoinMethodHint **join_method_hints)
3486 LeadingHint *lhint = NULL;
3489 * Create bitmap of relids from alias names for each join method hint.
3490 * Bitmaps are more handy than strings in join searching.
3492 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
3494 JoinMethodHint *hint = hstate->join_hints[i];
3496 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3499 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3500 initial_rels, hint->nrels, hint->relnames);
3502 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
3505 hstate->join_hint_level[hint->nrels] =
3506 lappend(hstate->join_hint_level[hint->nrels], hint);
3510 * Create bitmap of relids from alias names for each rows hint.
3511 * Bitmaps are more handy than strings in join searching.
3513 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
3515 RowsHint *hint = hstate->rows_hints[i];
3517 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3520 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3521 initial_rels, hint->nrels, hint->relnames);
3524 /* Do nothing if no Leading hint was supplied. */
3525 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
3529 * Decide whether to use Leading hint
3531 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
3533 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
3536 if (leading_hint->base.state == HINT_STATE_ERROR)
3542 foreach(l, leading_hint->relations)
3544 relname = (char *)lfirst(l);;
3546 relid = find_relid_aliasname(root, relname, initial_rels,
3547 leading_hint->base.hint_str);
3549 leading_hint->base.state = HINT_STATE_ERROR;
3554 if (bms_is_member(relid, relids))
3556 hint_ereport(leading_hint->base.hint_str,
3557 ("Relation name \"%s\" is duplicated.", relname));
3558 leading_hint->base.state = HINT_STATE_ERROR;
3562 relids = bms_add_member(relids, relid);
3565 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3570 hint_ereport(lhint->base.hint_str,
3571 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3572 lhint->base.state = HINT_STATE_DUPLICATION;
3574 leading_hint->base.state = HINT_STATE_USED;
3575 lhint = leading_hint;
3578 /* check to exist Leading hint marked with 'used'. */
3583 * We need join method hints which fit specified join order in every join
3584 * level. For example, Leading(A B C) virtually requires following join
3585 * method hints, if no join method hint supplied:
3587 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3588 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3590 * If we already have join method hint which fits specified join order in
3591 * that join level, we leave it as-is and don't add new hints.
3595 if (lhint->outer_inner == NULL)
3597 foreach(l, lhint->relations)
3599 JoinMethodHint *hint;
3601 relname = (char *)lfirst(l);
3604 * Find relid of the relation which has given name. If we have the
3605 * name given in Leading hint multiple times in the join, nothing to
3608 relid = find_relid_aliasname(root, relname, initial_rels,
3611 /* Create bitmap of relids for current join level. */
3612 joinrelids = bms_add_member(joinrelids, relid);
3615 /* We never have join method hint for single relation. */
3620 * If we don't have join method hint, create new one for the
3621 * join combination with all join methods are enabled.
3623 hint = find_join_hint(joinrelids);
3627 * Here relnames is not set, since Relids bitmap is sufficient
3628 * to control paths of this query afterward.
3630 hint = (JoinMethodHint *) JoinMethodHintCreate(
3631 lhint->base.hint_str,
3633 HINT_KEYWORD_LEADING);
3634 hint->base.state = HINT_STATE_USED;
3635 hint->nrels = njoinrels;
3636 hint->enforce_mask = ENABLE_ALL_JOIN;
3637 hint->joinrelids = bms_copy(joinrelids);
3640 join_method_hints[njoinrels] = hint;
3642 if (njoinrels >= nbaserel)
3645 bms_free(joinrelids);
3651 * Delete all join hints which have different combination from Leading
3654 for (i = 2; i <= njoinrels; i++)
3656 list_free(hstate->join_hint_level[i]);
3658 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3663 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3670 njoinrels = bms_num_members(joinrelids);
3671 Assert(njoinrels >= 2);
3674 * Delete all join hints which have different combination from Leading
3677 for (i = 2;i <= njoinrels; i++)
3679 if (hstate->join_hint_level[i] != NIL)
3681 ListCell *prev = NULL;
3682 ListCell *next = NULL;
3683 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3686 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3690 if (hint->inner_nrels == 0 &&
3691 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3692 bms_equal(bms_union(hint->joinrelids, joinrelids),
3695 hstate->join_hint_level[i] =
3696 list_delete_cell(hstate->join_hint_level[i], l,
3705 bms_free(joinrelids);
3708 if (hint_state_enabled(lhint))
3710 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3717 * set_plain_rel_pathlist
3718 * Build access paths for a plain relation (no subquery, no inheritance)
3720 * This function was copied and edited from set_plain_rel_pathlist() in
3721 * src/backend/optimizer/path/allpaths.c
3724 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3726 /* Consider sequential scan */
3727 add_path(rel, create_seqscan_path(root, rel, NULL));
3729 /* Consider index scans */
3730 create_index_paths(root, rel);
3732 /* Consider TID scans */
3733 create_tidscan_paths(root, rel);
3735 /* Now find the cheapest of the paths for this rel */
3740 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3745 foreach(l, initial_rels)
3747 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3749 ScanMethodHint *hint;
3751 /* Skip relations which we can't choose scan method. */
3752 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3755 rte = root->simple_rte_array[rel->relid];
3757 /* We can't force scan method of foreign tables */
3758 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3762 * Create scan paths with GUC parameters which are at the beginning of
3763 * planner if scan method hint is not specified, otherwise use
3764 * specified hints and mark the hint as used.
3766 if ((hint = find_scan_hint(root, rel->relid, rel)) == NULL)
3767 set_scan_config_options(hstate->init_scan_mask,
3771 set_scan_config_options(hint->enforce_mask, hstate->context);
3772 hint->base.state = HINT_STATE_USED;
3775 list_free_deep(rel->pathlist);
3776 rel->pathlist = NIL;
3779 /* It's an "append relation", process accordingly */
3780 set_append_rel_pathlist(root, rel, rel->relid, rte);
3784 set_plain_rel_pathlist(root, rel, rte);
3789 * Restore the GUC variables we set above.
3791 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3795 * wrapper of make_join_rel()
3797 * call make_join_rel() after changing enable_* parameters according to given
3801 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3804 JoinMethodHint *hint;
3808 joinrelids = bms_union(rel1->relids, rel2->relids);
3809 hint = find_join_hint(joinrelids);
3810 bms_free(joinrelids);
3813 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3815 if (hint->inner_nrels == 0)
3817 save_nestlevel = NewGUCNestLevel();
3819 set_join_config_options(hint->enforce_mask, current_hint->context);
3821 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3822 hint->base.state = HINT_STATE_USED;
3825 * Restore the GUC variables we set above.
3827 AtEOXact_GUC(true, save_nestlevel);
3830 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3839 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3840 RelOptInfo *joinrel,
3841 RelOptInfo *outerrel,
3842 RelOptInfo *innerrel,
3844 SpecialJoinInfo *sjinfo,
3847 ScanMethodHint *scan_hint = NULL;
3849 JoinMethodHint *join_hint;
3852 if ((scan_hint = find_scan_hint(root, innerrel->relid, innerrel)) != NULL)
3854 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3855 scan_hint->base.state = HINT_STATE_USED;
3858 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3859 join_hint = find_join_hint(joinrelids);
3860 bms_free(joinrelids);
3862 if (join_hint && join_hint->inner_nrels != 0)
3864 save_nestlevel = NewGUCNestLevel();
3866 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3869 set_join_config_options(join_hint->enforce_mask,
3870 current_hint->context);
3872 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3873 sjinfo, restrictlist);
3874 join_hint->base.state = HINT_STATE_USED;
3878 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3879 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3880 sjinfo, restrictlist);
3884 * Restore the GUC variables we set above.
3886 AtEOXact_GUC(true, save_nestlevel);
3889 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3890 sjinfo, restrictlist);
3892 if (scan_hint != NULL)
3893 set_scan_config_options(current_hint->init_scan_mask,
3894 current_hint->context);
3898 get_num_baserels(List *initial_rels)
3903 foreach(l, initial_rels)
3905 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3907 if (rel->reloptkind == RELOPT_BASEREL)
3909 else if (rel->reloptkind ==RELOPT_JOINREL)
3910 nbaserel+= bms_num_members(rel->relids);
3913 /* other values not expected here */
3914 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3922 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3925 JoinMethodHint **join_method_hints;
3929 bool leading_hint_enable;
3932 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3933 * valid hint is supplied or current nesting depth is nesting depth of SPI
3936 if (!current_hint || nested_level > 0)
3938 if (prev_join_search)
3939 return (*prev_join_search) (root, levels_needed, initial_rels);
3940 else if (enable_geqo && levels_needed >= geqo_threshold)
3941 return geqo(root, levels_needed, initial_rels);
3943 return standard_join_search(root, levels_needed, initial_rels);
3946 /* We apply scan method hint rebuild scan path. */
3947 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3950 * In the case using GEQO, only scan method hints and Set hints have
3951 * effect. Join method and join order is not controllable by hints.
3953 if (enable_geqo && levels_needed >= geqo_threshold)
3954 return geqo(root, levels_needed, initial_rels);
3956 nbaserel = get_num_baserels(initial_rels);
3957 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3958 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3960 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3961 initial_rels, join_method_hints);
3963 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3965 for (i = 2; i <= nbaserel; i++)
3967 list_free(current_hint->join_hint_level[i]);
3969 /* free Leading hint only */
3970 if (join_method_hints[i] != NULL &&
3971 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3972 JoinMethodHintDelete(join_method_hints[i]);
3974 pfree(current_hint->join_hint_level);
3975 pfree(join_method_hints);
3977 if (leading_hint_enable)
3978 set_join_config_options(current_hint->init_join_mask,
3979 current_hint->context);
3986 * Build access paths for a base relation
3988 * This function was copied and edited from set_rel_pathlist() in
3989 * src/backend/optimizer/path/allpaths.c
3992 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3993 Index rti, RangeTblEntry *rte)
3995 if (IS_DUMMY_REL(rel))
3997 /* We already proved the relation empty, so nothing more to do */
4001 /* It's an "append relation", process accordingly */
4002 set_append_rel_pathlist(root, rel, rti, rte);
4006 if (rel->rtekind == RTE_RELATION)
4008 if (rte->relkind == RELKIND_RELATION)
4010 /* Plain relation */
4011 set_plain_rel_pathlist(root, rel, rte);
4014 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4017 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4022 * stmt_beg callback is called when each query in PL/pgSQL function is about
4023 * to be executed. At that timing, we save query string in the global variable
4024 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4025 * variable for the purpose, because its content is only necessary until
4026 * planner hook is called for the query, so recursive PL/pgSQL function calls
4027 * don't harm this mechanism.
4030 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4032 PLpgSQL_expr *expr = NULL;
4034 switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
4036 case PLPGSQL_STMT_FORS:
4037 expr = ((PLpgSQL_stmt_fors *) stmt)->query;
4039 case PLPGSQL_STMT_FORC:
4040 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_forc *)stmt)->curvar]))->cursor_explicit_expr;
4042 case PLPGSQL_STMT_RETURN_QUERY:
4043 if (((PLpgSQL_stmt_return_query *) stmt)->query != NULL)
4044 expr = ((PLpgSQL_stmt_return_query *) stmt)->query;
4046 expr = ((PLpgSQL_stmt_return_query *) stmt)->dynquery;
4048 case PLPGSQL_STMT_EXECSQL:
4049 expr = ((PLpgSQL_stmt_execsql *) stmt)->sqlstmt;
4051 case PLPGSQL_STMT_DYNEXECUTE:
4052 expr = ((PLpgSQL_stmt_dynexecute *) stmt)->query;
4054 case PLPGSQL_STMT_DYNFORS:
4055 expr = ((PLpgSQL_stmt_dynfors *) stmt)->query;
4057 case PLPGSQL_STMT_OPEN:
4058 if (((PLpgSQL_stmt_open *) stmt)->query != NULL)
4059 expr = ((PLpgSQL_stmt_open *) stmt)->query;
4060 else if (((PLpgSQL_stmt_open *) stmt)->dynquery != NULL)
4061 expr = ((PLpgSQL_stmt_open *) stmt)->dynquery;
4063 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_open *)stmt)->curvar]))->cursor_explicit_expr;
4071 plpgsql_query_string = expr->query;
4072 plpgsql_query_string_src = (enum PLpgSQL_stmt_types) stmt->cmd_type;
4077 * stmt_end callback is called then each query in PL/pgSQL function has
4078 * finished. At that timing, we clear plpgsql_query_string to tell planner
4079 * hook that next call is not for a query written in PL/pgSQL block.
4082 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4084 if (plpgsql_query_string &&
4085 plpgsql_query_string_src == stmt->cmd_type)
4086 plpgsql_query_string = NULL;
4089 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4094 if (phase != RESOURCE_RELEASE_AFTER_LOCKS)
4096 /* Force erase stored plpgsql query string */
4097 plpgsql_query_string = NULL;
4100 #define standard_join_search pg_hint_plan_standard_join_search
4101 #define join_search_one_level pg_hint_plan_join_search_one_level
4102 #define make_join_rel make_join_rel_wrapper
4105 #undef make_join_rel
4106 #define make_join_rel pg_hint_plan_make_join_rel
4107 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4108 #include "make_join_rel.c"
4110 #include "pg_stat_statements.c"