1 /*-------------------------------------------------------------------------
4 * hinting on how to execute a query for PostgreSQL
6 * Copyright (c) 2012-2017, 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 "nodes/relation.h"
21 #include "optimizer/clauses.h"
22 #include "optimizer/cost.h"
23 #include "optimizer/geqo.h"
24 #include "optimizer/joininfo.h"
25 #include "optimizer/pathnode.h"
26 #include "optimizer/paths.h"
27 #include "optimizer/plancat.h"
28 #include "optimizer/planner.h"
29 #include "optimizer/prep.h"
30 #include "optimizer/restrictinfo.h"
31 #include "parser/analyze.h"
32 #include "parser/parsetree.h"
33 #include "parser/scansup.h"
34 #include "tcop/utility.h"
35 #include "utils/builtins.h"
36 #include "utils/lsyscache.h"
37 #include "utils/memutils.h"
38 #include "utils/rel.h"
39 #include "utils/snapmgr.h"
40 #include "utils/syscache.h"
41 #include "utils/resowner.h"
43 #include "catalog/pg_class.h"
45 #include "executor/spi.h"
46 #include "catalog/pg_type.h"
50 /* partially copied from pg_stat_statements */
51 #include "normalize_query.h"
54 #include "access/htup_details.h"
56 #ifdef PG_MODULE_MAGIC
60 #define BLOCK_COMMENT_START "/*"
61 #define BLOCK_COMMENT_END "*/"
62 #define HINT_COMMENT_KEYWORD "+"
63 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
64 #define HINT_END BLOCK_COMMENT_END
67 #define HINT_SEQSCAN "SeqScan"
68 #define HINT_INDEXSCAN "IndexScan"
69 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
70 #define HINT_BITMAPSCAN "BitmapScan"
71 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
72 #define HINT_TIDSCAN "TidScan"
73 #define HINT_NOSEQSCAN "NoSeqScan"
74 #define HINT_NOINDEXSCAN "NoIndexScan"
75 #define HINT_NOBITMAPSCAN "NoBitmapScan"
76 #define HINT_NOTIDSCAN "NoTidScan"
77 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
78 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
79 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
80 #define HINT_PARALLEL "Parallel"
82 #define HINT_NESTLOOP "NestLoop"
83 #define HINT_MERGEJOIN "MergeJoin"
84 #define HINT_HASHJOIN "HashJoin"
85 #define HINT_NONESTLOOP "NoNestLoop"
86 #define HINT_NOMERGEJOIN "NoMergeJoin"
87 #define HINT_NOHASHJOIN "NoHashJoin"
88 #define HINT_LEADING "Leading"
89 #define HINT_SET "Set"
90 #define HINT_ROWS "Rows"
92 #define HINT_ARRAY_DEFAULT_INITSIZE 8
94 #define hint_ereport(str, detail) \
96 ereport(pg_hint_plan_message_level, \
97 (errmsg("pg_hint_plan%s: hint syntax error at or near \"%s\"", qnostr, (str)), \
102 #define skip_space(str) \
103 while (isspace(*str)) \
108 ENABLE_SEQSCAN = 0x01,
109 ENABLE_INDEXSCAN = 0x02,
110 ENABLE_BITMAPSCAN = 0x04,
111 ENABLE_TIDSCAN = 0x08,
112 ENABLE_INDEXONLYSCAN = 0x10
117 ENABLE_NESTLOOP = 0x01,
118 ENABLE_MERGEJOIN = 0x02,
119 ENABLE_HASHJOIN = 0x04
122 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
123 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
124 ENABLE_INDEXONLYSCAN)
125 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
126 #define DISABLE_ALL_SCAN 0
127 #define DISABLE_ALL_JOIN 0
129 /* hint keyword of enum type*/
130 typedef enum HintKeyword
132 HINT_KEYWORD_SEQSCAN,
133 HINT_KEYWORD_INDEXSCAN,
134 HINT_KEYWORD_INDEXSCANREGEXP,
135 HINT_KEYWORD_BITMAPSCAN,
136 HINT_KEYWORD_BITMAPSCANREGEXP,
137 HINT_KEYWORD_TIDSCAN,
138 HINT_KEYWORD_NOSEQSCAN,
139 HINT_KEYWORD_NOINDEXSCAN,
140 HINT_KEYWORD_NOBITMAPSCAN,
141 HINT_KEYWORD_NOTIDSCAN,
142 HINT_KEYWORD_INDEXONLYSCAN,
143 HINT_KEYWORD_INDEXONLYSCANREGEXP,
144 HINT_KEYWORD_NOINDEXONLYSCAN,
146 HINT_KEYWORD_NESTLOOP,
147 HINT_KEYWORD_MERGEJOIN,
148 HINT_KEYWORD_HASHJOIN,
149 HINT_KEYWORD_NONESTLOOP,
150 HINT_KEYWORD_NOMERGEJOIN,
151 HINT_KEYWORD_NOHASHJOIN,
153 HINT_KEYWORD_LEADING,
156 HINT_KEYWORD_PARALLEL,
158 HINT_KEYWORD_UNRECOGNIZED
161 #define SCAN_HINT_ACCEPTS_INDEX_NAMES(kw) \
162 (kw == HINT_KEYWORD_INDEXSCAN || \
163 kw == HINT_KEYWORD_INDEXSCANREGEXP || \
164 kw == HINT_KEYWORD_INDEXONLYSCAN || \
165 kw == HINT_KEYWORD_INDEXONLYSCANREGEXP || \
166 kw == HINT_KEYWORD_BITMAPSCAN || \
167 kw == HINT_KEYWORD_BITMAPSCANREGEXP)
170 typedef struct Hint Hint;
171 typedef struct HintState HintState;
173 typedef Hint *(*HintCreateFunction) (const char *hint_str,
175 HintKeyword hint_keyword);
176 typedef void (*HintDeleteFunction) (Hint *hint);
177 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf, bool nolf);
178 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
179 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
180 Query *parse, const char *str);
183 #define NUM_HINT_TYPE 6
184 typedef enum HintType
186 HINT_TYPE_SCAN_METHOD,
187 HINT_TYPE_JOIN_METHOD,
194 typedef enum HintTypeBitmap
196 HINT_BM_SCAN_METHOD = 1,
200 static const char *HintTypeName[] = {
210 typedef enum HintStatus
212 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
213 HINT_STATE_USED, /* hint is used */
214 HINT_STATE_DUPLICATION, /* specified hint duplication */
215 HINT_STATE_ERROR /* execute error (parse error does not include
219 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
220 (hint)->base.state == HINT_STATE_USED)
222 static unsigned int qno = 0;
223 static unsigned int msgqno = 0;
224 static char qnostr[32];
225 static const char *current_hint_str = NULL;
227 /* common data for all hints. */
230 const char *hint_str; /* must not do pfree */
231 const char *keyword; /* must not do pfree */
232 HintKeyword hint_keyword;
235 HintDeleteFunction delete_func;
236 HintDescFunction desc_func;
237 HintCmpFunction cmp_func;
238 HintParseFunction parse_func;
241 /* scan method hints */
242 typedef struct ScanMethodHint
248 unsigned char enforce_mask;
251 typedef struct ParentIndexInfo
256 char *expression_str;
263 /* join method hints */
264 typedef struct JoinMethodHint
270 unsigned char enforce_mask;
272 Relids inner_joinrelids;
275 /* join order hints */
276 typedef struct OuterInnerRels
279 List *outer_inner_pair;
282 typedef struct LeadingHint
285 List *relations; /* relation names specified in Leading hint */
286 OuterInnerRels *outer_inner;
289 /* change a run-time parameter hints */
290 typedef struct SetHint
293 char *name; /* name of variable */
299 typedef enum RowsValueType {
300 RVT_ABSOLUTE, /* Rows(... #1000) */
301 RVT_ADD, /* Rows(... +1000) */
302 RVT_SUB, /* Rows(... -1000) */
303 RVT_MULTI, /* Rows(... *1.2) */
305 typedef struct RowsHint
312 Relids inner_joinrelids;
314 RowsValueType value_type;
319 typedef struct ParallelHint
323 char *nworkers_str; /* original string of nworkers */
324 int nworkers; /* num of workers specified by Worker */
325 bool force_parallel; /* force parallel scan */
329 * Describes a context of hint processing.
333 char *hint_str; /* original hint string */
336 int nall_hints; /* # of valid all hints */
337 int max_all_hints; /* # of slots for all hints */
338 Hint **all_hints; /* parsed all hints */
340 /* # of each hints */
341 int num_hints[NUM_HINT_TYPE];
343 /* for scan method hints */
344 ScanMethodHint **scan_hints; /* parsed scan hints */
346 /* Initial values of parameters */
347 int init_scan_mask; /* enable_* mask */
348 int init_nworkers; /* max_parallel_workers_per_gather */
349 /* min_parallel_table_scan_size*/
350 int init_min_para_tablescan_size;
351 /* min_parallel_index_scan_size*/
352 int init_min_para_indexscan_size;
353 int init_paratup_cost; /* parallel_tuple_cost */
354 int init_parasetup_cost;/* parallel_setup_cost */
356 Index parent_relid; /* inherit parent of table relid */
357 ScanMethodHint *parent_scan_hint; /* scan hint for the parent */
358 ParallelHint *parent_parallel_hint; /* parallel hint for the parent */
359 List *parent_index_infos; /* list of parent table's index */
361 JoinMethodHint **join_hints; /* parsed join hints */
362 int init_join_mask; /* initial value join parameter */
363 List **join_hint_level;
364 LeadingHint **leading_hint; /* parsed Leading hints */
365 SetHint **set_hints; /* parsed Set hints */
366 GucContext context; /* which GUC parameters can we set? */
367 RowsHint **rows_hints; /* parsed Rows hints */
368 ParallelHint **parallel_hints; /* parsed Parallel hints */
372 * Describes a hint parser module which is bound with particular hint keyword.
374 typedef struct HintParser
377 HintCreateFunction create_func;
378 HintKeyword hint_keyword;
381 /* Module callbacks */
385 static void push_hint(HintState *hstate);
386 static void pop_hint(void);
388 static void pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query);
389 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
390 ParamListInfo boundParams);
391 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
395 /* Scan method hint callbacks */
396 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
397 HintKeyword hint_keyword);
398 static void ScanMethodHintDelete(ScanMethodHint *hint);
399 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
400 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
401 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
402 Query *parse, const char *str);
404 /* Join method hint callbacks */
405 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
406 HintKeyword hint_keyword);
407 static void JoinMethodHintDelete(JoinMethodHint *hint);
408 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
409 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
410 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
411 Query *parse, const char *str);
413 /* Leading hint callbacks */
414 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
415 HintKeyword hint_keyword);
416 static void LeadingHintDelete(LeadingHint *hint);
417 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
418 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
419 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
420 Query *parse, const char *str);
422 /* Set hint callbacks */
423 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
424 HintKeyword hint_keyword);
425 static void SetHintDelete(SetHint *hint);
426 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
427 static int SetHintCmp(const SetHint *a, const SetHint *b);
428 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
431 /* Rows hint callbacks */
432 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
433 HintKeyword hint_keyword);
434 static void RowsHintDelete(RowsHint *hint);
435 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
436 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
437 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
438 Query *parse, const char *str);
440 /* Parallel hint callbacks */
441 static Hint *ParallelHintCreate(const char *hint_str, const char *keyword,
442 HintKeyword hint_keyword);
443 static void ParallelHintDelete(ParallelHint *hint);
444 static void ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf);
445 static int ParallelHintCmp(const ParallelHint *a, const ParallelHint *b);
446 static const char *ParallelHintParse(ParallelHint *hint, HintState *hstate,
447 Query *parse, const char *str);
449 static void quote_value(StringInfo buf, const char *value);
451 static const char *parse_quoted_value(const char *str, char **word,
454 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
457 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
458 void pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
459 Index rti, RangeTblEntry *rte);
460 static void create_plain_partial_paths(PlannerInfo *root,
462 static void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel,
463 List *live_childrels);
464 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
465 ListCell *other_rels);
466 static void make_rels_by_clauseless_joins(PlannerInfo *root,
468 ListCell *other_rels);
469 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
470 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
472 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
473 Index rti, RangeTblEntry *rte);
474 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
475 List *live_childrels,
476 List *all_child_pathkeys,
477 List *partitioned_rels);
478 static Path *get_cheapest_parameterized_child_path(PlannerInfo *root,
480 Relids required_outer);
481 static List *accumulate_append_subpath(List *subpaths, Path *path);
482 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
485 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
487 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
489 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
493 static int set_config_option_noerror(const char *name, const char *value,
494 GucContext context, GucSource source,
495 GucAction action, bool changeVal, int elevel);
496 static void setup_scan_method_enforcement(ScanMethodHint *scanhint,
498 static int set_config_int32_option(const char *name, int32 value,
502 static bool pg_hint_plan_enable_hint = true;
503 static int debug_level = 0;
504 static int pg_hint_plan_message_level = INFO;
505 /* Default is off, to keep backward compatibility. */
506 static bool pg_hint_plan_enable_hint_table = false;
508 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
509 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
510 /* (This could not be above 1) */
511 static int max_hint_nworkers = -1; /* Maximum nworkers of Workers hints */
513 static const struct config_enum_entry parse_messages_level_options[] = {
514 {"debug", DEBUG2, true},
515 {"debug5", DEBUG5, false},
516 {"debug4", DEBUG4, false},
517 {"debug3", DEBUG3, false},
518 {"debug2", DEBUG2, false},
519 {"debug1", DEBUG1, false},
521 {"info", INFO, false},
522 {"notice", NOTICE, false},
523 {"warning", WARNING, false},
524 {"error", ERROR, false},
526 * {"fatal", FATAL, true},
527 * {"panic", PANIC, true},
532 static const struct config_enum_entry parse_debug_level_options[] = {
535 {"detailed", 2, false},
536 {"verbose", 3, false},
548 /* Saved hook values in case of unload */
549 static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
550 static planner_hook_type prev_planner = NULL;
551 static join_search_hook_type prev_join_search = NULL;
552 static set_rel_pathlist_hook_type prev_set_rel_pathlist = NULL;
554 /* Hold reference to currently active hint */
555 static HintState *current_hint_state = NULL;
558 * List of hint contexts. We treat the head of the list as the Top of the
559 * context stack, so current_hint_state always points the first element of this
562 static List *HintStateStack = NIL;
565 * Holds statement name during executing EXECUTE command. NULL for other
568 static char *stmt_name = NULL;
570 static const HintParser parsers[] = {
571 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
572 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
573 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
574 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
575 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
576 HINT_KEYWORD_BITMAPSCANREGEXP},
577 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
578 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
579 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
580 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
581 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
582 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
583 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
584 HINT_KEYWORD_INDEXONLYSCANREGEXP},
585 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
587 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
588 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
589 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
590 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
591 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
592 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
594 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
595 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
596 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
597 {HINT_PARALLEL, ParallelHintCreate, HINT_KEYWORD_PARALLEL},
599 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
602 PLpgSQL_plugin plugin_funcs = {
606 pg_hint_plan_plpgsql_stmt_beg,
607 pg_hint_plan_plpgsql_stmt_end,
613 * Module load callbacks
618 PLpgSQL_plugin **var_ptr;
620 /* Define custom GUC variables. */
621 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
622 "Force planner to use plans specified in the hint comment preceding to the query.",
624 &pg_hint_plan_enable_hint,
632 DefineCustomEnumVariable("pg_hint_plan.debug_print",
633 "Logs results of hint parsing.",
637 parse_debug_level_options,
644 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
645 "Message level of parse errors.",
647 &pg_hint_plan_message_level,
649 parse_messages_level_options,
656 DefineCustomEnumVariable("pg_hint_plan.message_level",
657 "Message level of debug messages.",
659 &pg_hint_plan_message_level,
661 parse_messages_level_options,
668 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
669 "Let pg_hint_plan look up the hint table.",
671 &pg_hint_plan_enable_hint_table,
680 prev_post_parse_analyze_hook = post_parse_analyze_hook;
681 post_parse_analyze_hook = pg_hint_plan_post_parse_analyze;
682 prev_planner = planner_hook;
683 planner_hook = pg_hint_plan_planner;
684 prev_join_search = join_search_hook;
685 join_search_hook = pg_hint_plan_join_search;
686 prev_set_rel_pathlist = set_rel_pathlist_hook;
687 set_rel_pathlist_hook = pg_hint_plan_set_rel_pathlist;
689 /* setup PL/pgSQL plugin hook */
690 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
691 *var_ptr = &plugin_funcs;
693 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
697 * Module unload callback
703 PLpgSQL_plugin **var_ptr;
705 /* Uninstall hooks. */
706 post_parse_analyze_hook = prev_post_parse_analyze_hook;
707 planner_hook = prev_planner;
708 join_search_hook = prev_join_search;
709 set_rel_pathlist_hook = prev_set_rel_pathlist;
711 /* uninstall PL/pgSQL plugin hook */
712 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
717 * create and delete functions the hint object
721 ScanMethodHintCreate(const char *hint_str, const char *keyword,
722 HintKeyword hint_keyword)
724 ScanMethodHint *hint;
726 hint = palloc(sizeof(ScanMethodHint));
727 hint->base.hint_str = hint_str;
728 hint->base.keyword = keyword;
729 hint->base.hint_keyword = hint_keyword;
730 hint->base.type = HINT_TYPE_SCAN_METHOD;
731 hint->base.state = HINT_STATE_NOTUSED;
732 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
733 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
734 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
735 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
736 hint->relname = NULL;
737 hint->indexnames = NIL;
738 hint->regexp = false;
739 hint->enforce_mask = 0;
741 return (Hint *) hint;
745 ScanMethodHintDelete(ScanMethodHint *hint)
751 pfree(hint->relname);
752 list_free_deep(hint->indexnames);
757 JoinMethodHintCreate(const char *hint_str, const char *keyword,
758 HintKeyword hint_keyword)
760 JoinMethodHint *hint;
762 hint = palloc(sizeof(JoinMethodHint));
763 hint->base.hint_str = hint_str;
764 hint->base.keyword = keyword;
765 hint->base.hint_keyword = hint_keyword;
766 hint->base.type = HINT_TYPE_JOIN_METHOD;
767 hint->base.state = HINT_STATE_NOTUSED;
768 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
769 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
770 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
771 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
773 hint->inner_nrels = 0;
774 hint->relnames = NULL;
775 hint->enforce_mask = 0;
776 hint->joinrelids = NULL;
777 hint->inner_joinrelids = NULL;
779 return (Hint *) hint;
783 JoinMethodHintDelete(JoinMethodHint *hint)
792 for (i = 0; i < hint->nrels; i++)
793 pfree(hint->relnames[i]);
794 pfree(hint->relnames);
797 bms_free(hint->joinrelids);
798 bms_free(hint->inner_joinrelids);
803 LeadingHintCreate(const char *hint_str, const char *keyword,
804 HintKeyword hint_keyword)
808 hint = palloc(sizeof(LeadingHint));
809 hint->base.hint_str = hint_str;
810 hint->base.keyword = keyword;
811 hint->base.hint_keyword = hint_keyword;
812 hint->base.type = HINT_TYPE_LEADING;
813 hint->base.state = HINT_STATE_NOTUSED;
814 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
815 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
816 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
817 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
818 hint->relations = NIL;
819 hint->outer_inner = NULL;
821 return (Hint *) hint;
825 LeadingHintDelete(LeadingHint *hint)
830 list_free_deep(hint->relations);
831 if (hint->outer_inner)
832 pfree(hint->outer_inner);
837 SetHintCreate(const char *hint_str, const char *keyword,
838 HintKeyword hint_keyword)
842 hint = palloc(sizeof(SetHint));
843 hint->base.hint_str = hint_str;
844 hint->base.keyword = keyword;
845 hint->base.hint_keyword = hint_keyword;
846 hint->base.type = HINT_TYPE_SET;
847 hint->base.state = HINT_STATE_NOTUSED;
848 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
849 hint->base.desc_func = (HintDescFunction) SetHintDesc;
850 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
851 hint->base.parse_func = (HintParseFunction) SetHintParse;
856 return (Hint *) hint;
860 SetHintDelete(SetHint *hint)
870 list_free(hint->words);
875 RowsHintCreate(const char *hint_str, const char *keyword,
876 HintKeyword hint_keyword)
880 hint = palloc(sizeof(RowsHint));
881 hint->base.hint_str = hint_str;
882 hint->base.keyword = keyword;
883 hint->base.hint_keyword = hint_keyword;
884 hint->base.type = HINT_TYPE_ROWS;
885 hint->base.state = HINT_STATE_NOTUSED;
886 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
887 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
888 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
889 hint->base.parse_func = (HintParseFunction) RowsHintParse;
891 hint->inner_nrels = 0;
892 hint->relnames = NULL;
893 hint->joinrelids = NULL;
894 hint->inner_joinrelids = NULL;
895 hint->rows_str = NULL;
896 hint->value_type = RVT_ABSOLUTE;
899 return (Hint *) hint;
903 RowsHintDelete(RowsHint *hint)
912 for (i = 0; i < hint->nrels; i++)
913 pfree(hint->relnames[i]);
914 pfree(hint->relnames);
917 bms_free(hint->joinrelids);
918 bms_free(hint->inner_joinrelids);
923 ParallelHintCreate(const char *hint_str, const char *keyword,
924 HintKeyword hint_keyword)
928 hint = palloc(sizeof(ScanMethodHint));
929 hint->base.hint_str = hint_str;
930 hint->base.keyword = keyword;
931 hint->base.hint_keyword = hint_keyword;
932 hint->base.type = HINT_TYPE_PARALLEL;
933 hint->base.state = HINT_STATE_NOTUSED;
934 hint->base.delete_func = (HintDeleteFunction) ParallelHintDelete;
935 hint->base.desc_func = (HintDescFunction) ParallelHintDesc;
936 hint->base.cmp_func = (HintCmpFunction) ParallelHintCmp;
937 hint->base.parse_func = (HintParseFunction) ParallelHintParse;
938 hint->relname = NULL;
940 hint->nworkers_str = "0";
942 return (Hint *) hint;
946 ParallelHintDelete(ParallelHint *hint)
952 pfree(hint->relname);
958 HintStateCreate(void)
962 hstate = palloc(sizeof(HintState));
963 hstate->hint_str = NULL;
964 hstate->nall_hints = 0;
965 hstate->max_all_hints = 0;
966 hstate->all_hints = NULL;
967 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
968 hstate->scan_hints = NULL;
969 hstate->init_scan_mask = 0;
970 hstate->init_nworkers = 0;
971 hstate->init_min_para_tablescan_size = 0;
972 hstate->init_min_para_indexscan_size = 0;
973 hstate->init_paratup_cost = 0;
974 hstate->init_parasetup_cost = 0;
975 hstate->parent_relid = 0;
976 hstate->parent_scan_hint = NULL;
977 hstate->parent_parallel_hint = NULL;
978 hstate->parent_index_infos = NIL;
979 hstate->join_hints = NULL;
980 hstate->init_join_mask = 0;
981 hstate->join_hint_level = NULL;
982 hstate->leading_hint = NULL;
983 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
984 hstate->set_hints = NULL;
985 hstate->rows_hints = NULL;
986 hstate->parallel_hints = NULL;
992 HintStateDelete(HintState *hstate)
999 if (hstate->hint_str)
1000 pfree(hstate->hint_str);
1002 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1003 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
1004 if (hstate->all_hints)
1005 pfree(hstate->all_hints);
1006 if (hstate->parent_index_infos)
1007 list_free(hstate->parent_index_infos);
1011 * Copy given value into buf, with quoting with '"' if necessary.
1014 quote_value(StringInfo buf, const char *value)
1016 bool need_quote = false;
1019 for (str = value; *str != '\0'; str++)
1021 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
1024 appendStringInfoCharMacro(buf, '"');
1029 for (str = value; *str != '\0'; str++)
1032 appendStringInfoCharMacro(buf, '"');
1034 appendStringInfoCharMacro(buf, *str);
1038 appendStringInfoCharMacro(buf, '"');
1042 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
1046 appendStringInfo(buf, "%s(", hint->base.keyword);
1047 if (hint->relname != NULL)
1049 quote_value(buf, hint->relname);
1050 foreach(l, hint->indexnames)
1052 appendStringInfoCharMacro(buf, ' ');
1053 quote_value(buf, (char *) lfirst(l));
1056 appendStringInfoString(buf, ")");
1058 appendStringInfoChar(buf, '\n');
1062 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
1066 appendStringInfo(buf, "%s(", hint->base.keyword);
1067 if (hint->relnames != NULL)
1069 quote_value(buf, hint->relnames[0]);
1070 for (i = 1; i < hint->nrels; i++)
1072 appendStringInfoCharMacro(buf, ' ');
1073 quote_value(buf, hint->relnames[i]);
1076 appendStringInfoString(buf, ")");
1078 appendStringInfoChar(buf, '\n');
1082 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
1084 if (outer_inner->relation == NULL)
1091 appendStringInfoCharMacro(buf, '(');
1092 foreach(l, outer_inner->outer_inner_pair)
1097 appendStringInfoCharMacro(buf, ' ');
1099 OuterInnerDesc(lfirst(l), buf);
1102 appendStringInfoCharMacro(buf, ')');
1105 quote_value(buf, outer_inner->relation);
1109 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
1111 appendStringInfo(buf, "%s(", HINT_LEADING);
1112 if (hint->outer_inner == NULL)
1119 foreach(l, hint->relations)
1124 appendStringInfoCharMacro(buf, ' ');
1126 quote_value(buf, (char *) lfirst(l));
1130 OuterInnerDesc(hint->outer_inner, buf);
1132 appendStringInfoString(buf, ")");
1134 appendStringInfoChar(buf, '\n');
1138 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1140 bool is_first = true;
1143 appendStringInfo(buf, "%s(", HINT_SET);
1144 foreach(l, hint->words)
1149 appendStringInfoCharMacro(buf, ' ');
1151 quote_value(buf, (char *) lfirst(l));
1153 appendStringInfo(buf, ")");
1155 appendStringInfoChar(buf, '\n');
1159 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1163 appendStringInfo(buf, "%s(", hint->base.keyword);
1164 if (hint->relnames != NULL)
1166 quote_value(buf, hint->relnames[0]);
1167 for (i = 1; i < hint->nrels; i++)
1169 appendStringInfoCharMacro(buf, ' ');
1170 quote_value(buf, hint->relnames[i]);
1173 appendStringInfo(buf, " %s", hint->rows_str);
1174 appendStringInfoString(buf, ")");
1176 appendStringInfoChar(buf, '\n');
1180 ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf)
1182 appendStringInfo(buf, "%s(", hint->base.keyword);
1183 if (hint->relname != NULL)
1185 quote_value(buf, hint->relname);
1187 /* number of workers */
1188 appendStringInfoCharMacro(buf, ' ');
1189 quote_value(buf, hint->nworkers_str);
1190 /* application mode of num of workers */
1191 appendStringInfoCharMacro(buf, ' ');
1192 appendStringInfoString(buf,
1193 (hint->force_parallel ? "hard" : "soft"));
1195 appendStringInfoString(buf, ")");
1197 appendStringInfoChar(buf, '\n');
1201 * Append string which represents all hints in a given state to buf, with
1202 * preceding title with them.
1205 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1206 HintStatus state, bool nolf)
1210 appendStringInfo(buf, "%s:", title);
1212 appendStringInfoChar(buf, '\n');
1215 for (i = 0; i < hstate->nall_hints; i++)
1217 if (hstate->all_hints[i]->state != state)
1220 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1224 if (nolf && nshown == 0)
1225 appendStringInfoString(buf, "(none)");
1229 * Dump contents of given hstate to server log with log level LOG.
1232 HintStateDump(HintState *hstate)
1238 elog(LOG, "pg_hint_plan:\nno hint");
1242 initStringInfo(&buf);
1244 appendStringInfoString(&buf, "pg_hint_plan:\n");
1245 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1246 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1247 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1248 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1250 elog(LOG, "%s", buf.data);
1256 HintStateDump2(HintState *hstate)
1262 elog(pg_hint_plan_message_level,
1263 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1267 initStringInfo(&buf);
1268 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1269 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1270 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1271 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1272 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1273 appendStringInfoChar(&buf, '}');
1275 ereport(pg_hint_plan_message_level,
1276 (errmsg("%s", buf.data),
1278 errhidecontext(true)));
1288 RelnameCmp(const void *a, const void *b)
1290 const char *relnamea = *((const char **) a);
1291 const char *relnameb = *((const char **) b);
1293 return strcmp(relnamea, relnameb);
1297 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1299 return RelnameCmp(&a->relname, &b->relname);
1303 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1307 if (a->nrels != b->nrels)
1308 return a->nrels - b->nrels;
1310 for (i = 0; i < a->nrels; i++)
1313 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1321 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1327 SetHintCmp(const SetHint *a, const SetHint *b)
1329 return strcmp(a->name, b->name);
1333 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1337 if (a->nrels != b->nrels)
1338 return a->nrels - b->nrels;
1340 for (i = 0; i < a->nrels; i++)
1343 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1351 ParallelHintCmp(const ParallelHint *a, const ParallelHint *b)
1353 return RelnameCmp(&a->relname, &b->relname);
1357 HintCmp(const void *a, const void *b)
1359 const Hint *hinta = *((const Hint **) a);
1360 const Hint *hintb = *((const Hint **) b);
1362 if (hinta->type != hintb->type)
1363 return hinta->type - hintb->type;
1364 if (hinta->state == HINT_STATE_ERROR)
1366 if (hintb->state == HINT_STATE_ERROR)
1368 return hinta->cmp_func(hinta, hintb);
1372 * Returns byte offset of hint b from hint a. If hint a was specified before
1373 * b, positive value is returned.
1376 HintCmpWithPos(const void *a, const void *b)
1378 const Hint *hinta = *((const Hint **) a);
1379 const Hint *hintb = *((const Hint **) b);
1382 result = HintCmp(a, b);
1384 result = hinta->hint_str - hintb->hint_str;
1393 parse_keyword(const char *str, StringInfo buf)
1397 while (!isspace(*str) && *str != '(' && *str != '\0')
1398 appendStringInfoCharMacro(buf, *str++);
1404 skip_parenthesis(const char *str, char parenthesis)
1408 if (*str != parenthesis)
1410 if (parenthesis == '(')
1411 hint_ereport(str, ("Opening parenthesis is necessary."));
1412 else if (parenthesis == ')')
1413 hint_ereport(str, ("Closing parenthesis is necessary."));
1424 * Parse a token from str, and store malloc'd copy into word. A token can be
1425 * quoted with '"'. Return value is pointer to unparsed portion of original
1426 * string, or NULL if an error occurred.
1428 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1431 parse_quoted_value(const char *str, char **word, bool truncate)
1436 /* Skip leading spaces. */
1439 initStringInfo(&buf);
1452 /* Double quotation must be closed. */
1456 hint_ereport(str, ("Unterminated quoted string."));
1461 * Skip escaped double quotation.
1463 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1464 * block comments) to be an object name, so users must specify
1465 * alias for such object names.
1467 * Those special names can be allowed if we care escaped slashes
1468 * and asterisks, but we don't.
1477 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1481 appendStringInfoCharMacro(&buf, *str++);
1486 hint_ereport(str, ("Zero-length delimited string."));
1493 /* Truncate name if it's too long */
1495 truncate_identifier(buf.data, strlen(buf.data), true);
1502 static OuterInnerRels *
1503 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1505 OuterInnerRels *outer_inner;
1507 outer_inner = palloc(sizeof(OuterInnerRels));
1508 outer_inner->relation = name;
1509 outer_inner->outer_inner_pair = outer_inner_list;
1515 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1517 List *outer_inner_pair = NIL;
1519 if ((str = skip_parenthesis(str, '(')) == NULL)
1524 /* Store words in parentheses into outer_inner_list. */
1525 while(*str != ')' && *str != '\0')
1527 OuterInnerRels *outer_inner_rels;
1531 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1539 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1542 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1545 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1550 (str = skip_parenthesis(str, ')')) == NULL)
1552 list_free(outer_inner_pair);
1556 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1562 parse_parentheses_Leading(const char *str, List **name_list,
1563 OuterInnerRels **outer_inner)
1566 bool truncate = true;
1568 if ((str = skip_parenthesis(str, '(')) == NULL)
1574 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1579 /* Store words in parentheses into name_list. */
1580 while(*str != ')' && *str != '\0')
1582 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1584 list_free(*name_list);
1588 *name_list = lappend(*name_list, name);
1593 if ((str = skip_parenthesis(str, ')')) == NULL)
1599 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1602 bool truncate = true;
1604 if ((str = skip_parenthesis(str, '(')) == NULL)
1609 /* Store words in parentheses into name_list. */
1610 while(*str != ')' && *str != '\0')
1612 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1614 list_free(*name_list);
1618 *name_list = lappend(*name_list, name);
1621 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1622 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1623 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1624 keyword == HINT_KEYWORD_SET)
1630 if ((str = skip_parenthesis(str, ')')) == NULL)
1636 parse_hints(HintState *hstate, Query *parse, const char *str)
1641 initStringInfo(&buf);
1642 while (*str != '\0')
1644 const HintParser *parser;
1646 /* in error message, we output the comment including the keyword. */
1647 head = (char *) str;
1649 /* parse only the keyword of the hint. */
1650 resetStringInfo(&buf);
1651 str = parse_keyword(str, &buf);
1653 for (parser = parsers; parser->keyword != NULL; parser++)
1655 char *keyword = parser->keyword;
1658 if (strcasecmp(buf.data, keyword) != 0)
1661 hint = parser->create_func(head, keyword, parser->hint_keyword);
1663 /* parser of each hint does parse in a parenthesis. */
1664 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1666 hint->delete_func(hint);
1672 * Add hint information into all_hints array. If we don't have
1673 * enough space, double the array.
1675 if (hstate->nall_hints == 0)
1677 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1678 hstate->all_hints = (Hint **)
1679 palloc(sizeof(Hint *) * hstate->max_all_hints);
1681 else if (hstate->nall_hints == hstate->max_all_hints)
1683 hstate->max_all_hints *= 2;
1684 hstate->all_hints = (Hint **)
1685 repalloc(hstate->all_hints,
1686 sizeof(Hint *) * hstate->max_all_hints);
1689 hstate->all_hints[hstate->nall_hints] = hint;
1690 hstate->nall_hints++;
1697 if (parser->keyword == NULL)
1700 ("Unrecognized hint keyword \"%s\".", buf.data));
1711 * Get hints from table by client-supplied query string and application name.
1714 get_hints_from_table(const char *client_query, const char *client_application)
1716 const char *search_query =
1718 " FROM hint_plan.hints "
1719 " WHERE norm_query_string = $1 "
1720 " AND ( application_name = $2 "
1721 " OR application_name = '' ) "
1722 " ORDER BY application_name DESC";
1723 static SPIPlanPtr plan = NULL;
1725 Oid argtypes[2] = { TEXTOID, TEXTOID };
1727 bool nulls[2] = { false, false };
1733 bool snapshot_set = false;
1735 hint_inhibit_level++;
1737 if (!ActiveSnapshotSet())
1739 PushActiveSnapshot(GetTransactionSnapshot());
1740 snapshot_set = true;
1748 p = SPI_prepare(search_query, 2, argtypes);
1749 plan = SPI_saveplan(p);
1753 qry = cstring_to_text(client_query);
1754 app = cstring_to_text(client_application);
1755 values[0] = PointerGetDatum(qry);
1756 values[1] = PointerGetDatum(app);
1758 SPI_execute_plan(plan, values, nulls, true, 1);
1760 if (SPI_processed > 0)
1764 hints = SPI_getvalue(SPI_tuptable->vals[0],
1765 SPI_tuptable->tupdesc, 1);
1767 * Here we use SPI_palloc to ensure that hints string is valid even
1768 * after SPI_finish call. We can't use simple palloc because it
1769 * allocates memory in SPI's context and that context is deleted in
1772 buf = SPI_palloc(strlen(hints) + 1);
1780 PopActiveSnapshot();
1782 hint_inhibit_level--;
1786 hint_inhibit_level--;
1795 * Get client-supplied query string. Addtion to that the jumbled query is
1796 * supplied if the caller requested. From the restriction of JumbleQuery, some
1797 * kind of query needs special amendments. Reutrns NULL if this query doesn't
1798 * change the current hint. This function returns NULL also when something
1799 * wrong has happend and let the caller continue using the current hints.
1802 get_query_string(ParseState *pstate, Query *query, Query **jumblequery)
1804 const char *p = debug_query_string;
1806 if (jumblequery != NULL)
1807 *jumblequery = query;
1809 if (query->commandType == CMD_UTILITY)
1811 Query *target_query = (Query *)query->utilityStmt;
1814 * Some CMD_UTILITY statements have a subquery that we can hint on.
1815 * Since EXPLAIN can be placed before other kind of utility statements
1816 * and EXECUTE can be contained other kind of utility statements, these
1817 * conditions are not mutually exclusive and should be considered in
1820 if (IsA(target_query, ExplainStmt))
1822 ExplainStmt *stmt = (ExplainStmt *)target_query;
1824 Assert(IsA(stmt->query, Query));
1825 target_query = (Query *)stmt->query;
1827 /* strip out the top-level query for further processing */
1828 if (target_query->commandType == CMD_UTILITY &&
1829 target_query->utilityStmt != NULL)
1830 target_query = (Query *)target_query->utilityStmt;
1833 if (IsA(target_query, DeclareCursorStmt))
1835 DeclareCursorStmt *stmt = (DeclareCursorStmt *)target_query;
1836 Query *query = (Query *)stmt->query;
1838 /* the target must be CMD_SELECT in this case */
1839 Assert(IsA(query, Query) && query->commandType == CMD_SELECT);
1840 target_query = query;
1843 if (IsA(target_query, CreateTableAsStmt))
1845 CreateTableAsStmt *stmt = (CreateTableAsStmt *) target_query;
1847 Assert(IsA(stmt->query, Query));
1848 target_query = (Query *) stmt->query;
1850 /* strip out the top-level query for further processing */
1851 if (target_query->commandType == CMD_UTILITY &&
1852 target_query->utilityStmt != NULL)
1853 target_query = (Query *)target_query->utilityStmt;
1856 if (IsA(target_query, ExecuteStmt))
1859 * Use the prepared query for EXECUTE. The Query for jumble
1860 * also replaced with the corresponding one.
1862 ExecuteStmt *stmt = (ExecuteStmt *)target_query;
1863 PreparedStatement *entry;
1865 entry = FetchPreparedStatement(stmt->name, true);
1866 p = entry->plansource->query_string;
1867 target_query = (Query *) linitial (entry->plansource->query_list);
1870 /* JumbleQuery accespts only a non-utility Query */
1871 if (!IsA(target_query, Query) ||
1872 target_query->utilityStmt != NULL)
1873 target_query = NULL;
1876 *jumblequery = target_query;
1878 /* Return NULL if the pstate is not identical to the top-level query */
1879 else if (strcmp(pstate->p_sourcetext, p) != 0)
1886 * Get hints from the head block comment in client-supplied query string.
1889 get_hints_from_comment(const char *p)
1891 const char *hint_head;
1899 /* extract query head comment. */
1900 hint_head = strstr(p, HINT_START);
1901 if (hint_head == NULL)
1903 for (;p < hint_head; p++)
1906 * Allow these characters precedes hint comment:
1908 * - alphabets which are in ASCII range
1909 * - space, tabs and new-lines
1910 * - underscores, for identifier
1911 * - commas, for SELECT clause, EXPLAIN and PREPARE
1912 * - parentheses, for EXPLAIN and PREPARE
1914 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1915 * avoid behavior which depends on locale setting.
1917 if (!(*p >= '0' && *p <= '9') &&
1918 !(*p >= 'A' && *p <= 'Z') &&
1919 !(*p >= 'a' && *p <= 'z') &&
1923 *p != '(' && *p != ')')
1927 len = strlen(HINT_START);
1932 /* find hint end keyword. */
1933 if ((tail = strstr(p, HINT_END)) == NULL)
1935 hint_ereport(head, ("Unterminated block comment."));
1939 /* We don't support nested block comments. */
1940 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1942 hint_ereport(head, ("Nested block comments are not supported."));
1946 /* Make a copy of hint. */
1948 head = palloc(len + 1);
1949 memcpy(head, p, len);
1957 * Parse hints that got, create hint struct from parse tree and parse hints.
1960 create_hintstate(Query *parse, const char *hints)
1969 /* -1 means that no Parallel hint is specified. */
1970 max_hint_nworkers = -1;
1973 hstate = HintStateCreate();
1974 hstate->hint_str = (char *) hints;
1976 /* parse each hint. */
1977 parse_hints(hstate, parse, p);
1979 /* When nothing specified a hint, we free HintState and returns NULL. */
1980 if (hstate->nall_hints == 0)
1982 HintStateDelete(hstate);
1986 /* Sort hints in order of original position. */
1987 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1990 /* Count number of hints per hint-type. */
1991 for (i = 0; i < hstate->nall_hints; i++)
1993 Hint *cur_hint = hstate->all_hints[i];
1994 hstate->num_hints[cur_hint->type]++;
1998 * If an object (or a set of objects) has multiple hints of same hint-type,
1999 * only the last hint is valid and others are ignored in planning.
2000 * Hints except the last are marked as 'duplicated' to remember the order.
2002 for (i = 0; i < hstate->nall_hints - 1; i++)
2004 Hint *cur_hint = hstate->all_hints[i];
2005 Hint *next_hint = hstate->all_hints[i + 1];
2008 * Leading hint is marked as 'duplicated' in transform_join_hints.
2010 if (cur_hint->type == HINT_TYPE_LEADING &&
2011 next_hint->type == HINT_TYPE_LEADING)
2015 * Note that we need to pass addresses of hint pointers, because
2016 * HintCmp is designed to sort array of Hint* by qsort.
2018 if (HintCmp(&cur_hint, &next_hint) == 0)
2020 hint_ereport(cur_hint->hint_str,
2021 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
2022 cur_hint->state = HINT_STATE_DUPLICATION;
2027 * Make sure that per-type array pointers point proper position in the
2028 * array which consists of all hints.
2030 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
2031 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
2032 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
2033 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
2034 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
2035 hstate->set_hints = (SetHint **) (hstate->leading_hint +
2036 hstate->num_hints[HINT_TYPE_LEADING]);
2037 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
2038 hstate->num_hints[HINT_TYPE_SET]);
2039 hstate->parallel_hints = (ParallelHint **) (hstate->set_hints +
2040 hstate->num_hints[HINT_TYPE_ROWS]);
2046 * Parse inside of parentheses of scan-method hints.
2049 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
2052 const char *keyword = hint->base.keyword;
2053 HintKeyword hint_keyword = hint->base.hint_keyword;
2054 List *name_list = NIL;
2057 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2060 /* Parse relation name and index name(s) if given hint accepts. */
2061 length = list_length(name_list);
2063 /* at least twp parameters required */
2067 ("%s hint requires a relation.", hint->base.keyword));
2068 hint->base.state = HINT_STATE_ERROR;
2072 hint->relname = linitial(name_list);
2073 hint->indexnames = list_delete_first(name_list);
2075 /* check whether the hint accepts index name(s) */
2076 if (length > 1 && !SCAN_HINT_ACCEPTS_INDEX_NAMES(hint_keyword))
2079 ("%s hint accepts only one relation.",
2080 hint->base.keyword));
2081 hint->base.state = HINT_STATE_ERROR;
2085 /* Set a bit for specified hint. */
2086 switch (hint_keyword)
2088 case HINT_KEYWORD_SEQSCAN:
2089 hint->enforce_mask = ENABLE_SEQSCAN;
2091 case HINT_KEYWORD_INDEXSCAN:
2092 hint->enforce_mask = ENABLE_INDEXSCAN;
2094 case HINT_KEYWORD_INDEXSCANREGEXP:
2095 hint->enforce_mask = ENABLE_INDEXSCAN;
2096 hint->regexp = true;
2098 case HINT_KEYWORD_BITMAPSCAN:
2099 hint->enforce_mask = ENABLE_BITMAPSCAN;
2101 case HINT_KEYWORD_BITMAPSCANREGEXP:
2102 hint->enforce_mask = ENABLE_BITMAPSCAN;
2103 hint->regexp = true;
2105 case HINT_KEYWORD_TIDSCAN:
2106 hint->enforce_mask = ENABLE_TIDSCAN;
2108 case HINT_KEYWORD_NOSEQSCAN:
2109 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
2111 case HINT_KEYWORD_NOINDEXSCAN:
2112 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
2114 case HINT_KEYWORD_NOBITMAPSCAN:
2115 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
2117 case HINT_KEYWORD_NOTIDSCAN:
2118 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
2120 case HINT_KEYWORD_INDEXONLYSCAN:
2121 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2123 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
2124 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2125 hint->regexp = true;
2127 case HINT_KEYWORD_NOINDEXONLYSCAN:
2128 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
2131 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2140 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2143 const char *keyword = hint->base.keyword;
2144 HintKeyword hint_keyword = hint->base.hint_keyword;
2145 List *name_list = NIL;
2147 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2150 hint->nrels = list_length(name_list);
2152 if (hint->nrels > 0)
2158 * Transform relation names from list to array to sort them with qsort
2161 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2162 foreach (l, name_list)
2164 hint->relnames[i] = lfirst(l);
2169 list_free(name_list);
2171 /* A join hint requires at least two relations */
2172 if (hint->nrels < 2)
2175 ("%s hint requires at least two relations.",
2176 hint->base.keyword));
2177 hint->base.state = HINT_STATE_ERROR;
2181 /* Sort hints in alphabetical order of relation names. */
2182 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2184 switch (hint_keyword)
2186 case HINT_KEYWORD_NESTLOOP:
2187 hint->enforce_mask = ENABLE_NESTLOOP;
2189 case HINT_KEYWORD_MERGEJOIN:
2190 hint->enforce_mask = ENABLE_MERGEJOIN;
2192 case HINT_KEYWORD_HASHJOIN:
2193 hint->enforce_mask = ENABLE_HASHJOIN;
2195 case HINT_KEYWORD_NONESTLOOP:
2196 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2198 case HINT_KEYWORD_NOMERGEJOIN:
2199 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2201 case HINT_KEYWORD_NOHASHJOIN:
2202 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2205 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2214 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2217 if (outer_inner->outer_inner_pair == NIL)
2219 if (outer_inner->relation)
2225 if (list_length(outer_inner->outer_inner_pair) == 2)
2227 foreach(l, outer_inner->outer_inner_pair)
2229 if (!OuterInnerPairCheck(lfirst(l)))
2240 OuterInnerList(OuterInnerRels *outer_inner)
2242 List *outer_inner_list = NIL;
2244 OuterInnerRels *outer_inner_rels;
2246 foreach(l, outer_inner->outer_inner_pair)
2248 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2250 if (outer_inner_rels->relation != NULL)
2251 outer_inner_list = lappend(outer_inner_list,
2252 outer_inner_rels->relation);
2254 outer_inner_list = list_concat(outer_inner_list,
2255 OuterInnerList(outer_inner_rels));
2257 return outer_inner_list;
2261 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2264 List *name_list = NIL;
2265 OuterInnerRels *outer_inner = NULL;
2267 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2271 if (outer_inner != NULL)
2272 name_list = OuterInnerList(outer_inner);
2274 hint->relations = name_list;
2275 hint->outer_inner = outer_inner;
2277 /* A Leading hint requires at least two relations */
2278 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2280 hint_ereport(hint->base.hint_str,
2281 ("%s hint requires at least two relations.",
2283 hint->base.state = HINT_STATE_ERROR;
2285 else if (hint->outer_inner != NULL &&
2286 !OuterInnerPairCheck(hint->outer_inner))
2288 hint_ereport(hint->base.hint_str,
2289 ("%s hint requires two sets of relations when parentheses nests.",
2291 hint->base.state = HINT_STATE_ERROR;
2298 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2300 List *name_list = NIL;
2302 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2306 hint->words = name_list;
2308 /* We need both name and value to set GUC parameter. */
2309 if (list_length(name_list) == 2)
2311 hint->name = linitial(name_list);
2312 hint->value = lsecond(name_list);
2316 hint_ereport(hint->base.hint_str,
2317 ("%s hint requires name and value of GUC parameter.",
2319 hint->base.state = HINT_STATE_ERROR;
2326 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2329 HintKeyword hint_keyword = hint->base.hint_keyword;
2330 List *name_list = NIL;
2334 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2337 /* Last element must be rows specification */
2338 hint->nrels = list_length(name_list) - 1;
2340 if (hint->nrels > 0)
2346 * Transform relation names from list to array to sort them with qsort
2349 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2350 foreach (l, name_list)
2352 if (hint->nrels <= i)
2354 hint->relnames[i] = lfirst(l);
2359 /* Retieve rows estimation */
2360 rows_str = list_nth(name_list, hint->nrels);
2361 hint->rows_str = rows_str; /* store as-is for error logging */
2362 if (rows_str[0] == '#')
2364 hint->value_type = RVT_ABSOLUTE;
2367 else if (rows_str[0] == '+')
2369 hint->value_type = RVT_ADD;
2372 else if (rows_str[0] == '-')
2374 hint->value_type = RVT_SUB;
2377 else if (rows_str[0] == '*')
2379 hint->value_type = RVT_MULTI;
2384 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2385 hint->base.state = HINT_STATE_ERROR;
2388 hint->rows = strtod(rows_str, &end_ptr);
2391 hint_ereport(rows_str,
2392 ("%s hint requires valid number as rows estimation.",
2393 hint->base.keyword));
2394 hint->base.state = HINT_STATE_ERROR;
2398 /* A join hint requires at least two relations */
2399 if (hint->nrels < 2)
2402 ("%s hint requires at least two relations.",
2403 hint->base.keyword));
2404 hint->base.state = HINT_STATE_ERROR;
2408 list_free(name_list);
2410 /* Sort relnames in alphabetical order. */
2411 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2417 ParallelHintParse(ParallelHint *hint, HintState *hstate, Query *parse,
2420 HintKeyword hint_keyword = hint->base.hint_keyword;
2421 List *name_list = NIL;
2425 bool force_parallel = false;
2427 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2430 /* Parse relation name and index name(s) if given hint accepts. */
2431 length = list_length(name_list);
2433 if (length < 2 || length > 3)
2436 ("wrong number of arguments (%d): %s",
2437 length, hint->base.keyword));
2438 hint->base.state = HINT_STATE_ERROR;
2442 hint->relname = linitial(name_list);
2444 /* The second parameter is number of workers */
2445 hint->nworkers_str = list_nth(name_list, 1);
2446 nworkers = strtod(hint->nworkers_str, &end_ptr);
2447 if (*end_ptr || nworkers < 0 || nworkers > max_worker_processes)
2450 hint_ereport(hint->nworkers_str,
2451 ("number of workers must be a number: %s",
2452 hint->base.keyword));
2453 else if (nworkers < 0)
2454 hint_ereport(hint->nworkers_str,
2455 ("number of workers must be positive: %s",
2456 hint->base.keyword));
2457 else if (nworkers > max_worker_processes)
2458 hint_ereport(hint->nworkers_str,
2459 ("number of workers = %d is larger than max_worker_processes(%d): %s",
2460 nworkers, max_worker_processes, hint->base.keyword));
2462 hint->base.state = HINT_STATE_ERROR;
2465 hint->nworkers = nworkers;
2467 /* optional third parameter is specified */
2470 const char *modeparam = (const char *)list_nth(name_list, 2);
2471 if (strcasecmp(modeparam, "hard") == 0)
2472 force_parallel = true;
2473 else if (strcasecmp(modeparam, "soft") != 0)
2475 hint_ereport(modeparam,
2476 ("enforcement must be soft or hard: %s",
2477 hint->base.keyword));
2478 hint->base.state = HINT_STATE_ERROR;
2482 hint->force_parallel = force_parallel;
2484 if (hint->base.state != HINT_STATE_ERROR &&
2485 nworkers > max_hint_nworkers)
2486 max_hint_nworkers = nworkers;
2492 * set GUC parameter functions
2496 get_current_scan_mask()
2501 mask |= ENABLE_SEQSCAN;
2502 if (enable_indexscan)
2503 mask |= ENABLE_INDEXSCAN;
2504 if (enable_bitmapscan)
2505 mask |= ENABLE_BITMAPSCAN;
2507 mask |= ENABLE_TIDSCAN;
2508 if (enable_indexonlyscan)
2509 mask |= ENABLE_INDEXONLYSCAN;
2515 get_current_join_mask()
2519 if (enable_nestloop)
2520 mask |= ENABLE_NESTLOOP;
2521 if (enable_mergejoin)
2522 mask |= ENABLE_MERGEJOIN;
2523 if (enable_hashjoin)
2524 mask |= ENABLE_HASHJOIN;
2530 * Sets GUC prameters without throwing exception. Reutrns false if something
2534 set_config_option_noerror(const char *name, const char *value,
2535 GucContext context, GucSource source,
2536 GucAction action, bool changeVal, int elevel)
2539 MemoryContext ccxt = CurrentMemoryContext;
2543 result = set_config_option(name, value, context, source,
2544 action, changeVal, 0, false);
2550 /* Save error info */
2551 MemoryContextSwitchTo(ccxt);
2552 errdata = CopyErrorData();
2556 (errcode(errdata->sqlerrcode),
2557 errmsg("%s", errdata->message),
2558 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2559 errdata->hint ? errhint("%s", errdata->hint) : 0));
2561 FreeErrorData(errdata);
2569 * Sets GUC parameter of int32 type without throwing exceptions. Returns false
2570 * if something wrong.
2573 set_config_int32_option(const char *name, int32 value, GucContext context)
2575 char buf[16]; /* enough for int32 */
2577 if (snprintf(buf, 16, "%d", value) < 0)
2579 ereport(pg_hint_plan_message_level,
2580 (errmsg ("Cannot set integer value: %d: %s",
2581 max_hint_nworkers, strerror(errno))));
2586 set_config_option_noerror(name, buf, context,
2587 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2588 pg_hint_plan_message_level);
2591 /* setup scan method enforcement according to given options */
2593 setup_guc_enforcement(SetHint **options, int noptions, GucContext context)
2597 for (i = 0; i < noptions; i++)
2599 SetHint *hint = options[i];
2602 if (!hint_state_enabled(hint))
2605 result = set_config_option_noerror(hint->name, hint->value, context,
2606 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2607 pg_hint_plan_message_level);
2609 hint->base.state = HINT_STATE_USED;
2611 hint->base.state = HINT_STATE_ERROR;
2618 * Setup parallel execution environment.
2620 * If hint is not NULL, set up using it, elsewise reset to initial environment.
2623 setup_parallel_plan_enforcement(ParallelHint *hint, HintState *state)
2627 hint->base.state = HINT_STATE_USED;
2628 set_config_int32_option("max_parallel_workers_per_gather",
2629 hint->nworkers, state->context);
2632 set_config_int32_option("max_parallel_workers_per_gather",
2633 state->init_nworkers, state->context);
2635 /* force means that enforce parallel as far as possible */
2636 if (hint && hint->force_parallel)
2638 set_config_int32_option("parallel_tuple_cost", 0, state->context);
2639 set_config_int32_option("parallel_setup_cost", 0, state->context);
2640 set_config_int32_option("min_parallel_table_scan_size", 0,
2642 set_config_int32_option("min_parallel_index_scan_size", 0,
2647 set_config_int32_option("parallel_tuple_cost",
2648 state->init_paratup_cost, state->context);
2649 set_config_int32_option("parallel_setup_cost",
2650 state->init_parasetup_cost, state->context);
2651 set_config_int32_option("min_parallel_table_scan_size",
2652 state->init_min_para_tablescan_size,
2654 set_config_int32_option("min_parallel_index_scan_size",
2655 state->init_min_para_indexscan_size,
2660 #define SET_CONFIG_OPTION(name, type_bits) \
2661 set_config_option_noerror((name), \
2662 (mask & (type_bits)) ? "true" : "false", \
2663 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2667 * Setup GUC environment to enforce scan methods. If scanhint is NULL, reset
2668 * GUCs to the saved state in state.
2671 setup_scan_method_enforcement(ScanMethodHint *scanhint, HintState *state)
2673 unsigned char enforce_mask = state->init_scan_mask;
2674 GucContext context = state->context;
2679 enforce_mask = scanhint->enforce_mask;
2680 scanhint->base.state = HINT_STATE_USED;
2683 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2684 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2685 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2687 mask = enforce_mask;
2689 mask = enforce_mask & current_hint_state->init_scan_mask;
2691 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2692 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2693 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2694 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2695 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2699 set_join_config_options(unsigned char enforce_mask, GucContext context)
2703 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2704 enforce_mask == ENABLE_HASHJOIN)
2705 mask = enforce_mask;
2707 mask = enforce_mask & current_hint_state->init_join_mask;
2709 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2710 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2711 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2715 * Push a hint into hint stack which is implemented with List struct. Head of
2716 * list is top of stack.
2719 push_hint(HintState *hstate)
2721 /* Prepend new hint to the list means pushing to stack. */
2722 HintStateStack = lcons(hstate, HintStateStack);
2724 /* Pushed hint is the one which should be used hereafter. */
2725 current_hint_state = hstate;
2728 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2732 /* Hint stack must not be empty. */
2733 if(HintStateStack == NIL)
2734 elog(ERROR, "hint stack is empty");
2737 * Take a hint at the head from the list, and free it. Switch
2738 * current_hint_state to point new head (NULL if the list is empty).
2740 HintStateStack = list_delete_first(HintStateStack);
2741 HintStateDelete(current_hint_state);
2742 if(HintStateStack == NIL)
2743 current_hint_state = NULL;
2745 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
2749 * Retrieve and store a hint string from given query or from the hint table.
2750 * If we are using the hint table, the query string is needed to be normalized.
2751 * However, ParseState, which is not available in planner_hook, is required to
2752 * check if the query tree (Query) is surely corresponding to the target query.
2755 pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query)
2757 const char *query_str;
2758 MemoryContext oldcontext;
2760 if (prev_post_parse_analyze_hook)
2761 prev_post_parse_analyze_hook(pstate, query);
2763 /* do nothing under hint table search */
2764 if (hint_inhibit_level > 0)
2767 if (!pg_hint_plan_enable_hint)
2769 if (current_hint_str)
2771 pfree((void *)current_hint_str);
2772 current_hint_str = NULL;
2777 /* increment the query number */
2779 if (debug_level > 1)
2780 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2783 /* search the hint table for a hint if requested */
2784 if (pg_hint_plan_enable_hint_table)
2787 pgssJumbleState jstate;
2789 char *normalized_query = NULL;
2791 query_str = get_query_string(pstate, query, &jumblequery);
2793 /* If this query is not for hint, just return */
2797 /* clear the previous hint string */
2798 if (current_hint_str)
2800 pfree((void *)current_hint_str);
2801 current_hint_str = NULL;
2807 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2808 * careful to PostgreSQL's version up.
2810 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2811 jstate.jumble_len = 0;
2812 jstate.clocations_buf_size = 32;
2813 jstate.clocations = (pgssLocationLen *)
2814 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2815 jstate.clocations_count = 0;
2817 JumbleQuery(&jstate, jumblequery);
2820 * Normalize the query string by replacing constants with '?'
2823 * Search hint string which is stored keyed by query string
2824 * and application name. The query string is normalized to allow
2827 * Adding 1 byte to query_len ensures that the returned string has
2828 * a terminating NULL.
2830 query_len = strlen(query_str) + 1;
2832 generate_normalized_query(&jstate, query_str,
2834 GetDatabaseEncoding());
2837 * find a hint for the normalized query. the result should be in
2840 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2842 get_hints_from_table(normalized_query, application_name);
2843 MemoryContextSwitchTo(oldcontext);
2845 if (debug_level > 1)
2847 if (current_hint_str)
2848 ereport(pg_hint_plan_message_level,
2849 (errmsg("pg_hint_plan[qno=0x%x]: "
2850 "post_parse_analyze_hook: "
2851 "hints from table: \"%s\": "
2852 "normalized_query=\"%s\", "
2853 "application name =\"%s\"",
2854 qno, current_hint_str,
2855 normalized_query, application_name),
2856 errhidestmt(msgqno != qno),
2857 errhidecontext(msgqno != qno)));
2859 ereport(pg_hint_plan_message_level,
2860 (errmsg("pg_hint_plan[qno=0x%x]: "
2861 "no match found in table: "
2862 "application name = \"%s\", "
2863 "normalized_query=\"%s\"",
2864 qno, application_name,
2866 errhidestmt(msgqno != qno),
2867 errhidecontext(msgqno != qno)));
2873 /* retrun if we have hint here */
2874 if (current_hint_str)
2878 query_str = get_query_string(pstate, query, NULL);
2883 * get hints from the comment. However we may have the same query
2884 * string with the previous call, but just retrieving hints is expected
2885 * to be faster than checking for identicalness before retrieval.
2887 if (current_hint_str)
2888 pfree((void *)current_hint_str);
2890 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2891 current_hint_str = get_hints_from_comment(query_str);
2892 MemoryContextSwitchTo(oldcontext);
2895 if (debug_level > 1)
2897 if (debug_level == 1 &&
2898 (stmt_name || strcmp(query_str, debug_query_string)))
2899 ereport(pg_hint_plan_message_level,
2900 (errmsg("hints in comment=\"%s\"",
2901 current_hint_str ? current_hint_str : "(none)"),
2902 errhidestmt(msgqno != qno),
2903 errhidecontext(msgqno != qno)));
2905 ereport(pg_hint_plan_message_level,
2906 (errmsg("hints in comment=\"%s\", stmt=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2907 current_hint_str ? current_hint_str : "(none)",
2908 stmt_name, query_str, debug_query_string),
2909 errhidestmt(msgqno != qno),
2910 errhidecontext(msgqno != qno)));
2916 * Read and set up hint information
2918 static PlannedStmt *
2919 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2922 PlannedStmt *result;
2926 * Use standard planner if pg_hint_plan is disabled or current nesting
2927 * depth is nesting depth of SPI calls. Other hook functions try to change
2928 * plan with current_hint_state if any, so set it to NULL.
2930 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2932 if (debug_level > 1)
2933 ereport(pg_hint_plan_message_level,
2934 (errmsg ("pg_hint_plan%s: planner: enable_hint=%d,"
2935 " hint_inhibit_level=%d",
2936 qnostr, pg_hint_plan_enable_hint,
2937 hint_inhibit_level),
2938 errhidestmt(msgqno != qno)));
2941 goto standard_planner_proc;
2945 * Support for nested plpgsql functions. This is quite ugly but this is the
2946 * only point I could find where I can get the query string.
2948 if (plpgsql_recurse_level > 0)
2950 MemoryContext oldcontext;
2952 if (current_hint_str)
2953 pfree((void *)current_hint_str);
2955 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2957 get_hints_from_comment((char *)error_context_stack->arg);
2958 MemoryContextSwitchTo(oldcontext);
2961 if (!current_hint_str)
2962 goto standard_planner_proc;
2964 /* parse the hint into hint state struct */
2965 hstate = create_hintstate(parse, pstrdup(current_hint_str));
2967 /* run standard planner if the statement has not valid hint */
2969 goto standard_planner_proc;
2972 * Push new hint struct to the hint stack to disable previous hint context.
2976 /* Set scan enforcement here. */
2977 save_nestlevel = NewGUCNestLevel();
2979 /* Apply Set hints, then save it as the initial state */
2980 setup_guc_enforcement(current_hint_state->set_hints,
2981 current_hint_state->num_hints[HINT_TYPE_SET],
2982 current_hint_state->context);
2984 current_hint_state->init_scan_mask = get_current_scan_mask();
2985 current_hint_state->init_join_mask = get_current_join_mask();
2986 current_hint_state->init_min_para_tablescan_size =
2987 min_parallel_table_scan_size;
2988 current_hint_state->init_min_para_indexscan_size =
2989 min_parallel_index_scan_size;
2990 current_hint_state->init_paratup_cost = parallel_tuple_cost;
2991 current_hint_state->init_parasetup_cost = parallel_setup_cost;
2994 * max_parallel_workers_per_gather should be non-zero here if Workers hint
2997 if (max_hint_nworkers > 0 && max_parallel_workers_per_gather < 1)
2998 set_config_int32_option("max_parallel_workers_per_gather",
2999 1, current_hint_state->context);
3000 current_hint_state->init_nworkers = max_parallel_workers_per_gather;
3002 if (debug_level > 1)
3004 ereport(pg_hint_plan_message_level,
3005 (errhidestmt(msgqno != qno),
3006 errmsg("pg_hint_plan%s: planner", qnostr)));
3011 * Use PG_TRY mechanism to recover GUC parameters and current_hint_state to
3012 * the state when this planner started when error occurred in planner.
3017 result = (*prev_planner) (parse, cursorOptions, boundParams);
3019 result = standard_planner(parse, cursorOptions, boundParams);
3024 * Rollback changes of GUC parameters, and pop current hint context
3025 * from hint stack to rewind the state.
3027 AtEOXact_GUC(true, save_nestlevel);
3033 /* Print hint in debug mode. */
3034 if (debug_level == 1)
3035 HintStateDump(current_hint_state);
3036 else if (debug_level > 1)
3037 HintStateDump2(current_hint_state);
3040 * Rollback changes of GUC parameters, and pop current hint context from
3041 * hint stack to rewind the state.
3043 AtEOXact_GUC(true, save_nestlevel);
3048 standard_planner_proc:
3049 if (debug_level > 1)
3051 ereport(pg_hint_plan_message_level,
3052 (errhidestmt(msgqno != qno),
3053 errmsg("pg_hint_plan%s: planner: no valid hint",
3057 current_hint_state = NULL;
3059 return (*prev_planner) (parse, cursorOptions, boundParams);
3061 return standard_planner(parse, cursorOptions, boundParams);
3065 * Find scan method hint to be applied to the given relation
3068 static ScanMethodHint *
3069 find_scan_hint(PlannerInfo *root, Index relid)
3073 ScanMethodHint *real_name_hint = NULL;
3074 ScanMethodHint *alias_hint = NULL;
3077 /* This should not be a join rel */
3079 rel = root->simple_rel_array[relid];
3082 * This function is called for any RelOptInfo or its inheritance parent if
3083 * any. If we are called from inheritance planner, the RelOptInfo for the
3084 * parent of target child relation is not set in the planner info.
3086 * Otherwise we should check that the reloptinfo is base relation or
3087 * inheritance children.
3090 rel->reloptkind != RELOPT_BASEREL &&
3091 rel->reloptkind != RELOPT_OTHER_MEMBER_REL)
3095 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3097 rte = root->simple_rte_array[relid];
3100 /* We don't hint on other than relation and foreign tables */
3101 if (rte->rtekind != RTE_RELATION ||
3102 rte->relkind == RELKIND_FOREIGN_TABLE)
3105 /* Find scan method hint, which matches given names, from the list. */
3106 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
3108 ScanMethodHint *hint = current_hint_state->scan_hints[i];
3110 /* We ignore disabled hints. */
3111 if (!hint_state_enabled(hint))
3115 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3118 /* check the real name for appendrel children */
3119 if (!real_name_hint &&
3120 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3122 char *realname = get_rel_name(rte->relid);
3124 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3125 real_name_hint = hint;
3128 /* No more match expected, break */
3129 if(alias_hint && real_name_hint)
3133 /* real name match precedes alias match */
3135 return real_name_hint;
3140 static ParallelHint *
3141 find_parallel_hint(PlannerInfo *root, Index relid)
3145 ParallelHint *real_name_hint = NULL;
3146 ParallelHint *alias_hint = NULL;
3149 /* This should not be a join rel */
3151 rel = root->simple_rel_array[relid];
3154 * Parallel planning is appliable only on base relation, which has
3161 * We have set root->glob->parallelModeOK if needed. What we should do here
3162 * is just following the decision of planner.
3164 if (!rel->consider_parallel)
3168 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3170 rte = root->simple_rte_array[relid];
3173 /* Find parallel method hint, which matches given names, from the list. */
3174 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_PARALLEL]; i++)
3176 ParallelHint *hint = current_hint_state->parallel_hints[i];
3178 /* We ignore disabled hints. */
3179 if (!hint_state_enabled(hint))
3183 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3186 /* check the real name for appendrel children */
3187 if (!real_name_hint &&
3188 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3190 char *realname = get_rel_name(rte->relid);
3192 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3193 real_name_hint = hint;
3196 /* No more match expected, break */
3197 if(alias_hint && real_name_hint)
3201 /* real name match precedes alias match */
3203 return real_name_hint;
3211 * Returns TRUE on match, FALSE on no match.
3213 * s1 --- the data to match against
3214 * s2 --- the pattern
3216 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
3219 regexpeq(const char *s1, const char *s2)
3225 strcpy(name.data, s1);
3226 regexp = cstring_to_text(s2);
3228 result = DirectFunctionCall2Coll(nameregexeq,
3229 DEFAULT_COLLATION_OID,
3230 NameGetDatum(&name),
3231 PointerGetDatum(regexp));
3232 return DatumGetBool(result);
3236 /* Remove indexes instructed not to use by hint. */
3238 restrict_indexes(PlannerInfo *root, ScanMethodHint *hint, RelOptInfo *rel,
3239 bool using_parent_hint)
3245 RangeTblEntry *rte = root->simple_rte_array[rel->relid];
3246 Oid relationObjectId = rte->relid;
3249 * We delete all the IndexOptInfo list and prevent you from being usable by
3252 if (hint->enforce_mask == ENABLE_SEQSCAN ||
3253 hint->enforce_mask == ENABLE_TIDSCAN)
3255 list_free_deep(rel->indexlist);
3256 rel->indexlist = NIL;
3257 hint->base.state = HINT_STATE_USED;
3263 * When a list of indexes is not specified, we just use all indexes.
3265 if (hint->indexnames == NIL)
3269 * Leaving only an specified index, we delete it from a IndexOptInfo list
3273 if (debug_level > 0)
3274 initStringInfo(&buf);
3276 for (cell = list_head(rel->indexlist); cell; cell = next)
3278 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
3279 char *indexname = get_rel_name(info->indexoid);
3281 bool use_index = false;
3285 foreach(l, hint->indexnames)
3287 char *hintname = (char *) lfirst(l);
3291 result = regexpeq(indexname, hintname);
3293 result = RelnameCmp(&indexname, &hintname) == 0;
3298 if (debug_level > 0)
3300 appendStringInfoCharMacro(&buf, ' ');
3301 quote_value(&buf, indexname);
3309 * Apply index restriction of parent hint to children. Since index
3310 * inheritance is not explicitly described we should search for an
3311 * children's index with the same definition to that of the parent.
3313 if (using_parent_hint && !use_index)
3315 foreach(l, current_hint_state->parent_index_infos)
3319 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
3322 * we check the 'same' index by comparing uniqueness, access
3323 * method and index key columns.
3325 if (p_info->indisunique != info->unique ||
3326 p_info->method != info->relam ||
3327 list_length(p_info->column_names) != info->ncolumns)
3330 /* Check if index key columns match */
3331 for (i = 0; i < info->ncolumns; i++)
3333 char *c_attname = NULL;
3334 char *p_attname = NULL;
3336 p_attname = list_nth(p_info->column_names, i);
3339 * if both of the key of the same position are expressions,
3340 * ignore them for now and check later.
3342 if (info->indexkeys[i] == 0 && !p_attname)
3345 /* deny if one is expression while another is not */
3346 if (info->indexkeys[i] == 0 || !p_attname)
3349 c_attname = get_attname(relationObjectId,
3350 info->indexkeys[i]);
3352 /* deny if any of column attributes don't match */
3353 if (strcmp(p_attname, c_attname) != 0 ||
3354 p_info->indcollation[i] != info->indexcollations[i] ||
3355 p_info->opclass[i] != info->opcintype[i]||
3356 ((p_info->indoption[i] & INDOPTION_DESC) != 0)
3357 != info->reverse_sort[i] ||
3358 ((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0)
3359 != info->nulls_first[i])
3363 /* deny this if any difference found */
3364 if (i != info->ncolumns)
3367 /* check on key expressions */
3368 if ((p_info->expression_str && (info->indexprs != NIL)) ||
3369 (p_info->indpred_str && (info->indpred != NIL)))
3371 /* fetch the index of this child */
3372 ht_idx = SearchSysCache1(INDEXRELID,
3373 ObjectIdGetDatum(info->indexoid));
3375 /* check expressions if both expressions are available */
3376 if (p_info->expression_str &&
3377 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
3384 * to change the expression's parameter of child's
3387 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3388 Anum_pg_index_indexprs,
3391 result = DirectFunctionCall2(pg_get_expr,
3396 /* deny if expressions don't match */
3397 if (strcmp(p_info->expression_str,
3398 text_to_cstring(DatumGetTextP(result))) != 0)
3401 ReleaseSysCache(ht_idx);
3406 /* compare index predicates */
3407 if (p_info->indpred_str &&
3408 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
3414 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3415 Anum_pg_index_indpred,
3418 result = DirectFunctionCall2(pg_get_expr,
3423 if (strcmp(p_info->indpred_str,
3424 text_to_cstring(DatumGetTextP(result))) != 0)
3427 ReleaseSysCache(ht_idx);
3433 ReleaseSysCache(ht_idx);
3435 else if (p_info->expression_str || (info->indexprs != NIL))
3437 else if (p_info->indpred_str || (info->indpred != NIL))
3442 /* to log the candidate of index */
3443 if (debug_level > 0)
3445 appendStringInfoCharMacro(&buf, ' ');
3446 quote_value(&buf, indexname);
3454 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
3461 if (debug_level == 1)
3463 StringInfoData rel_buf;
3464 char *disprelname = "";
3467 * If this hint targetted the parent, use the real name of this
3468 * child. Otherwise use hint specification.
3470 if (using_parent_hint)
3471 disprelname = get_rel_name(rte->relid);
3473 disprelname = hint->relname;
3476 initStringInfo(&rel_buf);
3477 quote_value(&rel_buf, disprelname);
3480 (errmsg("available indexes for %s(%s):%s",
3485 pfree(rel_buf.data);
3490 * Return information of index definition.
3492 static ParentIndexInfo *
3493 get_parent_index_info(Oid indexoid, Oid relid)
3495 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3496 Relation indexRelation;
3497 Form_pg_index index;
3501 indexRelation = index_open(indexoid, RowExclusiveLock);
3503 index = indexRelation->rd_index;
3505 p_info->indisunique = index->indisunique;
3506 p_info->method = indexRelation->rd_rel->relam;
3508 p_info->column_names = NIL;
3509 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3510 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3511 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3513 for (i = 0; i < index->indnatts; i++)
3515 attname = get_attname(relid, index->indkey.values[i]);
3516 p_info->column_names = lappend(p_info->column_names, attname);
3518 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3519 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3520 p_info->indoption[i] = indexRelation->rd_indoption[i];
3524 * to check to match the expression's parameter of index with child indexes
3526 p_info->expression_str = NULL;
3527 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
3533 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3534 Anum_pg_index_indexprs, &isnull);
3536 result = DirectFunctionCall2(pg_get_expr,
3538 ObjectIdGetDatum(relid));
3540 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3544 * to check to match the predicate's parameter of index with child indexes
3546 p_info->indpred_str = NULL;
3547 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
3553 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3554 Anum_pg_index_indpred, &isnull);
3556 result = DirectFunctionCall2(pg_get_expr,
3558 ObjectIdGetDatum(relid));
3560 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3563 index_close(indexRelation, NoLock);
3569 * cancel hint enforcement
3572 reset_hint_enforcement()
3574 setup_scan_method_enforcement(NULL, current_hint_state);
3575 setup_parallel_plan_enforcement(NULL, current_hint_state);
3579 * Set planner guc parameters according to corresponding scan hints. Returns
3580 * bitmap of HintTypeBitmap. If shint or phint is not NULL, set used hint
3581 * there respectively.
3584 setup_hint_enforcement(PlannerInfo *root, RelOptInfo *rel,
3585 ScanMethodHint **rshint, ParallelHint **rphint)
3587 Index new_parent_relid = 0;
3589 ScanMethodHint *shint = NULL;
3590 ParallelHint *phint = NULL;
3591 bool inhparent = root->simple_rte_array[rel->relid]->inh;
3592 Oid relationObjectId = root->simple_rte_array[rel->relid]->relid;
3595 /* reset returns if requested */
3596 if (rshint != NULL) *rshint = NULL;
3597 if (rphint != NULL) *rphint = NULL;
3600 * We could register the parent relation of the following children here
3601 * when inhparent == true but inheritnce planner doesn't call this function
3602 * for parents. Since we cannot distinguish who called this function we
3603 * cannot do other than always seeking the parent regardless of who called
3608 if (debug_level > 1)
3609 ereport(pg_hint_plan_message_level,
3611 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3612 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3613 " current_hint_state=%p, hint_inhibit_level=%d",
3614 qnostr, relationObjectId,
3615 get_rel_name(relationObjectId),
3616 inhparent, current_hint_state, hint_inhibit_level)));
3620 /* Find the parent for this relation other than the registered parent */
3621 foreach (l, root->append_rel_list)
3623 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3625 if (appinfo->child_relid == rel->relid)
3627 if (current_hint_state->parent_relid != appinfo->parent_relid)
3628 new_parent_relid = appinfo->parent_relid;
3635 /* This relation doesn't have a parent. Cancel current_hint_state. */
3636 current_hint_state->parent_relid = 0;
3637 current_hint_state->parent_scan_hint = NULL;
3638 current_hint_state->parent_parallel_hint = NULL;
3641 if (new_parent_relid > 0)
3644 * Here we found a new parent for the current relation. Scan continues
3645 * hint to other childrens of this parent so remember it * to avoid
3646 * hinthintredundant setup cost.
3648 current_hint_state->parent_relid = new_parent_relid;
3650 /* Find hints for the parent */
3651 current_hint_state->parent_scan_hint =
3652 find_scan_hint(root, current_hint_state->parent_relid);
3654 current_hint_state->parent_parallel_hint =
3655 find_parallel_hint(root, current_hint_state->parent_relid);
3658 * If hint is found for the parent, apply it for this child instead
3661 if (current_hint_state->parent_scan_hint)
3663 ScanMethodHint * pshint = current_hint_state->parent_scan_hint;
3665 pshint->base.state = HINT_STATE_USED;
3667 /* Apply index mask in the same manner to the parent. */
3668 if (pshint->indexnames)
3671 Relation parent_rel;
3674 root->simple_rte_array[current_hint_state->parent_relid]->relid;
3675 parent_rel = heap_open(parentrel_oid, NoLock);
3677 /* Search the parent relation for indexes match the hint spec */
3678 foreach(l, RelationGetIndexList(parent_rel))
3680 Oid indexoid = lfirst_oid(l);
3681 char *indexname = get_rel_name(indexoid);
3683 ParentIndexInfo *parent_index_info;
3685 foreach(lc, pshint->indexnames)
3687 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3694 get_parent_index_info(indexoid, parentrel_oid);
3695 current_hint_state->parent_index_infos =
3696 lappend(current_hint_state->parent_index_infos,
3699 heap_close(parent_rel, NoLock);
3704 shint = find_scan_hint(root, rel->relid);
3706 shint = current_hint_state->parent_scan_hint;
3710 bool using_parent_hint =
3711 (shint == current_hint_state->parent_scan_hint);
3713 ret |= HINT_BM_SCAN_METHOD;
3715 /* Setup scan enforcement environment */
3716 setup_scan_method_enforcement(shint, current_hint_state);
3718 /* restrict unwanted inexes */
3719 restrict_indexes(root, shint, rel, using_parent_hint);
3721 if (debug_level > 1)
3723 char *additional_message = "";
3725 if (shint == current_hint_state->parent_scan_hint)
3726 additional_message = " by parent hint";
3728 ereport(pg_hint_plan_message_level,
3730 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3731 " index deletion%s:"
3732 " relation=%u(%s), inhparent=%d, "
3733 "current_hint_state=%p,"
3734 " hint_inhibit_level=%d, scanmask=0x%x",
3735 qnostr, additional_message,
3737 get_rel_name(relationObjectId),
3738 inhparent, current_hint_state,
3740 shint->enforce_mask)));
3744 /* Do the same for parallel plan enforcement */
3745 phint = find_parallel_hint(root, rel->relid);
3747 phint = current_hint_state->parent_parallel_hint;
3749 setup_parallel_plan_enforcement(phint, current_hint_state);
3752 ret |= HINT_BM_PARALLEL;
3754 /* Nothing to apply. Reset the scan mask to intial state */
3755 if (!shint && ! phint)
3757 if (debug_level > 1)
3758 ereport(pg_hint_plan_message_level,
3759 (errhidestmt (true),
3760 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3762 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3763 " hint_inhibit_level=%d, scanmask=0x%x",
3764 qnostr, relationObjectId,
3765 get_rel_name(relationObjectId),
3766 inhparent, current_hint_state, hint_inhibit_level,
3767 current_hint_state->init_scan_mask)));
3769 setup_scan_method_enforcement(NULL, current_hint_state);
3774 if (rshint != NULL) *rshint = shint;
3775 if (rphint != NULL) *rphint = phint;
3781 * Return index of relation which matches given aliasname, or 0 if not found.
3782 * If same aliasname was used multiple times in a query, return -1.
3785 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3791 for (i = 1; i < root->simple_rel_array_size; i++)
3795 if (root->simple_rel_array[i] == NULL)
3798 Assert(i == root->simple_rel_array[i]->relid);
3800 if (RelnameCmp(&aliasname,
3801 &root->simple_rte_array[i]->eref->aliasname) != 0)
3804 foreach(l, initial_rels)
3806 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3808 if (rel->reloptkind == RELOPT_BASEREL)
3810 if (rel->relid != i)
3815 Assert(rel->reloptkind == RELOPT_JOINREL);
3817 if (!bms_is_member(i, rel->relids))
3824 ("Relation name \"%s\" is ambiguous.",
3839 * Return join hint which matches given joinrelids.
3841 static JoinMethodHint *
3842 find_join_hint(Relids joinrelids)
3847 join_hint = current_hint_state->join_hint_level[bms_num_members(joinrelids)];
3849 foreach(l, join_hint)
3851 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3853 if (bms_equal(joinrelids, hint->joinrelids))
3861 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3862 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3864 OuterInnerRels *outer_rels;
3865 OuterInnerRels *inner_rels;
3866 Relids outer_relids;
3867 Relids inner_relids;
3869 JoinMethodHint *hint;
3871 if (outer_inner->relation != NULL)
3873 return bms_make_singleton(
3874 find_relid_aliasname(root, outer_inner->relation,
3876 leading_hint->base.hint_str));
3879 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3880 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3882 outer_relids = OuterInnerJoinCreate(outer_rels,
3888 inner_relids = OuterInnerJoinCreate(inner_rels,
3895 join_relids = bms_add_members(outer_relids, inner_relids);
3897 if (bms_num_members(join_relids) > nbaserel)
3901 * If we don't have join method hint, create new one for the
3902 * join combination with all join methods are enabled.
3904 hint = find_join_hint(join_relids);
3908 * Here relnames is not set, since Relids bitmap is sufficient to
3909 * control paths of this query afterward.
3911 hint = (JoinMethodHint *) JoinMethodHintCreate(
3912 leading_hint->base.hint_str,
3914 HINT_KEYWORD_LEADING);
3915 hint->base.state = HINT_STATE_USED;
3916 hint->nrels = bms_num_members(join_relids);
3917 hint->enforce_mask = ENABLE_ALL_JOIN;
3918 hint->joinrelids = bms_copy(join_relids);
3919 hint->inner_nrels = bms_num_members(inner_relids);
3920 hint->inner_joinrelids = bms_copy(inner_relids);
3922 hstate->join_hint_level[hint->nrels] =
3923 lappend(hstate->join_hint_level[hint->nrels], hint);
3927 hint->inner_nrels = bms_num_members(inner_relids);
3928 hint->inner_joinrelids = bms_copy(inner_relids);
3935 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3936 int nrels, char **relnames)
3939 Relids relids = NULL;
3943 for (j = 0; j < nrels; j++)
3945 relname = relnames[j];
3947 relid = find_relid_aliasname(root, relname, initial_rels,
3951 base->state = HINT_STATE_ERROR;
3954 * the aliasname is not found(relid == 0) or same aliasname was used
3955 * multiple times in a query(relid == -1)
3962 if (bms_is_member(relid, relids))
3964 hint_ereport(base->hint_str,
3965 ("Relation name \"%s\" is duplicated.", relname));
3966 base->state = HINT_STATE_ERROR;
3970 relids = bms_add_member(relids, relid);
3975 * Transform join method hint into handy form.
3977 * - create bitmap of relids from alias names, to make it easier to check
3978 * whether a join path matches a join method hint.
3979 * - add join method hints which are necessary to enforce join order
3980 * specified by Leading hint
3983 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
3984 List *initial_rels, JoinMethodHint **join_method_hints)
3992 LeadingHint *lhint = NULL;
3995 * Create bitmap of relids from alias names for each join method hint.
3996 * Bitmaps are more handy than strings in join searching.
3998 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
4000 JoinMethodHint *hint = hstate->join_hints[i];
4002 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4005 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4006 initial_rels, hint->nrels, hint->relnames);
4008 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
4011 hstate->join_hint_level[hint->nrels] =
4012 lappend(hstate->join_hint_level[hint->nrels], hint);
4016 * Create bitmap of relids from alias names for each rows hint.
4017 * Bitmaps are more handy than strings in join searching.
4019 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
4021 RowsHint *hint = hstate->rows_hints[i];
4023 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4026 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4027 initial_rels, hint->nrels, hint->relnames);
4030 /* Do nothing if no Leading hint was supplied. */
4031 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
4035 * Decide whether to use Leading hint
4037 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
4039 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
4042 if (leading_hint->base.state == HINT_STATE_ERROR)
4048 foreach(l, leading_hint->relations)
4050 relname = (char *)lfirst(l);;
4052 relid = find_relid_aliasname(root, relname, initial_rels,
4053 leading_hint->base.hint_str);
4055 leading_hint->base.state = HINT_STATE_ERROR;
4060 if (bms_is_member(relid, relids))
4062 hint_ereport(leading_hint->base.hint_str,
4063 ("Relation name \"%s\" is duplicated.", relname));
4064 leading_hint->base.state = HINT_STATE_ERROR;
4068 relids = bms_add_member(relids, relid);
4071 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
4076 hint_ereport(lhint->base.hint_str,
4077 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
4078 lhint->base.state = HINT_STATE_DUPLICATION;
4080 leading_hint->base.state = HINT_STATE_USED;
4081 lhint = leading_hint;
4084 /* check to exist Leading hint marked with 'used'. */
4089 * We need join method hints which fit specified join order in every join
4090 * level. For example, Leading(A B C) virtually requires following join
4091 * method hints, if no join method hint supplied:
4093 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
4094 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
4096 * If we already have join method hint which fits specified join order in
4097 * that join level, we leave it as-is and don't add new hints.
4101 if (lhint->outer_inner == NULL)
4103 foreach(l, lhint->relations)
4105 JoinMethodHint *hint;
4107 relname = (char *)lfirst(l);
4110 * Find relid of the relation which has given name. If we have the
4111 * name given in Leading hint multiple times in the join, nothing to
4114 relid = find_relid_aliasname(root, relname, initial_rels,
4117 /* Create bitmap of relids for current join level. */
4118 joinrelids = bms_add_member(joinrelids, relid);
4121 /* We never have join method hint for single relation. */
4126 * If we don't have join method hint, create new one for the
4127 * join combination with all join methods are enabled.
4129 hint = find_join_hint(joinrelids);
4133 * Here relnames is not set, since Relids bitmap is sufficient
4134 * to control paths of this query afterward.
4136 hint = (JoinMethodHint *) JoinMethodHintCreate(
4137 lhint->base.hint_str,
4139 HINT_KEYWORD_LEADING);
4140 hint->base.state = HINT_STATE_USED;
4141 hint->nrels = njoinrels;
4142 hint->enforce_mask = ENABLE_ALL_JOIN;
4143 hint->joinrelids = bms_copy(joinrelids);
4146 join_method_hints[njoinrels] = hint;
4148 if (njoinrels >= nbaserel)
4151 bms_free(joinrelids);
4157 * Delete all join hints which have different combination from Leading
4160 for (i = 2; i <= njoinrels; i++)
4162 list_free(hstate->join_hint_level[i]);
4164 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
4169 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
4176 njoinrels = bms_num_members(joinrelids);
4177 Assert(njoinrels >= 2);
4180 * Delete all join hints which have different combination from Leading
4183 for (i = 2;i <= njoinrels; i++)
4185 if (hstate->join_hint_level[i] != NIL)
4187 ListCell *prev = NULL;
4188 ListCell *next = NULL;
4189 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
4192 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
4196 if (hint->inner_nrels == 0 &&
4197 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
4198 bms_equal(bms_union(hint->joinrelids, joinrelids),
4201 hstate->join_hint_level[i] =
4202 list_delete_cell(hstate->join_hint_level[i], l,
4211 bms_free(joinrelids);
4214 if (hint_state_enabled(lhint))
4216 set_join_config_options(DISABLE_ALL_JOIN, current_hint_state->context);
4223 * wrapper of make_join_rel()
4225 * call make_join_rel() after changing enable_* parameters according to given
4229 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
4232 JoinMethodHint *hint;
4236 joinrelids = bms_union(rel1->relids, rel2->relids);
4237 hint = find_join_hint(joinrelids);
4238 bms_free(joinrelids);
4241 return pg_hint_plan_make_join_rel(root, rel1, rel2);
4243 if (hint->inner_nrels == 0)
4245 save_nestlevel = NewGUCNestLevel();
4247 set_join_config_options(hint->enforce_mask,
4248 current_hint_state->context);
4250 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4251 hint->base.state = HINT_STATE_USED;
4254 * Restore the GUC variables we set above.
4256 AtEOXact_GUC(true, save_nestlevel);
4259 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4268 add_paths_to_joinrel_wrapper(PlannerInfo *root,
4269 RelOptInfo *joinrel,
4270 RelOptInfo *outerrel,
4271 RelOptInfo *innerrel,
4273 SpecialJoinInfo *sjinfo,
4277 JoinMethodHint *join_hint;
4280 joinrelids = bms_union(outerrel->relids, innerrel->relids);
4281 join_hint = find_join_hint(joinrelids);
4282 bms_free(joinrelids);
4284 if (join_hint && join_hint->inner_nrels != 0)
4286 save_nestlevel = NewGUCNestLevel();
4288 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
4291 set_join_config_options(join_hint->enforce_mask,
4292 current_hint_state->context);
4294 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4295 sjinfo, restrictlist);
4296 join_hint->base.state = HINT_STATE_USED;
4300 set_join_config_options(DISABLE_ALL_JOIN,
4301 current_hint_state->context);
4302 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4303 sjinfo, restrictlist);
4307 * Restore the GUC variables we set above.
4309 AtEOXact_GUC(true, save_nestlevel);
4312 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4313 sjinfo, restrictlist);
4317 get_num_baserels(List *initial_rels)
4322 foreach(l, initial_rels)
4324 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
4326 if (rel->reloptkind == RELOPT_BASEREL)
4328 else if (rel->reloptkind ==RELOPT_JOINREL)
4329 nbaserel+= bms_num_members(rel->relids);
4332 /* other values not expected here */
4333 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
4341 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
4344 JoinMethodHint **join_method_hints;
4348 bool leading_hint_enable;
4351 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
4352 * valid hint is supplied or current nesting depth is nesting depth of SPI
4355 if (!current_hint_state || hint_inhibit_level > 0)
4357 if (prev_join_search)
4358 return (*prev_join_search) (root, levels_needed, initial_rels);
4359 else if (enable_geqo && levels_needed >= geqo_threshold)
4360 return geqo(root, levels_needed, initial_rels);
4362 return standard_join_search(root, levels_needed, initial_rels);
4366 * In the case using GEQO, only scan method hints and Set hints have
4367 * effect. Join method and join order is not controllable by hints.
4369 if (enable_geqo && levels_needed >= geqo_threshold)
4370 return geqo(root, levels_needed, initial_rels);
4372 nbaserel = get_num_baserels(initial_rels);
4373 current_hint_state->join_hint_level =
4374 palloc0(sizeof(List *) * (nbaserel + 1));
4375 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4377 leading_hint_enable = transform_join_hints(current_hint_state,
4379 initial_rels, join_method_hints);
4381 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4383 for (i = 2; i <= nbaserel; i++)
4385 list_free(current_hint_state->join_hint_level[i]);
4387 /* free Leading hint only */
4388 if (join_method_hints[i] != NULL &&
4389 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4390 JoinMethodHintDelete(join_method_hints[i]);
4392 pfree(current_hint_state->join_hint_level);
4393 pfree(join_method_hints);
4395 if (leading_hint_enable)
4396 set_join_config_options(current_hint_state->init_join_mask,
4397 current_hint_state->context);
4403 * Force number of wokers if instructed by hint
4406 pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
4407 Index rti, RangeTblEntry *rte)
4409 ParallelHint *phint;
4413 /* call the previous hook */
4414 if (prev_set_rel_pathlist)
4415 prev_set_rel_pathlist(root, rel, rti, rte);
4417 /* Nothing to do if no hint available */
4418 if (current_hint_state == NULL)
4421 /* Don't touch dummy rels. */
4422 if (IS_DUMMY_REL(rel))
4426 * We can accept only plain relations, foreign tables and table saples are
4427 * also unacceptable. See set_rel_pathlist.
4429 if (rel->rtekind != RTE_RELATION ||
4430 rte->relkind == RELKIND_FOREIGN_TABLE ||
4431 rte->tablesample != NULL)
4434 /* We cannot handle if this requires an outer */
4435 if (rel->lateral_relids)
4438 /* Return if this relation gets no enfocement */
4439 if ((found_hints = setup_hint_enforcement(root, rel, NULL, &phint)) == 0)
4442 /* Here, we regenerate paths with the current hint restriction */
4443 if (found_hints & HINT_BM_SCAN_METHOD || found_hints & HINT_BM_PARALLEL)
4445 /* Just discard all the paths considered so far */
4446 list_free_deep(rel->pathlist);
4447 rel->pathlist = NIL;
4449 /* Remove all the partial paths if Parallel hint is specfied */
4450 if ((found_hints & HINT_BM_PARALLEL) && rel->partial_pathlist)
4452 list_free_deep(rel->partial_pathlist);
4453 rel->partial_pathlist = NIL;
4456 /* Regenerate paths with the current enforcement */
4457 set_plain_rel_pathlist(root, rel, rte);
4459 /* Additional work to enforce parallel query execution */
4460 if (phint && phint->nworkers > 0)
4462 /* Lower the priorities of non-parallel paths */
4463 foreach (l, rel->pathlist)
4465 Path *path = (Path *) lfirst(l);
4467 if (path->startup_cost < disable_cost)
4469 path->startup_cost += disable_cost;
4470 path->total_cost += disable_cost;
4474 /* enforce number of workers if requested */
4475 if (phint->force_parallel)
4477 foreach (l, rel->partial_pathlist)
4479 Path *ppath = (Path *) lfirst(l);
4481 ppath->parallel_workers = phint->nworkers;
4485 /* Generate gather paths for base rels */
4486 if (rel->reloptkind == RELOPT_BASEREL)
4487 generate_gather_paths(root, rel);
4491 reset_hint_enforcement();
4496 * Build access paths for a base relation
4498 * This function was copied and edited from set_rel_pathlist() in
4499 * src/backend/optimizer/path/allpaths.c in order not to copy other static
4500 * functions not required here.
4503 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4504 Index rti, RangeTblEntry *rte)
4506 if (IS_DUMMY_REL(rel))
4508 /* We already proved the relation empty, so nothing more to do */
4512 /* It's an "append relation", process accordingly */
4513 set_append_rel_pathlist(root, rel, rti, rte);
4517 if (rel->rtekind == RTE_RELATION)
4519 if (rte->relkind == RELKIND_RELATION)
4521 if(rte->tablesample != NULL)
4522 elog(ERROR, "sampled relation is not supported");
4524 /* Plain relation */
4525 set_plain_rel_pathlist(root, rel, rte);
4528 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4531 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4535 * Allow a plugin to editorialize on the set of Paths for this base
4536 * relation. It could add new paths (such as CustomPaths) by calling
4537 * add_path(), or delete or modify paths added by the core code.
4539 if (set_rel_pathlist_hook)
4540 (*set_rel_pathlist_hook) (root, rel, rti, rte);
4542 /* Now find the cheapest of the paths for this rel */
4547 * stmt_beg callback is called when each query in PL/pgSQL function is about
4548 * to be executed. At that timing, we save query string in the global variable
4549 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4550 * variable for the purpose, because its content is only necessary until
4551 * planner hook is called for the query, so recursive PL/pgSQL function calls
4552 * don't harm this mechanism.
4555 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4557 plpgsql_recurse_level++;
4561 * stmt_end callback is called then each query in PL/pgSQL function has
4562 * finished. At that timing, we clear plpgsql_query_string to tell planner
4563 * hook that next call is not for a query written in PL/pgSQL block.
4566 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4568 plpgsql_recurse_level--;
4571 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4576 if (phase != RESOURCE_RELEASE_AFTER_LOCKS)
4578 /* Cancel plpgsql nest level*/
4579 plpgsql_recurse_level = 0;
4582 #define standard_join_search pg_hint_plan_standard_join_search
4583 #define join_search_one_level pg_hint_plan_join_search_one_level
4584 #define make_join_rel make_join_rel_wrapper
4587 #undef make_join_rel
4588 #define make_join_rel pg_hint_plan_make_join_rel
4589 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4590 #include "make_join_rel.c"
4592 #include "pg_stat_statements.c"