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"
36 #include "catalog/pg_class.h"
38 #include "executor/spi.h"
39 #include "catalog/pg_type.h"
42 * We have our own header file "plpgsql-9.1", which is necessary to support
43 * hints for queries in PL/pgSQL blocks, in pg_hint_plan source package,
44 * because PostgreSQL 9.1 doesn't provide the header file as a part of
45 * installation. This header file is a copy of src/pl/plpgsql/src/plpgsql.h in
46 * PostgreSQL 9.1.9 source tree,
48 * On the other hand, 9.2 installation provides that header file for external
49 * modules, so we include the header in ordinary place.
53 /* partially copied from pg_stat_statements */
54 #include "normalize_query.h"
57 #include "access/htup_details.h"
59 #ifdef PG_MODULE_MAGIC
63 #define BLOCK_COMMENT_START "/*"
64 #define BLOCK_COMMENT_END "*/"
65 #define HINT_COMMENT_KEYWORD "+"
66 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
67 #define HINT_END BLOCK_COMMENT_END
70 #define HINT_SEQSCAN "SeqScan"
71 #define HINT_INDEXSCAN "IndexScan"
72 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
73 #define HINT_BITMAPSCAN "BitmapScan"
74 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
75 #define HINT_TIDSCAN "TidScan"
76 #define HINT_NOSEQSCAN "NoSeqScan"
77 #define HINT_NOINDEXSCAN "NoIndexScan"
78 #define HINT_NOBITMAPSCAN "NoBitmapScan"
79 #define HINT_NOTIDSCAN "NoTidScan"
80 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
81 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
82 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
83 #define HINT_NESTLOOP "NestLoop"
84 #define HINT_NESTLOOP_NM "NestLoop_NM"
85 #define HINT_MERGEJOIN "MergeJoin"
86 #define HINT_HASHJOIN "HashJoin"
87 #define HINT_NONESTLOOP "NoNestLoop"
88 #define HINT_NOMERGEJOIN "NoMergeJoin"
89 #define HINT_NOHASHJOIN "NoHashJoin"
90 #define HINT_LEADING "Leading"
91 #define HINT_SET "Set"
92 #define HINT_ROWS "Rows"
94 #define HINT_ARRAY_DEFAULT_INITSIZE 8
96 #define hint_ereport(str, detail) \
97 ereport(pg_hint_plan_parse_messages, \
98 (errmsg("hint syntax error at or near \"%s\"", (str)), \
101 #define skip_space(str) \
102 while (isspace(*str)) \
107 ENABLE_SEQSCAN = 0x01,
108 ENABLE_INDEXSCAN = 0x02,
109 ENABLE_BITMAPSCAN = 0x04,
110 ENABLE_TIDSCAN = 0x08,
111 ENABLE_INDEXONLYSCAN = 0x10
116 ENABLE_NESTLOOP = 0x01,
117 ENABLE_MERGEJOIN = 0x02,
118 ENABLE_HASHJOIN = 0x04,
119 ENABLE_MATERIALIZE = 0x08
122 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
123 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
124 ENABLE_INDEXONLYSCAN)
125 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN |\
127 #define DISABLE_ALL_SCAN 0
128 #define DISABLE_ALL_JOIN 0
130 /* hint keyword of enum type*/
131 typedef enum HintKeyword
133 HINT_KEYWORD_SEQSCAN,
134 HINT_KEYWORD_INDEXSCAN,
135 HINT_KEYWORD_INDEXSCANREGEXP,
136 HINT_KEYWORD_BITMAPSCAN,
137 HINT_KEYWORD_BITMAPSCANREGEXP,
138 HINT_KEYWORD_TIDSCAN,
139 HINT_KEYWORD_NOSEQSCAN,
140 HINT_KEYWORD_NOINDEXSCAN,
141 HINT_KEYWORD_NOBITMAPSCAN,
142 HINT_KEYWORD_NOTIDSCAN,
143 HINT_KEYWORD_INDEXONLYSCAN,
144 HINT_KEYWORD_INDEXONLYSCANREGEXP,
145 HINT_KEYWORD_NOINDEXONLYSCAN,
146 HINT_KEYWORD_NESTLOOP,
147 HINT_KEYWORD_NESTLOOP_NM,
148 HINT_KEYWORD_MERGEJOIN,
149 HINT_KEYWORD_HASHJOIN,
150 HINT_KEYWORD_NONESTLOOP,
151 HINT_KEYWORD_NOMERGEJOIN,
152 HINT_KEYWORD_NOHASHJOIN,
153 HINT_KEYWORD_LEADING,
156 HINT_KEYWORD_UNRECOGNIZED
159 typedef struct Hint Hint;
160 typedef struct HintState HintState;
162 typedef Hint *(*HintCreateFunction) (const char *hint_str,
164 HintKeyword hint_keyword);
165 typedef void (*HintDeleteFunction) (Hint *hint);
166 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf);
167 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
168 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
169 Query *parse, const char *str);
172 #define NUM_HINT_TYPE 5
173 typedef enum HintType
175 HINT_TYPE_SCAN_METHOD,
176 HINT_TYPE_JOIN_METHOD,
182 static const char *HintTypeName[] = {
191 typedef enum HintStatus
193 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
194 HINT_STATE_USED, /* hint is used */
195 HINT_STATE_DUPLICATION, /* specified hint duplication */
196 HINT_STATE_ERROR /* execute error (parse error does not include
200 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
201 (hint)->base.state == HINT_STATE_USED)
203 /* common data for all hints. */
206 const char *hint_str; /* must not do pfree */
207 const char *keyword; /* must not do pfree */
208 HintKeyword hint_keyword;
211 HintDeleteFunction delete_func;
212 HintDescFunction desc_func;
213 HintCmpFunction cmp_func;
214 HintParseFunction parse_func;
217 /* scan method hints */
218 typedef struct ScanMethodHint
224 unsigned char enforce_mask;
227 typedef struct ParentIndexInfo
232 char *expression_str;
239 /* join method hints */
240 typedef struct JoinMethodHint
246 unsigned char enforce_mask;
248 Relids inner_joinrelids;
249 bool inhibit_materialize;
252 /* join order hints */
253 typedef struct OuterInnerRels
256 List *outer_inner_pair;
259 typedef struct LeadingHint
262 List *relations; /* relation names specified in Leading hint */
263 OuterInnerRels *outer_inner;
266 /* change a run-time parameter hints */
267 typedef struct SetHint
270 char *name; /* name of variable */
276 typedef enum RowsValueType {
277 RVT_ABSOLUTE, /* Rows(... #1000) */
278 RVT_ADD, /* Rows(... +1000) */
279 RVT_SUB, /* Rows(... -1000) */
280 RVT_MULTI, /* Rows(... *1.2) */
282 typedef struct RowsHint
289 Relids inner_joinrelids;
291 RowsValueType value_type;
296 * Describes a context of hint processing.
300 char *hint_str; /* original hint string */
303 int nall_hints; /* # of valid all hints */
304 int max_all_hints; /* # of slots for all hints */
305 Hint **all_hints; /* parsed all hints */
307 /* # of each hints */
308 int num_hints[NUM_HINT_TYPE];
310 /* for scan method hints */
311 ScanMethodHint **scan_hints; /* parsed scan hints */
312 int init_scan_mask; /* initial value scan parameter */
313 Index parent_relid; /* inherit parent table relid */
314 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
315 List *parent_index_infos; /* information of inherit parent table's
318 /* for join method hints */
319 JoinMethodHint **join_hints; /* parsed join hints */
320 int init_join_mask; /* initial value join parameter */
321 List **join_hint_level;
323 /* for Leading hint */
324 LeadingHint **leading_hint; /* parsed Leading hints */
327 SetHint **set_hints; /* parsed Set hints */
328 GucContext context; /* which GUC parameters can we set? */
331 RowsHint **rows_hints; /* parsed Rows hints */
335 * Describes a hint parser module which is bound with particular hint keyword.
337 typedef struct HintParser
340 HintCreateFunction create_func;
341 HintKeyword hint_keyword;
344 /* Module callbacks */
348 static void push_hint(HintState *hstate);
349 static void pop_hint(void);
351 static void pg_hint_plan_ProcessUtility(Node *parsetree,
352 const char *queryString,
353 ProcessUtilityContext context,
354 ParamListInfo params,
355 DestReceiver *dest, char *completionTag);
356 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
357 ParamListInfo boundParams);
358 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
359 Oid relationObjectId,
360 bool inhparent, RelOptInfo *rel);
361 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
365 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
366 HintKeyword hint_keyword);
367 static void ScanMethodHintDelete(ScanMethodHint *hint);
368 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf);
369 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
370 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
371 Query *parse, const char *str);
372 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
373 HintKeyword hint_keyword);
374 static void JoinMethodHintDelete(JoinMethodHint *hint);
375 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf);
376 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
377 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
378 Query *parse, const char *str);
379 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
380 HintKeyword hint_keyword);
381 static void LeadingHintDelete(LeadingHint *hint);
382 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf);
383 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
384 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
385 Query *parse, const char *str);
386 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
387 HintKeyword hint_keyword);
388 static void SetHintDelete(SetHint *hint);
389 static void SetHintDesc(SetHint *hint, StringInfo buf);
390 static int SetHintCmp(const SetHint *a, const SetHint *b);
391 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
393 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
394 HintKeyword hint_keyword);
395 static void RowsHintDelete(RowsHint *hint);
396 static void RowsHintDesc(RowsHint *hint, StringInfo buf);
397 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
398 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
399 Query *parse, const char *str);
400 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
401 HintKeyword hint_keyword);
403 static void quote_value(StringInfo buf, const char *value);
405 static const char *parse_quoted_value(const char *str, char **word,
408 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
411 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
412 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
413 ListCell *other_rels);
414 static void make_rels_by_clauseless_joins(PlannerInfo *root,
416 ListCell *other_rels);
417 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
418 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
419 Index rti, RangeTblEntry *rte);
420 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
421 List *live_childrels,
422 List *all_child_pathkeys);
423 static Path *get_cheapest_parameterized_child_path(PlannerInfo *root,
425 Relids required_outer);
426 static List *accumulate_append_subpath(List *subpaths, Path *path);
427 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
430 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
432 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
436 static bool pg_hint_plan_enable_hint = true;
437 static bool pg_hint_plan_debug_print = false;
438 static int pg_hint_plan_parse_messages = INFO;
439 /* Default is off, to keep backward compatibility. */
440 static bool pg_hint_plan_enable_hint_table = false;
442 static const struct config_enum_entry parse_messages_level_options[] = {
443 {"debug", DEBUG2, true},
444 {"debug5", DEBUG5, false},
445 {"debug4", DEBUG4, false},
446 {"debug3", DEBUG3, false},
447 {"debug2", DEBUG2, false},
448 {"debug1", DEBUG1, false},
450 {"info", INFO, false},
451 {"notice", NOTICE, false},
452 {"warning", WARNING, false},
453 {"error", ERROR, false},
455 * {"fatal", FATAL, true},
456 * {"panic", PANIC, true},
461 /* Saved hook values in case of unload */
462 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
463 static planner_hook_type prev_planner = NULL;
464 static get_relation_info_hook_type prev_get_relation_info = NULL;
465 static join_search_hook_type prev_join_search = NULL;
467 /* Hold reference to currently active hint */
468 static HintState *current_hint = NULL;
471 * List of hint contexts. We treat the head of the list as the Top of the
472 * context stack, so current_hint always points the first element of this list.
474 static List *HintStateStack = NIL;
477 * Holds statement name during executing EXECUTE command. NULL for other
480 static char *stmt_name = NULL;
482 static const HintParser parsers[] = {
483 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
484 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
485 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
486 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
487 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
488 HINT_KEYWORD_BITMAPSCANREGEXP},
489 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
490 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
491 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
492 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
493 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
494 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
495 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
496 HINT_KEYWORD_INDEXONLYSCANREGEXP},
497 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
498 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
499 {HINT_NESTLOOP_NM, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP_NM},
500 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
501 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
502 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
503 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
504 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
505 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
506 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
507 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
508 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
512 * PL/pgSQL plugin for retrieving string representation of each query during
513 * function execution.
515 const char *plpgsql_query_string = NULL;
516 PLpgSQL_plugin plugin_funcs = {
520 pg_hint_plan_plpgsql_stmt_beg,
521 pg_hint_plan_plpgsql_stmt_end,
526 /* Current nesting depth of SPI calls, used to prevent recursive calls */
527 static int nested_level = 0;
530 * Module load callbacks
535 PLpgSQL_plugin **var_ptr;
537 /* Define custom GUC variables. */
538 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
539 "Force planner to use plans specified in the hint comment preceding to the query.",
541 &pg_hint_plan_enable_hint,
549 DefineCustomBoolVariable("pg_hint_plan.debug_print",
550 "Logs results of hint parsing.",
552 &pg_hint_plan_debug_print,
560 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
561 "Message level of parse errors.",
563 &pg_hint_plan_parse_messages,
565 parse_messages_level_options,
572 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
573 "Force planner to not get hint by using table lookups.",
575 &pg_hint_plan_enable_hint_table,
584 prev_ProcessUtility = ProcessUtility_hook;
585 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
586 prev_planner = planner_hook;
587 planner_hook = pg_hint_plan_planner;
588 prev_get_relation_info = get_relation_info_hook;
589 get_relation_info_hook = pg_hint_plan_get_relation_info;
590 prev_join_search = join_search_hook;
591 join_search_hook = pg_hint_plan_join_search;
593 /* setup PL/pgSQL plugin hook */
594 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
595 *var_ptr = &plugin_funcs;
599 * Module unload callback
605 PLpgSQL_plugin **var_ptr;
607 /* Uninstall hooks. */
608 ProcessUtility_hook = prev_ProcessUtility;
609 planner_hook = prev_planner;
610 get_relation_info_hook = prev_get_relation_info;
611 join_search_hook = prev_join_search;
613 /* uninstall PL/pgSQL plugin hook */
614 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
619 * create and delete functions the hint object
623 ScanMethodHintCreate(const char *hint_str, const char *keyword,
624 HintKeyword hint_keyword)
626 ScanMethodHint *hint;
628 hint = palloc(sizeof(ScanMethodHint));
629 hint->base.hint_str = hint_str;
630 hint->base.keyword = keyword;
631 hint->base.hint_keyword = hint_keyword;
632 hint->base.type = HINT_TYPE_SCAN_METHOD;
633 hint->base.state = HINT_STATE_NOTUSED;
634 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
635 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
636 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
637 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
638 hint->relname = NULL;
639 hint->indexnames = NIL;
640 hint->regexp = false;
641 hint->enforce_mask = 0;
643 return (Hint *) hint;
647 ScanMethodHintDelete(ScanMethodHint *hint)
653 pfree(hint->relname);
654 list_free_deep(hint->indexnames);
659 JoinMethodHintCreate(const char *hint_str, const char *keyword,
660 HintKeyword hint_keyword)
662 JoinMethodHint *hint;
664 hint = palloc(sizeof(JoinMethodHint));
665 hint->base.hint_str = hint_str;
666 hint->base.keyword = keyword;
667 hint->base.hint_keyword = hint_keyword;
668 hint->base.type = HINT_TYPE_JOIN_METHOD;
669 hint->base.state = HINT_STATE_NOTUSED;
670 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
671 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
672 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
673 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
675 hint->inner_nrels = 0;
676 hint->relnames = NULL;
677 hint->enforce_mask = 0;
678 hint->joinrelids = NULL;
679 hint->inner_joinrelids = NULL;
680 hint->inhibit_materialize = false;
682 return (Hint *) hint;
686 JoinMethodHintDelete(JoinMethodHint *hint)
695 for (i = 0; i < hint->nrels; i++)
696 pfree(hint->relnames[i]);
697 pfree(hint->relnames);
700 bms_free(hint->joinrelids);
701 bms_free(hint->inner_joinrelids);
706 LeadingHintCreate(const char *hint_str, const char *keyword,
707 HintKeyword hint_keyword)
711 hint = palloc(sizeof(LeadingHint));
712 hint->base.hint_str = hint_str;
713 hint->base.keyword = keyword;
714 hint->base.hint_keyword = hint_keyword;
715 hint->base.type = HINT_TYPE_LEADING;
716 hint->base.state = HINT_STATE_NOTUSED;
717 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
718 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
719 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
720 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
721 hint->relations = NIL;
722 hint->outer_inner = NULL;
724 return (Hint *) hint;
728 LeadingHintDelete(LeadingHint *hint)
733 list_free_deep(hint->relations);
734 if (hint->outer_inner)
735 pfree(hint->outer_inner);
740 SetHintCreate(const char *hint_str, const char *keyword,
741 HintKeyword hint_keyword)
745 hint = palloc(sizeof(SetHint));
746 hint->base.hint_str = hint_str;
747 hint->base.keyword = keyword;
748 hint->base.hint_keyword = hint_keyword;
749 hint->base.type = HINT_TYPE_SET;
750 hint->base.state = HINT_STATE_NOTUSED;
751 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
752 hint->base.desc_func = (HintDescFunction) SetHintDesc;
753 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
754 hint->base.parse_func = (HintParseFunction) SetHintParse;
759 return (Hint *) hint;
763 SetHintDelete(SetHint *hint)
773 list_free(hint->words);
778 RowsHintCreate(const char *hint_str, const char *keyword,
779 HintKeyword hint_keyword)
783 hint = palloc(sizeof(RowsHint));
784 hint->base.hint_str = hint_str;
785 hint->base.keyword = keyword;
786 hint->base.hint_keyword = hint_keyword;
787 hint->base.type = HINT_TYPE_ROWS;
788 hint->base.state = HINT_STATE_NOTUSED;
789 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
790 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
791 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
792 hint->base.parse_func = (HintParseFunction) RowsHintParse;
794 hint->inner_nrels = 0;
795 hint->relnames = NULL;
796 hint->joinrelids = NULL;
797 hint->inner_joinrelids = NULL;
798 hint->rows_str = NULL;
799 hint->value_type = RVT_ABSOLUTE;
802 return (Hint *) hint;
806 RowsHintDelete(RowsHint *hint)
815 for (i = 0; i < hint->nrels; i++)
816 pfree(hint->relnames[i]);
817 pfree(hint->relnames);
820 bms_free(hint->joinrelids);
821 bms_free(hint->inner_joinrelids);
826 HintStateCreate(void)
830 hstate = palloc(sizeof(HintState));
831 hstate->hint_str = NULL;
832 hstate->nall_hints = 0;
833 hstate->max_all_hints = 0;
834 hstate->all_hints = NULL;
835 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
836 hstate->scan_hints = NULL;
837 hstate->init_scan_mask = 0;
838 hstate->parent_relid = 0;
839 hstate->parent_hint = NULL;
840 hstate->parent_index_infos = NIL;
841 hstate->join_hints = NULL;
842 hstate->init_join_mask = 0;
843 hstate->join_hint_level = NULL;
844 hstate->leading_hint = NULL;
845 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
846 hstate->set_hints = NULL;
847 hstate->rows_hints = NULL;
853 HintStateDelete(HintState *hstate)
860 if (hstate->hint_str)
861 pfree(hstate->hint_str);
863 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
864 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
865 if (hstate->all_hints)
866 pfree(hstate->all_hints);
867 if (hstate->parent_index_infos)
868 list_free(hstate->parent_index_infos);
872 * Copy given value into buf, with quoting with '"' if necessary.
875 quote_value(StringInfo buf, const char *value)
877 bool need_quote = false;
880 for (str = value; *str != '\0'; str++)
882 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
885 appendStringInfoCharMacro(buf, '"');
890 for (str = value; *str != '\0'; str++)
893 appendStringInfoCharMacro(buf, '"');
895 appendStringInfoCharMacro(buf, *str);
899 appendStringInfoCharMacro(buf, '"');
903 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
907 appendStringInfo(buf, "%s(", hint->base.keyword);
908 if (hint->relname != NULL)
910 quote_value(buf, hint->relname);
911 foreach(l, hint->indexnames)
913 appendStringInfoCharMacro(buf, ' ');
914 quote_value(buf, (char *) lfirst(l));
917 appendStringInfoString(buf, ")\n");
921 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
925 appendStringInfo(buf, "%s(", hint->base.keyword);
926 if (hint->relnames != NULL)
928 quote_value(buf, hint->relnames[0]);
929 for (i = 1; i < hint->nrels; i++)
931 appendStringInfoCharMacro(buf, ' ');
932 quote_value(buf, hint->relnames[i]);
935 appendStringInfoString(buf, ")\n");
940 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
942 if (outer_inner->relation == NULL)
949 appendStringInfoCharMacro(buf, '(');
950 foreach(l, outer_inner->outer_inner_pair)
955 appendStringInfoCharMacro(buf, ' ');
957 OuterInnerDesc(lfirst(l), buf);
960 appendStringInfoCharMacro(buf, ')');
963 quote_value(buf, outer_inner->relation);
967 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
969 appendStringInfo(buf, "%s(", HINT_LEADING);
970 if (hint->outer_inner == NULL)
977 foreach(l, hint->relations)
982 appendStringInfoCharMacro(buf, ' ');
984 quote_value(buf, (char *) lfirst(l));
988 OuterInnerDesc(hint->outer_inner, buf);
990 appendStringInfoString(buf, ")\n");
994 SetHintDesc(SetHint *hint, StringInfo buf)
996 bool is_first = true;
999 appendStringInfo(buf, "%s(", HINT_SET);
1000 foreach(l, hint->words)
1005 appendStringInfoCharMacro(buf, ' ');
1007 quote_value(buf, (char *) lfirst(l));
1009 appendStringInfo(buf, ")\n");
1013 RowsHintDesc(RowsHint *hint, StringInfo buf)
1017 appendStringInfo(buf, "%s(", hint->base.keyword);
1018 if (hint->relnames != NULL)
1020 quote_value(buf, hint->relnames[0]);
1021 for (i = 1; i < hint->nrels; i++)
1023 appendStringInfoCharMacro(buf, ' ');
1024 quote_value(buf, hint->relnames[i]);
1027 appendStringInfo(buf, " %s", hint->rows_str);
1028 appendStringInfoString(buf, ")\n");
1033 * Append string which represents all hints in a given state to buf, with
1034 * preceding title with them.
1037 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1042 appendStringInfo(buf, "%s:\n", title);
1043 for (i = 0; i < hstate->nall_hints; i++)
1045 if (hstate->all_hints[i]->state != state)
1048 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf);
1053 * Dump contents of given hstate to server log with log level LOG.
1056 HintStateDump(HintState *hstate)
1062 elog(LOG, "pg_hint_plan:\nno hint");
1066 initStringInfo(&buf);
1068 appendStringInfoString(&buf, "pg_hint_plan:\n");
1069 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
1070 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
1071 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
1072 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
1074 elog(LOG, "%s", buf.data);
1084 RelnameCmp(const void *a, const void *b)
1086 const char *relnamea = *((const char **) a);
1087 const char *relnameb = *((const char **) b);
1089 return strcmp(relnamea, relnameb);
1093 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1095 return RelnameCmp(&a->relname, &b->relname);
1099 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1103 if (a->nrels != b->nrels)
1104 return a->nrels - b->nrels;
1106 for (i = 0; i < a->nrels; i++)
1109 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1117 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1123 SetHintCmp(const SetHint *a, const SetHint *b)
1125 return strcmp(a->name, b->name);
1129 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1133 if (a->nrels != b->nrels)
1134 return a->nrels - b->nrels;
1136 for (i = 0; i < a->nrels; i++)
1139 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1147 HintCmp(const void *a, const void *b)
1149 const Hint *hinta = *((const Hint **) a);
1150 const Hint *hintb = *((const Hint **) b);
1152 if (hinta->type != hintb->type)
1153 return hinta->type - hintb->type;
1154 if (hinta->state == HINT_STATE_ERROR)
1156 if (hintb->state == HINT_STATE_ERROR)
1158 return hinta->cmp_func(hinta, hintb);
1162 * Returns byte offset of hint b from hint a. If hint a was specified before
1163 * b, positive value is returned.
1166 HintCmpWithPos(const void *a, const void *b)
1168 const Hint *hinta = *((const Hint **) a);
1169 const Hint *hintb = *((const Hint **) b);
1172 result = HintCmp(a, b);
1174 result = hinta->hint_str - hintb->hint_str;
1183 parse_keyword(const char *str, StringInfo buf)
1187 while (!isspace(*str) && *str != '(' && *str != '\0')
1188 appendStringInfoCharMacro(buf, *str++);
1194 skip_parenthesis(const char *str, char parenthesis)
1198 if (*str != parenthesis)
1200 if (parenthesis == '(')
1201 hint_ereport(str, ("Opening parenthesis is necessary."));
1202 else if (parenthesis == ')')
1203 hint_ereport(str, ("Closing parenthesis is necessary."));
1214 * Parse a token from str, and store malloc'd copy into word. A token can be
1215 * quoted with '"'. Return value is pointer to unparsed portion of original
1216 * string, or NULL if an error occurred.
1218 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1221 parse_quoted_value(const char *str, char **word, bool truncate)
1226 /* Skip leading spaces. */
1229 initStringInfo(&buf);
1242 /* Double quotation must be closed. */
1246 hint_ereport(str, ("Unterminated quoted string."));
1251 * Skip escaped double quotation.
1253 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1254 * block comments) to be an object name, so users must specify
1255 * alias for such object names.
1257 * Those special names can be allowed if we care escaped slashes
1258 * and asterisks, but we don't.
1267 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1271 appendStringInfoCharMacro(&buf, *str++);
1276 hint_ereport(str, ("Zero-length delimited string."));
1283 /* Truncate name if it's too long */
1285 truncate_identifier(buf.data, strlen(buf.data), true);
1292 static OuterInnerRels *
1293 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1295 OuterInnerRels *outer_inner;
1297 outer_inner = palloc(sizeof(OuterInnerRels));
1298 outer_inner->relation = name;
1299 outer_inner->outer_inner_pair = outer_inner_list;
1305 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1307 List *outer_inner_pair = NIL;
1309 if ((str = skip_parenthesis(str, '(')) == NULL)
1314 /* Store words in parentheses into outer_inner_list. */
1315 while(*str != ')' && *str != '\0')
1317 OuterInnerRels *outer_inner_rels;
1321 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1329 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1332 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1335 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1340 (str = skip_parenthesis(str, ')')) == NULL)
1342 list_free(outer_inner_pair);
1346 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1352 parse_parentheses_Leading(const char *str, List **name_list,
1353 OuterInnerRels **outer_inner)
1356 bool truncate = true;
1358 if ((str = skip_parenthesis(str, '(')) == NULL)
1364 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1369 /* Store words in parentheses into name_list. */
1370 while(*str != ')' && *str != '\0')
1372 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1374 list_free(*name_list);
1378 *name_list = lappend(*name_list, name);
1383 if ((str = skip_parenthesis(str, ')')) == NULL)
1389 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1392 bool truncate = true;
1394 if ((str = skip_parenthesis(str, '(')) == NULL)
1399 /* Store words in parentheses into name_list. */
1400 while(*str != ')' && *str != '\0')
1402 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1404 list_free(*name_list);
1408 *name_list = lappend(*name_list, name);
1411 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1412 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1413 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1414 keyword == HINT_KEYWORD_SET)
1420 if ((str = skip_parenthesis(str, ')')) == NULL)
1426 parse_hints(HintState *hstate, Query *parse, const char *str)
1431 initStringInfo(&buf);
1432 while (*str != '\0')
1434 const HintParser *parser;
1436 /* in error message, we output the comment including the keyword. */
1437 head = (char *) str;
1439 /* parse only the keyword of the hint. */
1440 resetStringInfo(&buf);
1441 str = parse_keyword(str, &buf);
1443 for (parser = parsers; parser->keyword != NULL; parser++)
1445 char *keyword = parser->keyword;
1448 if (strcasecmp(buf.data, keyword) != 0)
1451 hint = parser->create_func(head, keyword, parser->hint_keyword);
1453 /* parser of each hint does parse in a parenthesis. */
1454 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1456 hint->delete_func(hint);
1462 * Add hint information into all_hints array. If we don't have
1463 * enough space, double the array.
1465 if (hstate->nall_hints == 0)
1467 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1468 hstate->all_hints = (Hint **)
1469 palloc(sizeof(Hint *) * hstate->max_all_hints);
1471 else if (hstate->nall_hints == hstate->max_all_hints)
1473 hstate->max_all_hints *= 2;
1474 hstate->all_hints = (Hint **)
1475 repalloc(hstate->all_hints,
1476 sizeof(Hint *) * hstate->max_all_hints);
1479 hstate->all_hints[hstate->nall_hints] = hint;
1480 hstate->nall_hints++;
1487 if (parser->keyword == NULL)
1490 ("Unrecognized hint keyword \"%s\".", buf.data));
1501 * Get hints from table by client-supplied query string and application name.
1504 get_hints_from_table(const char *client_query, const char *client_application)
1506 const char *search_query =
1508 " FROM hint_plan.hints "
1509 " WHERE norm_query_string = $1 "
1510 " AND ( application_name = $2 "
1511 " OR application_name = '' ) "
1512 " ORDER BY application_name DESC";
1513 static SPIPlanPtr plan = NULL;
1515 Oid argtypes[2] = { TEXTOID, TEXTOID };
1517 bool nulls[2] = { false, false };
1530 p = SPI_prepare(search_query, 2, argtypes);
1531 plan = SPI_saveplan(p);
1535 qry = cstring_to_text(client_query);
1536 app = cstring_to_text(client_application);
1537 values[0] = PointerGetDatum(qry);
1538 values[1] = PointerGetDatum(app);
1540 SPI_execute_plan(plan, values, nulls, true, 1);
1542 if (SPI_processed > 0)
1546 hints = SPI_getvalue(SPI_tuptable->vals[0],
1547 SPI_tuptable->tupdesc, 1);
1549 * Here we use SPI_palloc to ensure that hints string is valid even
1550 * after SPI_finish call. We can't use simple palloc because it
1551 * allocates memory in SPI's context and that context is deleted in
1554 buf = SPI_palloc(strlen(hints) + 1);
1574 * Get client-supplied query string.
1577 get_query_string(void)
1583 PreparedStatement *entry;
1585 entry = FetchPreparedStatement(stmt_name, true);
1586 p = entry->plansource->query_string;
1588 else if (plpgsql_query_string)
1589 p = plpgsql_query_string;
1591 p = debug_query_string;
1597 * Get hints from the head block comment in client-supplied query string.
1600 get_hints_from_comment(const char *p)
1602 const char *hint_head;
1610 /* extract query head comment. */
1611 hint_head = strstr(p, HINT_START);
1612 if (hint_head == NULL)
1614 for (;p < hint_head; p++)
1617 * Allow these characters precedes hint comment:
1619 * - alphabets which are in ASCII range
1620 * - space, tabs and new-lines
1621 * - underscores, for identifier
1622 * - commas, for SELECT clause, EXPLAIN and PREPARE
1623 * - parentheses, for EXPLAIN and PREPARE
1625 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1626 * avoid behavior which depends on locale setting.
1628 if (!(*p >= '0' && *p <= '9') &&
1629 !(*p >= 'A' && *p <= 'Z') &&
1630 !(*p >= 'a' && *p <= 'z') &&
1634 *p != '(' && *p != ')')
1638 len = strlen(HINT_START);
1643 /* find hint end keyword. */
1644 if ((tail = strstr(p, HINT_END)) == NULL)
1646 hint_ereport(head, ("Unterminated block comment."));
1650 /* We don't support nested block comments. */
1651 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1653 hint_ereport(head, ("Nested block comments are not supported."));
1657 /* Make a copy of hint. */
1659 head = palloc(len + 1);
1660 memcpy(head, p, len);
1668 * Parse hints that got, create hint struct from parse tree and parse hints.
1671 create_hintstate(Query *parse, const char *hints)
1681 hstate = HintStateCreate();
1682 hstate->hint_str = (char *) hints;
1684 /* parse each hint. */
1685 parse_hints(hstate, parse, p);
1687 /* When nothing specified a hint, we free HintState and returns NULL. */
1688 if (hstate->nall_hints == 0)
1690 HintStateDelete(hstate);
1694 /* Sort hints in order of original position. */
1695 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1698 /* Count number of hints per hint-type. */
1699 for (i = 0; i < hstate->nall_hints; i++)
1701 Hint *cur_hint = hstate->all_hints[i];
1702 hstate->num_hints[cur_hint->type]++;
1706 * If an object (or a set of objects) has multiple hints of same hint-type,
1707 * only the last hint is valid and others are ignored in planning.
1708 * Hints except the last are marked as 'duplicated' to remember the order.
1710 for (i = 0; i < hstate->nall_hints - 1; i++)
1712 Hint *cur_hint = hstate->all_hints[i];
1713 Hint *next_hint = hstate->all_hints[i + 1];
1716 * Leading hint is marked as 'duplicated' in transform_join_hints.
1718 if (cur_hint->type == HINT_TYPE_LEADING &&
1719 next_hint->type == HINT_TYPE_LEADING)
1723 * Note that we need to pass addresses of hint pointers, because
1724 * HintCmp is designed to sort array of Hint* by qsort.
1726 if (HintCmp(&cur_hint, &next_hint) == 0)
1728 hint_ereport(cur_hint->hint_str,
1729 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1730 cur_hint->state = HINT_STATE_DUPLICATION;
1735 * Make sure that per-type array pointers point proper position in the
1736 * array which consists of all hints.
1738 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1739 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1740 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1741 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1742 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1743 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1744 hstate->num_hints[HINT_TYPE_LEADING]);
1745 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
1746 hstate->num_hints[HINT_TYPE_SET]);
1752 * Parse inside of parentheses of scan-method hints.
1755 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1758 const char *keyword = hint->base.keyword;
1759 HintKeyword hint_keyword = hint->base.hint_keyword;
1760 List *name_list = NIL;
1763 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1766 /* Parse relation name and index name(s) if given hint accepts. */
1767 length = list_length(name_list);
1770 hint->relname = linitial(name_list);
1771 hint->indexnames = list_delete_first(name_list);
1773 /* check whether the hint accepts index name(s). */
1775 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1776 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1777 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1778 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1779 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1780 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1783 ("%s hint accepts only one relation.",
1784 hint->base.keyword));
1785 hint->base.state = HINT_STATE_ERROR;
1792 ("%s hint requires a relation.",
1793 hint->base.keyword));
1794 hint->base.state = HINT_STATE_ERROR;
1798 /* Set a bit for specified hint. */
1799 switch (hint_keyword)
1801 case HINT_KEYWORD_SEQSCAN:
1802 hint->enforce_mask = ENABLE_SEQSCAN;
1804 case HINT_KEYWORD_INDEXSCAN:
1805 hint->enforce_mask = ENABLE_INDEXSCAN;
1807 case HINT_KEYWORD_INDEXSCANREGEXP:
1808 hint->enforce_mask = ENABLE_INDEXSCAN;
1809 hint->regexp = true;
1811 case HINT_KEYWORD_BITMAPSCAN:
1812 hint->enforce_mask = ENABLE_BITMAPSCAN;
1814 case HINT_KEYWORD_BITMAPSCANREGEXP:
1815 hint->enforce_mask = ENABLE_BITMAPSCAN;
1816 hint->regexp = true;
1818 case HINT_KEYWORD_TIDSCAN:
1819 hint->enforce_mask = ENABLE_TIDSCAN;
1821 case HINT_KEYWORD_NOSEQSCAN:
1822 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1824 case HINT_KEYWORD_NOINDEXSCAN:
1825 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1827 case HINT_KEYWORD_NOBITMAPSCAN:
1828 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1830 case HINT_KEYWORD_NOTIDSCAN:
1831 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1833 case HINT_KEYWORD_INDEXONLYSCAN:
1834 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1836 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1837 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1838 hint->regexp = true;
1840 case HINT_KEYWORD_NOINDEXONLYSCAN:
1841 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1844 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1853 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1856 const char *keyword = hint->base.keyword;
1857 HintKeyword hint_keyword = hint->base.hint_keyword;
1858 List *name_list = NIL;
1860 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1863 hint->nrels = list_length(name_list);
1865 if (hint->nrels > 0)
1871 * Transform relation names from list to array to sort them with qsort
1874 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1875 foreach (l, name_list)
1877 hint->relnames[i] = lfirst(l);
1882 list_free(name_list);
1884 /* A join hint requires at least two relations */
1885 if (hint->nrels < 2)
1888 ("%s hint requires at least two relations.",
1889 hint->base.keyword));
1890 hint->base.state = HINT_STATE_ERROR;
1894 /* Sort hints in alphabetical order of relation names. */
1895 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1897 switch (hint_keyword)
1899 case HINT_KEYWORD_NESTLOOP_NM:
1900 hint->enforce_mask = ENABLE_NESTLOOP;
1902 case HINT_KEYWORD_NESTLOOP:
1903 hint->enforce_mask |= (ENABLE_NESTLOOP | ENABLE_MATERIALIZE);
1905 case HINT_KEYWORD_MERGEJOIN:
1906 hint->enforce_mask = ENABLE_MERGEJOIN;
1908 case HINT_KEYWORD_HASHJOIN:
1909 hint->enforce_mask = ENABLE_HASHJOIN;
1911 case HINT_KEYWORD_NONESTLOOP:
1912 hint->enforce_mask = (ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP);
1914 case HINT_KEYWORD_NOMERGEJOIN:
1915 hint->enforce_mask = (ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN);
1917 case HINT_KEYWORD_NOHASHJOIN:
1918 hint->enforce_mask = (ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN);
1921 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1930 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1933 if (outer_inner->outer_inner_pair == NIL)
1935 if (outer_inner->relation)
1941 if (list_length(outer_inner->outer_inner_pair) == 2)
1943 foreach(l, outer_inner->outer_inner_pair)
1945 if (!OuterInnerPairCheck(lfirst(l)))
1956 OuterInnerList(OuterInnerRels *outer_inner)
1958 List *outer_inner_list = NIL;
1960 OuterInnerRels *outer_inner_rels;
1962 foreach(l, outer_inner->outer_inner_pair)
1964 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
1966 if (outer_inner_rels->relation != NULL)
1967 outer_inner_list = lappend(outer_inner_list,
1968 outer_inner_rels->relation);
1970 outer_inner_list = list_concat(outer_inner_list,
1971 OuterInnerList(outer_inner_rels));
1973 return outer_inner_list;
1977 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1980 List *name_list = NIL;
1981 OuterInnerRels *outer_inner = NULL;
1983 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
1987 if (outer_inner != NULL)
1988 name_list = OuterInnerList(outer_inner);
1990 hint->relations = name_list;
1991 hint->outer_inner = outer_inner;
1993 /* A Leading hint requires at least two relations */
1994 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
1996 hint_ereport(hint->base.hint_str,
1997 ("%s hint requires at least two relations.",
1999 hint->base.state = HINT_STATE_ERROR;
2001 else if (hint->outer_inner != NULL &&
2002 !OuterInnerPairCheck(hint->outer_inner))
2004 hint_ereport(hint->base.hint_str,
2005 ("%s hint requires two sets of relations when parentheses nests.",
2007 hint->base.state = HINT_STATE_ERROR;
2014 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2016 List *name_list = NIL;
2018 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2022 hint->words = name_list;
2024 /* We need both name and value to set GUC parameter. */
2025 if (list_length(name_list) == 2)
2027 hint->name = linitial(name_list);
2028 hint->value = lsecond(name_list);
2032 hint_ereport(hint->base.hint_str,
2033 ("%s hint requires name and value of GUC parameter.",
2035 hint->base.state = HINT_STATE_ERROR;
2042 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2045 HintKeyword hint_keyword = hint->base.hint_keyword;
2046 List *name_list = NIL;
2050 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2053 /* Last element must be rows specification */
2054 hint->nrels = list_length(name_list) - 1;
2056 if (hint->nrels > 0)
2062 * Transform relation names from list to array to sort them with qsort
2065 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2066 foreach (l, name_list)
2068 if (hint->nrels <= i)
2070 hint->relnames[i] = lfirst(l);
2075 /* Retieve rows estimation */
2076 rows_str = list_nth(name_list, hint->nrels);
2077 hint->rows_str = rows_str; /* store as-is for error logging */
2078 if (rows_str[0] == '#')
2080 hint->value_type = RVT_ABSOLUTE;
2083 else if (rows_str[0] == '+')
2085 hint->value_type = RVT_ADD;
2088 else if (rows_str[0] == '-')
2090 hint->value_type = RVT_SUB;
2093 else if (rows_str[0] == '*')
2095 hint->value_type = RVT_MULTI;
2100 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2101 hint->base.state = HINT_STATE_ERROR;
2104 hint->rows = strtod(rows_str, &end_ptr);
2107 hint_ereport(rows_str,
2108 ("%s hint requires valid number as rows estimation.",
2109 hint->base.keyword));
2110 hint->base.state = HINT_STATE_ERROR;
2114 /* A join hint requires at least two relations */
2115 if (hint->nrels < 2)
2118 ("%s hint requires at least two relations.",
2119 hint->base.keyword));
2120 hint->base.state = HINT_STATE_ERROR;
2124 list_free(name_list);
2126 /* Sort relnames in alphabetical order. */
2127 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2133 * set GUC parameter functions
2137 set_config_option_wrapper(const char *name, const char *value,
2138 GucContext context, GucSource source,
2139 GucAction action, bool changeVal, int elevel)
2142 MemoryContext ccxt = CurrentMemoryContext;
2146 result = set_config_option(name, value, context, source,
2147 action, changeVal, 0);
2153 /* Save error info */
2154 MemoryContextSwitchTo(ccxt);
2155 errdata = CopyErrorData();
2158 ereport(elevel, (errcode(errdata->sqlerrcode),
2159 errmsg("%s", errdata->message),
2160 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2161 errdata->hint ? errhint("%s", errdata->hint) : 0));
2162 FreeErrorData(errdata);
2170 set_config_options(SetHint **options, int noptions, GucContext context)
2175 save_nestlevel = NewGUCNestLevel();
2177 for (i = 0; i < noptions; i++)
2179 SetHint *hint = options[i];
2182 if (!hint_state_enabled(hint))
2185 result = set_config_option_wrapper(hint->name, hint->value, context,
2186 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2187 pg_hint_plan_parse_messages);
2189 hint->base.state = HINT_STATE_USED;
2191 hint->base.state = HINT_STATE_ERROR;
2194 return save_nestlevel;
2197 #define SET_CONFIG_OPTION(name, type_bits) \
2198 set_config_option_wrapper((name), \
2199 (mask & (type_bits)) ? "true" : "false", \
2200 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2203 set_scan_config_options(unsigned char enforce_mask, GucContext context)
2207 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2208 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2209 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2211 mask = enforce_mask;
2213 mask = enforce_mask & current_hint->init_scan_mask;
2215 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2216 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2217 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2218 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2219 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2223 set_join_config_options(unsigned char enforce_mask, GucContext context)
2227 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2228 enforce_mask == ENABLE_HASHJOIN)
2229 mask = enforce_mask;
2231 mask = enforce_mask & current_hint->init_join_mask;
2233 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2234 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2235 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2236 SET_CONFIG_OPTION("enable_material", ENABLE_MATERIALIZE);
2240 * pg_hint_plan hook functions
2244 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
2245 ProcessUtilityContext context,
2246 ParamListInfo params,
2247 DestReceiver *dest, char *completionTag)
2252 * Use standard planner if pg_hint_plan is disabled or current nesting
2253 * depth is nesting depth of SPI calls.
2255 if (!pg_hint_plan_enable_hint || nested_level > 0)
2257 if (prev_ProcessUtility)
2258 (*prev_ProcessUtility) (parsetree, queryString,
2260 dest, completionTag);
2262 standard_ProcessUtility(parsetree, queryString,
2264 dest, completionTag);
2269 if (IsA(node, ExplainStmt))
2272 * Draw out parse tree of actual query from Query struct of EXPLAIN
2278 stmt = (ExplainStmt *) node;
2280 Assert(IsA(stmt->query, Query));
2281 query = (Query *) stmt->query;
2283 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2284 node = query->utilityStmt;
2288 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2289 * specified to preceding PREPARE command to use it as source of hints.
2291 if (IsA(node, ExecuteStmt))
2295 stmt = (ExecuteStmt *) node;
2296 stmt_name = stmt->name;
2300 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2303 if (IsA(node, CreateTableAsStmt))
2305 CreateTableAsStmt *stmt;
2308 stmt = (CreateTableAsStmt *) node;
2309 Assert(IsA(stmt->query, Query));
2310 query = (Query *) stmt->query;
2312 if (query->commandType == CMD_UTILITY &&
2313 IsA(query->utilityStmt, ExecuteStmt))
2315 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2316 stmt_name = estmt->name;
2324 if (prev_ProcessUtility)
2325 (*prev_ProcessUtility) (parsetree, queryString,
2327 dest, completionTag);
2329 standard_ProcessUtility(parsetree, queryString,
2331 dest, completionTag);
2345 if (prev_ProcessUtility)
2346 (*prev_ProcessUtility) (parsetree, queryString,
2348 dest, completionTag);
2350 standard_ProcessUtility(parsetree, queryString,
2352 dest, completionTag);
2356 * Push a hint into hint stack which is implemented with List struct. Head of
2357 * list is top of stack.
2360 push_hint(HintState *hstate)
2362 /* Prepend new hint to the list means pushing to stack. */
2363 HintStateStack = lcons(hstate, HintStateStack);
2365 /* Pushed hint is the one which should be used hereafter. */
2366 current_hint = hstate;
2369 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2373 /* Hint stack must not be empty. */
2374 if(HintStateStack == NIL)
2375 elog(ERROR, "hint stack is empty");
2378 * Take a hint at the head from the list, and free it. Switch current_hint
2379 * to point new head (NULL if the list is empty).
2381 HintStateStack = list_delete_first(HintStateStack);
2382 HintStateDelete(current_hint);
2383 if(HintStateStack == NIL)
2384 current_hint = NULL;
2386 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2389 static PlannedStmt *
2390 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2392 const char *hints = NULL;
2395 pgssJumbleState jstate;
2398 PlannedStmt *result;
2402 * Use standard planner if pg_hint_plan is disabled or current nesting
2403 * depth is nesting depth of SPI calls. Other hook functions try to change
2404 * plan with current_hint if any, so set it to NULL.
2406 if (!pg_hint_plan_enable_hint || nested_level > 0)
2407 goto standard_planner_proc;
2409 /* Create hint struct from client-supplied query string. */
2410 query = get_query_string();
2413 * Create hintstate from hint specified for the query, if any.
2415 * First we lookup hint in pg_hint.hints table by normalized query string,
2416 * unless pg_hint_plan.enable_hint_table is OFF.
2417 * This parameter provides option to avoid overhead of table lookup during
2420 * If no hint was found, then we try to get hint from special query comment.
2422 if (pg_hint_plan_enable_hint_table)
2425 * Search hint information which is stored for the query and the
2426 * application. Query string is normalized before using in condition
2427 * in order to allow fuzzy matching.
2429 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2430 * careful when supporting PostgreSQL's version up.
2432 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2433 jstate.jumble_len = 0;
2434 jstate.clocations_buf_size = 32;
2435 jstate.clocations = (pgssLocationLen *)
2436 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2437 jstate.clocations_count = 0;
2438 JumbleQuery(&jstate, parse);
2440 * generate_normalized_query() copies exact given query_len bytes, so we
2441 * add 1 byte for null-termination here. As comments on
2442 * generate_normalized_query says, generate_normalized_query doesn't
2443 * take care of null-terminate, but additional 1 byte ensures that '\0'
2444 * byte in the source buffer to be copied into norm_query.
2446 query_len = strlen(query) + 1;
2447 norm_query = generate_normalized_query(&jstate,
2450 GetDatabaseEncoding());
2451 hints = get_hints_from_table(norm_query, application_name);
2453 "pg_hint_plan: get_hints_from_table [%s][%s]=>[%s]",
2454 norm_query, application_name, hints ? hints : "(none)");
2457 hints = get_hints_from_comment(query);
2458 hstate = create_hintstate(parse, hints);
2461 * Use standard planner if the statement has not valid hint. Other hook
2462 * functions try to change plan with current_hint if any, so set it to
2466 goto standard_planner_proc;
2469 * Push new hint struct to the hint stack to disable previous hint context.
2473 /* Set GUC parameters which are specified with Set hint. */
2474 save_nestlevel = set_config_options(current_hint->set_hints,
2475 current_hint->num_hints[HINT_TYPE_SET],
2476 current_hint->context);
2479 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2480 if (enable_indexscan)
2481 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2482 if (enable_bitmapscan)
2483 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2485 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2486 if (enable_indexonlyscan)
2487 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2488 if (enable_nestloop)
2489 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2490 if (enable_mergejoin)
2491 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2492 if (enable_hashjoin)
2493 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2494 if (enable_material)
2495 current_hint->init_join_mask |= ENABLE_MATERIALIZE;
2498 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2499 * state when this planner started when error occurred in planner.
2504 result = (*prev_planner) (parse, cursorOptions, boundParams);
2506 result = standard_planner(parse, cursorOptions, boundParams);
2511 * Rollback changes of GUC parameters, and pop current hint context
2512 * from hint stack to rewind the state.
2514 AtEOXact_GUC(true, save_nestlevel);
2520 /* Print hint in debug mode. */
2521 if (pg_hint_plan_debug_print)
2522 HintStateDump(current_hint);
2525 * Rollback changes of GUC parameters, and pop current hint context from
2526 * hint stack to rewind the state.
2528 AtEOXact_GUC(true, save_nestlevel);
2533 standard_planner_proc:
2534 current_hint = NULL;
2536 return (*prev_planner) (parse, cursorOptions, boundParams);
2538 return standard_planner(parse, cursorOptions, boundParams);
2542 * Return scan method hint which matches given aliasname.
2544 static ScanMethodHint *
2545 find_scan_hint(PlannerInfo *root, Index relid, RelOptInfo *rel)
2551 * We can't apply scan method hint if the relation is:
2552 * - not a base relation
2553 * - not an ordinary relation (such as join and subquery)
2555 if (rel && (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION))
2558 rte = root->simple_rte_array[relid];
2560 /* We can't force scan method of foreign tables */
2561 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2564 /* Find scan method hint, which matches given names, from the list. */
2565 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2567 ScanMethodHint *hint = current_hint->scan_hints[i];
2569 /* We ignore disabled hints. */
2570 if (!hint_state_enabled(hint))
2573 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2583 * Returns TRUE on match, FALSE on no match.
2585 * s1 --- the data to match against
2586 * s2 --- the pattern
2588 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2591 regexpeq(const char *s1, const char *s2)
2597 strcpy(name.data, s1);
2598 regexp = cstring_to_text(s2);
2600 result = DirectFunctionCall2Coll(nameregexeq,
2601 DEFAULT_COLLATION_OID,
2602 NameGetDatum(&name),
2603 PointerGetDatum(regexp));
2604 return DatumGetBool(result);
2608 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2616 * We delete all the IndexOptInfo list and prevent you from being usable by
2619 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2620 hint->enforce_mask == ENABLE_TIDSCAN)
2622 list_free_deep(rel->indexlist);
2623 rel->indexlist = NIL;
2624 hint->base.state = HINT_STATE_USED;
2630 * When a list of indexes is not specified, we just use all indexes.
2632 if (hint->indexnames == NIL)
2636 * Leaving only an specified index, we delete it from a IndexOptInfo list
2640 if (pg_hint_plan_debug_print)
2641 initStringInfo(&buf);
2643 for (cell = list_head(rel->indexlist); cell; cell = next)
2645 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2646 char *indexname = get_rel_name(info->indexoid);
2648 bool use_index = false;
2652 foreach(l, hint->indexnames)
2654 char *hintname = (char *) lfirst(l);
2658 result = regexpeq(indexname, hintname);
2660 result = RelnameCmp(&indexname, &hintname) == 0;
2665 if (pg_hint_plan_debug_print)
2667 appendStringInfoCharMacro(&buf, ' ');
2668 quote_value(&buf, indexname);
2676 * to make the index a candidate when definition of this index is
2677 * matched with the index's definition of current_hint.
2679 if (OidIsValid(relationObjectId) && !use_index)
2681 foreach(l, current_hint->parent_index_infos)
2685 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2687 /* check to match the parameter of unique */
2688 if (p_info->indisunique != info->unique)
2691 /* check to match the parameter of index's method */
2692 if (p_info->method != info->relam)
2695 /* to check to match the indexkey's configuration */
2696 if ((list_length(p_info->column_names)) !=
2700 /* check to match the indexkey's configuration */
2701 for (i = 0; i < info->ncolumns; i++)
2703 char *c_attname = NULL;
2704 char *p_attname = NULL;
2707 list_nth(p_info->column_names, i);
2709 /* both are expressions */
2710 if (info->indexkeys[i] == 0 && !p_attname)
2713 /* one's column is expression, the other is not */
2714 if (info->indexkeys[i] == 0 || !p_attname)
2717 c_attname = get_attname(relationObjectId,
2718 info->indexkeys[i]);
2720 if (strcmp(p_attname, c_attname) != 0)
2723 if (p_info->indcollation[i] != info->indexcollations[i])
2726 if (p_info->opclass[i] != info->opcintype[i])
2729 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2730 info->reverse_sort[i])
2733 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2734 info->nulls_first[i])
2739 if (i != info->ncolumns)
2742 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2743 (p_info->indpred_str && (info->indpred != NIL)))
2746 * Fetch the pg_index tuple by the Oid of the index
2748 ht_idx = SearchSysCache1(INDEXRELID,
2749 ObjectIdGetDatum(info->indexoid));
2751 /* check to match the expression's parameter of index */
2752 if (p_info->expression_str &&
2753 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2760 * to change the expression's parameter of child's
2763 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2764 Anum_pg_index_indexprs,
2767 result = DirectFunctionCall2(pg_get_expr,
2772 if (strcmp(p_info->expression_str,
2773 text_to_cstring(DatumGetTextP(result))) != 0)
2776 ReleaseSysCache(ht_idx);
2782 /* Check to match the predicate's parameter of index */
2783 if (p_info->indpred_str &&
2784 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2791 * to change the predicate's parameter of child's
2794 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2795 Anum_pg_index_indpred,
2798 result = DirectFunctionCall2(pg_get_expr,
2803 if (strcmp(p_info->indpred_str,
2804 text_to_cstring(DatumGetTextP(result))) != 0)
2807 ReleaseSysCache(ht_idx);
2814 ReleaseSysCache(ht_idx);
2816 else if (p_info->expression_str || (info->indexprs != NIL))
2818 else if (p_info->indpred_str || (info->indpred != NIL))
2823 /* to log the candidate of index */
2824 if (pg_hint_plan_debug_print)
2826 appendStringInfoCharMacro(&buf, ' ');
2827 quote_value(&buf, indexname);
2835 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2842 if (pg_hint_plan_debug_print)
2845 StringInfoData rel_buf;
2847 if (OidIsValid(relationObjectId))
2848 relname = get_rel_name(relationObjectId);
2850 relname = hint->relname;
2852 initStringInfo(&rel_buf);
2853 quote_value(&rel_buf, relname);
2856 (errmsg("available indexes for %s(%s):%s",
2861 pfree(rel_buf.data);
2866 * Return information of index definition.
2868 static ParentIndexInfo *
2869 get_parent_index_info(Oid indexoid, Oid relid)
2871 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
2872 Relation indexRelation;
2873 Form_pg_index index;
2877 indexRelation = index_open(indexoid, RowExclusiveLock);
2879 index = indexRelation->rd_index;
2881 p_info->indisunique = index->indisunique;
2882 p_info->method = indexRelation->rd_rel->relam;
2884 p_info->column_names = NIL;
2885 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2886 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2887 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
2889 for (i = 0; i < index->indnatts; i++)
2891 attname = get_attname(relid, index->indkey.values[i]);
2892 p_info->column_names = lappend(p_info->column_names, attname);
2894 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
2895 p_info->opclass[i] = indexRelation->rd_opcintype[i];
2896 p_info->indoption[i] = indexRelation->rd_indoption[i];
2900 * to check to match the expression's parameter of index with child indexes
2902 p_info->expression_str = NULL;
2903 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
2909 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2910 Anum_pg_index_indexprs, &isnull);
2912 result = DirectFunctionCall2(pg_get_expr,
2914 ObjectIdGetDatum(relid));
2916 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
2920 * to check to match the predicate's parameter of index with child indexes
2922 p_info->indpred_str = NULL;
2923 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
2929 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2930 Anum_pg_index_indpred, &isnull);
2932 result = DirectFunctionCall2(pg_get_expr,
2934 ObjectIdGetDatum(relid));
2936 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
2939 index_close(indexRelation, NoLock);
2945 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2946 bool inhparent, RelOptInfo *rel)
2948 ScanMethodHint *hint = NULL;
2950 Index new_parent_relid = 0;
2952 if (prev_get_relation_info)
2953 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2956 * Do nothing if we don't have a valid hint in this context or current
2957 * nesting depth is at SPI calls.
2959 if (!current_hint || nested_level > 0)
2963 * We could register the parent relation of the following children here
2964 * when inhparent == true but inheritnce planner doesn't request
2965 * information for inheritance parents. We also cannot distinguish the
2966 * caller so we should always find the parents without this function being
2972 /* Find the parent for this relation */
2973 foreach (l, root->append_rel_list)
2975 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2977 if (appinfo->child_relid == rel->relid)
2979 if (current_hint->parent_relid != appinfo->parent_relid)
2980 new_parent_relid = appinfo->parent_relid;
2987 /* This relation doesn't have a parent. Cancel current_hint. */
2988 current_hint->parent_relid = 0;
2989 current_hint->parent_hint = NULL;
2992 if (new_parent_relid > 0)
2995 * Here we found a parent relation different from the remembered one.
2996 * Remember it, apply the scan mask of it and then resolve the index
2997 * restriction in order to be used by its children.
2999 int scanmask = current_hint->init_scan_mask;
3000 ScanMethodHint *parent_hint;
3002 current_hint->parent_relid = new_parent_relid;
3005 * Get and apply the hint for the new parent relation. It should be an
3006 * ordinary relation so calling find_scan_hint with rel == NULL is
3009 current_hint->parent_hint = parent_hint =
3010 find_scan_hint(root, current_hint->parent_relid, NULL);
3014 scanmask = current_hint->parent_hint->enforce_mask;
3015 parent_hint->base.state = HINT_STATE_USED;
3017 /* Resolve index name mask (if any) using the parent. */
3018 if (parent_hint->indexnames)
3021 Relation parent_rel;
3024 root->simple_rte_array[current_hint->parent_relid]->relid;
3025 parent_rel = heap_open(parentrel_oid, NoLock);
3027 /* Search the parent relation for indexes match the hint spec */
3028 foreach(l, RelationGetIndexList(parent_rel))
3030 Oid indexoid = lfirst_oid(l);
3031 char *indexname = get_rel_name(indexoid);
3033 ParentIndexInfo *parent_index_info;
3035 foreach(lc, parent_hint->indexnames)
3037 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3044 get_parent_index_info(indexoid, parentrel_oid);
3045 current_hint->parent_index_infos =
3046 lappend(current_hint->parent_index_infos, parent_index_info);
3048 heap_close(parent_rel, NoLock);
3052 set_scan_config_options(scanmask, current_hint->context);
3055 if (current_hint->parent_hint != 0)
3057 delete_indexes(current_hint->parent_hint, rel,
3060 /* Scan fixation status is the same to the parent. */
3064 /* This table doesn't have a parent hint. Apply its own hint if any. */
3065 if ((hint = find_scan_hint(root, rel->relid, rel)) != NULL)
3067 set_scan_config_options(hint->enforce_mask, current_hint->context);
3068 hint->base.state = HINT_STATE_USED;
3070 delete_indexes(hint, rel, InvalidOid);
3073 set_scan_config_options(current_hint->init_scan_mask,
3074 current_hint->context);
3079 * Return index of relation which matches given aliasname, or 0 if not found.
3080 * If same aliasname was used multiple times in a query, return -1.
3083 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3089 for (i = 1; i < root->simple_rel_array_size; i++)
3093 if (root->simple_rel_array[i] == NULL)
3096 Assert(i == root->simple_rel_array[i]->relid);
3098 if (RelnameCmp(&aliasname,
3099 &root->simple_rte_array[i]->eref->aliasname) != 0)
3102 foreach(l, initial_rels)
3104 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3106 if (rel->reloptkind == RELOPT_BASEREL)
3108 if (rel->relid != i)
3113 Assert(rel->reloptkind == RELOPT_JOINREL);
3115 if (!bms_is_member(i, rel->relids))
3122 ("Relation name \"%s\" is ambiguous.",
3137 * Return join hint which matches given joinrelids.
3139 static JoinMethodHint *
3140 find_join_hint(Relids joinrelids)
3145 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
3147 foreach(l, join_hint)
3149 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3151 if (bms_equal(joinrelids, hint->joinrelids))
3159 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3160 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3162 OuterInnerRels *outer_rels;
3163 OuterInnerRels *inner_rels;
3164 Relids outer_relids;
3165 Relids inner_relids;
3167 JoinMethodHint *hint;
3169 if (outer_inner->relation != NULL)
3171 return bms_make_singleton(
3172 find_relid_aliasname(root, outer_inner->relation,
3174 leading_hint->base.hint_str));
3177 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3178 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3180 outer_relids = OuterInnerJoinCreate(outer_rels,
3186 inner_relids = OuterInnerJoinCreate(inner_rels,
3193 join_relids = bms_add_members(outer_relids, inner_relids);
3195 if (bms_num_members(join_relids) > nbaserel)
3199 * If we don't have join method hint, create new one for the
3200 * join combination with all join methods are enabled.
3202 hint = find_join_hint(join_relids);
3206 * Here relnames is not set, since Relids bitmap is sufficient to
3207 * control paths of this query afterward.
3209 hint = (JoinMethodHint *) JoinMethodHintCreate(
3210 leading_hint->base.hint_str,
3212 HINT_KEYWORD_LEADING);
3213 hint->base.state = HINT_STATE_USED;
3214 hint->nrels = bms_num_members(join_relids);
3215 hint->enforce_mask = ENABLE_ALL_JOIN;
3216 hint->joinrelids = bms_copy(join_relids);
3217 hint->inner_nrels = bms_num_members(inner_relids);
3218 hint->inner_joinrelids = bms_copy(inner_relids);
3220 hstate->join_hint_level[hint->nrels] =
3221 lappend(hstate->join_hint_level[hint->nrels], hint);
3225 hint->inner_nrels = bms_num_members(inner_relids);
3226 hint->inner_joinrelids = bms_copy(inner_relids);
3233 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3234 int nrels, char **relnames)
3237 Relids relids = NULL;
3241 for (j = 0; j < nrels; j++)
3243 relname = relnames[j];
3245 relid = find_relid_aliasname(root, relname, initial_rels,
3249 base->state = HINT_STATE_ERROR;
3252 * the aliasname is not found(relid == 0) or same aliasname was used
3253 * multiple times in a query(relid == -1)
3260 if (bms_is_member(relid, relids))
3262 hint_ereport(base->hint_str,
3263 ("Relation name \"%s\" is duplicated.", relname));
3264 base->state = HINT_STATE_ERROR;
3268 relids = bms_add_member(relids, relid);
3273 * Transform join method hint into handy form.
3275 * - create bitmap of relids from alias names, to make it easier to check
3276 * whether a join path matches a join method hint.
3277 * - add join method hints which are necessary to enforce join order
3278 * specified by Leading hint
3281 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
3282 List *initial_rels, JoinMethodHint **join_method_hints)
3290 LeadingHint *lhint = NULL;
3293 * Create bitmap of relids from alias names for each join method hint.
3294 * Bitmaps are more handy than strings in join searching.
3296 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
3298 JoinMethodHint *hint = hstate->join_hints[i];
3300 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3303 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3304 initial_rels, hint->nrels, hint->relnames);
3306 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
3309 hstate->join_hint_level[hint->nrels] =
3310 lappend(hstate->join_hint_level[hint->nrels], hint);
3314 * Create bitmap of relids from alias names for each rows hint.
3315 * Bitmaps are more handy than strings in join searching.
3317 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
3319 RowsHint *hint = hstate->rows_hints[i];
3321 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3324 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3325 initial_rels, hint->nrels, hint->relnames);
3328 /* Do nothing if no Leading hint was supplied. */
3329 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
3333 * Decide whether to use Leading hint
3335 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
3337 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
3340 if (leading_hint->base.state == HINT_STATE_ERROR)
3346 foreach(l, leading_hint->relations)
3348 relname = (char *)lfirst(l);;
3350 relid = find_relid_aliasname(root, relname, initial_rels,
3351 leading_hint->base.hint_str);
3353 leading_hint->base.state = HINT_STATE_ERROR;
3358 if (bms_is_member(relid, relids))
3360 hint_ereport(leading_hint->base.hint_str,
3361 ("Relation name \"%s\" is duplicated.", relname));
3362 leading_hint->base.state = HINT_STATE_ERROR;
3366 relids = bms_add_member(relids, relid);
3369 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3374 hint_ereport(lhint->base.hint_str,
3375 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3376 lhint->base.state = HINT_STATE_DUPLICATION;
3378 leading_hint->base.state = HINT_STATE_USED;
3379 lhint = leading_hint;
3382 /* check to exist Leading hint marked with 'used'. */
3387 * We need join method hints which fit specified join order in every join
3388 * level. For example, Leading(A B C) virtually requires following join
3389 * method hints, if no join method hint supplied:
3391 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3392 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3394 * If we already have join method hint which fits specified join order in
3395 * that join level, we leave it as-is and don't add new hints.
3399 if (lhint->outer_inner == NULL)
3401 foreach(l, lhint->relations)
3403 JoinMethodHint *hint;
3405 relname = (char *)lfirst(l);
3408 * Find relid of the relation which has given name. If we have the
3409 * name given in Leading hint multiple times in the join, nothing to
3412 relid = find_relid_aliasname(root, relname, initial_rels,
3415 /* Create bitmap of relids for current join level. */
3416 joinrelids = bms_add_member(joinrelids, relid);
3419 /* We never have join method hint for single relation. */
3424 * If we don't have join method hint, create new one for the
3425 * join combination with all join methods are enabled.
3427 hint = find_join_hint(joinrelids);
3431 * Here relnames is not set, since Relids bitmap is sufficient
3432 * to control paths of this query afterward.
3434 hint = (JoinMethodHint *) JoinMethodHintCreate(
3435 lhint->base.hint_str,
3437 HINT_KEYWORD_LEADING);
3438 hint->base.state = HINT_STATE_USED;
3439 hint->nrels = njoinrels;
3440 hint->enforce_mask = ENABLE_ALL_JOIN;
3441 hint->joinrelids = bms_copy(joinrelids);
3444 join_method_hints[njoinrels] = hint;
3446 if (njoinrels >= nbaserel)
3449 bms_free(joinrelids);
3455 * Delete all join hints which have different combination from Leading
3458 for (i = 2; i <= njoinrels; i++)
3460 list_free(hstate->join_hint_level[i]);
3462 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3467 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3474 njoinrels = bms_num_members(joinrelids);
3475 Assert(njoinrels >= 2);
3478 * Delete all join hints which have different combination from Leading
3481 for (i = 2;i <= njoinrels; i++)
3483 if (hstate->join_hint_level[i] != NIL)
3485 ListCell *prev = NULL;
3486 ListCell *next = NULL;
3487 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3490 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3494 if (hint->inner_nrels == 0 &&
3495 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3496 bms_equal(bms_union(hint->joinrelids, joinrelids),
3499 hstate->join_hint_level[i] =
3500 list_delete_cell(hstate->join_hint_level[i], l,
3509 bms_free(joinrelids);
3512 if (hint_state_enabled(lhint))
3514 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3521 * set_plain_rel_pathlist
3522 * Build access paths for a plain relation (no subquery, no inheritance)
3524 * This function was copied and edited from set_plain_rel_pathlist() in
3525 * src/backend/optimizer/path/allpaths.c
3528 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3530 /* Consider sequential scan */
3531 add_path(rel, create_seqscan_path(root, rel, NULL));
3533 /* Consider index scans */
3534 create_index_paths(root, rel);
3536 /* Consider TID scans */
3537 create_tidscan_paths(root, rel);
3539 /* Now find the cheapest of the paths for this rel */
3544 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3549 foreach(l, initial_rels)
3551 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3553 ScanMethodHint *hint;
3555 /* Skip relations which we can't choose scan method. */
3556 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3559 rte = root->simple_rte_array[rel->relid];
3561 /* We can't force scan method of foreign tables */
3562 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3566 * Create scan paths with GUC parameters which are at the beginning of
3567 * planner if scan method hint is not specified, otherwise use
3568 * specified hints and mark the hint as used.
3570 if ((hint = find_scan_hint(root, rel->relid, rel)) == NULL)
3571 set_scan_config_options(hstate->init_scan_mask,
3575 set_scan_config_options(hint->enforce_mask, hstate->context);
3576 hint->base.state = HINT_STATE_USED;
3579 list_free_deep(rel->pathlist);
3580 rel->pathlist = NIL;
3583 /* It's an "append relation", process accordingly */
3584 set_append_rel_pathlist(root, rel, rel->relid, rte);
3588 set_plain_rel_pathlist(root, rel, rte);
3593 * Restore the GUC variables we set above.
3595 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3599 * wrapper of make_join_rel()
3601 * call make_join_rel() after changing enable_* parameters according to given
3605 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3608 JoinMethodHint *hint;
3612 joinrelids = bms_union(rel1->relids, rel2->relids);
3613 hint = find_join_hint(joinrelids);
3614 bms_free(joinrelids);
3617 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3619 if (hint->inner_nrels == 0)
3621 save_nestlevel = NewGUCNestLevel();
3623 set_join_config_options(hint->enforce_mask, current_hint->context);
3625 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3626 hint->base.state = HINT_STATE_USED;
3629 * Restore the GUC variables we set above.
3631 AtEOXact_GUC(true, save_nestlevel);
3634 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3643 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3644 RelOptInfo *joinrel,
3645 RelOptInfo *outerrel,
3646 RelOptInfo *innerrel,
3648 SpecialJoinInfo *sjinfo,
3651 ScanMethodHint *scan_hint = NULL;
3653 JoinMethodHint *join_hint;
3656 if ((scan_hint = find_scan_hint(root, innerrel->relid, innerrel)) != NULL)
3658 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3659 scan_hint->base.state = HINT_STATE_USED;
3662 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3663 join_hint = find_join_hint(joinrelids);
3664 bms_free(joinrelids);
3666 if (join_hint && join_hint->inner_nrels != 0)
3668 save_nestlevel = NewGUCNestLevel();
3670 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3673 set_join_config_options(join_hint->enforce_mask,
3674 current_hint->context);
3676 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3677 sjinfo, restrictlist);
3678 join_hint->base.state = HINT_STATE_USED;
3682 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3683 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3684 sjinfo, restrictlist);
3688 * Restore the GUC variables we set above.
3690 AtEOXact_GUC(true, save_nestlevel);
3693 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3694 sjinfo, restrictlist);
3696 if (scan_hint != NULL)
3697 set_scan_config_options(current_hint->init_scan_mask,
3698 current_hint->context);
3702 get_num_baserels(List *initial_rels)
3707 foreach(l, initial_rels)
3709 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3711 if (rel->reloptkind == RELOPT_BASEREL)
3713 else if (rel->reloptkind ==RELOPT_JOINREL)
3714 nbaserel+= bms_num_members(rel->relids);
3717 /* other values not expected here */
3718 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3726 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3729 JoinMethodHint **join_method_hints;
3733 bool leading_hint_enable;
3736 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3737 * valid hint is supplied or current nesting depth is nesting depth of SPI
3740 if (!current_hint || nested_level > 0)
3742 if (prev_join_search)
3743 return (*prev_join_search) (root, levels_needed, initial_rels);
3744 else if (enable_geqo && levels_needed >= geqo_threshold)
3745 return geqo(root, levels_needed, initial_rels);
3747 return standard_join_search(root, levels_needed, initial_rels);
3750 /* We apply scan method hint rebuild scan path. */
3751 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3754 * In the case using GEQO, only scan method hints and Set hints have
3755 * effect. Join method and join order is not controllable by hints.
3757 if (enable_geqo && levels_needed >= geqo_threshold)
3758 return geqo(root, levels_needed, initial_rels);
3760 nbaserel = get_num_baserels(initial_rels);
3761 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3762 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3764 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3765 initial_rels, join_method_hints);
3767 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3769 for (i = 2; i <= nbaserel; i++)
3771 list_free(current_hint->join_hint_level[i]);
3773 /* free Leading hint only */
3774 if (join_method_hints[i] != NULL &&
3775 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3776 JoinMethodHintDelete(join_method_hints[i]);
3778 pfree(current_hint->join_hint_level);
3779 pfree(join_method_hints);
3781 if (leading_hint_enable)
3782 set_join_config_options(current_hint->init_join_mask,
3783 current_hint->context);
3790 * Build access paths for a base relation
3792 * This function was copied and edited from set_rel_pathlist() in
3793 * src/backend/optimizer/path/allpaths.c
3796 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3797 Index rti, RangeTblEntry *rte)
3799 if (IS_DUMMY_REL(rel))
3801 /* We already proved the relation empty, so nothing more to do */
3805 /* It's an "append relation", process accordingly */
3806 set_append_rel_pathlist(root, rel, rti, rte);
3810 if (rel->rtekind == RTE_RELATION)
3812 if (rte->relkind == RELKIND_RELATION)
3814 /* Plain relation */
3815 set_plain_rel_pathlist(root, rel, rte);
3818 elog(ERROR, "unexpected relkind: %c", rte->relkind);
3821 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
3826 * stmt_beg callback is called when each query in PL/pgSQL function is about
3827 * to be executed. At that timing, we save query string in the global variable
3828 * plpgsql_query_string to use it in planner hook. It's safe to use one global
3829 * variable for the purpose, because its content is only necessary until
3830 * planner hook is called for the query, so recursive PL/pgSQL function calls
3831 * don't harm this mechanism.
3834 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3836 PLpgSQL_expr *expr = NULL;
3838 switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
3840 case PLPGSQL_STMT_FORS:
3841 expr = ((PLpgSQL_stmt_fors *) stmt)->query;
3843 case PLPGSQL_STMT_FORC:
3844 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_forc *)stmt)->curvar]))->cursor_explicit_expr;
3846 case PLPGSQL_STMT_RETURN_QUERY:
3847 if (((PLpgSQL_stmt_return_query *) stmt)->query != NULL)
3848 expr = ((PLpgSQL_stmt_return_query *) stmt)->query;
3850 expr = ((PLpgSQL_stmt_return_query *) stmt)->dynquery;
3852 case PLPGSQL_STMT_EXECSQL:
3853 expr = ((PLpgSQL_stmt_execsql *) stmt)->sqlstmt;
3855 case PLPGSQL_STMT_DYNEXECUTE:
3856 expr = ((PLpgSQL_stmt_dynexecute *) stmt)->query;
3858 case PLPGSQL_STMT_DYNFORS:
3859 expr = ((PLpgSQL_stmt_dynfors *) stmt)->query;
3861 case PLPGSQL_STMT_OPEN:
3862 if (((PLpgSQL_stmt_open *) stmt)->query != NULL)
3863 expr = ((PLpgSQL_stmt_open *) stmt)->query;
3864 else if (((PLpgSQL_stmt_open *) stmt)->dynquery != NULL)
3865 expr = ((PLpgSQL_stmt_open *) stmt)->dynquery;
3867 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_open *)stmt)->curvar]))->cursor_explicit_expr;
3874 plpgsql_query_string = expr->query;
3878 * stmt_end callback is called then each query in PL/pgSQL function has
3879 * finished. At that timing, we clear plpgsql_query_string to tell planner
3880 * hook that next call is not for a query written in PL/pgSQL block.
3883 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3885 if ((enum PLpgSQL_stmt_types) stmt->cmd_type == PLPGSQL_STMT_EXECSQL)
3886 plpgsql_query_string = NULL;
3889 #define standard_join_search pg_hint_plan_standard_join_search
3890 #define join_search_one_level pg_hint_plan_join_search_one_level
3891 #define make_join_rel make_join_rel_wrapper
3894 #undef make_join_rel
3895 #define make_join_rel pg_hint_plan_make_join_rel
3896 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
3897 #include "make_join_rel.c"
3899 #include "pg_stat_statements.c"