1 /*-------------------------------------------------------------------------
4 * hinting on how to execute a query for PostgreSQL
6 * Copyright (c) 2012-2018, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
8 *-------------------------------------------------------------------------
13 #include "catalog/pg_collation.h"
14 #include "catalog/pg_index.h"
15 #include "commands/prepare.h"
16 #include "mb/pg_wchar.h"
17 #include "miscadmin.h"
18 #include "nodes/nodeFuncs.h"
19 #include "nodes/params.h"
20 #include "optimizer/clauses.h"
21 #include "optimizer/cost.h"
22 #include "optimizer/geqo.h"
23 #include "optimizer/joininfo.h"
24 #include "optimizer/pathnode.h"
25 #include "optimizer/paths.h"
26 #include "optimizer/plancat.h"
27 #include "optimizer/planner.h"
28 #include "optimizer/prep.h"
29 #include "optimizer/restrictinfo.h"
30 #include "parser/analyze.h"
31 #include "parser/scansup.h"
32 #include "tcop/utility.h"
33 #include "utils/builtins.h"
34 #include "utils/lsyscache.h"
35 #include "utils/memutils.h"
36 #include "utils/rel.h"
37 #include "utils/snapmgr.h"
38 #include "utils/syscache.h"
39 #include "utils/resowner.h"
41 #include "catalog/pg_class.h"
43 #include "executor/spi.h"
44 #include "catalog/pg_type.h"
48 /* partially copied from pg_stat_statements */
49 #include "normalize_query.h"
52 #include "access/htup_details.h"
54 #ifdef PG_MODULE_MAGIC
58 #define BLOCK_COMMENT_START "/*"
59 #define BLOCK_COMMENT_END "*/"
60 #define HINT_COMMENT_KEYWORD "+"
61 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
62 #define HINT_END BLOCK_COMMENT_END
65 #define HINT_SEQSCAN "SeqScan"
66 #define HINT_INDEXSCAN "IndexScan"
67 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
68 #define HINT_BITMAPSCAN "BitmapScan"
69 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
70 #define HINT_TIDSCAN "TidScan"
71 #define HINT_NOSEQSCAN "NoSeqScan"
72 #define HINT_NOINDEXSCAN "NoIndexScan"
73 #define HINT_NOBITMAPSCAN "NoBitmapScan"
74 #define HINT_NOTIDSCAN "NoTidScan"
75 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
76 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
77 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
78 #define HINT_PARALLEL "Parallel"
80 #define HINT_NESTLOOP "NestLoop"
81 #define HINT_MERGEJOIN "MergeJoin"
82 #define HINT_HASHJOIN "HashJoin"
83 #define HINT_NONESTLOOP "NoNestLoop"
84 #define HINT_NOMERGEJOIN "NoMergeJoin"
85 #define HINT_NOHASHJOIN "NoHashJoin"
86 #define HINT_LEADING "Leading"
87 #define HINT_SET "Set"
88 #define HINT_ROWS "Rows"
90 #define HINT_ARRAY_DEFAULT_INITSIZE 8
92 #define hint_ereport(str, detail) \
94 ereport(pg_hint_plan_message_level, \
95 (errmsg("pg_hint_plan%s: hint syntax error at or near \"%s\"", qnostr, (str)), \
100 #define skip_space(str) \
101 while (isspace(*str)) \
106 ENABLE_SEQSCAN = 0x01,
107 ENABLE_INDEXSCAN = 0x02,
108 ENABLE_BITMAPSCAN = 0x04,
109 ENABLE_TIDSCAN = 0x08,
110 ENABLE_INDEXONLYSCAN = 0x10
115 ENABLE_NESTLOOP = 0x01,
116 ENABLE_MERGEJOIN = 0x02,
117 ENABLE_HASHJOIN = 0x04
120 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
121 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
122 ENABLE_INDEXONLYSCAN)
123 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
124 #define DISABLE_ALL_SCAN 0
125 #define DISABLE_ALL_JOIN 0
127 /* hint keyword of enum type*/
128 typedef enum HintKeyword
130 HINT_KEYWORD_SEQSCAN,
131 HINT_KEYWORD_INDEXSCAN,
132 HINT_KEYWORD_INDEXSCANREGEXP,
133 HINT_KEYWORD_BITMAPSCAN,
134 HINT_KEYWORD_BITMAPSCANREGEXP,
135 HINT_KEYWORD_TIDSCAN,
136 HINT_KEYWORD_NOSEQSCAN,
137 HINT_KEYWORD_NOINDEXSCAN,
138 HINT_KEYWORD_NOBITMAPSCAN,
139 HINT_KEYWORD_NOTIDSCAN,
140 HINT_KEYWORD_INDEXONLYSCAN,
141 HINT_KEYWORD_INDEXONLYSCANREGEXP,
142 HINT_KEYWORD_NOINDEXONLYSCAN,
144 HINT_KEYWORD_NESTLOOP,
145 HINT_KEYWORD_MERGEJOIN,
146 HINT_KEYWORD_HASHJOIN,
147 HINT_KEYWORD_NONESTLOOP,
148 HINT_KEYWORD_NOMERGEJOIN,
149 HINT_KEYWORD_NOHASHJOIN,
151 HINT_KEYWORD_LEADING,
154 HINT_KEYWORD_PARALLEL,
156 HINT_KEYWORD_UNRECOGNIZED
159 #define SCAN_HINT_ACCEPTS_INDEX_NAMES(kw) \
160 (kw == HINT_KEYWORD_INDEXSCAN || \
161 kw == HINT_KEYWORD_INDEXSCANREGEXP || \
162 kw == HINT_KEYWORD_INDEXONLYSCAN || \
163 kw == HINT_KEYWORD_INDEXONLYSCANREGEXP || \
164 kw == HINT_KEYWORD_BITMAPSCAN || \
165 kw == HINT_KEYWORD_BITMAPSCANREGEXP)
168 typedef struct Hint Hint;
169 typedef struct HintState HintState;
171 typedef Hint *(*HintCreateFunction) (const char *hint_str,
173 HintKeyword hint_keyword);
174 typedef void (*HintDeleteFunction) (Hint *hint);
175 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf, bool nolf);
176 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
177 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
178 Query *parse, const char *str);
181 #define NUM_HINT_TYPE 6
182 typedef enum HintType
184 HINT_TYPE_SCAN_METHOD,
185 HINT_TYPE_JOIN_METHOD,
192 typedef enum HintTypeBitmap
194 HINT_BM_SCAN_METHOD = 1,
198 static const char *HintTypeName[] = {
208 typedef enum HintStatus
210 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
211 HINT_STATE_USED, /* hint is used */
212 HINT_STATE_DUPLICATION, /* specified hint duplication */
213 HINT_STATE_ERROR /* execute error (parse error does not include
217 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
218 (hint)->base.state == HINT_STATE_USED)
220 static unsigned int qno = 0;
221 static unsigned int msgqno = 0;
222 static char qnostr[32];
223 static const char *current_hint_str = NULL;
225 /* common data for all hints. */
228 const char *hint_str; /* must not do pfree */
229 const char *keyword; /* must not do pfree */
230 HintKeyword hint_keyword;
233 HintDeleteFunction delete_func;
234 HintDescFunction desc_func;
235 HintCmpFunction cmp_func;
236 HintParseFunction parse_func;
239 /* scan method hints */
240 typedef struct ScanMethodHint
246 unsigned char enforce_mask;
249 typedef struct ParentIndexInfo
254 char *expression_str;
261 /* join method hints */
262 typedef struct JoinMethodHint
268 unsigned char enforce_mask;
270 Relids inner_joinrelids;
273 /* join order hints */
274 typedef struct OuterInnerRels
277 List *outer_inner_pair;
280 typedef struct LeadingHint
283 List *relations; /* relation names specified in Leading hint */
284 OuterInnerRels *outer_inner;
287 /* change a run-time parameter hints */
288 typedef struct SetHint
291 char *name; /* name of variable */
297 typedef enum RowsValueType {
298 RVT_ABSOLUTE, /* Rows(... #1000) */
299 RVT_ADD, /* Rows(... +1000) */
300 RVT_SUB, /* Rows(... -1000) */
301 RVT_MULTI, /* Rows(... *1.2) */
303 typedef struct RowsHint
310 Relids inner_joinrelids;
312 RowsValueType value_type;
317 typedef struct ParallelHint
321 char *nworkers_str; /* original string of nworkers */
322 int nworkers; /* num of workers specified by Worker */
323 bool force_parallel; /* force parallel scan */
327 * Describes a context of hint processing.
331 char *hint_str; /* original hint string */
334 int nall_hints; /* # of valid all hints */
335 int max_all_hints; /* # of slots for all hints */
336 Hint **all_hints; /* parsed all hints */
338 /* # of each hints */
339 int num_hints[NUM_HINT_TYPE];
341 /* for scan method hints */
342 ScanMethodHint **scan_hints; /* parsed scan hints */
344 /* Initial values of parameters */
345 int init_scan_mask; /* enable_* mask */
346 int init_nworkers; /* max_parallel_workers_per_gather */
347 int init_min_para_size; /* min_parallel_relation_size*/
348 int init_paratup_cost; /* parallel_tuple_cost */
349 int init_parasetup_cost;/* parallel_setup_cost */
351 Index parent_relid; /* inherit parent of table relid */
352 ScanMethodHint *parent_scan_hint; /* scan hint for the parent */
353 ParallelHint *parent_parallel_hint; /* parallel hint for the parent */
354 List *parent_index_infos; /* list of parent table's index */
356 JoinMethodHint **join_hints; /* parsed join hints */
357 int init_join_mask; /* initial value join parameter */
358 List **join_hint_level;
359 LeadingHint **leading_hint; /* parsed Leading hints */
360 SetHint **set_hints; /* parsed Set hints */
361 GucContext context; /* which GUC parameters can we set? */
362 RowsHint **rows_hints; /* parsed Rows hints */
363 ParallelHint **parallel_hints; /* parsed Parallel hints */
367 * Describes a hint parser module which is bound with particular hint keyword.
369 typedef struct HintParser
372 HintCreateFunction create_func;
373 HintKeyword hint_keyword;
376 /* Module callbacks */
380 static void push_hint(HintState *hstate);
381 static void pop_hint(void);
383 static void pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query);
384 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
385 ParamListInfo boundParams);
386 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
390 /* Scan method hint callbacks */
391 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
392 HintKeyword hint_keyword);
393 static void ScanMethodHintDelete(ScanMethodHint *hint);
394 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
395 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
396 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
397 Query *parse, const char *str);
399 /* Join method hint callbacks */
400 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
401 HintKeyword hint_keyword);
402 static void JoinMethodHintDelete(JoinMethodHint *hint);
403 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
404 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
405 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
406 Query *parse, const char *str);
408 /* Leading hint callbacks */
409 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
410 HintKeyword hint_keyword);
411 static void LeadingHintDelete(LeadingHint *hint);
412 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
413 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
414 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
415 Query *parse, const char *str);
417 /* Set hint callbacks */
418 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
419 HintKeyword hint_keyword);
420 static void SetHintDelete(SetHint *hint);
421 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
422 static int SetHintCmp(const SetHint *a, const SetHint *b);
423 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
426 /* Rows hint callbacks */
427 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
428 HintKeyword hint_keyword);
429 static void RowsHintDelete(RowsHint *hint);
430 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
431 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
432 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
433 Query *parse, const char *str);
435 /* Parallel hint callbacks */
436 static Hint *ParallelHintCreate(const char *hint_str, const char *keyword,
437 HintKeyword hint_keyword);
438 static void ParallelHintDelete(ParallelHint *hint);
439 static void ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf);
440 static int ParallelHintCmp(const ParallelHint *a, const ParallelHint *b);
441 static const char *ParallelHintParse(ParallelHint *hint, HintState *hstate,
442 Query *parse, const char *str);
444 static void quote_value(StringInfo buf, const char *value);
446 static const char *parse_quoted_value(const char *str, char **word,
449 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
452 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
453 void pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
454 Index rti, RangeTblEntry *rte);
455 static void create_plain_partial_paths(PlannerInfo *root,
458 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
459 ListCell *other_rels);
460 static void make_rels_by_clauseless_joins(PlannerInfo *root,
462 ListCell *other_rels);
463 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
464 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
466 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
467 Index rti, RangeTblEntry *rte);
468 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
469 List *live_childrels,
470 List *all_child_pathkeys);
471 static Path *get_cheapest_parameterized_child_path(PlannerInfo *root,
473 Relids required_outer);
474 static List *accumulate_append_subpath(List *subpaths, Path *path);
475 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
478 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
480 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
482 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
486 static int set_config_option_noerror(const char *name, const char *value,
487 GucContext context, GucSource source,
488 GucAction action, bool changeVal, int elevel);
489 static void setup_scan_method_enforcement(ScanMethodHint *scanhint,
491 static int set_config_int32_option(const char *name, int32 value,
495 static bool pg_hint_plan_enable_hint = true;
496 static int debug_level = 0;
497 static int pg_hint_plan_message_level = INFO;
498 /* Default is off, to keep backward compatibility. */
499 static bool pg_hint_plan_enable_hint_table = false;
501 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
502 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
503 /* (This could not be above 1) */
504 static int max_hint_nworkers = -1; /* Maximum nworkers of Workers hints */
506 static const struct config_enum_entry parse_messages_level_options[] = {
507 {"debug", DEBUG2, true},
508 {"debug5", DEBUG5, false},
509 {"debug4", DEBUG4, false},
510 {"debug3", DEBUG3, false},
511 {"debug2", DEBUG2, false},
512 {"debug1", DEBUG1, false},
514 {"info", INFO, false},
515 {"notice", NOTICE, false},
516 {"warning", WARNING, false},
517 {"error", ERROR, false},
519 * {"fatal", FATAL, true},
520 * {"panic", PANIC, true},
525 static const struct config_enum_entry parse_debug_level_options[] = {
528 {"detailed", 2, false},
529 {"verbose", 3, false},
541 /* Saved hook values in case of unload */
542 static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
543 static planner_hook_type prev_planner = NULL;
544 static join_search_hook_type prev_join_search = NULL;
545 static set_rel_pathlist_hook_type prev_set_rel_pathlist = NULL;
547 /* Hold reference to currently active hint */
548 static HintState *current_hint_state = NULL;
551 * List of hint contexts. We treat the head of the list as the Top of the
552 * context stack, so current_hint_state always points the first element of this
555 static List *HintStateStack = NIL;
558 * Holds statement name during executing EXECUTE command. NULL for other
561 static char *stmt_name = NULL;
563 static const HintParser parsers[] = {
564 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
565 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
566 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
567 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
568 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
569 HINT_KEYWORD_BITMAPSCANREGEXP},
570 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
571 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
572 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
573 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
574 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
575 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
576 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
577 HINT_KEYWORD_INDEXONLYSCANREGEXP},
578 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
580 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
581 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
582 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
583 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
584 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
585 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
587 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
588 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
589 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
590 {HINT_PARALLEL, ParallelHintCreate, HINT_KEYWORD_PARALLEL},
592 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
595 PLpgSQL_plugin plugin_funcs = {
599 pg_hint_plan_plpgsql_stmt_beg,
600 pg_hint_plan_plpgsql_stmt_end,
606 * Module load callbacks
611 PLpgSQL_plugin **var_ptr;
613 /* Define custom GUC variables. */
614 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
615 "Force planner to use plans specified in the hint comment preceding to the query.",
617 &pg_hint_plan_enable_hint,
625 DefineCustomEnumVariable("pg_hint_plan.debug_print",
626 "Logs results of hint parsing.",
630 parse_debug_level_options,
637 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
638 "Message level of parse errors.",
640 &pg_hint_plan_message_level,
642 parse_messages_level_options,
649 DefineCustomEnumVariable("pg_hint_plan.message_level",
650 "Message level of debug messages.",
652 &pg_hint_plan_message_level,
654 parse_messages_level_options,
661 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
662 "Let pg_hint_plan look up the hint table.",
664 &pg_hint_plan_enable_hint_table,
673 prev_post_parse_analyze_hook = post_parse_analyze_hook;
674 post_parse_analyze_hook = pg_hint_plan_post_parse_analyze;
675 prev_planner = planner_hook;
676 planner_hook = pg_hint_plan_planner;
677 prev_join_search = join_search_hook;
678 join_search_hook = pg_hint_plan_join_search;
679 prev_set_rel_pathlist = set_rel_pathlist_hook;
680 set_rel_pathlist_hook = pg_hint_plan_set_rel_pathlist;
682 /* setup PL/pgSQL plugin hook */
683 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
684 *var_ptr = &plugin_funcs;
686 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
690 * Module unload callback
696 PLpgSQL_plugin **var_ptr;
698 /* Uninstall hooks. */
699 post_parse_analyze_hook = prev_post_parse_analyze_hook;
700 planner_hook = prev_planner;
701 join_search_hook = prev_join_search;
702 set_rel_pathlist_hook = prev_set_rel_pathlist;
704 /* uninstall PL/pgSQL plugin hook */
705 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
710 * create and delete functions the hint object
714 ScanMethodHintCreate(const char *hint_str, const char *keyword,
715 HintKeyword hint_keyword)
717 ScanMethodHint *hint;
719 hint = palloc(sizeof(ScanMethodHint));
720 hint->base.hint_str = hint_str;
721 hint->base.keyword = keyword;
722 hint->base.hint_keyword = hint_keyword;
723 hint->base.type = HINT_TYPE_SCAN_METHOD;
724 hint->base.state = HINT_STATE_NOTUSED;
725 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
726 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
727 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
728 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
729 hint->relname = NULL;
730 hint->indexnames = NIL;
731 hint->regexp = false;
732 hint->enforce_mask = 0;
734 return (Hint *) hint;
738 ScanMethodHintDelete(ScanMethodHint *hint)
744 pfree(hint->relname);
745 list_free_deep(hint->indexnames);
750 JoinMethodHintCreate(const char *hint_str, const char *keyword,
751 HintKeyword hint_keyword)
753 JoinMethodHint *hint;
755 hint = palloc(sizeof(JoinMethodHint));
756 hint->base.hint_str = hint_str;
757 hint->base.keyword = keyword;
758 hint->base.hint_keyword = hint_keyword;
759 hint->base.type = HINT_TYPE_JOIN_METHOD;
760 hint->base.state = HINT_STATE_NOTUSED;
761 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
762 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
763 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
764 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
766 hint->inner_nrels = 0;
767 hint->relnames = NULL;
768 hint->enforce_mask = 0;
769 hint->joinrelids = NULL;
770 hint->inner_joinrelids = NULL;
772 return (Hint *) hint;
776 JoinMethodHintDelete(JoinMethodHint *hint)
785 for (i = 0; i < hint->nrels; i++)
786 pfree(hint->relnames[i]);
787 pfree(hint->relnames);
790 bms_free(hint->joinrelids);
791 bms_free(hint->inner_joinrelids);
796 LeadingHintCreate(const char *hint_str, const char *keyword,
797 HintKeyword hint_keyword)
801 hint = palloc(sizeof(LeadingHint));
802 hint->base.hint_str = hint_str;
803 hint->base.keyword = keyword;
804 hint->base.hint_keyword = hint_keyword;
805 hint->base.type = HINT_TYPE_LEADING;
806 hint->base.state = HINT_STATE_NOTUSED;
807 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
808 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
809 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
810 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
811 hint->relations = NIL;
812 hint->outer_inner = NULL;
814 return (Hint *) hint;
818 LeadingHintDelete(LeadingHint *hint)
823 list_free_deep(hint->relations);
824 if (hint->outer_inner)
825 pfree(hint->outer_inner);
830 SetHintCreate(const char *hint_str, const char *keyword,
831 HintKeyword hint_keyword)
835 hint = palloc(sizeof(SetHint));
836 hint->base.hint_str = hint_str;
837 hint->base.keyword = keyword;
838 hint->base.hint_keyword = hint_keyword;
839 hint->base.type = HINT_TYPE_SET;
840 hint->base.state = HINT_STATE_NOTUSED;
841 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
842 hint->base.desc_func = (HintDescFunction) SetHintDesc;
843 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
844 hint->base.parse_func = (HintParseFunction) SetHintParse;
849 return (Hint *) hint;
853 SetHintDelete(SetHint *hint)
863 list_free(hint->words);
868 RowsHintCreate(const char *hint_str, const char *keyword,
869 HintKeyword hint_keyword)
873 hint = palloc(sizeof(RowsHint));
874 hint->base.hint_str = hint_str;
875 hint->base.keyword = keyword;
876 hint->base.hint_keyword = hint_keyword;
877 hint->base.type = HINT_TYPE_ROWS;
878 hint->base.state = HINT_STATE_NOTUSED;
879 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
880 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
881 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
882 hint->base.parse_func = (HintParseFunction) RowsHintParse;
884 hint->inner_nrels = 0;
885 hint->relnames = NULL;
886 hint->joinrelids = NULL;
887 hint->inner_joinrelids = NULL;
888 hint->rows_str = NULL;
889 hint->value_type = RVT_ABSOLUTE;
892 return (Hint *) hint;
896 RowsHintDelete(RowsHint *hint)
905 for (i = 0; i < hint->nrels; i++)
906 pfree(hint->relnames[i]);
907 pfree(hint->relnames);
910 bms_free(hint->joinrelids);
911 bms_free(hint->inner_joinrelids);
916 ParallelHintCreate(const char *hint_str, const char *keyword,
917 HintKeyword hint_keyword)
921 hint = palloc(sizeof(ScanMethodHint));
922 hint->base.hint_str = hint_str;
923 hint->base.keyword = keyword;
924 hint->base.hint_keyword = hint_keyword;
925 hint->base.type = HINT_TYPE_PARALLEL;
926 hint->base.state = HINT_STATE_NOTUSED;
927 hint->base.delete_func = (HintDeleteFunction) ParallelHintDelete;
928 hint->base.desc_func = (HintDescFunction) ParallelHintDesc;
929 hint->base.cmp_func = (HintCmpFunction) ParallelHintCmp;
930 hint->base.parse_func = (HintParseFunction) ParallelHintParse;
931 hint->relname = NULL;
933 hint->nworkers_str = "0";
935 return (Hint *) hint;
939 ParallelHintDelete(ParallelHint *hint)
945 pfree(hint->relname);
951 HintStateCreate(void)
955 hstate = palloc(sizeof(HintState));
956 hstate->hint_str = NULL;
957 hstate->nall_hints = 0;
958 hstate->max_all_hints = 0;
959 hstate->all_hints = NULL;
960 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
961 hstate->scan_hints = NULL;
962 hstate->init_scan_mask = 0;
963 hstate->init_nworkers = 0;
964 hstate->init_min_para_size = 0;
965 hstate->init_paratup_cost = 0;
966 hstate->init_parasetup_cost = 0;
967 hstate->parent_relid = 0;
968 hstate->parent_scan_hint = NULL;
969 hstate->parent_parallel_hint = NULL;
970 hstate->parent_index_infos = NIL;
971 hstate->join_hints = NULL;
972 hstate->init_join_mask = 0;
973 hstate->join_hint_level = NULL;
974 hstate->leading_hint = NULL;
975 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
976 hstate->set_hints = NULL;
977 hstate->rows_hints = NULL;
978 hstate->parallel_hints = NULL;
984 HintStateDelete(HintState *hstate)
991 if (hstate->hint_str)
992 pfree(hstate->hint_str);
994 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
995 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
996 if (hstate->all_hints)
997 pfree(hstate->all_hints);
998 if (hstate->parent_index_infos)
999 list_free(hstate->parent_index_infos);
1003 * Copy given value into buf, with quoting with '"' if necessary.
1006 quote_value(StringInfo buf, const char *value)
1008 bool need_quote = false;
1011 for (str = value; *str != '\0'; str++)
1013 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
1016 appendStringInfoCharMacro(buf, '"');
1021 for (str = value; *str != '\0'; str++)
1024 appendStringInfoCharMacro(buf, '"');
1026 appendStringInfoCharMacro(buf, *str);
1030 appendStringInfoCharMacro(buf, '"');
1034 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
1038 appendStringInfo(buf, "%s(", hint->base.keyword);
1039 if (hint->relname != NULL)
1041 quote_value(buf, hint->relname);
1042 foreach(l, hint->indexnames)
1044 appendStringInfoCharMacro(buf, ' ');
1045 quote_value(buf, (char *) lfirst(l));
1048 appendStringInfoString(buf, ")");
1050 appendStringInfoChar(buf, '\n');
1054 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
1058 appendStringInfo(buf, "%s(", hint->base.keyword);
1059 if (hint->relnames != NULL)
1061 quote_value(buf, hint->relnames[0]);
1062 for (i = 1; i < hint->nrels; i++)
1064 appendStringInfoCharMacro(buf, ' ');
1065 quote_value(buf, hint->relnames[i]);
1068 appendStringInfoString(buf, ")");
1070 appendStringInfoChar(buf, '\n');
1074 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
1076 if (outer_inner->relation == NULL)
1083 appendStringInfoCharMacro(buf, '(');
1084 foreach(l, outer_inner->outer_inner_pair)
1089 appendStringInfoCharMacro(buf, ' ');
1091 OuterInnerDesc(lfirst(l), buf);
1094 appendStringInfoCharMacro(buf, ')');
1097 quote_value(buf, outer_inner->relation);
1101 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
1103 appendStringInfo(buf, "%s(", HINT_LEADING);
1104 if (hint->outer_inner == NULL)
1111 foreach(l, hint->relations)
1116 appendStringInfoCharMacro(buf, ' ');
1118 quote_value(buf, (char *) lfirst(l));
1122 OuterInnerDesc(hint->outer_inner, buf);
1124 appendStringInfoString(buf, ")");
1126 appendStringInfoChar(buf, '\n');
1130 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1132 bool is_first = true;
1135 appendStringInfo(buf, "%s(", HINT_SET);
1136 foreach(l, hint->words)
1141 appendStringInfoCharMacro(buf, ' ');
1143 quote_value(buf, (char *) lfirst(l));
1145 appendStringInfo(buf, ")");
1147 appendStringInfoChar(buf, '\n');
1151 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1155 appendStringInfo(buf, "%s(", hint->base.keyword);
1156 if (hint->relnames != NULL)
1158 quote_value(buf, hint->relnames[0]);
1159 for (i = 1; i < hint->nrels; i++)
1161 appendStringInfoCharMacro(buf, ' ');
1162 quote_value(buf, hint->relnames[i]);
1165 appendStringInfo(buf, " %s", hint->rows_str);
1166 appendStringInfoString(buf, ")");
1168 appendStringInfoChar(buf, '\n');
1172 ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf)
1174 appendStringInfo(buf, "%s(", hint->base.keyword);
1175 if (hint->relname != NULL)
1177 quote_value(buf, hint->relname);
1179 /* number of workers */
1180 appendStringInfoCharMacro(buf, ' ');
1181 quote_value(buf, hint->nworkers_str);
1182 /* application mode of num of workers */
1183 appendStringInfoCharMacro(buf, ' ');
1184 appendStringInfoString(buf,
1185 (hint->force_parallel ? "hard" : "soft"));
1187 appendStringInfoString(buf, ")");
1189 appendStringInfoChar(buf, '\n');
1193 * Append string which represents all hints in a given state to buf, with
1194 * preceding title with them.
1197 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1198 HintStatus state, bool nolf)
1202 appendStringInfo(buf, "%s:", title);
1204 appendStringInfoChar(buf, '\n');
1207 for (i = 0; i < hstate->nall_hints; i++)
1209 if (hstate->all_hints[i]->state != state)
1212 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1216 if (nolf && nshown == 0)
1217 appendStringInfoString(buf, "(none)");
1221 * Dump contents of given hstate to server log with log level LOG.
1224 HintStateDump(HintState *hstate)
1230 elog(LOG, "pg_hint_plan:\nno hint");
1234 initStringInfo(&buf);
1236 appendStringInfoString(&buf, "pg_hint_plan:\n");
1237 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1238 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1239 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1240 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1242 elog(LOG, "%s", buf.data);
1248 HintStateDump2(HintState *hstate)
1254 elog(pg_hint_plan_message_level,
1255 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1259 initStringInfo(&buf);
1260 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1261 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1262 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1263 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1264 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1265 appendStringInfoChar(&buf, '}');
1267 ereport(pg_hint_plan_message_level,
1268 (errmsg("%s", buf.data),
1270 errhidecontext(true)));
1280 RelnameCmp(const void *a, const void *b)
1282 const char *relnamea = *((const char **) a);
1283 const char *relnameb = *((const char **) b);
1285 return strcmp(relnamea, relnameb);
1289 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1291 return RelnameCmp(&a->relname, &b->relname);
1295 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1299 if (a->nrels != b->nrels)
1300 return a->nrels - b->nrels;
1302 for (i = 0; i < a->nrels; i++)
1305 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1313 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1319 SetHintCmp(const SetHint *a, const SetHint *b)
1321 return strcmp(a->name, b->name);
1325 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1329 if (a->nrels != b->nrels)
1330 return a->nrels - b->nrels;
1332 for (i = 0; i < a->nrels; i++)
1335 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1343 ParallelHintCmp(const ParallelHint *a, const ParallelHint *b)
1345 return RelnameCmp(&a->relname, &b->relname);
1349 HintCmp(const void *a, const void *b)
1351 const Hint *hinta = *((const Hint **) a);
1352 const Hint *hintb = *((const Hint **) b);
1354 if (hinta->type != hintb->type)
1355 return hinta->type - hintb->type;
1356 if (hinta->state == HINT_STATE_ERROR)
1358 if (hintb->state == HINT_STATE_ERROR)
1360 return hinta->cmp_func(hinta, hintb);
1364 * Returns byte offset of hint b from hint a. If hint a was specified before
1365 * b, positive value is returned.
1368 HintCmpWithPos(const void *a, const void *b)
1370 const Hint *hinta = *((const Hint **) a);
1371 const Hint *hintb = *((const Hint **) b);
1374 result = HintCmp(a, b);
1376 result = hinta->hint_str - hintb->hint_str;
1385 parse_keyword(const char *str, StringInfo buf)
1389 while (!isspace(*str) && *str != '(' && *str != '\0')
1390 appendStringInfoCharMacro(buf, *str++);
1396 skip_parenthesis(const char *str, char parenthesis)
1400 if (*str != parenthesis)
1402 if (parenthesis == '(')
1403 hint_ereport(str, ("Opening parenthesis is necessary."));
1404 else if (parenthesis == ')')
1405 hint_ereport(str, ("Closing parenthesis is necessary."));
1416 * Parse a token from str, and store malloc'd copy into word. A token can be
1417 * quoted with '"'. Return value is pointer to unparsed portion of original
1418 * string, or NULL if an error occurred.
1420 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1423 parse_quoted_value(const char *str, char **word, bool truncate)
1428 /* Skip leading spaces. */
1431 initStringInfo(&buf);
1444 /* Double quotation must be closed. */
1448 hint_ereport(str, ("Unterminated quoted string."));
1453 * Skip escaped double quotation.
1455 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1456 * block comments) to be an object name, so users must specify
1457 * alias for such object names.
1459 * Those special names can be allowed if we care escaped slashes
1460 * and asterisks, but we don't.
1469 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1473 appendStringInfoCharMacro(&buf, *str++);
1478 hint_ereport(str, ("Zero-length delimited string."));
1485 /* Truncate name if it's too long */
1487 truncate_identifier(buf.data, strlen(buf.data), true);
1494 static OuterInnerRels *
1495 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1497 OuterInnerRels *outer_inner;
1499 outer_inner = palloc(sizeof(OuterInnerRels));
1500 outer_inner->relation = name;
1501 outer_inner->outer_inner_pair = outer_inner_list;
1507 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1509 List *outer_inner_pair = NIL;
1511 if ((str = skip_parenthesis(str, '(')) == NULL)
1516 /* Store words in parentheses into outer_inner_list. */
1517 while(*str != ')' && *str != '\0')
1519 OuterInnerRels *outer_inner_rels;
1523 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1531 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1534 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1537 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1542 (str = skip_parenthesis(str, ')')) == NULL)
1544 list_free(outer_inner_pair);
1548 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1554 parse_parentheses_Leading(const char *str, List **name_list,
1555 OuterInnerRels **outer_inner)
1558 bool truncate = true;
1560 if ((str = skip_parenthesis(str, '(')) == NULL)
1566 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1571 /* Store words in parentheses into name_list. */
1572 while(*str != ')' && *str != '\0')
1574 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1576 list_free(*name_list);
1580 *name_list = lappend(*name_list, name);
1585 if ((str = skip_parenthesis(str, ')')) == NULL)
1591 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1594 bool truncate = true;
1596 if ((str = skip_parenthesis(str, '(')) == NULL)
1601 /* Store words in parentheses into name_list. */
1602 while(*str != ')' && *str != '\0')
1604 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1606 list_free(*name_list);
1610 *name_list = lappend(*name_list, name);
1613 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1614 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1615 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1616 keyword == HINT_KEYWORD_SET)
1622 if ((str = skip_parenthesis(str, ')')) == NULL)
1628 parse_hints(HintState *hstate, Query *parse, const char *str)
1633 initStringInfo(&buf);
1634 while (*str != '\0')
1636 const HintParser *parser;
1638 /* in error message, we output the comment including the keyword. */
1639 head = (char *) str;
1641 /* parse only the keyword of the hint. */
1642 resetStringInfo(&buf);
1643 str = parse_keyword(str, &buf);
1645 for (parser = parsers; parser->keyword != NULL; parser++)
1647 char *keyword = parser->keyword;
1650 if (pg_strcasecmp(buf.data, keyword) != 0)
1653 hint = parser->create_func(head, keyword, parser->hint_keyword);
1655 /* parser of each hint does parse in a parenthesis. */
1656 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1658 hint->delete_func(hint);
1664 * Add hint information into all_hints array. If we don't have
1665 * enough space, double the array.
1667 if (hstate->nall_hints == 0)
1669 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1670 hstate->all_hints = (Hint **)
1671 palloc(sizeof(Hint *) * hstate->max_all_hints);
1673 else if (hstate->nall_hints == hstate->max_all_hints)
1675 hstate->max_all_hints *= 2;
1676 hstate->all_hints = (Hint **)
1677 repalloc(hstate->all_hints,
1678 sizeof(Hint *) * hstate->max_all_hints);
1681 hstate->all_hints[hstate->nall_hints] = hint;
1682 hstate->nall_hints++;
1689 if (parser->keyword == NULL)
1692 ("Unrecognized hint keyword \"%s\".", buf.data));
1703 * Get hints from table by client-supplied query string and application name.
1706 get_hints_from_table(const char *client_query, const char *client_application)
1708 const char *search_query =
1710 " FROM hint_plan.hints "
1711 " WHERE norm_query_string = $1 "
1712 " AND ( application_name = $2 "
1713 " OR application_name = '' ) "
1714 " ORDER BY application_name DESC";
1715 static SPIPlanPtr plan = NULL;
1717 Oid argtypes[2] = { TEXTOID, TEXTOID };
1719 bool nulls[2] = { false, false };
1725 bool snapshot_set = false;
1727 hint_inhibit_level++;
1729 if (!ActiveSnapshotSet())
1731 PushActiveSnapshot(GetTransactionSnapshot());
1732 snapshot_set = true;
1740 p = SPI_prepare(search_query, 2, argtypes);
1741 plan = SPI_saveplan(p);
1745 qry = cstring_to_text(client_query);
1746 app = cstring_to_text(client_application);
1747 values[0] = PointerGetDatum(qry);
1748 values[1] = PointerGetDatum(app);
1750 SPI_execute_plan(plan, values, nulls, true, 1);
1752 if (SPI_processed > 0)
1756 hints = SPI_getvalue(SPI_tuptable->vals[0],
1757 SPI_tuptable->tupdesc, 1);
1759 * Here we use SPI_palloc to ensure that hints string is valid even
1760 * after SPI_finish call. We can't use simple palloc because it
1761 * allocates memory in SPI's context and that context is deleted in
1764 buf = SPI_palloc(strlen(hints) + 1);
1772 PopActiveSnapshot();
1774 hint_inhibit_level--;
1778 hint_inhibit_level--;
1787 * Get client-supplied query string. Addtion to that the jumbled query is
1788 * supplied if the caller requested. From the restriction of JumbleQuery, some
1789 * kind of query needs special amendments. Reutrns NULL if this query doesn't
1790 * change the current hint. This function returns NULL also when something
1791 * wrong has happend and let the caller continue using the current hints.
1794 get_query_string(ParseState *pstate, Query *query, Query **jumblequery)
1796 const char *p = debug_query_string;
1799 * If debug_query_string is set, it is the top level statement. But in some
1800 * cases we reach here with debug_query_string set NULL for example in the
1801 * case of DESCRIBE message handling. We may still see a candidate
1802 * top-level query in pstate in the case.
1806 /* We don't see a query string, return NULL */
1807 if (!pstate->p_sourcetext)
1810 p = pstate->p_sourcetext;
1813 if (jumblequery != NULL)
1814 *jumblequery = query;
1816 /* Query for DeclareCursorStmt is CMD_SELECT and has query->utilityStmt */
1817 if (query->commandType == CMD_UTILITY || query->utilityStmt)
1819 Query *target_query = query;
1822 * Some utility statements have a subquery that we can hint on. Since
1823 * EXPLAIN can be placed before other kind of utility statements and
1824 * EXECUTE can be contained other kind of utility statements, these
1825 * conditions are not mutually exclusive and should be considered in
1828 if (IsA(target_query->utilityStmt, ExplainStmt))
1830 ExplainStmt *stmt = (ExplainStmt *)target_query->utilityStmt;
1832 Assert(IsA(stmt->query, Query));
1833 target_query = (Query *)stmt->query;
1835 /* strip out the top-level query for further processing */
1836 if (target_query->commandType == CMD_UTILITY &&
1837 target_query->utilityStmt != NULL)
1838 target_query = (Query *)target_query->utilityStmt;
1842 * JumbleQuery does not accept a Query that has utilityStmt. On the
1843 * other hand DeclareCursorStmt is in a bit strange shape that is
1844 * flipped upside down.
1846 if (IsA(target_query, Query) &&
1847 target_query->utilityStmt &&
1848 IsA(target_query->utilityStmt, DeclareCursorStmt))
1851 * The given Query cannot be modified so copy it and modify so that
1852 * JumbleQuery can accept it.
1854 Assert(IsA(target_query, Query) &&
1855 target_query->commandType == CMD_SELECT);
1856 target_query = copyObject(target_query);
1857 target_query->utilityStmt = NULL;
1860 if (IsA(target_query, CreateTableAsStmt))
1862 CreateTableAsStmt *stmt = (CreateTableAsStmt *) target_query;
1864 Assert(IsA(stmt->query, Query));
1865 target_query = (Query *) stmt->query;
1867 /* strip out the top-level query for further processing */
1868 if (target_query->commandType == CMD_UTILITY &&
1869 target_query->utilityStmt != NULL)
1870 target_query = (Query *)target_query->utilityStmt;
1873 if (IsA(target_query, ExecuteStmt))
1876 * Use the prepared query for EXECUTE. The Query for jumble
1877 * also replaced with the corresponding one.
1879 ExecuteStmt *stmt = (ExecuteStmt *)target_query;
1880 PreparedStatement *entry;
1882 entry = FetchPreparedStatement(stmt->name, true);
1883 p = entry->plansource->query_string;
1884 target_query = (Query *) linitial (entry->plansource->query_list);
1887 /* JumbleQuery accespts only a non-utility Query */
1888 if (!IsA(target_query, Query) ||
1889 target_query->utilityStmt != NULL)
1890 target_query = NULL;
1893 *jumblequery = target_query;
1896 /* Return NULL if the pstate is not identical to the top-level query */
1897 else if (strcmp(pstate->p_sourcetext, p) != 0)
1904 * Get hints from the head block comment in client-supplied query string.
1907 get_hints_from_comment(const char *p)
1909 const char *hint_head;
1917 /* extract query head comment. */
1918 hint_head = strstr(p, HINT_START);
1919 if (hint_head == NULL)
1921 for (;p < hint_head; p++)
1924 * Allow these characters precedes hint comment:
1926 * - alphabets which are in ASCII range
1927 * - space, tabs and new-lines
1928 * - underscores, for identifier
1929 * - commas, for SELECT clause, EXPLAIN and PREPARE
1930 * - parentheses, for EXPLAIN and PREPARE
1932 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1933 * avoid behavior which depends on locale setting.
1935 if (!(*p >= '0' && *p <= '9') &&
1936 !(*p >= 'A' && *p <= 'Z') &&
1937 !(*p >= 'a' && *p <= 'z') &&
1941 *p != '(' && *p != ')')
1945 len = strlen(HINT_START);
1950 /* find hint end keyword. */
1951 if ((tail = strstr(p, HINT_END)) == NULL)
1953 hint_ereport(head, ("Unterminated block comment."));
1957 /* We don't support nested block comments. */
1958 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1960 hint_ereport(head, ("Nested block comments are not supported."));
1964 /* Make a copy of hint. */
1966 head = palloc(len + 1);
1967 memcpy(head, p, len);
1975 * Parse hints that got, create hint struct from parse tree and parse hints.
1978 create_hintstate(Query *parse, const char *hints)
1987 /* -1 means that no Parallel hint is specified. */
1988 max_hint_nworkers = -1;
1991 hstate = HintStateCreate();
1992 hstate->hint_str = (char *) hints;
1994 /* parse each hint. */
1995 parse_hints(hstate, parse, p);
1997 /* When nothing specified a hint, we free HintState and returns NULL. */
1998 if (hstate->nall_hints == 0)
2000 HintStateDelete(hstate);
2004 /* Sort hints in order of original position. */
2005 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
2008 /* Count number of hints per hint-type. */
2009 for (i = 0; i < hstate->nall_hints; i++)
2011 Hint *cur_hint = hstate->all_hints[i];
2012 hstate->num_hints[cur_hint->type]++;
2016 * If an object (or a set of objects) has multiple hints of same hint-type,
2017 * only the last hint is valid and others are ignored in planning.
2018 * Hints except the last are marked as 'duplicated' to remember the order.
2020 for (i = 0; i < hstate->nall_hints - 1; i++)
2022 Hint *cur_hint = hstate->all_hints[i];
2023 Hint *next_hint = hstate->all_hints[i + 1];
2026 * Leading hint is marked as 'duplicated' in transform_join_hints.
2028 if (cur_hint->type == HINT_TYPE_LEADING &&
2029 next_hint->type == HINT_TYPE_LEADING)
2033 * Note that we need to pass addresses of hint pointers, because
2034 * HintCmp is designed to sort array of Hint* by qsort.
2036 if (HintCmp(&cur_hint, &next_hint) == 0)
2038 hint_ereport(cur_hint->hint_str,
2039 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
2040 cur_hint->state = HINT_STATE_DUPLICATION;
2045 * Make sure that per-type array pointers point proper position in the
2046 * array which consists of all hints.
2048 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
2049 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
2050 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
2051 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
2052 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
2053 hstate->set_hints = (SetHint **) (hstate->leading_hint +
2054 hstate->num_hints[HINT_TYPE_LEADING]);
2055 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
2056 hstate->num_hints[HINT_TYPE_SET]);
2057 hstate->parallel_hints = (ParallelHint **) (hstate->set_hints +
2058 hstate->num_hints[HINT_TYPE_ROWS]);
2064 * Parse inside of parentheses of scan-method hints.
2067 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
2070 const char *keyword = hint->base.keyword;
2071 HintKeyword hint_keyword = hint->base.hint_keyword;
2072 List *name_list = NIL;
2075 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2078 /* Parse relation name and index name(s) if given hint accepts. */
2079 length = list_length(name_list);
2081 /* at least twp parameters required */
2085 ("%s hint requires a relation.", hint->base.keyword));
2086 hint->base.state = HINT_STATE_ERROR;
2090 hint->relname = linitial(name_list);
2091 hint->indexnames = list_delete_first(name_list);
2093 /* check whether the hint accepts index name(s) */
2094 if (length > 1 && !SCAN_HINT_ACCEPTS_INDEX_NAMES(hint_keyword))
2097 ("%s hint accepts only one relation.",
2098 hint->base.keyword));
2099 hint->base.state = HINT_STATE_ERROR;
2103 /* Set a bit for specified hint. */
2104 switch (hint_keyword)
2106 case HINT_KEYWORD_SEQSCAN:
2107 hint->enforce_mask = ENABLE_SEQSCAN;
2109 case HINT_KEYWORD_INDEXSCAN:
2110 hint->enforce_mask = ENABLE_INDEXSCAN;
2112 case HINT_KEYWORD_INDEXSCANREGEXP:
2113 hint->enforce_mask = ENABLE_INDEXSCAN;
2114 hint->regexp = true;
2116 case HINT_KEYWORD_BITMAPSCAN:
2117 hint->enforce_mask = ENABLE_BITMAPSCAN;
2119 case HINT_KEYWORD_BITMAPSCANREGEXP:
2120 hint->enforce_mask = ENABLE_BITMAPSCAN;
2121 hint->regexp = true;
2123 case HINT_KEYWORD_TIDSCAN:
2124 hint->enforce_mask = ENABLE_TIDSCAN;
2126 case HINT_KEYWORD_NOSEQSCAN:
2127 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
2129 case HINT_KEYWORD_NOINDEXSCAN:
2130 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
2132 case HINT_KEYWORD_NOBITMAPSCAN:
2133 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
2135 case HINT_KEYWORD_NOTIDSCAN:
2136 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
2138 case HINT_KEYWORD_INDEXONLYSCAN:
2139 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2141 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
2142 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2143 hint->regexp = true;
2145 case HINT_KEYWORD_NOINDEXONLYSCAN:
2146 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
2149 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2158 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2161 const char *keyword = hint->base.keyword;
2162 HintKeyword hint_keyword = hint->base.hint_keyword;
2163 List *name_list = NIL;
2165 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2168 hint->nrels = list_length(name_list);
2170 if (hint->nrels > 0)
2176 * Transform relation names from list to array to sort them with qsort
2179 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2180 foreach (l, name_list)
2182 hint->relnames[i] = lfirst(l);
2187 list_free(name_list);
2189 /* A join hint requires at least two relations */
2190 if (hint->nrels < 2)
2193 ("%s hint requires at least two relations.",
2194 hint->base.keyword));
2195 hint->base.state = HINT_STATE_ERROR;
2199 /* Sort hints in alphabetical order of relation names. */
2200 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2202 switch (hint_keyword)
2204 case HINT_KEYWORD_NESTLOOP:
2205 hint->enforce_mask = ENABLE_NESTLOOP;
2207 case HINT_KEYWORD_MERGEJOIN:
2208 hint->enforce_mask = ENABLE_MERGEJOIN;
2210 case HINT_KEYWORD_HASHJOIN:
2211 hint->enforce_mask = ENABLE_HASHJOIN;
2213 case HINT_KEYWORD_NONESTLOOP:
2214 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2216 case HINT_KEYWORD_NOMERGEJOIN:
2217 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2219 case HINT_KEYWORD_NOHASHJOIN:
2220 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2223 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2232 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2235 if (outer_inner->outer_inner_pair == NIL)
2237 if (outer_inner->relation)
2243 if (list_length(outer_inner->outer_inner_pair) == 2)
2245 foreach(l, outer_inner->outer_inner_pair)
2247 if (!OuterInnerPairCheck(lfirst(l)))
2258 OuterInnerList(OuterInnerRels *outer_inner)
2260 List *outer_inner_list = NIL;
2262 OuterInnerRels *outer_inner_rels;
2264 foreach(l, outer_inner->outer_inner_pair)
2266 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2268 if (outer_inner_rels->relation != NULL)
2269 outer_inner_list = lappend(outer_inner_list,
2270 outer_inner_rels->relation);
2272 outer_inner_list = list_concat(outer_inner_list,
2273 OuterInnerList(outer_inner_rels));
2275 return outer_inner_list;
2279 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2282 List *name_list = NIL;
2283 OuterInnerRels *outer_inner = NULL;
2285 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2289 if (outer_inner != NULL)
2290 name_list = OuterInnerList(outer_inner);
2292 hint->relations = name_list;
2293 hint->outer_inner = outer_inner;
2295 /* A Leading hint requires at least two relations */
2296 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2298 hint_ereport(hint->base.hint_str,
2299 ("%s hint requires at least two relations.",
2301 hint->base.state = HINT_STATE_ERROR;
2303 else if (hint->outer_inner != NULL &&
2304 !OuterInnerPairCheck(hint->outer_inner))
2306 hint_ereport(hint->base.hint_str,
2307 ("%s hint requires two sets of relations when parentheses nests.",
2309 hint->base.state = HINT_STATE_ERROR;
2316 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2318 List *name_list = NIL;
2320 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2324 hint->words = name_list;
2326 /* We need both name and value to set GUC parameter. */
2327 if (list_length(name_list) == 2)
2329 hint->name = linitial(name_list);
2330 hint->value = lsecond(name_list);
2334 hint_ereport(hint->base.hint_str,
2335 ("%s hint requires name and value of GUC parameter.",
2337 hint->base.state = HINT_STATE_ERROR;
2344 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2347 HintKeyword hint_keyword = hint->base.hint_keyword;
2348 List *name_list = NIL;
2352 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2355 /* Last element must be rows specification */
2356 hint->nrels = list_length(name_list) - 1;
2358 if (hint->nrels > 0)
2364 * Transform relation names from list to array to sort them with qsort
2367 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2368 foreach (l, name_list)
2370 if (hint->nrels <= i)
2372 hint->relnames[i] = lfirst(l);
2377 /* Retieve rows estimation */
2378 rows_str = list_nth(name_list, hint->nrels);
2379 hint->rows_str = rows_str; /* store as-is for error logging */
2380 if (rows_str[0] == '#')
2382 hint->value_type = RVT_ABSOLUTE;
2385 else if (rows_str[0] == '+')
2387 hint->value_type = RVT_ADD;
2390 else if (rows_str[0] == '-')
2392 hint->value_type = RVT_SUB;
2395 else if (rows_str[0] == '*')
2397 hint->value_type = RVT_MULTI;
2402 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2403 hint->base.state = HINT_STATE_ERROR;
2406 hint->rows = strtod(rows_str, &end_ptr);
2409 hint_ereport(rows_str,
2410 ("%s hint requires valid number as rows estimation.",
2411 hint->base.keyword));
2412 hint->base.state = HINT_STATE_ERROR;
2416 /* A join hint requires at least two relations */
2417 if (hint->nrels < 2)
2420 ("%s hint requires at least two relations.",
2421 hint->base.keyword));
2422 hint->base.state = HINT_STATE_ERROR;
2426 list_free(name_list);
2428 /* Sort relnames in alphabetical order. */
2429 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2435 ParallelHintParse(ParallelHint *hint, HintState *hstate, Query *parse,
2438 HintKeyword hint_keyword = hint->base.hint_keyword;
2439 List *name_list = NIL;
2443 bool force_parallel = false;
2445 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2448 /* Parse relation name and index name(s) if given hint accepts. */
2449 length = list_length(name_list);
2451 if (length < 2 || length > 3)
2454 ("wrong number of arguments (%d): %s",
2455 length, hint->base.keyword));
2456 hint->base.state = HINT_STATE_ERROR;
2460 hint->relname = linitial(name_list);
2462 /* The second parameter is number of workers */
2463 hint->nworkers_str = list_nth(name_list, 1);
2464 nworkers = strtod(hint->nworkers_str, &end_ptr);
2465 if (*end_ptr || nworkers < 0 || nworkers > max_worker_processes)
2468 hint_ereport(hint->nworkers_str,
2469 ("number of workers must be a number: %s",
2470 hint->base.keyword));
2471 else if (nworkers < 0)
2472 hint_ereport(hint->nworkers_str,
2473 ("number of workers must be positive: %s",
2474 hint->base.keyword));
2475 else if (nworkers > max_worker_processes)
2476 hint_ereport(hint->nworkers_str,
2477 ("number of workers = %d is larger than max_worker_processes(%d): %s",
2478 nworkers, max_worker_processes, hint->base.keyword));
2480 hint->base.state = HINT_STATE_ERROR;
2483 hint->nworkers = nworkers;
2485 /* optional third parameter is specified */
2488 const char *modeparam = (const char *)list_nth(name_list, 2);
2489 if (pg_strcasecmp(modeparam, "hard") == 0)
2490 force_parallel = true;
2491 else if (pg_strcasecmp(modeparam, "soft") != 0)
2493 hint_ereport(modeparam,
2494 ("enforcement must be soft or hard: %s",
2495 hint->base.keyword));
2496 hint->base.state = HINT_STATE_ERROR;
2500 hint->force_parallel = force_parallel;
2502 if (hint->base.state != HINT_STATE_ERROR &&
2503 nworkers > max_hint_nworkers)
2504 max_hint_nworkers = nworkers;
2510 * set GUC parameter functions
2514 get_current_scan_mask()
2519 mask |= ENABLE_SEQSCAN;
2520 if (enable_indexscan)
2521 mask |= ENABLE_INDEXSCAN;
2522 if (enable_bitmapscan)
2523 mask |= ENABLE_BITMAPSCAN;
2525 mask |= ENABLE_TIDSCAN;
2526 if (enable_indexonlyscan)
2527 mask |= ENABLE_INDEXONLYSCAN;
2533 get_current_join_mask()
2537 if (enable_nestloop)
2538 mask |= ENABLE_NESTLOOP;
2539 if (enable_mergejoin)
2540 mask |= ENABLE_MERGEJOIN;
2541 if (enable_hashjoin)
2542 mask |= ENABLE_HASHJOIN;
2548 * Sets GUC prameters without throwing exception. Reutrns false if something
2552 set_config_option_noerror(const char *name, const char *value,
2553 GucContext context, GucSource source,
2554 GucAction action, bool changeVal, int elevel)
2557 MemoryContext ccxt = CurrentMemoryContext;
2561 result = set_config_option(name, value, context, source,
2562 action, changeVal, 0, false);
2568 /* Save error info */
2569 MemoryContextSwitchTo(ccxt);
2570 errdata = CopyErrorData();
2574 (errcode(errdata->sqlerrcode),
2575 errmsg("%s", errdata->message),
2576 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2577 errdata->hint ? errhint("%s", errdata->hint) : 0));
2579 FreeErrorData(errdata);
2587 * Sets GUC parameter of int32 type without throwing exceptions. Returns false
2588 * if something wrong.
2591 set_config_int32_option(const char *name, int32 value, GucContext context)
2593 char buf[16]; /* enough for int32 */
2595 if (snprintf(buf, 16, "%d", value) < 0)
2597 ereport(pg_hint_plan_message_level,
2598 (errmsg ("Failed to convert integer to string: %d", value)));
2603 set_config_option_noerror(name, buf, context,
2604 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2605 pg_hint_plan_message_level);
2608 /* setup scan method enforcement according to given options */
2610 setup_guc_enforcement(SetHint **options, int noptions, GucContext context)
2614 for (i = 0; i < noptions; i++)
2616 SetHint *hint = options[i];
2619 if (!hint_state_enabled(hint))
2622 result = set_config_option_noerror(hint->name, hint->value, context,
2623 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2624 pg_hint_plan_message_level);
2626 hint->base.state = HINT_STATE_USED;
2628 hint->base.state = HINT_STATE_ERROR;
2635 * Setup parallel execution environment.
2637 * If hint is not NULL, set up using it, elsewise reset to initial environment.
2640 setup_parallel_plan_enforcement(ParallelHint *hint, HintState *state)
2644 hint->base.state = HINT_STATE_USED;
2645 set_config_int32_option("max_parallel_workers_per_gather",
2646 hint->nworkers, state->context);
2649 set_config_int32_option("max_parallel_workers_per_gather",
2650 state->init_nworkers, state->context);
2652 /* force means that enforce parallel as far as possible */
2653 if (hint && hint->force_parallel)
2655 set_config_int32_option("parallel_tuple_cost", 0, state->context);
2656 set_config_int32_option("parallel_setup_cost", 0, state->context);
2657 set_config_int32_option("min_parallel_relation_size", 0,
2662 set_config_int32_option("parallel_tuple_cost",
2663 state->init_paratup_cost, state->context);
2664 set_config_int32_option("parallel_setup_cost",
2665 state->init_parasetup_cost, state->context);
2666 set_config_int32_option("min_parallel_relation_size",
2667 state->init_min_para_size, state->context);
2671 #define SET_CONFIG_OPTION(name, type_bits) \
2672 set_config_option_noerror((name), \
2673 (mask & (type_bits)) ? "true" : "false", \
2674 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2678 * Setup GUC environment to enforce scan methods. If scanhint is NULL, reset
2679 * GUCs to the saved state in state.
2682 setup_scan_method_enforcement(ScanMethodHint *scanhint, HintState *state)
2684 unsigned char enforce_mask = state->init_scan_mask;
2685 GucContext context = state->context;
2690 enforce_mask = scanhint->enforce_mask;
2691 scanhint->base.state = HINT_STATE_USED;
2694 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2695 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2696 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2698 mask = enforce_mask;
2700 mask = enforce_mask & current_hint_state->init_scan_mask;
2702 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2703 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2704 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2705 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2706 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2710 set_join_config_options(unsigned char enforce_mask, GucContext context)
2714 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2715 enforce_mask == ENABLE_HASHJOIN)
2716 mask = enforce_mask;
2718 mask = enforce_mask & current_hint_state->init_join_mask;
2720 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2721 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2722 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2726 * Push a hint into hint stack which is implemented with List struct. Head of
2727 * list is top of stack.
2730 push_hint(HintState *hstate)
2732 /* Prepend new hint to the list means pushing to stack. */
2733 HintStateStack = lcons(hstate, HintStateStack);
2735 /* Pushed hint is the one which should be used hereafter. */
2736 current_hint_state = hstate;
2739 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2743 /* Hint stack must not be empty. */
2744 if(HintStateStack == NIL)
2745 elog(ERROR, "hint stack is empty");
2748 * Take a hint at the head from the list, and free it. Switch
2749 * current_hint_state to point new head (NULL if the list is empty).
2751 HintStateStack = list_delete_first(HintStateStack);
2752 HintStateDelete(current_hint_state);
2753 if(HintStateStack == NIL)
2754 current_hint_state = NULL;
2756 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
2760 * Retrieve and store a hint string from given query or from the hint table.
2761 * If we are using the hint table, the query string is needed to be normalized.
2762 * However, ParseState, which is not available in planner_hook, is required to
2763 * check if the query tree (Query) is surely corresponding to the target query.
2766 pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query)
2768 const char *query_str;
2769 MemoryContext oldcontext;
2771 if (prev_post_parse_analyze_hook)
2772 prev_post_parse_analyze_hook(pstate, query);
2774 /* do nothing under hint table search */
2775 if (hint_inhibit_level > 0)
2778 if (!pg_hint_plan_enable_hint)
2780 if (current_hint_str)
2782 pfree((void *)current_hint_str);
2783 current_hint_str = NULL;
2788 /* increment the query number */
2790 if (debug_level > 1)
2791 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2794 /* search the hint table for a hint if requested */
2795 if (pg_hint_plan_enable_hint_table)
2798 pgssJumbleState jstate;
2800 char *normalized_query = NULL;
2802 query_str = get_query_string(pstate, query, &jumblequery);
2804 /* If this query is not for hint, just return */
2808 /* clear the previous hint string */
2809 if (current_hint_str)
2811 pfree((void *)current_hint_str);
2812 current_hint_str = NULL;
2818 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2819 * careful to PostgreSQL's version up.
2821 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2822 jstate.jumble_len = 0;
2823 jstate.clocations_buf_size = 32;
2824 jstate.clocations = (pgssLocationLen *)
2825 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2826 jstate.clocations_count = 0;
2828 JumbleQuery(&jstate, jumblequery);
2831 * Normalize the query string by replacing constants with '?'
2834 * Search hint string which is stored keyed by query string
2835 * and application name. The query string is normalized to allow
2838 * Adding 1 byte to query_len ensures that the returned string has
2839 * a terminating NULL.
2841 query_len = strlen(query_str) + 1;
2843 generate_normalized_query(&jstate, query_str,
2845 GetDatabaseEncoding());
2848 * find a hint for the normalized query. the result should be in
2851 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2853 get_hints_from_table(normalized_query, application_name);
2854 MemoryContextSwitchTo(oldcontext);
2856 if (debug_level > 1)
2858 if (current_hint_str)
2859 ereport(pg_hint_plan_message_level,
2860 (errmsg("pg_hint_plan[qno=0x%x]: "
2861 "post_parse_analyze_hook: "
2862 "hints from table: \"%s\": "
2863 "normalized_query=\"%s\", "
2864 "application name =\"%s\"",
2865 qno, current_hint_str,
2866 normalized_query, application_name),
2867 errhidestmt(msgqno != qno),
2868 errhidecontext(msgqno != qno)));
2870 ereport(pg_hint_plan_message_level,
2871 (errmsg("pg_hint_plan[qno=0x%x]: "
2872 "no match found in table: "
2873 "application name = \"%s\", "
2874 "normalized_query=\"%s\"",
2875 qno, application_name,
2877 errhidestmt(msgqno != qno),
2878 errhidecontext(msgqno != qno)));
2884 /* retrun if we have hint here */
2885 if (current_hint_str)
2889 query_str = get_query_string(pstate, query, NULL);
2894 * get hints from the comment. However we may have the same query
2895 * string with the previous call, but just retrieving hints is expected
2896 * to be faster than checking for identicalness before retrieval.
2898 if (current_hint_str)
2899 pfree((void *)current_hint_str);
2901 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2902 current_hint_str = get_hints_from_comment(query_str);
2903 MemoryContextSwitchTo(oldcontext);
2906 if (debug_level > 1)
2908 if (debug_level == 1 &&
2909 (stmt_name || strcmp(query_str, debug_query_string)))
2910 ereport(pg_hint_plan_message_level,
2911 (errmsg("hints in comment=\"%s\"",
2912 current_hint_str ? current_hint_str : "(none)"),
2913 errhidestmt(msgqno != qno),
2914 errhidecontext(msgqno != qno)));
2916 ereport(pg_hint_plan_message_level,
2917 (errmsg("hints in comment=\"%s\", stmt=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2918 current_hint_str ? current_hint_str : "(none)",
2919 stmt_name, query_str, debug_query_string),
2920 errhidestmt(msgqno != qno),
2921 errhidecontext(msgqno != qno)));
2927 * Read and set up hint information
2929 static PlannedStmt *
2930 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2933 PlannedStmt *result;
2937 * Use standard planner if pg_hint_plan is disabled or current nesting
2938 * depth is nesting depth of SPI calls. Other hook functions try to change
2939 * plan with current_hint_state if any, so set it to NULL.
2941 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2943 if (debug_level > 1)
2944 ereport(pg_hint_plan_message_level,
2945 (errmsg ("pg_hint_plan%s: planner: enable_hint=%d,"
2946 " hint_inhibit_level=%d",
2947 qnostr, pg_hint_plan_enable_hint,
2948 hint_inhibit_level),
2949 errhidestmt(msgqno != qno)));
2952 goto standard_planner_proc;
2956 * Support for nested plpgsql functions. This is quite ugly but this is the
2957 * only point I could find where I can get the query string.
2959 if (plpgsql_recurse_level > 0)
2961 MemoryContext oldcontext;
2963 if (current_hint_str)
2964 pfree((void *)current_hint_str);
2966 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2968 get_hints_from_comment((char *)error_context_stack->arg);
2969 MemoryContextSwitchTo(oldcontext);
2972 if (!current_hint_str)
2973 goto standard_planner_proc;
2975 /* parse the hint into hint state struct */
2976 hstate = create_hintstate(parse, pstrdup(current_hint_str));
2978 /* run standard planner if the statement has not valid hint */
2980 goto standard_planner_proc;
2983 * Push new hint struct to the hint stack to disable previous hint context.
2987 /* Set scan enforcement here. */
2988 save_nestlevel = NewGUCNestLevel();
2990 /* Apply Set hints, then save it as the initial state */
2991 setup_guc_enforcement(current_hint_state->set_hints,
2992 current_hint_state->num_hints[HINT_TYPE_SET],
2993 current_hint_state->context);
2995 current_hint_state->init_scan_mask = get_current_scan_mask();
2996 current_hint_state->init_join_mask = get_current_join_mask();
2997 current_hint_state->init_min_para_size = min_parallel_relation_size;
2998 current_hint_state->init_paratup_cost = parallel_tuple_cost;
2999 current_hint_state->init_parasetup_cost = parallel_setup_cost;
3002 * max_parallel_workers_per_gather should be non-zero here if Workers hint
3005 if (max_hint_nworkers > 0 && max_parallel_workers_per_gather < 1)
3006 set_config_int32_option("max_parallel_workers_per_gather",
3007 1, current_hint_state->context);
3008 current_hint_state->init_nworkers = max_parallel_workers_per_gather;
3010 if (debug_level > 1)
3012 ereport(pg_hint_plan_message_level,
3013 (errhidestmt(msgqno != qno),
3014 errmsg("pg_hint_plan%s: planner", qnostr)));
3019 * Use PG_TRY mechanism to recover GUC parameters and current_hint_state to
3020 * the state when this planner started when error occurred in planner.
3025 result = (*prev_planner) (parse, cursorOptions, boundParams);
3027 result = standard_planner(parse, cursorOptions, boundParams);
3032 * Rollback changes of GUC parameters, and pop current hint context
3033 * from hint stack to rewind the state.
3035 AtEOXact_GUC(true, save_nestlevel);
3041 /* Print hint in debug mode. */
3042 if (debug_level == 1)
3043 HintStateDump(current_hint_state);
3044 else if (debug_level > 1)
3045 HintStateDump2(current_hint_state);
3048 * Rollback changes of GUC parameters, and pop current hint context from
3049 * hint stack to rewind the state.
3051 AtEOXact_GUC(true, save_nestlevel);
3056 standard_planner_proc:
3057 if (debug_level > 1)
3059 ereport(pg_hint_plan_message_level,
3060 (errhidestmt(msgqno != qno),
3061 errmsg("pg_hint_plan%s: planner: no valid hint",
3065 current_hint_state = NULL;
3067 return (*prev_planner) (parse, cursorOptions, boundParams);
3069 return standard_planner(parse, cursorOptions, boundParams);
3073 * Find scan method hint to be applied to the given relation
3076 static ScanMethodHint *
3077 find_scan_hint(PlannerInfo *root, Index relid)
3081 ScanMethodHint *real_name_hint = NULL;
3082 ScanMethodHint *alias_hint = NULL;
3085 /* This should not be a join rel */
3087 rel = root->simple_rel_array[relid];
3090 * This function is called for any RelOptInfo or its inheritance parent if
3091 * any. If we are called from inheritance planner, the RelOptInfo for the
3092 * parent of target child relation is not set in the planner info.
3094 * Otherwise we should check that the reloptinfo is base relation or
3095 * inheritance children.
3098 rel->reloptkind != RELOPT_BASEREL &&
3099 rel->reloptkind != RELOPT_OTHER_MEMBER_REL)
3103 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3105 rte = root->simple_rte_array[relid];
3108 /* We don't hint on other than relation and foreign tables */
3109 if (rte->rtekind != RTE_RELATION ||
3110 rte->relkind == RELKIND_FOREIGN_TABLE)
3113 /* Find scan method hint, which matches given names, from the list. */
3114 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
3116 ScanMethodHint *hint = current_hint_state->scan_hints[i];
3118 /* We ignore disabled hints. */
3119 if (!hint_state_enabled(hint))
3123 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3126 /* check the real name for appendrel children */
3127 if (!real_name_hint &&
3128 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3130 char *realname = get_rel_name(rte->relid);
3132 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3133 real_name_hint = hint;
3136 /* No more match expected, break */
3137 if(alias_hint && real_name_hint)
3141 /* real name match precedes alias match */
3143 return real_name_hint;
3148 static ParallelHint *
3149 find_parallel_hint(PlannerInfo *root, Index relid)
3153 ParallelHint *real_name_hint = NULL;
3154 ParallelHint *alias_hint = NULL;
3157 /* This should not be a join rel */
3159 rel = root->simple_rel_array[relid];
3162 * Parallel planning is appliable only on base relation, which has
3169 * We have set root->glob->parallelModeOK if needed. What we should do here
3170 * is just following the decision of planner.
3172 if (!rel->consider_parallel)
3176 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3178 rte = root->simple_rte_array[relid];
3181 /* Find parallel method hint, which matches given names, from the list. */
3182 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_PARALLEL]; i++)
3184 ParallelHint *hint = current_hint_state->parallel_hints[i];
3186 /* We ignore disabled hints. */
3187 if (!hint_state_enabled(hint))
3191 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3194 /* check the real name for appendrel children */
3195 if (!real_name_hint &&
3196 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3198 char *realname = get_rel_name(rte->relid);
3200 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3201 real_name_hint = hint;
3204 /* No more match expected, break */
3205 if(alias_hint && real_name_hint)
3209 /* real name match precedes alias match */
3211 return real_name_hint;
3219 * Returns TRUE on match, FALSE on no match.
3221 * s1 --- the data to match against
3222 * s2 --- the pattern
3224 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
3227 regexpeq(const char *s1, const char *s2)
3233 strcpy(name.data, s1);
3234 regexp = cstring_to_text(s2);
3236 result = DirectFunctionCall2Coll(nameregexeq,
3237 DEFAULT_COLLATION_OID,
3238 NameGetDatum(&name),
3239 PointerGetDatum(regexp));
3240 return DatumGetBool(result);
3244 /* Remove indexes instructed not to use by hint. */
3246 restrict_indexes(PlannerInfo *root, ScanMethodHint *hint, RelOptInfo *rel,
3247 bool using_parent_hint)
3253 RangeTblEntry *rte = root->simple_rte_array[rel->relid];
3254 Oid relationObjectId = rte->relid;
3257 * We delete all the IndexOptInfo list and prevent you from being usable by
3260 if (hint->enforce_mask == ENABLE_SEQSCAN ||
3261 hint->enforce_mask == ENABLE_TIDSCAN)
3263 list_free_deep(rel->indexlist);
3264 rel->indexlist = NIL;
3265 hint->base.state = HINT_STATE_USED;
3271 * When a list of indexes is not specified, we just use all indexes.
3273 if (hint->indexnames == NIL)
3277 * Leaving only an specified index, we delete it from a IndexOptInfo list
3281 if (debug_level > 0)
3282 initStringInfo(&buf);
3284 for (cell = list_head(rel->indexlist); cell; cell = next)
3286 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
3287 char *indexname = get_rel_name(info->indexoid);
3289 bool use_index = false;
3293 foreach(l, hint->indexnames)
3295 char *hintname = (char *) lfirst(l);
3299 result = regexpeq(indexname, hintname);
3301 result = RelnameCmp(&indexname, &hintname) == 0;
3306 if (debug_level > 0)
3308 appendStringInfoCharMacro(&buf, ' ');
3309 quote_value(&buf, indexname);
3317 * Apply index restriction of parent hint to children. Since index
3318 * inheritance is not explicitly described we should search for an
3319 * children's index with the same definition to that of the parent.
3321 if (using_parent_hint && !use_index)
3323 foreach(l, current_hint_state->parent_index_infos)
3327 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
3330 * we check the 'same' index by comparing uniqueness, access
3331 * method and index key columns.
3333 if (p_info->indisunique != info->unique ||
3334 p_info->method != info->relam ||
3335 list_length(p_info->column_names) != info->ncolumns)
3338 /* Check if index key columns match */
3339 for (i = 0; i < info->ncolumns; i++)
3341 char *c_attname = NULL;
3342 char *p_attname = NULL;
3344 p_attname = list_nth(p_info->column_names, i);
3347 * if both of the key of the same position are expressions,
3348 * ignore them for now and check later.
3350 if (info->indexkeys[i] == 0 && !p_attname)
3353 /* deny if one is expression while another is not */
3354 if (info->indexkeys[i] == 0 || !p_attname)
3357 c_attname = get_attname(relationObjectId,
3358 info->indexkeys[i]);
3360 /* deny if any of column attributes don't match */
3361 if (strcmp(p_attname, c_attname) != 0 ||
3362 p_info->indcollation[i] != info->indexcollations[i] ||
3363 p_info->opclass[i] != info->opcintype[i]||
3364 ((p_info->indoption[i] & INDOPTION_DESC) != 0)
3365 != info->reverse_sort[i] ||
3366 ((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0)
3367 != info->nulls_first[i])
3371 /* deny this if any difference found */
3372 if (i != info->ncolumns)
3375 /* check on key expressions */
3376 if ((p_info->expression_str && (info->indexprs != NIL)) ||
3377 (p_info->indpred_str && (info->indpred != NIL)))
3379 /* fetch the index of this child */
3380 ht_idx = SearchSysCache1(INDEXRELID,
3381 ObjectIdGetDatum(info->indexoid));
3383 /* check expressions if both expressions are available */
3384 if (p_info->expression_str &&
3385 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
3392 * to change the expression's parameter of child's
3395 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3396 Anum_pg_index_indexprs,
3399 result = DirectFunctionCall2(pg_get_expr,
3404 /* deny if expressions don't match */
3405 if (strcmp(p_info->expression_str,
3406 text_to_cstring(DatumGetTextP(result))) != 0)
3409 ReleaseSysCache(ht_idx);
3414 /* compare index predicates */
3415 if (p_info->indpred_str &&
3416 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
3422 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3423 Anum_pg_index_indpred,
3426 result = DirectFunctionCall2(pg_get_expr,
3431 if (strcmp(p_info->indpred_str,
3432 text_to_cstring(DatumGetTextP(result))) != 0)
3435 ReleaseSysCache(ht_idx);
3441 ReleaseSysCache(ht_idx);
3443 else if (p_info->expression_str || (info->indexprs != NIL))
3445 else if (p_info->indpred_str || (info->indpred != NIL))
3450 /* to log the candidate of index */
3451 if (debug_level > 0)
3453 appendStringInfoCharMacro(&buf, ' ');
3454 quote_value(&buf, indexname);
3462 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
3469 if (debug_level == 1)
3471 StringInfoData rel_buf;
3472 char *disprelname = "";
3475 * If this hint targetted the parent, use the real name of this
3476 * child. Otherwise use hint specification.
3478 if (using_parent_hint)
3479 disprelname = get_rel_name(rte->relid);
3481 disprelname = hint->relname;
3484 initStringInfo(&rel_buf);
3485 quote_value(&rel_buf, disprelname);
3488 (errmsg("available indexes for %s(%s):%s",
3493 pfree(rel_buf.data);
3498 * Return information of index definition.
3500 static ParentIndexInfo *
3501 get_parent_index_info(Oid indexoid, Oid relid)
3503 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3504 Relation indexRelation;
3505 Form_pg_index index;
3509 indexRelation = index_open(indexoid, RowExclusiveLock);
3511 index = indexRelation->rd_index;
3513 p_info->indisunique = index->indisunique;
3514 p_info->method = indexRelation->rd_rel->relam;
3516 p_info->column_names = NIL;
3517 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3518 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3519 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3521 for (i = 0; i < index->indnatts; i++)
3523 attname = get_attname(relid, index->indkey.values[i]);
3524 p_info->column_names = lappend(p_info->column_names, attname);
3526 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3527 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3528 p_info->indoption[i] = indexRelation->rd_indoption[i];
3532 * to check to match the expression's parameter of index with child indexes
3534 p_info->expression_str = NULL;
3535 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
3541 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3542 Anum_pg_index_indexprs, &isnull);
3544 result = DirectFunctionCall2(pg_get_expr,
3546 ObjectIdGetDatum(relid));
3548 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3552 * to check to match the predicate's parameter of index with child indexes
3554 p_info->indpred_str = NULL;
3555 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
3561 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3562 Anum_pg_index_indpred, &isnull);
3564 result = DirectFunctionCall2(pg_get_expr,
3566 ObjectIdGetDatum(relid));
3568 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3571 index_close(indexRelation, NoLock);
3577 * cancel hint enforcement
3580 reset_hint_enforcement()
3582 setup_scan_method_enforcement(NULL, current_hint_state);
3583 setup_parallel_plan_enforcement(NULL, current_hint_state);
3587 * Set planner guc parameters according to corresponding scan hints. Returns
3588 * bitmap of HintTypeBitmap. If shint or phint is not NULL, set used hint
3589 * there respectively.
3592 setup_hint_enforcement(PlannerInfo *root, RelOptInfo *rel,
3593 ScanMethodHint **rshint, ParallelHint **rphint)
3595 Index new_parent_relid = 0;
3597 ScanMethodHint *shint = NULL;
3598 ParallelHint *phint = NULL;
3599 bool inhparent = root->simple_rte_array[rel->relid]->inh;
3600 Oid relationObjectId = root->simple_rte_array[rel->relid]->relid;
3603 /* reset returns if requested */
3604 if (rshint != NULL) *rshint = NULL;
3605 if (rphint != NULL) *rphint = NULL;
3608 * We could register the parent relation of the following children here
3609 * when inhparent == true but inheritnce planner doesn't call this function
3610 * for parents. Since we cannot distinguish who called this function we
3611 * cannot do other than always seeking the parent regardless of who called
3616 if (debug_level > 1)
3617 ereport(pg_hint_plan_message_level,
3619 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3620 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3621 " current_hint_state=%p, hint_inhibit_level=%d",
3622 qnostr, relationObjectId,
3623 get_rel_name(relationObjectId),
3624 inhparent, current_hint_state, hint_inhibit_level)));
3628 /* Find the parent for this relation other than the registered parent */
3629 foreach (l, root->append_rel_list)
3631 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3633 if (appinfo->child_relid == rel->relid)
3635 if (current_hint_state->parent_relid != appinfo->parent_relid)
3636 new_parent_relid = appinfo->parent_relid;
3643 /* This relation doesn't have a parent. Cancel current_hint_state. */
3644 current_hint_state->parent_relid = 0;
3645 current_hint_state->parent_scan_hint = NULL;
3646 current_hint_state->parent_parallel_hint = NULL;
3649 if (new_parent_relid > 0)
3652 * Here we found a new parent for the current relation. Scan continues
3653 * hint to other childrens of this parent so remember it * to avoid
3654 * hinthintredundant setup cost.
3656 current_hint_state->parent_relid = new_parent_relid;
3658 /* Find hints for the parent */
3659 current_hint_state->parent_scan_hint =
3660 find_scan_hint(root, current_hint_state->parent_relid);
3662 current_hint_state->parent_parallel_hint =
3663 find_parallel_hint(root, current_hint_state->parent_relid);
3666 * If hint is found for the parent, apply it for this child instead
3669 if (current_hint_state->parent_scan_hint)
3671 ScanMethodHint * pshint = current_hint_state->parent_scan_hint;
3673 pshint->base.state = HINT_STATE_USED;
3675 /* Apply index mask in the same manner to the parent. */
3676 if (pshint->indexnames)
3679 Relation parent_rel;
3682 root->simple_rte_array[current_hint_state->parent_relid]->relid;
3683 parent_rel = heap_open(parentrel_oid, NoLock);
3685 /* Search the parent relation for indexes match the hint spec */
3686 foreach(l, RelationGetIndexList(parent_rel))
3688 Oid indexoid = lfirst_oid(l);
3689 char *indexname = get_rel_name(indexoid);
3691 ParentIndexInfo *parent_index_info;
3693 foreach(lc, pshint->indexnames)
3695 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3702 get_parent_index_info(indexoid, parentrel_oid);
3703 current_hint_state->parent_index_infos =
3704 lappend(current_hint_state->parent_index_infos,
3707 heap_close(parent_rel, NoLock);
3712 shint = find_scan_hint(root, rel->relid);
3714 shint = current_hint_state->parent_scan_hint;
3718 bool using_parent_hint =
3719 (shint == current_hint_state->parent_scan_hint);
3721 ret |= HINT_BM_SCAN_METHOD;
3723 /* Setup scan enforcement environment */
3724 setup_scan_method_enforcement(shint, current_hint_state);
3726 /* restrict unwanted inexes */
3727 restrict_indexes(root, shint, rel, using_parent_hint);
3729 if (debug_level > 1)
3731 char *additional_message = "";
3733 if (shint == current_hint_state->parent_scan_hint)
3734 additional_message = " by parent hint";
3736 ereport(pg_hint_plan_message_level,
3738 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3739 " index deletion%s:"
3740 " relation=%u(%s), inhparent=%d, "
3741 "current_hint_state=%p,"
3742 " hint_inhibit_level=%d, scanmask=0x%x",
3743 qnostr, additional_message,
3745 get_rel_name(relationObjectId),
3746 inhparent, current_hint_state,
3748 shint->enforce_mask)));
3752 /* Do the same for parallel plan enforcement */
3753 phint = find_parallel_hint(root, rel->relid);
3755 phint = current_hint_state->parent_parallel_hint;
3757 setup_parallel_plan_enforcement(phint, current_hint_state);
3760 ret |= HINT_BM_PARALLEL;
3762 /* Nothing to apply. Reset the scan mask to intial state */
3763 if (!shint && ! phint)
3765 if (debug_level > 1)
3766 ereport(pg_hint_plan_message_level,
3767 (errhidestmt (true),
3768 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3770 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3771 " hint_inhibit_level=%d, scanmask=0x%x",
3772 qnostr, relationObjectId,
3773 get_rel_name(relationObjectId),
3774 inhparent, current_hint_state, hint_inhibit_level,
3775 current_hint_state->init_scan_mask)));
3777 setup_scan_method_enforcement(NULL, current_hint_state);
3782 if (rshint != NULL) *rshint = shint;
3783 if (rphint != NULL) *rphint = phint;
3789 * Return index of relation which matches given aliasname, or 0 if not found.
3790 * If same aliasname was used multiple times in a query, return -1.
3793 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3799 for (i = 1; i < root->simple_rel_array_size; i++)
3803 if (root->simple_rel_array[i] == NULL)
3806 Assert(i == root->simple_rel_array[i]->relid);
3808 if (RelnameCmp(&aliasname,
3809 &root->simple_rte_array[i]->eref->aliasname) != 0)
3812 foreach(l, initial_rels)
3814 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3816 if (rel->reloptkind == RELOPT_BASEREL)
3818 if (rel->relid != i)
3823 Assert(rel->reloptkind == RELOPT_JOINREL);
3825 if (!bms_is_member(i, rel->relids))
3832 ("Relation name \"%s\" is ambiguous.",
3847 * Return join hint which matches given joinrelids.
3849 static JoinMethodHint *
3850 find_join_hint(Relids joinrelids)
3855 join_hint = current_hint_state->join_hint_level[bms_num_members(joinrelids)];
3857 foreach(l, join_hint)
3859 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3861 if (bms_equal(joinrelids, hint->joinrelids))
3869 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3870 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3872 OuterInnerRels *outer_rels;
3873 OuterInnerRels *inner_rels;
3874 Relids outer_relids;
3875 Relids inner_relids;
3877 JoinMethodHint *hint;
3879 if (outer_inner->relation != NULL)
3881 return bms_make_singleton(
3882 find_relid_aliasname(root, outer_inner->relation,
3884 leading_hint->base.hint_str));
3887 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3888 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3890 outer_relids = OuterInnerJoinCreate(outer_rels,
3896 inner_relids = OuterInnerJoinCreate(inner_rels,
3903 join_relids = bms_add_members(outer_relids, inner_relids);
3905 if (bms_num_members(join_relids) > nbaserel)
3909 * If we don't have join method hint, create new one for the
3910 * join combination with all join methods are enabled.
3912 hint = find_join_hint(join_relids);
3916 * Here relnames is not set, since Relids bitmap is sufficient to
3917 * control paths of this query afterward.
3919 hint = (JoinMethodHint *) JoinMethodHintCreate(
3920 leading_hint->base.hint_str,
3922 HINT_KEYWORD_LEADING);
3923 hint->base.state = HINT_STATE_USED;
3924 hint->nrels = bms_num_members(join_relids);
3925 hint->enforce_mask = ENABLE_ALL_JOIN;
3926 hint->joinrelids = bms_copy(join_relids);
3927 hint->inner_nrels = bms_num_members(inner_relids);
3928 hint->inner_joinrelids = bms_copy(inner_relids);
3930 hstate->join_hint_level[hint->nrels] =
3931 lappend(hstate->join_hint_level[hint->nrels], hint);
3935 hint->inner_nrels = bms_num_members(inner_relids);
3936 hint->inner_joinrelids = bms_copy(inner_relids);
3943 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3944 int nrels, char **relnames)
3947 Relids relids = NULL;
3951 for (j = 0; j < nrels; j++)
3953 relname = relnames[j];
3955 relid = find_relid_aliasname(root, relname, initial_rels,
3959 base->state = HINT_STATE_ERROR;
3962 * the aliasname is not found(relid == 0) or same aliasname was used
3963 * multiple times in a query(relid == -1)
3970 if (bms_is_member(relid, relids))
3972 hint_ereport(base->hint_str,
3973 ("Relation name \"%s\" is duplicated.", relname));
3974 base->state = HINT_STATE_ERROR;
3978 relids = bms_add_member(relids, relid);
3983 * Transform join method hint into handy form.
3985 * - create bitmap of relids from alias names, to make it easier to check
3986 * whether a join path matches a join method hint.
3987 * - add join method hints which are necessary to enforce join order
3988 * specified by Leading hint
3991 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
3992 List *initial_rels, JoinMethodHint **join_method_hints)
4000 LeadingHint *lhint = NULL;
4003 * Create bitmap of relids from alias names for each join method hint.
4004 * Bitmaps are more handy than strings in join searching.
4006 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
4008 JoinMethodHint *hint = hstate->join_hints[i];
4010 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4013 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4014 initial_rels, hint->nrels, hint->relnames);
4016 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
4019 hstate->join_hint_level[hint->nrels] =
4020 lappend(hstate->join_hint_level[hint->nrels], hint);
4024 * Create bitmap of relids from alias names for each rows hint.
4025 * Bitmaps are more handy than strings in join searching.
4027 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
4029 RowsHint *hint = hstate->rows_hints[i];
4031 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4034 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4035 initial_rels, hint->nrels, hint->relnames);
4038 /* Do nothing if no Leading hint was supplied. */
4039 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
4043 * Decide whether to use Leading hint
4045 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
4047 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
4050 if (leading_hint->base.state == HINT_STATE_ERROR)
4056 foreach(l, leading_hint->relations)
4058 relname = (char *)lfirst(l);;
4060 relid = find_relid_aliasname(root, relname, initial_rels,
4061 leading_hint->base.hint_str);
4063 leading_hint->base.state = HINT_STATE_ERROR;
4068 if (bms_is_member(relid, relids))
4070 hint_ereport(leading_hint->base.hint_str,
4071 ("Relation name \"%s\" is duplicated.", relname));
4072 leading_hint->base.state = HINT_STATE_ERROR;
4076 relids = bms_add_member(relids, relid);
4079 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
4084 hint_ereport(lhint->base.hint_str,
4085 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
4086 lhint->base.state = HINT_STATE_DUPLICATION;
4088 leading_hint->base.state = HINT_STATE_USED;
4089 lhint = leading_hint;
4092 /* check to exist Leading hint marked with 'used'. */
4097 * We need join method hints which fit specified join order in every join
4098 * level. For example, Leading(A B C) virtually requires following join
4099 * method hints, if no join method hint supplied:
4101 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
4102 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
4104 * If we already have join method hint which fits specified join order in
4105 * that join level, we leave it as-is and don't add new hints.
4109 if (lhint->outer_inner == NULL)
4111 foreach(l, lhint->relations)
4113 JoinMethodHint *hint;
4115 relname = (char *)lfirst(l);
4118 * Find relid of the relation which has given name. If we have the
4119 * name given in Leading hint multiple times in the join, nothing to
4122 relid = find_relid_aliasname(root, relname, initial_rels,
4125 /* Create bitmap of relids for current join level. */
4126 joinrelids = bms_add_member(joinrelids, relid);
4129 /* We never have join method hint for single relation. */
4134 * If we don't have join method hint, create new one for the
4135 * join combination with all join methods are enabled.
4137 hint = find_join_hint(joinrelids);
4141 * Here relnames is not set, since Relids bitmap is sufficient
4142 * to control paths of this query afterward.
4144 hint = (JoinMethodHint *) JoinMethodHintCreate(
4145 lhint->base.hint_str,
4147 HINT_KEYWORD_LEADING);
4148 hint->base.state = HINT_STATE_USED;
4149 hint->nrels = njoinrels;
4150 hint->enforce_mask = ENABLE_ALL_JOIN;
4151 hint->joinrelids = bms_copy(joinrelids);
4154 join_method_hints[njoinrels] = hint;
4156 if (njoinrels >= nbaserel)
4159 bms_free(joinrelids);
4165 * Delete all join hints which have different combination from Leading
4168 for (i = 2; i <= njoinrels; i++)
4170 list_free(hstate->join_hint_level[i]);
4172 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
4177 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
4184 njoinrels = bms_num_members(joinrelids);
4185 Assert(njoinrels >= 2);
4188 * Delete all join hints which have different combination from Leading
4191 for (i = 2;i <= njoinrels; i++)
4193 if (hstate->join_hint_level[i] != NIL)
4195 ListCell *prev = NULL;
4196 ListCell *next = NULL;
4197 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
4200 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
4204 if (hint->inner_nrels == 0 &&
4205 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
4206 bms_equal(bms_union(hint->joinrelids, joinrelids),
4209 hstate->join_hint_level[i] =
4210 list_delete_cell(hstate->join_hint_level[i], l,
4219 bms_free(joinrelids);
4222 if (hint_state_enabled(lhint))
4224 set_join_config_options(DISABLE_ALL_JOIN, current_hint_state->context);
4231 * wrapper of make_join_rel()
4233 * call make_join_rel() after changing enable_* parameters according to given
4237 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
4240 JoinMethodHint *hint;
4244 joinrelids = bms_union(rel1->relids, rel2->relids);
4245 hint = find_join_hint(joinrelids);
4246 bms_free(joinrelids);
4249 return pg_hint_plan_make_join_rel(root, rel1, rel2);
4251 if (hint->inner_nrels == 0)
4253 save_nestlevel = NewGUCNestLevel();
4255 set_join_config_options(hint->enforce_mask,
4256 current_hint_state->context);
4258 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4259 hint->base.state = HINT_STATE_USED;
4262 * Restore the GUC variables we set above.
4264 AtEOXact_GUC(true, save_nestlevel);
4267 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4276 add_paths_to_joinrel_wrapper(PlannerInfo *root,
4277 RelOptInfo *joinrel,
4278 RelOptInfo *outerrel,
4279 RelOptInfo *innerrel,
4281 SpecialJoinInfo *sjinfo,
4285 JoinMethodHint *join_hint;
4288 joinrelids = bms_union(outerrel->relids, innerrel->relids);
4289 join_hint = find_join_hint(joinrelids);
4290 bms_free(joinrelids);
4292 if (join_hint && join_hint->inner_nrels != 0)
4294 save_nestlevel = NewGUCNestLevel();
4296 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
4299 set_join_config_options(join_hint->enforce_mask,
4300 current_hint_state->context);
4302 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4303 sjinfo, restrictlist);
4304 join_hint->base.state = HINT_STATE_USED;
4308 set_join_config_options(DISABLE_ALL_JOIN,
4309 current_hint_state->context);
4310 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4311 sjinfo, restrictlist);
4315 * Restore the GUC variables we set above.
4317 AtEOXact_GUC(true, save_nestlevel);
4320 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4321 sjinfo, restrictlist);
4325 get_num_baserels(List *initial_rels)
4330 foreach(l, initial_rels)
4332 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
4334 if (rel->reloptkind == RELOPT_BASEREL)
4336 else if (rel->reloptkind ==RELOPT_JOINREL)
4337 nbaserel+= bms_num_members(rel->relids);
4340 /* other values not expected here */
4341 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
4349 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
4352 JoinMethodHint **join_method_hints;
4356 bool leading_hint_enable;
4359 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
4360 * valid hint is supplied or current nesting depth is nesting depth of SPI
4363 if (!current_hint_state || hint_inhibit_level > 0)
4365 if (prev_join_search)
4366 return (*prev_join_search) (root, levels_needed, initial_rels);
4367 else if (enable_geqo && levels_needed >= geqo_threshold)
4368 return geqo(root, levels_needed, initial_rels);
4370 return standard_join_search(root, levels_needed, initial_rels);
4374 * In the case using GEQO, only scan method hints and Set hints have
4375 * effect. Join method and join order is not controllable by hints.
4377 if (enable_geqo && levels_needed >= geqo_threshold)
4378 return geqo(root, levels_needed, initial_rels);
4380 nbaserel = get_num_baserels(initial_rels);
4381 current_hint_state->join_hint_level =
4382 palloc0(sizeof(List *) * (nbaserel + 1));
4383 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4385 leading_hint_enable = transform_join_hints(current_hint_state,
4387 initial_rels, join_method_hints);
4389 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4391 for (i = 2; i <= nbaserel; i++)
4393 list_free(current_hint_state->join_hint_level[i]);
4395 /* free Leading hint only */
4396 if (join_method_hints[i] != NULL &&
4397 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4398 JoinMethodHintDelete(join_method_hints[i]);
4400 pfree(current_hint_state->join_hint_level);
4401 pfree(join_method_hints);
4403 if (leading_hint_enable)
4404 set_join_config_options(current_hint_state->init_join_mask,
4405 current_hint_state->context);
4411 * Force number of wokers if instructed by hint
4414 pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
4415 Index rti, RangeTblEntry *rte)
4417 ParallelHint *phint;
4421 /* call the previous hook */
4422 if (prev_set_rel_pathlist)
4423 prev_set_rel_pathlist(root, rel, rti, rte);
4425 /* Nothing to do if no hint available */
4426 if (current_hint_state == NULL)
4429 /* Don't touch dummy rels. */
4430 if (IS_DUMMY_REL(rel))
4434 * We can accept only plain relations, foreign tables and table saples are
4435 * also unacceptable. See set_rel_pathlist.
4437 if (rel->rtekind != RTE_RELATION ||
4438 rte->relkind == RELKIND_FOREIGN_TABLE ||
4439 rte->tablesample != NULL)
4442 /* We cannot handle if this requires an outer */
4443 if (rel->lateral_relids)
4446 /* Return if this relation gets no enfocement */
4447 if ((found_hints = setup_hint_enforcement(root, rel, NULL, &phint)) == 0)
4450 /* Here, we regenerate paths with the current hint restriction */
4452 if (found_hints & HINT_BM_SCAN_METHOD)
4455 * With scan hints, we regenerate paths for this relation from the
4456 * first under the restricion.
4458 list_free_deep(rel->pathlist);
4459 rel->pathlist = NIL;
4461 set_plain_rel_pathlist(root, rel, rte);
4464 if (found_hints & HINT_BM_PARALLEL)
4468 /* the partial_pathlist may be for different parameters, discard it */
4469 if (rel->partial_pathlist)
4471 list_free_deep(rel->partial_pathlist);
4472 rel->partial_pathlist = NIL;
4475 /* also remove gather path */
4478 ListCell *cell, *prev = NULL, *next;
4480 for (cell = list_head(rel->pathlist) ; cell; cell = next)
4482 Path *path = (Path *) lfirst(cell);
4485 if (IsA(path, GatherPath))
4486 rel->pathlist = list_delete_cell(rel->pathlist,
4493 /* then generate new paths if needed */
4494 if (phint->nworkers > 0)
4496 /* Lower the priorities of non-parallel paths */
4497 foreach (l, rel->pathlist)
4499 Path *path = (Path *) lfirst(l);
4501 if (path->startup_cost < disable_cost)
4503 path->startup_cost += disable_cost;
4504 path->total_cost += disable_cost;
4509 * generate partial paths with enforcement, this is affected by
4510 * scan method enforcement. Specifically, the cost of this partial
4511 * seqscan path will be disabled_cost if seqscan is inhibited by
4512 * hint or GUC parameters.
4514 Assert (rel->partial_pathlist == NIL);
4515 create_plain_partial_paths(root, rel);
4517 /* enforce number of workers if requested */
4518 if (phint->force_parallel)
4520 foreach (l, rel->partial_pathlist)
4522 Path *ppath = (Path *) lfirst(l);
4524 ppath->parallel_workers = phint->nworkers;
4528 /* Generate gather paths for base rels */
4529 if (rel->reloptkind == RELOPT_BASEREL)
4530 generate_gather_paths(root, rel);
4534 reset_hint_enforcement();
4539 * Build access paths for a base relation
4541 * This function was copied and edited from set_rel_pathlist() in
4542 * src/backend/optimizer/path/allpaths.c in order not to copy other static
4543 * functions not required here.
4546 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4547 Index rti, RangeTblEntry *rte)
4549 if (IS_DUMMY_REL(rel))
4551 /* We already proved the relation empty, so nothing more to do */
4555 /* It's an "append relation", process accordingly */
4556 set_append_rel_pathlist(root, rel, rti, rte);
4560 if (rel->rtekind == RTE_RELATION)
4562 if (rte->relkind == RELKIND_RELATION)
4564 if(rte->tablesample != NULL)
4565 elog(ERROR, "sampled relation is not supported");
4567 /* Plain relation */
4568 set_plain_rel_pathlist(root, rel, rte);
4571 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4574 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4578 * Allow a plugin to editorialize on the set of Paths for this base
4579 * relation. It could add new paths (such as CustomPaths) by calling
4580 * add_path(), or delete or modify paths added by the core code.
4582 if (set_rel_pathlist_hook)
4583 (*set_rel_pathlist_hook) (root, rel, rti, rte);
4585 /* Now find the cheapest of the paths for this rel */
4590 * stmt_beg callback is called when each query in PL/pgSQL function is about
4591 * to be executed. At that timing, we save query string in the global variable
4592 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4593 * variable for the purpose, because its content is only necessary until
4594 * planner hook is called for the query, so recursive PL/pgSQL function calls
4595 * don't harm this mechanism.
4598 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4600 plpgsql_recurse_level++;
4604 * stmt_end callback is called then each query in PL/pgSQL function has
4605 * finished. At that timing, we clear plpgsql_query_string to tell planner
4606 * hook that next call is not for a query written in PL/pgSQL block.
4609 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4611 plpgsql_recurse_level--;
4614 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4619 if (phase != RESOURCE_RELEASE_AFTER_LOCKS)
4621 /* Cancel plpgsql nest level*/
4622 plpgsql_recurse_level = 0;
4625 #define standard_join_search pg_hint_plan_standard_join_search
4626 #define join_search_one_level pg_hint_plan_join_search_one_level
4627 #define make_join_rel make_join_rel_wrapper
4630 #undef make_join_rel
4631 #define make_join_rel pg_hint_plan_make_join_rel
4632 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4633 #include "make_join_rel.c"
4635 #include "pg_stat_statements.c"