1 /*-------------------------------------------------------------------------
4 * do instructions or hints to the planner using C-style block comments
7 * Copyright (c) 2012-2013, 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 #if PG_VERSION_NUM >= 90200
36 #include "catalog/pg_class.h"
39 #include "executor/spi.h"
40 #include "catalog/pg_type.h"
42 * PG9.1でもPL/pgSQLのクエリにヒントを適用するために、ソースディレクトリに
44 * PG9.2以降ではplpgsql.hが外部モジュールでも使えるように公開されたので、公開さ
47 #if PG_VERSION_NUM >= 90200
50 #include "plpgsql-9.1.h"
53 /* partially copied from pg_stat_statements */
54 #include "normalize_query.h"
56 #ifdef PG_MODULE_MAGIC
60 #if PG_VERSION_NUM < 90100
61 #error unsupported PostgreSQL version
64 #define BLOCK_COMMENT_START "/*"
65 #define BLOCK_COMMENT_END "*/"
66 #define HINT_COMMENT_KEYWORD "+"
67 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
68 #define HINT_END BLOCK_COMMENT_END
71 #define HINT_SEQSCAN "SeqScan"
72 #define HINT_INDEXSCAN "IndexScan"
73 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
74 #define HINT_BITMAPSCAN "BitmapScan"
75 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
76 #define HINT_TIDSCAN "TidScan"
77 #define HINT_NOSEQSCAN "NoSeqScan"
78 #define HINT_NOINDEXSCAN "NoIndexScan"
79 #define HINT_NOBITMAPSCAN "NoBitmapScan"
80 #define HINT_NOTIDSCAN "NoTidScan"
81 #if PG_VERSION_NUM >= 90200
82 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
83 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
84 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
86 #define HINT_NESTLOOP "NestLoop"
87 #define HINT_MERGEJOIN "MergeJoin"
88 #define HINT_HASHJOIN "HashJoin"
89 #define HINT_NONESTLOOP "NoNestLoop"
90 #define HINT_NOMERGEJOIN "NoMergeJoin"
91 #define HINT_NOHASHJOIN "NoHashJoin"
92 #define HINT_LEADING "Leading"
93 #define HINT_SET "Set"
95 #define HINT_ARRAY_DEFAULT_INITSIZE 8
97 #define hint_ereport(str, detail) \
98 ereport(pg_hint_plan_parse_messages, \
99 (errmsg("hint syntax error at or near \"%s\"", (str)), \
102 #define skip_space(str) \
103 while (isspace(*str)) \
108 ENABLE_SEQSCAN = 0x01,
109 ENABLE_INDEXSCAN = 0x02,
110 ENABLE_BITMAPSCAN = 0x04,
111 ENABLE_TIDSCAN = 0x08,
112 #if PG_VERSION_NUM >= 90200
113 ENABLE_INDEXONLYSCAN = 0x10
119 ENABLE_NESTLOOP = 0x01,
120 ENABLE_MERGEJOIN = 0x02,
121 ENABLE_HASHJOIN = 0x04
124 #if PG_VERSION_NUM >= 90200
125 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
126 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
127 ENABLE_INDEXONLYSCAN)
129 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
130 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN)
132 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
133 #define DISABLE_ALL_SCAN 0
134 #define DISABLE_ALL_JOIN 0
136 /* hint keyword of enum type*/
137 typedef enum HintKeyword
139 HINT_KEYWORD_SEQSCAN,
140 HINT_KEYWORD_INDEXSCAN,
141 HINT_KEYWORD_INDEXSCANREGEXP,
142 HINT_KEYWORD_BITMAPSCAN,
143 HINT_KEYWORD_BITMAPSCANREGEXP,
144 HINT_KEYWORD_TIDSCAN,
145 HINT_KEYWORD_NOSEQSCAN,
146 HINT_KEYWORD_NOINDEXSCAN,
147 HINT_KEYWORD_NOBITMAPSCAN,
148 HINT_KEYWORD_NOTIDSCAN,
149 #if PG_VERSION_NUM >= 90200
150 HINT_KEYWORD_INDEXONLYSCAN,
151 HINT_KEYWORD_INDEXONLYSCANREGEXP,
152 HINT_KEYWORD_NOINDEXONLYSCAN,
154 HINT_KEYWORD_NESTLOOP,
155 HINT_KEYWORD_MERGEJOIN,
156 HINT_KEYWORD_HASHJOIN,
157 HINT_KEYWORD_NONESTLOOP,
158 HINT_KEYWORD_NOMERGEJOIN,
159 HINT_KEYWORD_NOHASHJOIN,
160 HINT_KEYWORD_LEADING,
162 HINT_KEYWORD_UNRECOGNIZED
165 typedef struct Hint Hint;
166 typedef struct HintState HintState;
168 typedef Hint *(*HintCreateFunction) (const char *hint_str,
170 HintKeyword hint_keyword);
171 typedef void (*HintDeleteFunction) (Hint *hint);
172 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf);
173 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
174 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
175 Query *parse, const char *str);
178 #define NUM_HINT_TYPE 4
179 typedef enum HintType
181 HINT_TYPE_SCAN_METHOD,
182 HINT_TYPE_JOIN_METHOD,
187 static const char *HintTypeName[] = {
195 typedef enum HintStatus
197 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
198 HINT_STATE_USED, /* hint is used */
199 HINT_STATE_DUPLICATION, /* specified hint duplication */
200 HINT_STATE_ERROR /* execute error (parse error does not include
204 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
205 (hint)->base.state == HINT_STATE_USED)
207 /* common data for all hints. */
210 const char *hint_str; /* must not do pfree */
211 const char *keyword; /* must not do pfree */
212 HintKeyword hint_keyword;
215 HintDeleteFunction delete_func;
216 HintDescFunction desc_func;
217 HintCmpFunction cmp_func;
218 HintParseFunction parse_func;
221 /* scan method hints */
222 typedef struct ScanMethodHint
228 unsigned char enforce_mask;
231 typedef struct ParentIndexInfo
236 char *expression_str;
243 /* join method hints */
244 typedef struct JoinMethodHint
250 unsigned char enforce_mask;
252 Relids inner_joinrelids;
255 /* join order hints */
256 typedef struct OuterInnerRels
259 List *outer_inner_pair;
262 typedef struct LeadingHint
265 List *relations; /* relation names specified in Leading hint */
266 OuterInnerRels *outer_inner;
269 /* change a run-time parameter hints */
270 typedef struct SetHint
273 char *name; /* name of variable */
279 * Describes a context of hint processing.
283 char *hint_str; /* original hint string */
286 int nall_hints; /* # of valid all hints */
287 int max_all_hints; /* # of slots for all hints */
288 Hint **all_hints; /* parsed all hints */
290 /* # of each hints */
291 int num_hints[NUM_HINT_TYPE];
293 /* for scan method hints */
294 ScanMethodHint **scan_hints; /* parsed scan hints */
295 int init_scan_mask; /* initial value scan parameter */
296 Index parent_relid; /* inherit parent table relid */
297 Oid parent_rel_oid; /* inherit parent table relid */
298 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
299 List *parent_index_infos; /* infomation of inherit parent table's
302 /* for join method hints */
303 JoinMethodHint **join_hints; /* parsed join hints */
304 int init_join_mask; /* initial value join parameter */
305 List **join_hint_level;
307 /* for Leading hint */
308 LeadingHint **leading_hint; /* parsed Leading hints */
311 SetHint **set_hints; /* parsed Set hints */
312 GucContext context; /* which GUC parameters can we set? */
316 * Describes a hint parser module which is bound with particular hint keyword.
318 typedef struct HintParser
321 HintCreateFunction create_func;
322 HintKeyword hint_keyword;
325 /* Module callbacks */
329 static void push_hint(HintState *hstate);
330 static void pop_hint(void);
332 static void pg_hint_plan_ProcessUtility(Node *parsetree,
333 const char *queryString,
334 ParamListInfo params, bool isTopLevel,
336 char *completionTag);
337 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
338 ParamListInfo boundParams);
339 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
340 Oid relationObjectId,
341 bool inhparent, RelOptInfo *rel);
342 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
346 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
347 HintKeyword hint_keyword);
348 static void ScanMethodHintDelete(ScanMethodHint *hint);
349 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf);
350 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
351 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
352 Query *parse, const char *str);
353 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
354 HintKeyword hint_keyword);
355 static void JoinMethodHintDelete(JoinMethodHint *hint);
356 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf);
357 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
358 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
359 Query *parse, const char *str);
360 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
361 HintKeyword hint_keyword);
362 static void LeadingHintDelete(LeadingHint *hint);
363 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf);
364 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
365 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
366 Query *parse, const char *str);
367 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
368 HintKeyword hint_keyword);
369 static void SetHintDelete(SetHint *hint);
370 static void SetHintDesc(SetHint *hint, StringInfo buf);
371 static int SetHintCmp(const SetHint *a, const SetHint *b);
372 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
375 static void quote_value(StringInfo buf, const char *value);
377 static const char *parse_quoted_value(const char *str, char **word,
380 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
383 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
384 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
385 ListCell *other_rels);
386 static void make_rels_by_clauseless_joins(PlannerInfo *root,
388 ListCell *other_rels);
389 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
390 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
391 Index rti, RangeTblEntry *rte);
392 #if PG_VERSION_NUM >= 90200
393 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
394 List *live_childrels,
395 List *all_child_pathkeys);
397 static List *accumulate_append_subpath(List *subpaths, Path *path);
398 #if PG_VERSION_NUM < 90200
399 static void set_dummy_rel_pathlist(RelOptInfo *rel);
401 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
404 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
406 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
410 static bool pg_hint_plan_enable_hint = true;
411 static bool pg_hint_plan_debug_print = false;
412 static int pg_hint_plan_parse_messages = INFO;
414 static const struct config_enum_entry parse_messages_level_options[] = {
415 {"debug", DEBUG2, true},
416 {"debug5", DEBUG5, false},
417 {"debug4", DEBUG4, false},
418 {"debug3", DEBUG3, false},
419 {"debug2", DEBUG2, false},
420 {"debug1", DEBUG1, false},
422 {"info", INFO, false},
423 {"notice", NOTICE, false},
424 {"warning", WARNING, false},
425 {"error", ERROR, false},
427 * {"fatal", FATAL, true},
428 * {"panic", PANIC, true},
433 /* Saved hook values in case of unload */
434 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
435 static planner_hook_type prev_planner = NULL;
436 static get_relation_info_hook_type prev_get_relation_info = NULL;
437 static join_search_hook_type prev_join_search = NULL;
439 /* Hold reference to currently active hint */
440 static HintState *current_hint = NULL;
443 * List of hint contexts. We treat the head of the list as the Top of the
444 * context stack, so current_hint always points the first element of this list.
446 static List *HintStateStack = NIL;
449 * Holds statement name during executing EXECUTE command. NULL for other
452 static char *stmt_name = NULL;
454 static const HintParser parsers[] = {
455 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
456 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
457 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
458 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
459 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
460 HINT_KEYWORD_BITMAPSCANREGEXP},
461 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
462 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
463 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
464 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
465 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
466 #if PG_VERSION_NUM >= 90200
467 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
468 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
469 HINT_KEYWORD_INDEXONLYSCANREGEXP},
470 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
472 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
473 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
474 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
475 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
476 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
477 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
478 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
479 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
480 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
484 * PL/pgSQL plugin for retrieving string representation of each query during
485 * function execution.
487 const char *plpgsql_query_string = NULL;
488 PLpgSQL_plugin plugin_funcs = {
492 pg_hint_plan_plpgsql_stmt_beg,
493 pg_hint_plan_plpgsql_stmt_end,
499 * Module load callbacks
504 PLpgSQL_plugin **var_ptr;
506 /* Define custom GUC variables. */
507 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
508 "Force planner to use plans specified in the hint comment preceding to the query.",
510 &pg_hint_plan_enable_hint,
518 DefineCustomBoolVariable("pg_hint_plan.debug_print",
519 "Logs results of hint parsing.",
521 &pg_hint_plan_debug_print,
529 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
530 "Message level of parse errors.",
532 &pg_hint_plan_parse_messages,
534 parse_messages_level_options,
542 prev_ProcessUtility = ProcessUtility_hook;
543 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
544 prev_planner = planner_hook;
545 planner_hook = pg_hint_plan_planner;
546 prev_get_relation_info = get_relation_info_hook;
547 get_relation_info_hook = pg_hint_plan_get_relation_info;
548 prev_join_search = join_search_hook;
549 join_search_hook = pg_hint_plan_join_search;
551 /* setup PL/pgSQL plugin hook */
552 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
553 *var_ptr = &plugin_funcs;
557 * Module unload callback
563 PLpgSQL_plugin **var_ptr;
565 /* Uninstall hooks. */
566 ProcessUtility_hook = prev_ProcessUtility;
567 planner_hook = prev_planner;
568 get_relation_info_hook = prev_get_relation_info;
569 join_search_hook = prev_join_search;
571 /* uninstall PL/pgSQL plugin hook */
572 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
577 * create and delete functions the hint object
581 ScanMethodHintCreate(const char *hint_str, const char *keyword,
582 HintKeyword hint_keyword)
584 ScanMethodHint *hint;
586 hint = palloc(sizeof(ScanMethodHint));
587 hint->base.hint_str = hint_str;
588 hint->base.keyword = keyword;
589 hint->base.hint_keyword = hint_keyword;
590 hint->base.type = HINT_TYPE_SCAN_METHOD;
591 hint->base.state = HINT_STATE_NOTUSED;
592 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
593 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
594 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
595 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
596 hint->relname = NULL;
597 hint->indexnames = NIL;
598 hint->regexp = false;
599 hint->enforce_mask = 0;
601 return (Hint *) hint;
605 ScanMethodHintDelete(ScanMethodHint *hint)
611 pfree(hint->relname);
612 list_free_deep(hint->indexnames);
617 JoinMethodHintCreate(const char *hint_str, const char *keyword,
618 HintKeyword hint_keyword)
620 JoinMethodHint *hint;
622 hint = palloc(sizeof(JoinMethodHint));
623 hint->base.hint_str = hint_str;
624 hint->base.keyword = keyword;
625 hint->base.hint_keyword = hint_keyword;
626 hint->base.type = HINT_TYPE_JOIN_METHOD;
627 hint->base.state = HINT_STATE_NOTUSED;
628 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
629 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
630 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
631 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
633 hint->inner_nrels = 0;
634 hint->relnames = NULL;
635 hint->enforce_mask = 0;
636 hint->joinrelids = NULL;
637 hint->inner_joinrelids = NULL;
639 return (Hint *) hint;
643 JoinMethodHintDelete(JoinMethodHint *hint)
652 for (i = 0; i < hint->nrels; i++)
653 pfree(hint->relnames[i]);
654 pfree(hint->relnames);
657 bms_free(hint->joinrelids);
658 bms_free(hint->inner_joinrelids);
663 LeadingHintCreate(const char *hint_str, const char *keyword,
664 HintKeyword hint_keyword)
668 hint = palloc(sizeof(LeadingHint));
669 hint->base.hint_str = hint_str;
670 hint->base.keyword = keyword;
671 hint->base.hint_keyword = hint_keyword;
672 hint->base.type = HINT_TYPE_LEADING;
673 hint->base.state = HINT_STATE_NOTUSED;
674 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
675 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
676 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
677 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
678 hint->relations = NIL;
679 hint->outer_inner = NULL;
681 return (Hint *) hint;
685 LeadingHintDelete(LeadingHint *hint)
690 list_free_deep(hint->relations);
691 if (hint->outer_inner)
692 pfree(hint->outer_inner);
697 SetHintCreate(const char *hint_str, const char *keyword,
698 HintKeyword hint_keyword)
702 hint = palloc(sizeof(SetHint));
703 hint->base.hint_str = hint_str;
704 hint->base.keyword = keyword;
705 hint->base.hint_keyword = hint_keyword;
706 hint->base.type = HINT_TYPE_SET;
707 hint->base.state = HINT_STATE_NOTUSED;
708 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
709 hint->base.desc_func = (HintDescFunction) SetHintDesc;
710 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
711 hint->base.parse_func = (HintParseFunction) SetHintParse;
716 return (Hint *) hint;
720 SetHintDelete(SetHint *hint)
730 list_free(hint->words);
735 HintStateCreate(void)
739 hstate = palloc(sizeof(HintState));
740 hstate->hint_str = NULL;
741 hstate->nall_hints = 0;
742 hstate->max_all_hints = 0;
743 hstate->all_hints = NULL;
744 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
745 hstate->scan_hints = NULL;
746 hstate->init_scan_mask = 0;
747 hstate->parent_relid = 0;
748 hstate->parent_rel_oid = InvalidOid;
749 hstate->parent_hint = NULL;
750 hstate->parent_index_infos = NIL;
751 hstate->join_hints = NULL;
752 hstate->init_join_mask = 0;
753 hstate->join_hint_level = NULL;
754 hstate->leading_hint = NULL;
755 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
756 hstate->set_hints = NULL;
762 HintStateDelete(HintState *hstate)
769 if (hstate->hint_str)
770 pfree(hstate->hint_str);
772 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
773 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
774 if (hstate->all_hints)
775 pfree(hstate->all_hints);
776 if (hstate->parent_index_infos)
777 list_free(hstate->parent_index_infos);
781 * Copy given value into buf, with quoting with '"' if necessary.
784 quote_value(StringInfo buf, const char *value)
786 bool need_quote = false;
789 for (str = value; *str != '\0'; str++)
791 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
794 appendStringInfoCharMacro(buf, '"');
799 for (str = value; *str != '\0'; str++)
802 appendStringInfoCharMacro(buf, '"');
804 appendStringInfoCharMacro(buf, *str);
808 appendStringInfoCharMacro(buf, '"');
812 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
816 appendStringInfo(buf, "%s(", hint->base.keyword);
817 if (hint->relname != NULL)
819 quote_value(buf, hint->relname);
820 foreach(l, hint->indexnames)
822 appendStringInfoCharMacro(buf, ' ');
823 quote_value(buf, (char *) lfirst(l));
826 appendStringInfoString(buf, ")\n");
830 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
834 appendStringInfo(buf, "%s(", hint->base.keyword);
835 if (hint->relnames != NULL)
837 quote_value(buf, hint->relnames[0]);
838 for (i = 1; i < hint->nrels; i++)
840 appendStringInfoCharMacro(buf, ' ');
841 quote_value(buf, hint->relnames[i]);
844 appendStringInfoString(buf, ")\n");
849 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
851 if (outer_inner->relation == NULL)
858 appendStringInfoCharMacro(buf, '(');
859 foreach(l, outer_inner->outer_inner_pair)
864 appendStringInfoCharMacro(buf, ' ');
866 OuterInnerDesc(lfirst(l), buf);
869 appendStringInfoCharMacro(buf, ')');
872 quote_value(buf, outer_inner->relation);
876 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
878 appendStringInfo(buf, "%s(", HINT_LEADING);
879 if (hint->outer_inner == NULL)
886 foreach(l, hint->relations)
891 appendStringInfoCharMacro(buf, ' ');
893 quote_value(buf, (char *) lfirst(l));
897 OuterInnerDesc(hint->outer_inner, buf);
899 appendStringInfoString(buf, ")\n");
903 SetHintDesc(SetHint *hint, StringInfo buf)
905 bool is_first = true;
908 appendStringInfo(buf, "%s(", HINT_SET);
909 foreach(l, hint->words)
914 appendStringInfoCharMacro(buf, ' ');
916 quote_value(buf, (char *) lfirst(l));
918 appendStringInfo(buf, ")\n");
922 * Append string which repserents all hints in a given state to buf, with
923 * preceding title with them.
926 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
931 appendStringInfo(buf, "%s:\n", title);
932 for (i = 0; i < hstate->nall_hints; i++)
934 if (hstate->all_hints[i]->state != state)
937 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf);
942 * Dump contents of given hstate to server log with log level LOG.
945 HintStateDump(HintState *hstate)
951 elog(LOG, "pg_hint_plan:\nno hint");
955 initStringInfo(&buf);
957 appendStringInfoString(&buf, "pg_hint_plan:\n");
958 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
959 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
960 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
961 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
963 elog(LOG, "%s", buf.data);
973 RelnameCmp(const void *a, const void *b)
975 const char *relnamea = *((const char **) a);
976 const char *relnameb = *((const char **) b);
978 return strcmp(relnamea, relnameb);
982 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
984 return RelnameCmp(&a->relname, &b->relname);
988 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
992 if (a->nrels != b->nrels)
993 return a->nrels - b->nrels;
995 for (i = 0; i < a->nrels; i++)
998 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1006 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1012 SetHintCmp(const SetHint *a, const SetHint *b)
1014 return strcmp(a->name, b->name);
1018 HintCmp(const void *a, const void *b)
1020 const Hint *hinta = *((const Hint **) a);
1021 const Hint *hintb = *((const Hint **) b);
1023 if (hinta->type != hintb->type)
1024 return hinta->type - hintb->type;
1025 if (hinta->state == HINT_STATE_ERROR)
1027 if (hintb->state == HINT_STATE_ERROR)
1029 return hinta->cmp_func(hinta, hintb);
1033 * Returns byte offset of hint b from hint a. If hint a was specified before
1034 * b, positive value is returned.
1037 HintCmpWithPos(const void *a, const void *b)
1039 const Hint *hinta = *((const Hint **) a);
1040 const Hint *hintb = *((const Hint **) b);
1043 result = HintCmp(a, b);
1045 result = hinta->hint_str - hintb->hint_str;
1054 parse_keyword(const char *str, StringInfo buf)
1058 while (!isspace(*str) && *str != '(' && *str != '\0')
1059 appendStringInfoCharMacro(buf, *str++);
1065 skip_parenthesis(const char *str, char parenthesis)
1069 if (*str != parenthesis)
1071 if (parenthesis == '(')
1072 hint_ereport(str, ("Opening parenthesis is necessary."));
1073 else if (parenthesis == ')')
1074 hint_ereport(str, ("Closing parenthesis is necessary."));
1085 * Parse a token from str, and store malloc'd copy into word. A token can be
1086 * quoted with '"'. Return value is pointer to unparsed portion of original
1087 * string, or NULL if an error occurred.
1089 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1092 parse_quoted_value(const char *str, char **word, bool truncate)
1097 /* Skip leading spaces. */
1100 initStringInfo(&buf);
1113 /* Double quotation must be closed. */
1117 hint_ereport(str, ("Unterminated quoted string."));
1122 * Skip escaped double quotation.
1124 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1125 * block comments) to be an object name, so users must specify
1126 * alias for such object names.
1128 * Those special names can be allowed if we care escaped slashes
1129 * and asterisks, but we don't.
1138 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1142 appendStringInfoCharMacro(&buf, *str++);
1147 hint_ereport(str, ("Zero-length delimited string."));
1154 /* Truncate name if it's too long */
1156 truncate_identifier(buf.data, strlen(buf.data), true);
1163 static OuterInnerRels *
1164 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1166 OuterInnerRels *outer_inner;
1168 outer_inner = palloc(sizeof(OuterInnerRels));
1169 outer_inner->relation = name;
1170 outer_inner->outer_inner_pair = outer_inner_list;
1176 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1178 List *outer_inner_pair = NIL;
1180 if ((str = skip_parenthesis(str, '(')) == NULL)
1185 /* Store words in parentheses into outer_inner_list. */
1186 while(*str != ')' && *str != '\0')
1188 OuterInnerRels *outer_inner_rels;
1192 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1200 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1203 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1206 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1211 (str = skip_parenthesis(str, ')')) == NULL)
1213 list_free(outer_inner_pair);
1217 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1223 parse_parentheses_Leading(const char *str, List **name_list,
1224 OuterInnerRels **outer_inner)
1227 bool truncate = true;
1229 if ((str = skip_parenthesis(str, '(')) == NULL)
1235 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1240 /* Store words in parentheses into name_list. */
1241 while(*str != ')' && *str != '\0')
1243 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1245 list_free(*name_list);
1249 *name_list = lappend(*name_list, name);
1254 if ((str = skip_parenthesis(str, ')')) == NULL)
1260 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1263 bool truncate = true;
1265 if ((str = skip_parenthesis(str, '(')) == NULL)
1270 /* Store words in parentheses into name_list. */
1271 while(*str != ')' && *str != '\0')
1273 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1275 list_free(*name_list);
1279 *name_list = lappend(*name_list, name);
1282 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1283 #if PG_VERSION_NUM >= 90200
1284 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1286 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1287 keyword == HINT_KEYWORD_SET)
1293 if ((str = skip_parenthesis(str, ')')) == NULL)
1299 parse_hints(HintState *hstate, Query *parse, const char *str)
1304 initStringInfo(&buf);
1305 while (*str != '\0')
1307 const HintParser *parser;
1309 /* in error message, we output the comment including the keyword. */
1310 head = (char *) str;
1312 /* parse only the keyword of the hint. */
1313 resetStringInfo(&buf);
1314 str = parse_keyword(str, &buf);
1316 for (parser = parsers; parser->keyword != NULL; parser++)
1318 char *keyword = parser->keyword;
1321 if (strcasecmp(buf.data, keyword) != 0)
1324 hint = parser->create_func(head, keyword, parser->hint_keyword);
1326 /* parser of each hint does parse in a parenthesis. */
1327 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1329 hint->delete_func(hint);
1335 * Add hint information into all_hints array. If we don't have
1336 * enough space, double the array.
1338 if (hstate->nall_hints == 0)
1340 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1341 hstate->all_hints = (Hint **)
1342 palloc(sizeof(Hint *) * hstate->max_all_hints);
1344 else if (hstate->nall_hints == hstate->max_all_hints)
1346 hstate->max_all_hints *= 2;
1347 hstate->all_hints = (Hint **)
1348 repalloc(hstate->all_hints,
1349 sizeof(Hint *) * hstate->max_all_hints);
1352 hstate->all_hints[hstate->nall_hints] = hint;
1353 hstate->nall_hints++;
1360 if (parser->keyword == NULL)
1363 ("Unrecognized hint keyword \"%s\".", buf.data));
1374 * Get hints from table by client-supplied query string and application name.
1377 get_hints_from_table(const char *client_query, const char *client_application)
1379 const char *search_query =
1381 " FROM hint_plan.hints "
1382 " WHERE norm_query_string = $1 "
1383 " AND ( application_name = $2 "
1384 " OR application_name = '' ) "
1385 " ORDER BY application_name DESC";
1386 static SPIPlanPtr plan = NULL;
1389 Oid argtypes[2] = { TEXTOID, TEXTOID };
1391 bool nulls[2] = { false, false };
1395 ret = SPI_connect();
1396 if (ret != SPI_OK_CONNECT)
1397 elog(ERROR, "pg_hint_plan: SPI_connect => %d", ret);
1402 p = SPI_prepare(search_query, 2, argtypes);
1404 elog(ERROR, "pg_hint_plan: SPI_prepare => %d", SPI_result);
1405 plan = SPI_saveplan(p);
1409 qry = cstring_to_text(client_query);
1410 app = cstring_to_text(client_application);
1411 values[0] = PointerGetDatum(qry);
1412 values[1] = PointerGetDatum(app);
1414 pg_hint_plan_enable_hint = false;
1415 ret = SPI_execute_plan(plan, values, nulls, true, 1);
1416 pg_hint_plan_enable_hint = true;
1417 if (ret != SPI_OK_SELECT)
1418 elog(ERROR, "pg_hint_plan: SPI_execute_plan => %d", ret);
1420 if (SPI_processed > 0)
1424 hints = SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
1426 * Here we use SPI_palloc to ensure that hints string is valid even
1427 * after SPI_finish call. We can't use simple palloc because it
1428 * allocates memory in SPI's context and that context is deleted in
1431 buf = SPI_palloc(strlen(hints) + 1);
1442 * Get client-supplied query string.
1445 get_query_string(void)
1451 PreparedStatement *entry;
1453 entry = FetchPreparedStatement(stmt_name, true);
1454 p = entry->plansource->query_string;
1456 else if (plpgsql_query_string)
1457 p = plpgsql_query_string;
1459 p = debug_query_string;
1465 * Get hints from the head block comment in client-supplied query string.
1468 get_hints_from_comment(const char *p)
1470 const char *hint_head;
1478 /* extract query head comment. */
1479 hint_head = strstr(p, HINT_START);
1480 if (hint_head == NULL)
1482 for (;p < hint_head; p++)
1485 * Allow these characters precedes hint comment:
1487 * - alphabets which are in ASCII range
1488 * - space, tabs and new-lines
1489 * - underscores, for identifier
1490 * - commas, for SELECT clause, EXPLAIN and PREPARE
1491 * - parentheses, for EXPLAIN and PREPARE
1493 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1494 * avoid behavior which depends on locale setting.
1496 if (!(*p >= '0' && *p <= '9') &&
1497 !(*p >= 'A' && *p <= 'Z') &&
1498 !(*p >= 'a' && *p <= 'z') &&
1502 *p != '(' && *p != ')')
1506 len = strlen(HINT_START);
1511 /* find hint end keyword. */
1512 if ((tail = strstr(p, HINT_END)) == NULL)
1514 hint_ereport(head, ("Unterminated block comment."));
1518 /* We don't support nested block comments. */
1519 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1521 hint_ereport(head, ("Nested block comments are not supported."));
1525 /* Make a copy of hint. */
1527 head = palloc(len + 1);
1528 memcpy(head, p, len);
1536 * Parse hints that got, create hint struct from parse tree and parse hints.
1539 create_hintstate(Query *parse, const char *hints)
1549 hstate = HintStateCreate();
1550 hstate->hint_str = (char *) hints;
1552 /* parse each hint. */
1553 parse_hints(hstate, parse, p);
1555 /* When nothing specified a hint, we free HintState and returns NULL. */
1556 if (hstate->nall_hints == 0)
1558 HintStateDelete(hstate);
1562 /* Sort hints in order of original position. */
1563 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1566 /* Count number of hints per hint-type. */
1567 for (i = 0; i < hstate->nall_hints; i++)
1569 Hint *cur_hint = hstate->all_hints[i];
1570 hstate->num_hints[cur_hint->type]++;
1574 * If an object (or a set of objects) has multiple hints of same hint-type,
1575 * only the last hint is valid and others are igonred in planning.
1576 * Hints except the last are marked as 'duplicated' to remember the order.
1578 for (i = 0; i < hstate->nall_hints - 1; i++)
1580 Hint *cur_hint = hstate->all_hints[i];
1581 Hint *next_hint = hstate->all_hints[i + 1];
1584 * Leading hint is marked as 'duplicated' in transform_join_hints.
1586 if (cur_hint->type == HINT_TYPE_LEADING &&
1587 next_hint->type == HINT_TYPE_LEADING)
1591 * Note that we need to pass addresses of hint pointers, because
1592 * HintCmp is designed to sort array of Hint* by qsort.
1594 if (HintCmp(&cur_hint, &next_hint) == 0)
1596 hint_ereport(cur_hint->hint_str,
1597 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1598 cur_hint->state = HINT_STATE_DUPLICATION;
1603 * Make sure that per-type array pointers point proper position in the
1604 * array which consists of all hints.
1606 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1607 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1608 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1609 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1610 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1611 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1612 hstate->num_hints[HINT_TYPE_LEADING]);
1618 * Parse inside of parentheses of scan-method hints.
1621 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1624 const char *keyword = hint->base.keyword;
1625 HintKeyword hint_keyword = hint->base.hint_keyword;
1626 List *name_list = NIL;
1629 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1632 /* Parse relation name and index name(s) if given hint accepts. */
1633 length = list_length(name_list);
1636 hint->relname = linitial(name_list);
1637 hint->indexnames = list_delete_first(name_list);
1639 /* check whether the hint accepts index name(s). */
1641 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1642 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1643 #if PG_VERSION_NUM >= 90200
1644 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1645 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1647 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1648 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1651 ("%s hint accepts only one relation.",
1652 hint->base.keyword));
1653 hint->base.state = HINT_STATE_ERROR;
1660 ("%s hint requires a relation.",
1661 hint->base.keyword));
1662 hint->base.state = HINT_STATE_ERROR;
1666 /* Set a bit for specified hint. */
1667 switch (hint_keyword)
1669 case HINT_KEYWORD_SEQSCAN:
1670 hint->enforce_mask = ENABLE_SEQSCAN;
1672 case HINT_KEYWORD_INDEXSCAN:
1673 hint->enforce_mask = ENABLE_INDEXSCAN;
1675 case HINT_KEYWORD_INDEXSCANREGEXP:
1676 hint->enforce_mask = ENABLE_INDEXSCAN;
1677 hint->regexp = true;
1679 case HINT_KEYWORD_BITMAPSCAN:
1680 hint->enforce_mask = ENABLE_BITMAPSCAN;
1682 case HINT_KEYWORD_BITMAPSCANREGEXP:
1683 hint->enforce_mask = ENABLE_BITMAPSCAN;
1684 hint->regexp = true;
1686 case HINT_KEYWORD_TIDSCAN:
1687 hint->enforce_mask = ENABLE_TIDSCAN;
1689 case HINT_KEYWORD_NOSEQSCAN:
1690 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1692 case HINT_KEYWORD_NOINDEXSCAN:
1693 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1695 case HINT_KEYWORD_NOBITMAPSCAN:
1696 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1698 case HINT_KEYWORD_NOTIDSCAN:
1699 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1701 #if PG_VERSION_NUM >= 90200
1702 case HINT_KEYWORD_INDEXONLYSCAN:
1703 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1705 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1706 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1707 hint->regexp = true;
1709 case HINT_KEYWORD_NOINDEXONLYSCAN:
1710 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1714 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1723 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1726 const char *keyword = hint->base.keyword;
1727 HintKeyword hint_keyword = hint->base.hint_keyword;
1728 List *name_list = NIL;
1730 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1733 hint->nrels = list_length(name_list);
1735 if (hint->nrels > 0)
1741 * Transform relation names from list to array to sort them with qsort
1744 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1745 foreach (l, name_list)
1747 hint->relnames[i] = lfirst(l);
1752 list_free(name_list);
1754 /* A join hint requires at least two relations */
1755 if (hint->nrels < 2)
1758 ("%s hint requires at least two relations.",
1759 hint->base.keyword));
1760 hint->base.state = HINT_STATE_ERROR;
1764 /* Sort hints in alphabetical order of relation names. */
1765 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1767 switch (hint_keyword)
1769 case HINT_KEYWORD_NESTLOOP:
1770 hint->enforce_mask = ENABLE_NESTLOOP;
1772 case HINT_KEYWORD_MERGEJOIN:
1773 hint->enforce_mask = ENABLE_MERGEJOIN;
1775 case HINT_KEYWORD_HASHJOIN:
1776 hint->enforce_mask = ENABLE_HASHJOIN;
1778 case HINT_KEYWORD_NONESTLOOP:
1779 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1781 case HINT_KEYWORD_NOMERGEJOIN:
1782 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1784 case HINT_KEYWORD_NOHASHJOIN:
1785 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1788 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1797 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1800 if (outer_inner->outer_inner_pair == NIL)
1802 if (outer_inner->relation)
1808 if (list_length(outer_inner->outer_inner_pair) == 2)
1810 foreach(l, outer_inner->outer_inner_pair)
1812 if (!OuterInnerPairCheck(lfirst(l)))
1823 OuterInnerList(OuterInnerRels *outer_inner)
1825 List *outer_inner_list = NIL;
1827 OuterInnerRels *outer_inner_rels;
1829 foreach(l, outer_inner->outer_inner_pair)
1831 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
1833 if (outer_inner_rels->relation != NULL)
1834 outer_inner_list = lappend(outer_inner_list,
1835 outer_inner_rels->relation);
1837 outer_inner_list = list_concat(outer_inner_list,
1838 OuterInnerList(outer_inner_rels));
1840 return outer_inner_list;
1844 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1847 List *name_list = NIL;
1848 OuterInnerRels *outer_inner = NULL;
1850 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
1854 if (outer_inner != NULL)
1855 name_list = OuterInnerList(outer_inner);
1857 hint->relations = name_list;
1858 hint->outer_inner = outer_inner;
1860 /* A Leading hint requires at least two relations */
1861 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
1863 hint_ereport(hint->base.hint_str,
1864 ("%s hint requires at least two relations.",
1866 hint->base.state = HINT_STATE_ERROR;
1868 else if (hint->outer_inner != NULL &&
1869 !OuterInnerPairCheck(hint->outer_inner))
1871 hint_ereport(hint->base.hint_str,
1872 ("%s hint requires two sets of relations when parentheses nests.",
1874 hint->base.state = HINT_STATE_ERROR;
1881 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1883 List *name_list = NIL;
1885 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
1889 hint->words = name_list;
1891 /* We need both name and value to set GUC parameter. */
1892 if (list_length(name_list) == 2)
1894 hint->name = linitial(name_list);
1895 hint->value = lsecond(name_list);
1899 hint_ereport(hint->base.hint_str,
1900 ("%s hint requires name and value of GUC parameter.",
1902 hint->base.state = HINT_STATE_ERROR;
1909 * set GUC parameter functions
1913 set_config_option_wrapper(const char *name, const char *value,
1914 GucContext context, GucSource source,
1915 GucAction action, bool changeVal, int elevel)
1918 MemoryContext ccxt = CurrentMemoryContext;
1922 #if PG_VERSION_NUM >= 90200
1923 result = set_config_option(name, value, context, source,
1924 action, changeVal, 0);
1926 result = set_config_option(name, value, context, source,
1934 /* Save error info */
1935 MemoryContextSwitchTo(ccxt);
1936 errdata = CopyErrorData();
1939 ereport(elevel, (errcode(errdata->sqlerrcode),
1940 errmsg("%s", errdata->message),
1941 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1942 errdata->hint ? errhint("%s", errdata->hint) : 0));
1943 FreeErrorData(errdata);
1951 set_config_options(SetHint **options, int noptions, GucContext context)
1956 save_nestlevel = NewGUCNestLevel();
1958 for (i = 0; i < noptions; i++)
1960 SetHint *hint = options[i];
1963 if (!hint_state_enabled(hint))
1966 result = set_config_option_wrapper(hint->name, hint->value, context,
1967 PGC_S_SESSION, GUC_ACTION_SAVE, true,
1968 pg_hint_plan_parse_messages);
1970 hint->base.state = HINT_STATE_USED;
1972 hint->base.state = HINT_STATE_ERROR;
1975 return save_nestlevel;
1978 #define SET_CONFIG_OPTION(name, type_bits) \
1979 set_config_option_wrapper((name), \
1980 (mask & (type_bits)) ? "true" : "false", \
1981 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1984 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1988 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1989 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1990 #if PG_VERSION_NUM >= 90200
1991 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1994 mask = enforce_mask;
1996 mask = enforce_mask & current_hint->init_scan_mask;
1998 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1999 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2000 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2001 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2002 #if PG_VERSION_NUM >= 90200
2003 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2008 set_join_config_options(unsigned char enforce_mask, GucContext context)
2012 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2013 enforce_mask == ENABLE_HASHJOIN)
2014 mask = enforce_mask;
2016 mask = enforce_mask & current_hint->init_join_mask;
2018 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2019 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2020 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2024 * pg_hint_plan hook functions
2028 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
2029 ParamListInfo params, bool isTopLevel,
2030 DestReceiver *dest, char *completionTag)
2034 if (!pg_hint_plan_enable_hint)
2036 if (prev_ProcessUtility)
2037 (*prev_ProcessUtility) (parsetree, queryString, params,
2038 isTopLevel, dest, completionTag);
2040 standard_ProcessUtility(parsetree, queryString, params,
2041 isTopLevel, dest, completionTag);
2047 if (IsA(node, ExplainStmt))
2050 * Draw out parse tree of actual query from Query struct of EXPLAIN
2056 stmt = (ExplainStmt *) node;
2058 Assert(IsA(stmt->query, Query));
2059 query = (Query *) stmt->query;
2061 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2062 node = query->utilityStmt;
2066 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2067 * specified to preceding PREPARE command to use it as source of hints.
2069 if (IsA(node, ExecuteStmt))
2073 stmt = (ExecuteStmt *) node;
2074 stmt_name = stmt->name;
2076 #if PG_VERSION_NUM >= 90200
2078 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2081 if (IsA(node, CreateTableAsStmt))
2083 CreateTableAsStmt *stmt;
2086 stmt = (CreateTableAsStmt *) node;
2087 Assert(IsA(stmt->query, Query));
2088 query = (Query *) stmt->query;
2090 if (query->commandType == CMD_UTILITY &&
2091 IsA(query->utilityStmt, ExecuteStmt))
2093 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2094 stmt_name = estmt->name;
2102 if (prev_ProcessUtility)
2103 (*prev_ProcessUtility) (parsetree, queryString, params,
2104 isTopLevel, dest, completionTag);
2106 standard_ProcessUtility(parsetree, queryString, params,
2107 isTopLevel, dest, completionTag);
2121 if (prev_ProcessUtility)
2122 (*prev_ProcessUtility) (parsetree, queryString, params,
2123 isTopLevel, dest, completionTag);
2125 standard_ProcessUtility(parsetree, queryString, params,
2126 isTopLevel, dest, completionTag);
2130 * Push a hint into hint stack which is implemented with List struct. Head of
2131 * list is top of stack.
2134 push_hint(HintState *hstate)
2136 /* Prepend new hint to the list means pushing to stack. */
2137 HintStateStack = lcons(hstate, HintStateStack);
2139 /* Pushed hint is the one which should be used hereafter. */
2140 current_hint = hstate;
2143 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2147 /* Hint stack must not be empty. */
2148 if(HintStateStack == NIL)
2149 elog(ERROR, "hint stack is empty");
2152 * Take a hint at the head from the list, and free it. Switch current_hint
2153 * to point new head (NULL if the list is empty).
2155 HintStateStack = list_delete_first(HintStateStack);
2156 HintStateDelete(current_hint);
2157 if(HintStateStack == NIL)
2158 current_hint = NULL;
2160 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2163 static PlannedStmt *
2164 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2169 pgssJumbleState jstate;
2172 PlannedStmt *result;
2176 * Use standard planner if pg_hint_plan is disabled. Other hook functions
2177 * try to change plan with current_hint if any, so set it to NULL.
2179 if (!pg_hint_plan_enable_hint)
2180 goto standard_planner_proc;
2182 /* Create hint struct from client-supplied query string. */
2183 query = get_query_string();
2186 * Search hint information which is stored for the query and the
2187 * application. Query string is normalized before using in condition
2188 * in order to allow fuzzy matching.
2190 * XXX: normalizing code is copied from pg_stat_statements.c, so be careful
2191 * when supporting PostgreSQL's version up.
2193 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2194 jstate.jumble_len = 0;
2195 jstate.clocations_buf_size = 32;
2196 jstate.clocations = (pgssLocationLen *)
2197 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2198 jstate.clocations_count = 0;
2199 JumbleQuery(&jstate, parse);
2201 * generate_normalized_query() copies exact given query_len bytes, so we
2202 * add 1 byte for null-termination here. As comments on
2203 * generate_normalized_query says, generate_normalized_query doesn't take
2204 * care of null-terminate, but additional 1 byte ensures that '\0' byte in
2205 * the source buffer to be copied into norm_query.
2207 query_len = strlen(query) + 1;
2208 norm_query = generate_normalized_query(&jstate,
2211 GetDatabaseEncoding());
2212 hints = get_hints_from_table(norm_query, application_name);
2214 "pg_hint_plan: get_hints_from_table [%s][%s]=>[%s]",
2215 norm_query, application_name,
2216 hints ? hints : "(none)");
2218 hints = get_hints_from_comment(query);
2219 hstate = create_hintstate(parse, hints);
2222 * Use standard planner if the statement has not valid hint. Other hook
2223 * functions try to change plan with current_hint if any, so set it to
2227 goto standard_planner_proc;
2230 * Push new hint struct to the hint stack to disable previous hint context.
2234 /* Set GUC parameters which are specified with Set hint. */
2235 save_nestlevel = set_config_options(current_hint->set_hints,
2236 current_hint->num_hints[HINT_TYPE_SET],
2237 current_hint->context);
2240 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2241 if (enable_indexscan)
2242 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2243 if (enable_bitmapscan)
2244 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2246 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2247 #if PG_VERSION_NUM >= 90200
2248 if (enable_indexonlyscan)
2249 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2251 if (enable_nestloop)
2252 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2253 if (enable_mergejoin)
2254 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2255 if (enable_hashjoin)
2256 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2259 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2260 * state when this planner started when error occurred in planner.
2265 result = (*prev_planner) (parse, cursorOptions, boundParams);
2267 result = standard_planner(parse, cursorOptions, boundParams);
2272 * Rollback changes of GUC parameters, and pop current hint context
2273 * from hint stack to rewind the state.
2275 AtEOXact_GUC(true, save_nestlevel);
2281 /* Print hint in debug mode. */
2282 if (pg_hint_plan_debug_print)
2283 HintStateDump(current_hint);
2286 * Rollback changes of GUC parameters, and pop current hint context from
2287 * hint stack to rewind the state.
2289 AtEOXact_GUC(true, save_nestlevel);
2294 standard_planner_proc:
2295 current_hint = NULL;
2297 return (*prev_planner) (parse, cursorOptions, boundParams);
2299 return standard_planner(parse, cursorOptions, boundParams);
2303 * Return scan method hint which matches given aliasname.
2305 static ScanMethodHint *
2306 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2312 * We can't apply scan method hint if the relation is:
2313 * - not a base relation
2314 * - not an ordinary relation (such as join and subquery)
2316 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2319 rte = root->simple_rte_array[rel->relid];
2321 /* We can't force scan method of foreign tables */
2322 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2325 /* Find scan method hint, which matches given names, from the list. */
2326 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2328 ScanMethodHint *hint = current_hint->scan_hints[i];
2330 /* We ignore disabled hints. */
2331 if (!hint_state_enabled(hint))
2334 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2344 * Returns TRUE on match, FALSE on no match.
2346 * s1 --- the data to match against
2347 * s2 --- the pattern
2349 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2352 regexpeq(const char *s1, const char *s2)
2358 strcpy(name.data, s1);
2359 regexp = cstring_to_text(s2);
2361 result = DirectFunctionCall2Coll(nameregexeq,
2362 DEFAULT_COLLATION_OID,
2363 NameGetDatum(&name),
2364 PointerGetDatum(regexp));
2365 return DatumGetBool(result);
2369 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2377 * We delete all the IndexOptInfo list and prevent you from being usable by
2380 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2381 hint->enforce_mask == ENABLE_TIDSCAN)
2383 list_free_deep(rel->indexlist);
2384 rel->indexlist = NIL;
2385 hint->base.state = HINT_STATE_USED;
2391 * When a list of indexes is not specified, we just use all indexes.
2393 if (hint->indexnames == NIL)
2397 * Leaving only an specified index, we delete it from a IndexOptInfo list
2401 if (pg_hint_plan_debug_print)
2402 initStringInfo(&buf);
2404 for (cell = list_head(rel->indexlist); cell; cell = next)
2406 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2407 char *indexname = get_rel_name(info->indexoid);
2409 bool use_index = false;
2413 foreach(l, hint->indexnames)
2415 char *hintname = (char *) lfirst(l);
2419 result = regexpeq(indexname, hintname);
2421 result = RelnameCmp(&indexname, &hintname) == 0;
2426 if (pg_hint_plan_debug_print)
2428 appendStringInfoCharMacro(&buf, ' ');
2429 quote_value(&buf, indexname);
2437 * to make the index a candidate when definition of this index is
2438 * matched with the index's definition of current_hint.
2440 if (OidIsValid(relationObjectId) && !use_index)
2442 foreach(l, current_hint->parent_index_infos)
2446 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2448 /* check to match the parameter of unique */
2449 if (p_info->indisunique != info->unique)
2452 /* check to match the parameter of index's method */
2453 if (p_info->method != info->relam)
2456 /* to check to match the indexkey's configuration */
2457 if ((list_length(p_info->column_names)) !=
2461 /* check to match the indexkey's configuration */
2462 for (i = 0; i < info->ncolumns; i++)
2464 char *c_attname = NULL;
2465 char *p_attname = NULL;
2468 list_nth(p_info->column_names, i);
2470 /* both are expressions */
2471 if (info->indexkeys[i] == 0 && !p_attname)
2474 /* one's column is expression, the other is not */
2475 if (info->indexkeys[i] == 0 || !p_attname)
2478 c_attname = get_attname(relationObjectId,
2479 info->indexkeys[i]);
2481 if (strcmp(p_attname, c_attname) != 0)
2484 if (p_info->indcollation[i] != info->indexcollations[i])
2487 if (p_info->opclass[i] != info->opcintype[i])
2490 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2491 info->reverse_sort[i])
2494 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2495 info->nulls_first[i])
2500 if (i != info->ncolumns)
2503 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2504 (p_info->indpred_str && (info->indpred != NIL)))
2507 * Fetch the pg_index tuple by the Oid of the index
2509 ht_idx = SearchSysCache1(INDEXRELID,
2510 ObjectIdGetDatum(info->indexoid));
2512 /* check to match the expression's parameter of index */
2513 if (p_info->expression_str &&
2514 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2521 * to change the expression's parameter of child's
2524 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2525 Anum_pg_index_indexprs,
2528 result = DirectFunctionCall2(pg_get_expr,
2533 if (strcmp(p_info->expression_str,
2534 text_to_cstring(DatumGetTextP(result))) != 0)
2537 ReleaseSysCache(ht_idx);
2543 /* Check to match the predicate's paraameter of index */
2544 if (p_info->indpred_str &&
2545 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2552 * to change the predicate's parabeter of child's
2555 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2556 Anum_pg_index_indpred,
2559 result = DirectFunctionCall2(pg_get_expr,
2564 if (strcmp(p_info->indpred_str,
2565 text_to_cstring(DatumGetTextP(result))) != 0)
2568 ReleaseSysCache(ht_idx);
2575 ReleaseSysCache(ht_idx);
2577 else if (p_info->expression_str || (info->indexprs != NIL))
2579 else if (p_info->indpred_str || (info->indpred != NIL))
2584 /* to log the candidate of index */
2585 if (pg_hint_plan_debug_print)
2587 appendStringInfoCharMacro(&buf, ' ');
2588 quote_value(&buf, indexname);
2596 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2603 if (pg_hint_plan_debug_print)
2606 StringInfoData rel_buf;
2608 if (OidIsValid(relationObjectId))
2609 relname = get_rel_name(relationObjectId);
2611 relname = hint->relname;
2613 initStringInfo(&rel_buf);
2614 quote_value(&rel_buf, relname);
2617 (errmsg("available indexes for %s(%s):%s",
2622 pfree(rel_buf.data);
2627 * Return information of index definition.
2629 static ParentIndexInfo *
2630 get_parent_index_info(Oid indexoid, Oid relid)
2632 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
2633 Relation indexRelation;
2634 Form_pg_index index;
2638 indexRelation = index_open(indexoid, RowExclusiveLock);
2640 index = indexRelation->rd_index;
2642 p_info->indisunique = index->indisunique;
2643 p_info->method = indexRelation->rd_rel->relam;
2645 p_info->column_names = NIL;
2646 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2647 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2648 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
2650 for (i = 0; i < index->indnatts; i++)
2652 attname = get_attname(relid, index->indkey.values[i]);
2653 p_info->column_names = lappend(p_info->column_names, attname);
2655 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
2656 p_info->opclass[i] = indexRelation->rd_opcintype[i];
2657 p_info->indoption[i] = indexRelation->rd_indoption[i];
2661 * to check to match the expression's paraameter of index with child indexes
2663 p_info->expression_str = NULL;
2664 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
2670 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2671 Anum_pg_index_indexprs, &isnull);
2673 result = DirectFunctionCall2(pg_get_expr,
2675 ObjectIdGetDatum(relid));
2677 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
2681 * to check to match the predicate's paraameter of index with child indexes
2683 p_info->indpred_str = NULL;
2684 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
2690 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2691 Anum_pg_index_indpred, &isnull);
2693 result = DirectFunctionCall2(pg_get_expr,
2695 ObjectIdGetDatum(relid));
2697 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
2700 index_close(indexRelation, NoLock);
2706 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2707 bool inhparent, RelOptInfo *rel)
2709 ScanMethodHint *hint;
2711 if (prev_get_relation_info)
2712 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2714 /* Do nothing if we don't have valid hint in this context. */
2720 /* store does relids of parent table. */
2721 current_hint->parent_relid = rel->relid;
2722 current_hint->parent_rel_oid = relationObjectId;
2724 else if (current_hint->parent_relid != 0)
2727 * We use the same GUC parameter if this table is the child table of a
2728 * table called pg_hint_plan_get_relation_info just before that.
2732 /* append_rel_list contains all append rels; ignore others */
2733 foreach(l, root->append_rel_list)
2735 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2737 /* This rel is child table. */
2738 if (appinfo->parent_relid == current_hint->parent_relid &&
2739 appinfo->child_relid == rel->relid)
2741 if (current_hint->parent_hint)
2742 delete_indexes(current_hint->parent_hint, rel,
2749 /* This rel is not inherit table. */
2750 current_hint->parent_relid = 0;
2751 current_hint->parent_rel_oid = InvalidOid;
2752 current_hint->parent_hint = NULL;
2756 * If scan method hint was given, reset GUC parameters which control
2757 * planner behavior about choosing scan methods.
2759 if ((hint = find_scan_hint(root, rel)) == NULL)
2761 set_scan_config_options(current_hint->init_scan_mask,
2762 current_hint->context);
2765 set_scan_config_options(hint->enforce_mask, current_hint->context);
2766 hint->base.state = HINT_STATE_USED;
2774 current_hint->parent_hint = hint;
2776 relation = heap_open(relationObjectId, NoLock);
2777 indexoidlist = RelationGetIndexList(relation);
2779 foreach(l, indexoidlist)
2781 Oid indexoid = lfirst_oid(l);
2782 char *indexname = get_rel_name(indexoid);
2783 bool use_index = false;
2785 ParentIndexInfo *parent_index_info;
2787 foreach(lc, hint->indexnames)
2789 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
2798 parent_index_info = get_parent_index_info(indexoid,
2800 current_hint->parent_index_infos =
2801 lappend(current_hint->parent_index_infos, parent_index_info);
2803 heap_close(relation, NoLock);
2806 delete_indexes(hint, rel, InvalidOid);
2810 * Return index of relation which matches given aliasname, or 0 if not found.
2811 * If same aliasname was used multiple times in a query, return -1.
2814 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
2820 for (i = 1; i < root->simple_rel_array_size; i++)
2824 if (root->simple_rel_array[i] == NULL)
2827 Assert(i == root->simple_rel_array[i]->relid);
2829 if (RelnameCmp(&aliasname,
2830 &root->simple_rte_array[i]->eref->aliasname) != 0)
2833 foreach(l, initial_rels)
2835 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2837 if (rel->reloptkind == RELOPT_BASEREL)
2839 if (rel->relid != i)
2844 Assert(rel->reloptkind == RELOPT_JOINREL);
2846 if (!bms_is_member(i, rel->relids))
2853 ("Relation name \"%s\" is ambiguous.",
2868 * Return join hint which matches given joinrelids.
2870 static JoinMethodHint *
2871 find_join_hint(Relids joinrelids)
2876 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
2878 foreach(l, join_hint)
2880 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
2882 if (bms_equal(joinrelids, hint->joinrelids))
2890 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
2891 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
2893 OuterInnerRels *outer_rels;
2894 OuterInnerRels *inner_rels;
2895 Relids outer_relids;
2896 Relids inner_relids;
2898 JoinMethodHint *hint;
2900 if (outer_inner->relation != NULL)
2902 return bms_make_singleton(
2903 find_relid_aliasname(root, outer_inner->relation,
2905 leading_hint->base.hint_str));
2908 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
2909 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
2911 outer_relids = OuterInnerJoinCreate(outer_rels,
2917 inner_relids = OuterInnerJoinCreate(inner_rels,
2924 join_relids = bms_add_members(outer_relids, inner_relids);
2926 if (bms_num_members(join_relids) > nbaserel)
2930 * If we don't have join method hint, create new one for the
2931 * join combination with all join methods are enabled.
2933 hint = find_join_hint(join_relids);
2937 * Here relnames is not set, since Relids bitmap is sufficient to
2938 * control paths of this query afterward.
2940 hint = (JoinMethodHint *) JoinMethodHintCreate(
2941 leading_hint->base.hint_str,
2943 HINT_KEYWORD_LEADING);
2944 hint->base.state = HINT_STATE_USED;
2945 hint->nrels = bms_num_members(join_relids);
2946 hint->enforce_mask = ENABLE_ALL_JOIN;
2947 hint->joinrelids = bms_copy(join_relids);
2948 hint->inner_nrels = bms_num_members(inner_relids);
2949 hint->inner_joinrelids = bms_copy(inner_relids);
2951 hstate->join_hint_level[hint->nrels] =
2952 lappend(hstate->join_hint_level[hint->nrels], hint);
2956 hint->inner_nrels = bms_num_members(inner_relids);
2957 hint->inner_joinrelids = bms_copy(inner_relids);
2964 * Transform join method hint into handy form.
2966 * - create bitmap of relids from alias names, to make it easier to check
2967 * whether a join path matches a join method hint.
2968 * - add join method hints which are necessary to enforce join order
2969 * specified by Leading hint
2972 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2973 List *initial_rels, JoinMethodHint **join_method_hints)
2981 LeadingHint *lhint = NULL;
2984 * Create bitmap of relids from alias names for each join method hint.
2985 * Bitmaps are more handy than strings in join searching.
2987 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2989 JoinMethodHint *hint = hstate->join_hints[i];
2992 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
2995 bms_free(hint->joinrelids);
2996 hint->joinrelids = NULL;
2998 for (j = 0; j < hint->nrels; j++)
3000 relname = hint->relnames[j];
3002 relid = find_relid_aliasname(root, relname, initial_rels,
3003 hint->base.hint_str);
3006 hint->base.state = HINT_STATE_ERROR;
3011 if (bms_is_member(relid, hint->joinrelids))
3013 hint_ereport(hint->base.hint_str,
3014 ("Relation name \"%s\" is duplicated.", relname));
3015 hint->base.state = HINT_STATE_ERROR;
3019 hint->joinrelids = bms_add_member(hint->joinrelids, relid);
3022 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
3025 hstate->join_hint_level[hint->nrels] =
3026 lappend(hstate->join_hint_level[hint->nrels], hint);
3029 /* Do nothing if no Leading hint was supplied. */
3030 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
3034 * Decide to use Leading hint。
3036 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
3038 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
3041 if (leading_hint->base.state == HINT_STATE_ERROR)
3047 foreach(l, leading_hint->relations)
3049 relname = (char *)lfirst(l);;
3051 relid = find_relid_aliasname(root, relname, initial_rels,
3052 leading_hint->base.hint_str);
3054 leading_hint->base.state = HINT_STATE_ERROR;
3059 if (bms_is_member(relid, relids))
3061 hint_ereport(leading_hint->base.hint_str,
3062 ("Relation name \"%s\" is duplicated.", relname));
3063 leading_hint->base.state = HINT_STATE_ERROR;
3067 relids = bms_add_member(relids, relid);
3070 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3075 hint_ereport(lhint->base.hint_str,
3076 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3077 lhint->base.state = HINT_STATE_DUPLICATION;
3079 leading_hint->base.state = HINT_STATE_USED;
3080 lhint = leading_hint;
3083 /* check to exist Leading hint marked with 'used'. */
3088 * We need join method hints which fit specified join order in every join
3089 * level. For example, Leading(A B C) virtually requires following join
3090 * method hints, if no join method hint supplied:
3092 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3093 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3095 * If we already have join method hint which fits specified join order in
3096 * that join level, we leave it as-is and don't add new hints.
3100 if (lhint->outer_inner == NULL)
3102 foreach(l, lhint->relations)
3104 JoinMethodHint *hint;
3106 relname = (char *)lfirst(l);
3109 * Find relid of the relation which has given name. If we have the
3110 * name given in Leading hint multiple times in the join, nothing to
3113 relid = find_relid_aliasname(root, relname, initial_rels,
3116 /* Create bitmap of relids for current join level. */
3117 joinrelids = bms_add_member(joinrelids, relid);
3120 /* We never have join method hint for single relation. */
3125 * If we don't have join method hint, create new one for the
3126 * join combination with all join methods are enabled.
3128 hint = find_join_hint(joinrelids);
3132 * Here relnames is not set, since Relids bitmap is sufficient
3133 * to control paths of this query afterward.
3135 hint = (JoinMethodHint *) JoinMethodHintCreate(
3136 lhint->base.hint_str,
3138 HINT_KEYWORD_LEADING);
3139 hint->base.state = HINT_STATE_USED;
3140 hint->nrels = njoinrels;
3141 hint->enforce_mask = ENABLE_ALL_JOIN;
3142 hint->joinrelids = bms_copy(joinrelids);
3145 join_method_hints[njoinrels] = hint;
3147 if (njoinrels >= nbaserel)
3150 bms_free(joinrelids);
3156 * Delete all join hints which have different combination from Leading
3159 for (i = 2; i <= njoinrels; i++)
3161 list_free(hstate->join_hint_level[i]);
3163 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3168 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3175 njoinrels = bms_num_members(joinrelids);
3176 Assert(njoinrels >= 2);
3179 * Delete all join hints which have different combination from Leading
3182 for (i = 2;i <= njoinrels; i++)
3184 if (hstate->join_hint_level[i] != NIL)
3186 ListCell *prev = NULL;
3187 ListCell *next = NULL;
3188 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3191 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3195 if (hint->inner_nrels == 0 &&
3196 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3197 bms_equal(bms_union(hint->joinrelids, joinrelids),
3200 hstate->join_hint_level[i] =
3201 list_delete_cell(hstate->join_hint_level[i], l,
3210 bms_free(joinrelids);
3213 if (hint_state_enabled(lhint))
3215 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3222 * set_plain_rel_pathlist
3223 * Build access paths for a plain relation (no subquery, no inheritance)
3225 * This function was copied and edited from set_plain_rel_pathlist() in
3226 * src/backend/optimizer/path/allpaths.c
3229 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3231 /* Consider sequential scan */
3232 #if PG_VERSION_NUM >= 90200
3233 add_path(rel, create_seqscan_path(root, rel, NULL));
3235 add_path(rel, create_seqscan_path(root, rel));
3238 /* Consider index scans */
3239 create_index_paths(root, rel);
3241 /* Consider TID scans */
3242 create_tidscan_paths(root, rel);
3244 /* Now find the cheapest of the paths for this rel */
3249 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3254 foreach(l, initial_rels)
3256 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3258 ScanMethodHint *hint;
3260 /* Skip relations which we can't choose scan method. */
3261 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3264 rte = root->simple_rte_array[rel->relid];
3266 /* We can't force scan method of foreign tables */
3267 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3271 * Create scan paths with GUC parameters which are at the beginning of
3272 * planner if scan method hint is not specified, otherwise use
3273 * specified hints and mark the hint as used.
3275 if ((hint = find_scan_hint(root, rel)) == NULL)
3276 set_scan_config_options(hstate->init_scan_mask,
3280 set_scan_config_options(hint->enforce_mask, hstate->context);
3281 hint->base.state = HINT_STATE_USED;
3284 list_free_deep(rel->pathlist);
3285 rel->pathlist = NIL;
3288 /* It's an "append relation", process accordingly */
3289 set_append_rel_pathlist(root, rel, rel->relid, rte);
3293 set_plain_rel_pathlist(root, rel, rte);
3298 * Restore the GUC variables we set above.
3300 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3304 * wrapper of make_join_rel()
3306 * call make_join_rel() after changing enable_* parameters according to given
3310 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3313 JoinMethodHint *hint;
3317 joinrelids = bms_union(rel1->relids, rel2->relids);
3318 hint = find_join_hint(joinrelids);
3319 bms_free(joinrelids);
3322 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3324 if (hint->inner_nrels == 0)
3326 save_nestlevel = NewGUCNestLevel();
3328 set_join_config_options(hint->enforce_mask, current_hint->context);
3330 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3331 hint->base.state = HINT_STATE_USED;
3334 * Restore the GUC variables we set above.
3336 AtEOXact_GUC(true, save_nestlevel);
3339 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3348 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3349 RelOptInfo *joinrel,
3350 RelOptInfo *outerrel,
3351 RelOptInfo *innerrel,
3353 SpecialJoinInfo *sjinfo,
3356 ScanMethodHint *scan_hint = NULL;
3358 JoinMethodHint *join_hint;
3361 if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
3363 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3364 scan_hint->base.state = HINT_STATE_USED;
3367 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3368 join_hint = find_join_hint(joinrelids);
3369 bms_free(joinrelids);
3371 if (join_hint && join_hint->inner_nrels != 0)
3373 save_nestlevel = NewGUCNestLevel();
3375 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3378 set_join_config_options(join_hint->enforce_mask,
3379 current_hint->context);
3381 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3382 sjinfo, restrictlist);
3383 join_hint->base.state = HINT_STATE_USED;
3387 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3388 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3389 sjinfo, restrictlist);
3393 * Restore the GUC variables we set above.
3395 AtEOXact_GUC(true, save_nestlevel);
3398 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3399 sjinfo, restrictlist);
3401 if (scan_hint != NULL)
3402 set_scan_config_options(current_hint->init_scan_mask,
3403 current_hint->context);
3407 get_num_baserels(List *initial_rels)
3412 foreach(l, initial_rels)
3414 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3416 if (rel->reloptkind == RELOPT_BASEREL)
3418 else if (rel->reloptkind ==RELOPT_JOINREL)
3419 nbaserel+= bms_num_members(rel->relids);
3422 /* other values not expected here */
3423 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3431 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3434 JoinMethodHint **join_method_hints;
3438 bool leading_hint_enable;
3441 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3442 * valid hint is supplied.
3446 if (prev_join_search)
3447 return (*prev_join_search) (root, levels_needed, initial_rels);
3448 else if (enable_geqo && levels_needed >= geqo_threshold)
3449 return geqo(root, levels_needed, initial_rels);
3451 return standard_join_search(root, levels_needed, initial_rels);
3454 /* We apply scan method hint rebuild scan path. */
3455 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3458 * In the case using GEQO, only scan method hints and Set hints have
3459 * effect. Join method and join order is not controllable by hints.
3461 if (enable_geqo && levels_needed >= geqo_threshold)
3462 return geqo(root, levels_needed, initial_rels);
3464 nbaserel = get_num_baserels(initial_rels);
3465 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3466 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3468 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3469 initial_rels, join_method_hints);
3471 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3473 for (i = 2; i <= nbaserel; i++)
3475 list_free(current_hint->join_hint_level[i]);
3477 /* free Leading hint only */
3478 if (join_method_hints[i] != NULL &&
3479 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3480 JoinMethodHintDelete(join_method_hints[i]);
3482 pfree(current_hint->join_hint_level);
3483 pfree(join_method_hints);
3485 if (leading_hint_enable)
3486 set_join_config_options(current_hint->init_join_mask,
3487 current_hint->context);
3494 * Build access paths for a base relation
3496 * This function was copied and edited from set_rel_pathlist() in
3497 * src/backend/optimizer/path/allpaths.c
3500 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3501 Index rti, RangeTblEntry *rte)
3503 #if PG_VERSION_NUM >= 90200
3504 if (IS_DUMMY_REL(rel))
3506 /* We already proved the relation empty, so nothing more to do */
3513 /* It's an "append relation", process accordingly */
3514 set_append_rel_pathlist(root, rel, rti, rte);
3518 if (rel->rtekind == RTE_RELATION)
3520 if (rte->relkind == RELKIND_RELATION)
3522 /* Plain relation */
3523 set_plain_rel_pathlist(root, rel, rte);
3526 elog(ERROR, "unexpected relkind: %c", rte->relkind);
3529 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
3534 * stmt_beg callback is called when each query in PL/pgSQL function is about
3535 * to be executed. At that timing, we save query string in the global variable
3536 * plpgsql_query_string to use it in planner hook. It's safe to use one global
3537 * variable for the purpose, because its content is only necessary until
3538 * planner hook is called for the query, so recursive PL/pgSQL function calls
3539 * don't harm this mechanismk.
3542 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3544 if ((enum PLpgSQL_stmt_types) stmt->cmd_type == PLPGSQL_STMT_EXECSQL)
3546 PLpgSQL_expr *expr = ((PLpgSQL_stmt_execsql *) stmt)->sqlstmt;
3547 plpgsql_query_string = expr->query;
3552 * stmt_end callback is called then each query in PL/pgSQL function has
3553 * finished. At that timing, we clear plpgsql_query_string to tell planner
3554 * hook that next call is not for a query written in PL/pgSQL block.
3557 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3559 if ((enum PLpgSQL_stmt_types) stmt->cmd_type == PLPGSQL_STMT_EXECSQL)
3560 plpgsql_query_string = NULL;
3563 #define standard_join_search pg_hint_plan_standard_join_search
3564 #define join_search_one_level pg_hint_plan_join_search_one_level
3565 #define make_join_rel make_join_rel_wrapper
3568 #undef make_join_rel
3569 #define make_join_rel pg_hint_plan_make_join_rel
3570 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
3571 #include "make_join_rel.c"
3573 #include "pg_stat_statements.c"