1 /*-------------------------------------------------------------------------
4 * hinting on how to execute a query for PostgreSQL
6 * Copyright (c) 2012-2020, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
8 *-------------------------------------------------------------------------
13 #include "access/genam.h"
14 #include "access/heapam.h"
15 #include "access/relation.h"
16 #include "catalog/pg_collation.h"
17 #include "catalog/pg_index.h"
18 #include "commands/prepare.h"
19 #include "mb/pg_wchar.h"
20 #include "miscadmin.h"
21 #include "nodes/nodeFuncs.h"
22 #include "nodes/params.h"
23 #include "optimizer/appendinfo.h"
24 #include "optimizer/clauses.h"
25 #include "optimizer/cost.h"
26 #include "optimizer/geqo.h"
27 #include "optimizer/joininfo.h"
28 #include "optimizer/optimizer.h"
29 #include "optimizer/pathnode.h"
30 #include "optimizer/paths.h"
31 #include "optimizer/plancat.h"
32 #include "optimizer/planner.h"
33 #include "optimizer/prep.h"
34 #include "optimizer/restrictinfo.h"
35 #include "parser/analyze.h"
36 #include "parser/parsetree.h"
37 #include "parser/scansup.h"
38 #include "partitioning/partbounds.h"
39 #include "tcop/utility.h"
40 #include "utils/builtins.h"
41 #include "utils/float.h"
42 #include "utils/lsyscache.h"
43 #include "utils/memutils.h"
44 #include "utils/rel.h"
45 #include "utils/snapmgr.h"
46 #include "utils/syscache.h"
47 #include "utils/resowner.h"
49 #include "catalog/pg_class.h"
51 #include "executor/spi.h"
52 #include "catalog/pg_type.h"
56 /* partially copied from pg_stat_statements */
57 #include "normalize_query.h"
60 #include "access/htup_details.h"
62 #ifdef PG_MODULE_MAGIC
66 #define BLOCK_COMMENT_START "/*"
67 #define BLOCK_COMMENT_END "*/"
68 #define HINT_COMMENT_KEYWORD "+"
69 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
70 #define HINT_END BLOCK_COMMENT_END
73 #define HINT_SEQSCAN "SeqScan"
74 #define HINT_INDEXSCAN "IndexScan"
75 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
76 #define HINT_BITMAPSCAN "BitmapScan"
77 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
78 #define HINT_TIDSCAN "TidScan"
79 #define HINT_NOSEQSCAN "NoSeqScan"
80 #define HINT_NOINDEXSCAN "NoIndexScan"
81 #define HINT_NOBITMAPSCAN "NoBitmapScan"
82 #define HINT_NOTIDSCAN "NoTidScan"
83 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
84 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
85 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
86 #define HINT_PARALLEL "Parallel"
88 #define HINT_NESTLOOP "NestLoop"
89 #define HINT_MERGEJOIN "MergeJoin"
90 #define HINT_HASHJOIN "HashJoin"
91 #define HINT_NONESTLOOP "NoNestLoop"
92 #define HINT_NOMERGEJOIN "NoMergeJoin"
93 #define HINT_NOHASHJOIN "NoHashJoin"
94 #define HINT_LEADING "Leading"
95 #define HINT_SET "Set"
96 #define HINT_ROWS "Rows"
97 #define HINT_MEMOIZE "Memoize"
98 #define HINT_NOMEMOIZE "NoMemoize"
100 #define HINT_ARRAY_DEFAULT_INITSIZE 8
102 #define hint_ereport(str, detail) hint_parse_ereport(str, detail)
103 #define hint_parse_ereport(str, detail) \
105 ereport(pg_hint_plan_parse_message_level, \
106 (errmsg("pg_hint_plan: hint syntax error at or near \"%s\"", (str)), \
107 errdetail detail)); \
110 #define skip_space(str) \
111 while (isspace(*str)) \
116 ENABLE_SEQSCAN = 0x01,
117 ENABLE_INDEXSCAN = 0x02,
118 ENABLE_BITMAPSCAN = 0x04,
119 ENABLE_TIDSCAN = 0x08,
120 ENABLE_INDEXONLYSCAN = 0x10
125 ENABLE_NESTLOOP = 0x01,
126 ENABLE_MERGEJOIN = 0x02,
127 ENABLE_HASHJOIN = 0x04,
128 ENABLE_MEMOIZE = 0x08
131 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
132 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
133 ENABLE_INDEXONLYSCAN)
134 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
135 #define DISABLE_ALL_SCAN 0
136 #define DISABLE_ALL_JOIN 0
138 /* hint keyword of enum type*/
139 typedef enum HintKeyword
141 HINT_KEYWORD_SEQSCAN,
142 HINT_KEYWORD_INDEXSCAN,
143 HINT_KEYWORD_INDEXSCANREGEXP,
144 HINT_KEYWORD_BITMAPSCAN,
145 HINT_KEYWORD_BITMAPSCANREGEXP,
146 HINT_KEYWORD_TIDSCAN,
147 HINT_KEYWORD_NOSEQSCAN,
148 HINT_KEYWORD_NOINDEXSCAN,
149 HINT_KEYWORD_NOBITMAPSCAN,
150 HINT_KEYWORD_NOTIDSCAN,
151 HINT_KEYWORD_INDEXONLYSCAN,
152 HINT_KEYWORD_INDEXONLYSCANREGEXP,
153 HINT_KEYWORD_NOINDEXONLYSCAN,
155 HINT_KEYWORD_NESTLOOP,
156 HINT_KEYWORD_MERGEJOIN,
157 HINT_KEYWORD_HASHJOIN,
158 HINT_KEYWORD_NONESTLOOP,
159 HINT_KEYWORD_NOMERGEJOIN,
160 HINT_KEYWORD_NOHASHJOIN,
162 HINT_KEYWORD_LEADING,
165 HINT_KEYWORD_PARALLEL,
166 HINT_KEYWORD_MEMOIZE,
167 HINT_KEYWORD_NOMEMOIZE,
169 HINT_KEYWORD_UNRECOGNIZED
172 #define SCAN_HINT_ACCEPTS_INDEX_NAMES(kw) \
173 (kw == HINT_KEYWORD_INDEXSCAN || \
174 kw == HINT_KEYWORD_INDEXSCANREGEXP || \
175 kw == HINT_KEYWORD_INDEXONLYSCAN || \
176 kw == HINT_KEYWORD_INDEXONLYSCANREGEXP || \
177 kw == HINT_KEYWORD_BITMAPSCAN || \
178 kw == HINT_KEYWORD_BITMAPSCANREGEXP)
181 typedef struct Hint Hint;
182 typedef struct HintState HintState;
184 typedef Hint *(*HintCreateFunction) (const char *hint_str,
186 HintKeyword hint_keyword);
187 typedef void (*HintDeleteFunction) (Hint *hint);
188 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf, bool nolf);
189 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
190 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
191 Query *parse, const char *str);
194 typedef enum HintType
196 HINT_TYPE_SCAN_METHOD,
197 HINT_TYPE_JOIN_METHOD,
207 typedef enum HintTypeBitmap
209 HINT_BM_SCAN_METHOD = 1,
213 static const char *HintTypeName[] = {
223 typedef enum HintStatus
225 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
226 HINT_STATE_USED, /* hint is used */
227 HINT_STATE_DUPLICATION, /* specified hint duplication */
228 HINT_STATE_ERROR /* execute error (parse error does not include
232 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
233 (hint)->base.state == HINT_STATE_USED)
235 static unsigned int qno = 0;
236 static unsigned int msgqno = 0;
237 static char qnostr[32];
238 static const char *current_hint_str = NULL;
240 /* common data for all hints. */
243 const char *hint_str; /* must not do pfree */
244 const char *keyword; /* must not do pfree */
245 HintKeyword hint_keyword;
248 HintDeleteFunction delete_func;
249 HintDescFunction desc_func;
250 HintCmpFunction cmp_func;
251 HintParseFunction parse_func;
254 /* scan method hints */
255 typedef struct ScanMethodHint
261 unsigned char enforce_mask;
264 typedef struct ParentIndexInfo
269 char *expression_str;
276 /* join method hints */
277 typedef struct JoinMethodHint
283 unsigned char enforce_mask;
285 Relids inner_joinrelids;
288 /* join order hints */
289 typedef struct OuterInnerRels
292 List *outer_inner_pair;
295 typedef struct LeadingHint
298 List *relations; /* relation names specified in Leading hint */
299 OuterInnerRels *outer_inner;
302 /* change a run-time parameter hints */
303 typedef struct SetHint
306 char *name; /* name of variable */
312 typedef enum RowsValueType {
313 RVT_ABSOLUTE, /* Rows(... #1000) */
314 RVT_ADD, /* Rows(... +1000) */
315 RVT_SUB, /* Rows(... -1000) */
316 RVT_MULTI, /* Rows(... *1.2) */
318 typedef struct RowsHint
325 Relids inner_joinrelids;
327 RowsValueType value_type;
332 typedef struct ParallelHint
336 char *nworkers_str; /* original string of nworkers */
337 int nworkers; /* num of workers specified by Worker */
338 bool force_parallel; /* force parallel scan */
342 * Describes a context of hint processing.
346 char *hint_str; /* original hint string */
349 int nall_hints; /* # of valid all hints */
350 int max_all_hints; /* # of slots for all hints */
351 Hint **all_hints; /* parsed all hints */
353 /* # of each hints */
354 int num_hints[NUM_HINT_TYPE];
356 /* for scan method hints */
357 ScanMethodHint **scan_hints; /* parsed scan hints */
359 /* Initial values of parameters */
360 int init_scan_mask; /* enable_* mask */
361 int init_nworkers; /* max_parallel_workers_per_gather */
362 /* min_parallel_table_scan_size*/
363 int init_min_para_tablescan_size;
364 /* min_parallel_index_scan_size*/
365 int init_min_para_indexscan_size;
366 double init_paratup_cost; /* parallel_tuple_cost */
367 double init_parasetup_cost;/* parallel_setup_cost */
369 PlannerInfo *current_root; /* PlannerInfo for the followings */
370 Index parent_relid; /* inherit parent of table relid */
371 ScanMethodHint *parent_scan_hint; /* scan hint for the parent */
372 ParallelHint *parent_parallel_hint; /* parallel hint for the parent */
373 List *parent_index_infos; /* list of parent table's index */
375 JoinMethodHint **join_hints; /* parsed join hints */
376 int init_join_mask; /* initial value join parameter */
377 List **join_hint_level;
378 List **memoize_hint_level;
379 LeadingHint **leading_hint; /* parsed Leading hints */
380 SetHint **set_hints; /* parsed Set hints */
381 GucContext context; /* which GUC parameters can we set? */
382 RowsHint **rows_hints; /* parsed Rows hints */
383 ParallelHint **parallel_hints; /* parsed Parallel hints */
384 JoinMethodHint **memoize_hints; /* parsed Memoize hints */
388 * Describes a hint parser module which is bound with particular hint keyword.
390 typedef struct HintParser
393 HintCreateFunction create_func;
394 HintKeyword hint_keyword;
397 /* Module callbacks */
401 static void push_hint(HintState *hstate);
402 static void pop_hint(void);
404 static PlannedStmt *pg_hint_plan_planner(Query *parse, const char *query_string,
406 ParamListInfo boundParams);
407 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
411 /* Scan method hint callbacks */
412 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
413 HintKeyword hint_keyword);
414 static void ScanMethodHintDelete(ScanMethodHint *hint);
415 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
416 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
417 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
418 Query *parse, const char *str);
420 /* Join method hint callbacks */
421 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
422 HintKeyword hint_keyword);
423 static void JoinMethodHintDelete(JoinMethodHint *hint);
424 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
425 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
426 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
427 Query *parse, const char *str);
429 /* Leading hint callbacks */
430 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
431 HintKeyword hint_keyword);
432 static void LeadingHintDelete(LeadingHint *hint);
433 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
434 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
435 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
436 Query *parse, const char *str);
438 /* Set hint callbacks */
439 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
440 HintKeyword hint_keyword);
441 static void SetHintDelete(SetHint *hint);
442 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
443 static int SetHintCmp(const SetHint *a, const SetHint *b);
444 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
447 /* Rows hint callbacks */
448 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
449 HintKeyword hint_keyword);
450 static void RowsHintDelete(RowsHint *hint);
451 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
452 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
453 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
454 Query *parse, const char *str);
456 /* Parallel hint callbacks */
457 static Hint *ParallelHintCreate(const char *hint_str, const char *keyword,
458 HintKeyword hint_keyword);
459 static void ParallelHintDelete(ParallelHint *hint);
460 static void ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf);
461 static int ParallelHintCmp(const ParallelHint *a, const ParallelHint *b);
462 static const char *ParallelHintParse(ParallelHint *hint, HintState *hstate,
463 Query *parse, const char *str);
465 static Hint *MemoizeHintCreate(const char *hint_str, const char *keyword,
466 HintKeyword hint_keyword);
468 static void quote_value(StringInfo buf, const char *value);
470 static const char *parse_quoted_value(const char *str, char **word,
473 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
476 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
477 void pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
478 Index rti, RangeTblEntry *rte);
479 static void create_plain_partial_paths(PlannerInfo *root,
481 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
482 List *other_rels_list,
483 ListCell *other_rels);
484 static void make_rels_by_clauseless_joins(PlannerInfo *root,
487 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
488 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
490 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
493 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
495 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
497 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
501 static int set_config_option_noerror(const char *name, const char *value,
502 GucContext context, GucSource source,
503 GucAction action, bool changeVal, int elevel);
504 static void setup_scan_method_enforcement(ScanMethodHint *scanhint,
506 static int set_config_int32_option(const char *name, int32 value,
508 static int set_config_double_option(const char *name, double value,
512 static bool pg_hint_plan_enable_hint = true;
513 static int debug_level = 0;
514 static int pg_hint_plan_parse_message_level = INFO;
515 static int pg_hint_plan_debug_message_level = LOG;
516 /* Default is off, to keep backward compatibility. */
517 static bool pg_hint_plan_enable_hint_table = false;
519 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
520 static int recurse_level = 0; /* recursion level incl. direct SPI calls */
521 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
522 /* (This could not be above 1) */
523 static int max_hint_nworkers = -1; /* Maximum nworkers of Workers hints */
525 static const struct config_enum_entry parse_messages_level_options[] = {
526 {"debug", DEBUG2, true},
527 {"debug5", DEBUG5, false},
528 {"debug4", DEBUG4, false},
529 {"debug3", DEBUG3, false},
530 {"debug2", DEBUG2, false},
531 {"debug1", DEBUG1, false},
533 {"info", INFO, false},
534 {"notice", NOTICE, false},
535 {"warning", WARNING, false},
536 {"error", ERROR, false},
538 * {"fatal", FATAL, true},
539 * {"panic", PANIC, true},
544 static const struct config_enum_entry parse_debug_level_options[] = {
547 {"detailed", 2, false},
548 {"verbose", 3, false},
560 /* Saved hook values in case of unload */
561 static planner_hook_type prev_planner = NULL;
562 static join_search_hook_type prev_join_search = NULL;
563 static set_rel_pathlist_hook_type prev_set_rel_pathlist = NULL;
565 /* Hold reference to currently active hint */
566 static HintState *current_hint_state = NULL;
569 * List of hint contexts. We treat the head of the list as the Top of the
570 * context stack, so current_hint_state always points the first element of this
573 static List *HintStateStack = NIL;
575 static const HintParser parsers[] = {
576 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
577 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
578 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
579 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
580 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
581 HINT_KEYWORD_BITMAPSCANREGEXP},
582 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
583 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
584 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
585 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
586 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
587 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
588 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
589 HINT_KEYWORD_INDEXONLYSCANREGEXP},
590 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
592 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
593 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
594 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
595 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
596 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
597 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
599 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
600 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
601 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
602 {HINT_PARALLEL, ParallelHintCreate, HINT_KEYWORD_PARALLEL},
603 {HINT_MEMOIZE, MemoizeHintCreate, HINT_KEYWORD_MEMOIZE},
604 {HINT_NOMEMOIZE, MemoizeHintCreate, HINT_KEYWORD_NOMEMOIZE},
606 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
609 PLpgSQL_plugin plugin_funcs = {
613 pg_hint_plan_plpgsql_stmt_beg,
614 pg_hint_plan_plpgsql_stmt_end,
620 * Module load callbacks
625 PLpgSQL_plugin **var_ptr;
627 /* Define custom GUC variables. */
628 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
629 "Force planner to use plans specified in the hint comment preceding to the query.",
631 &pg_hint_plan_enable_hint,
639 DefineCustomEnumVariable("pg_hint_plan.debug_print",
640 "Logs results of hint parsing.",
644 parse_debug_level_options,
651 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
652 "Message level of parse errors.",
654 &pg_hint_plan_parse_message_level,
656 parse_messages_level_options,
663 DefineCustomEnumVariable("pg_hint_plan.message_level",
664 "Message level of debug messages.",
666 &pg_hint_plan_debug_message_level,
668 parse_messages_level_options,
675 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
676 "Let pg_hint_plan look up the hint table.",
678 &pg_hint_plan_enable_hint_table,
687 prev_planner = planner_hook;
688 planner_hook = pg_hint_plan_planner;
689 prev_join_search = join_search_hook;
690 join_search_hook = pg_hint_plan_join_search;
691 prev_set_rel_pathlist = set_rel_pathlist_hook;
692 set_rel_pathlist_hook = pg_hint_plan_set_rel_pathlist;
694 /* setup PL/pgSQL plugin hook */
695 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
696 *var_ptr = &plugin_funcs;
698 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
702 * Module unload callback
708 PLpgSQL_plugin **var_ptr;
710 /* Uninstall hooks. */
711 planner_hook = prev_planner;
712 join_search_hook = prev_join_search;
713 set_rel_pathlist_hook = prev_set_rel_pathlist;
715 /* uninstall PL/pgSQL plugin hook */
716 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
721 * create and delete functions the hint object
725 ScanMethodHintCreate(const char *hint_str, const char *keyword,
726 HintKeyword hint_keyword)
728 ScanMethodHint *hint;
730 hint = palloc(sizeof(ScanMethodHint));
731 hint->base.hint_str = hint_str;
732 hint->base.keyword = keyword;
733 hint->base.hint_keyword = hint_keyword;
734 hint->base.type = HINT_TYPE_SCAN_METHOD;
735 hint->base.state = HINT_STATE_NOTUSED;
736 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
737 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
738 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
739 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
740 hint->relname = NULL;
741 hint->indexnames = NIL;
742 hint->regexp = false;
743 hint->enforce_mask = 0;
745 return (Hint *) hint;
749 ScanMethodHintDelete(ScanMethodHint *hint)
755 pfree(hint->relname);
756 list_free_deep(hint->indexnames);
761 JoinMethodHintCreate(const char *hint_str, const char *keyword,
762 HintKeyword hint_keyword)
764 JoinMethodHint *hint;
766 hint = palloc(sizeof(JoinMethodHint));
767 hint->base.hint_str = hint_str;
768 hint->base.keyword = keyword;
769 hint->base.hint_keyword = hint_keyword;
770 hint->base.type = HINT_TYPE_JOIN_METHOD;
771 hint->base.state = HINT_STATE_NOTUSED;
772 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
773 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
774 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
775 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
777 hint->inner_nrels = 0;
778 hint->relnames = NULL;
779 hint->enforce_mask = 0;
780 hint->joinrelids = NULL;
781 hint->inner_joinrelids = NULL;
783 return (Hint *) hint;
787 JoinMethodHintDelete(JoinMethodHint *hint)
796 for (i = 0; i < hint->nrels; i++)
797 pfree(hint->relnames[i]);
798 pfree(hint->relnames);
801 bms_free(hint->joinrelids);
802 bms_free(hint->inner_joinrelids);
807 LeadingHintCreate(const char *hint_str, const char *keyword,
808 HintKeyword hint_keyword)
812 hint = palloc(sizeof(LeadingHint));
813 hint->base.hint_str = hint_str;
814 hint->base.keyword = keyword;
815 hint->base.hint_keyword = hint_keyword;
816 hint->base.type = HINT_TYPE_LEADING;
817 hint->base.state = HINT_STATE_NOTUSED;
818 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
819 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
820 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
821 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
822 hint->relations = NIL;
823 hint->outer_inner = NULL;
825 return (Hint *) hint;
829 LeadingHintDelete(LeadingHint *hint)
834 list_free_deep(hint->relations);
835 if (hint->outer_inner)
836 pfree(hint->outer_inner);
841 SetHintCreate(const char *hint_str, const char *keyword,
842 HintKeyword hint_keyword)
846 hint = palloc(sizeof(SetHint));
847 hint->base.hint_str = hint_str;
848 hint->base.keyword = keyword;
849 hint->base.hint_keyword = hint_keyword;
850 hint->base.type = HINT_TYPE_SET;
851 hint->base.state = HINT_STATE_NOTUSED;
852 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
853 hint->base.desc_func = (HintDescFunction) SetHintDesc;
854 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
855 hint->base.parse_func = (HintParseFunction) SetHintParse;
860 return (Hint *) hint;
864 SetHintDelete(SetHint *hint)
874 list_free(hint->words);
879 RowsHintCreate(const char *hint_str, const char *keyword,
880 HintKeyword hint_keyword)
884 hint = palloc(sizeof(RowsHint));
885 hint->base.hint_str = hint_str;
886 hint->base.keyword = keyword;
887 hint->base.hint_keyword = hint_keyword;
888 hint->base.type = HINT_TYPE_ROWS;
889 hint->base.state = HINT_STATE_NOTUSED;
890 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
891 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
892 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
893 hint->base.parse_func = (HintParseFunction) RowsHintParse;
895 hint->inner_nrels = 0;
896 hint->relnames = NULL;
897 hint->joinrelids = NULL;
898 hint->inner_joinrelids = NULL;
899 hint->rows_str = NULL;
900 hint->value_type = RVT_ABSOLUTE;
903 return (Hint *) hint;
907 RowsHintDelete(RowsHint *hint)
916 for (i = 0; i < hint->nrels; i++)
917 pfree(hint->relnames[i]);
918 pfree(hint->relnames);
921 bms_free(hint->joinrelids);
922 bms_free(hint->inner_joinrelids);
927 ParallelHintCreate(const char *hint_str, const char *keyword,
928 HintKeyword hint_keyword)
932 hint = palloc(sizeof(ParallelHint));
933 hint->base.hint_str = hint_str;
934 hint->base.keyword = keyword;
935 hint->base.hint_keyword = hint_keyword;
936 hint->base.type = HINT_TYPE_PARALLEL;
937 hint->base.state = HINT_STATE_NOTUSED;
938 hint->base.delete_func = (HintDeleteFunction) ParallelHintDelete;
939 hint->base.desc_func = (HintDescFunction) ParallelHintDesc;
940 hint->base.cmp_func = (HintCmpFunction) ParallelHintCmp;
941 hint->base.parse_func = (HintParseFunction) ParallelHintParse;
942 hint->relname = NULL;
944 hint->nworkers_str = "0";
946 return (Hint *) hint;
950 ParallelHintDelete(ParallelHint *hint)
956 pfree(hint->relname);
962 MemoizeHintCreate(const char *hint_str, const char *keyword,
963 HintKeyword hint_keyword)
966 * MemoizeHintCreate shares the same struct with JoinMethodHint and the
967 * only difference is the hint type.
969 JoinMethodHint *hint =
970 (JoinMethodHint *)JoinMethodHintCreate(hint_str, keyword, hint_keyword);
972 hint->base.type = HINT_TYPE_MEMOIZE;
974 return (Hint *) hint;
979 HintStateCreate(void)
983 hstate = palloc(sizeof(HintState));
984 hstate->hint_str = NULL;
985 hstate->nall_hints = 0;
986 hstate->max_all_hints = 0;
987 hstate->all_hints = NULL;
988 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
989 hstate->scan_hints = NULL;
990 hstate->init_scan_mask = 0;
991 hstate->init_nworkers = 0;
992 hstate->init_min_para_tablescan_size = 0;
993 hstate->init_min_para_indexscan_size = 0;
994 hstate->init_paratup_cost = 0;
995 hstate->init_parasetup_cost = 0;
996 hstate->current_root = NULL;
997 hstate->parent_relid = 0;
998 hstate->parent_scan_hint = NULL;
999 hstate->parent_parallel_hint = NULL;
1000 hstate->parent_index_infos = NIL;
1001 hstate->join_hints = NULL;
1002 hstate->init_join_mask = 0;
1003 hstate->join_hint_level = NULL;
1004 hstate->memoize_hint_level = NULL;
1005 hstate->leading_hint = NULL;
1006 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
1007 hstate->set_hints = NULL;
1008 hstate->rows_hints = NULL;
1009 hstate->parallel_hints = NULL;
1015 HintStateDelete(HintState *hstate)
1022 if (hstate->hint_str)
1023 pfree(hstate->hint_str);
1025 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1026 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
1027 if (hstate->all_hints)
1028 pfree(hstate->all_hints);
1029 if (hstate->parent_index_infos)
1030 list_free(hstate->parent_index_infos);
1034 * Copy given value into buf, with quoting with '"' if necessary.
1037 quote_value(StringInfo buf, const char *value)
1039 bool need_quote = false;
1042 for (str = value; *str != '\0'; str++)
1044 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
1047 appendStringInfoCharMacro(buf, '"');
1052 for (str = value; *str != '\0'; str++)
1055 appendStringInfoCharMacro(buf, '"');
1057 appendStringInfoCharMacro(buf, *str);
1061 appendStringInfoCharMacro(buf, '"');
1065 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
1069 appendStringInfo(buf, "%s(", hint->base.keyword);
1070 if (hint->relname != NULL)
1072 quote_value(buf, hint->relname);
1073 foreach(l, hint->indexnames)
1075 appendStringInfoCharMacro(buf, ' ');
1076 quote_value(buf, (char *) lfirst(l));
1079 appendStringInfoString(buf, ")");
1081 appendStringInfoChar(buf, '\n');
1085 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
1089 appendStringInfo(buf, "%s(", hint->base.keyword);
1090 if (hint->relnames != NULL)
1092 quote_value(buf, hint->relnames[0]);
1093 for (i = 1; i < hint->nrels; i++)
1095 appendStringInfoCharMacro(buf, ' ');
1096 quote_value(buf, hint->relnames[i]);
1099 appendStringInfoString(buf, ")");
1101 appendStringInfoChar(buf, '\n');
1105 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
1107 if (outer_inner->relation == NULL)
1114 appendStringInfoCharMacro(buf, '(');
1115 foreach(l, outer_inner->outer_inner_pair)
1120 appendStringInfoCharMacro(buf, ' ');
1122 OuterInnerDesc(lfirst(l), buf);
1125 appendStringInfoCharMacro(buf, ')');
1128 quote_value(buf, outer_inner->relation);
1132 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
1134 appendStringInfo(buf, "%s(", HINT_LEADING);
1135 if (hint->outer_inner == NULL)
1142 foreach(l, hint->relations)
1147 appendStringInfoCharMacro(buf, ' ');
1149 quote_value(buf, (char *) lfirst(l));
1153 OuterInnerDesc(hint->outer_inner, buf);
1155 appendStringInfoString(buf, ")");
1157 appendStringInfoChar(buf, '\n');
1161 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1163 bool is_first = true;
1166 appendStringInfo(buf, "%s(", HINT_SET);
1167 foreach(l, hint->words)
1172 appendStringInfoCharMacro(buf, ' ');
1174 quote_value(buf, (char *) lfirst(l));
1176 appendStringInfo(buf, ")");
1178 appendStringInfoChar(buf, '\n');
1182 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1186 appendStringInfo(buf, "%s(", hint->base.keyword);
1187 if (hint->relnames != NULL)
1189 quote_value(buf, hint->relnames[0]);
1190 for (i = 1; i < hint->nrels; i++)
1192 appendStringInfoCharMacro(buf, ' ');
1193 quote_value(buf, hint->relnames[i]);
1196 if (hint->rows_str != NULL)
1197 appendStringInfo(buf, " %s", hint->rows_str);
1198 appendStringInfoString(buf, ")");
1200 appendStringInfoChar(buf, '\n');
1204 ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf)
1206 appendStringInfo(buf, "%s(", hint->base.keyword);
1207 if (hint->relname != NULL)
1209 quote_value(buf, hint->relname);
1211 /* number of workers */
1212 appendStringInfoCharMacro(buf, ' ');
1213 quote_value(buf, hint->nworkers_str);
1214 /* application mode of num of workers */
1215 appendStringInfoCharMacro(buf, ' ');
1216 appendStringInfoString(buf,
1217 (hint->force_parallel ? "hard" : "soft"));
1219 appendStringInfoString(buf, ")");
1221 appendStringInfoChar(buf, '\n');
1225 * Append string which represents all hints in a given state to buf, with
1226 * preceding title with them.
1229 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1230 HintStatus state, bool nolf)
1234 appendStringInfo(buf, "%s:", title);
1236 appendStringInfoChar(buf, '\n');
1239 for (i = 0; i < hstate->nall_hints; i++)
1241 if (hstate->all_hints[i]->state != state)
1244 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1248 if (nolf && nshown == 0)
1249 appendStringInfoString(buf, "(none)");
1253 * Dump contents of given hstate to server log with log level LOG.
1256 HintStateDump(HintState *hstate)
1262 elog(pg_hint_plan_debug_message_level, "pg_hint_plan:\nno hint");
1266 initStringInfo(&buf);
1268 appendStringInfoString(&buf, "pg_hint_plan:\n");
1269 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1270 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1271 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1272 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1274 ereport(pg_hint_plan_debug_message_level,
1275 (errmsg ("%s", buf.data)));
1281 HintStateDump2(HintState *hstate)
1287 elog(pg_hint_plan_debug_message_level,
1288 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1292 initStringInfo(&buf);
1293 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1294 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1295 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1296 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1297 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1298 appendStringInfoChar(&buf, '}');
1300 ereport(pg_hint_plan_debug_message_level,
1301 (errmsg("%s", buf.data),
1303 errhidecontext(true)));
1313 RelnameCmp(const void *a, const void *b)
1315 const char *relnamea = *((const char **) a);
1316 const char *relnameb = *((const char **) b);
1318 return strcmp(relnamea, relnameb);
1322 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1324 return RelnameCmp(&a->relname, &b->relname);
1328 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1332 if (a->nrels != b->nrels)
1333 return a->nrels - b->nrels;
1335 for (i = 0; i < a->nrels; i++)
1338 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1346 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1352 SetHintCmp(const SetHint *a, const SetHint *b)
1354 return strcmp(a->name, b->name);
1358 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1362 if (a->nrels != b->nrels)
1363 return a->nrels - b->nrels;
1365 for (i = 0; i < a->nrels; i++)
1368 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1376 ParallelHintCmp(const ParallelHint *a, const ParallelHint *b)
1378 return RelnameCmp(&a->relname, &b->relname);
1382 HintCmp(const void *a, const void *b)
1384 const Hint *hinta = *((const Hint **) a);
1385 const Hint *hintb = *((const Hint **) b);
1387 if (hinta->type != hintb->type)
1388 return hinta->type - hintb->type;
1389 if (hinta->state == HINT_STATE_ERROR)
1391 if (hintb->state == HINT_STATE_ERROR)
1393 return hinta->cmp_func(hinta, hintb);
1397 * Returns byte offset of hint b from hint a. If hint a was specified before
1398 * b, positive value is returned.
1401 HintCmpWithPos(const void *a, const void *b)
1403 const Hint *hinta = *((const Hint **) a);
1404 const Hint *hintb = *((const Hint **) b);
1407 result = HintCmp(a, b);
1409 result = hinta->hint_str - hintb->hint_str;
1418 parse_keyword(const char *str, StringInfo buf)
1422 while (!isspace(*str) && *str != '(' && *str != '\0')
1423 appendStringInfoCharMacro(buf, *str++);
1429 skip_parenthesis(const char *str, char parenthesis)
1433 if (*str != parenthesis)
1435 if (parenthesis == '(')
1436 hint_ereport(str, ("Opening parenthesis is necessary."));
1437 else if (parenthesis == ')')
1438 hint_ereport(str, ("Closing parenthesis is necessary."));
1449 * Parse a token from str, and store malloc'd copy into word. A token can be
1450 * quoted with '"'. Return value is pointer to unparsed portion of original
1451 * string, or NULL if an error occurred.
1453 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1456 parse_quoted_value(const char *str, char **word, bool truncate)
1461 /* Skip leading spaces. */
1464 initStringInfo(&buf);
1477 /* Double quotation must be closed. */
1481 hint_ereport(str, ("Unterminated quoted string."));
1486 * Skip escaped double quotation.
1488 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1489 * block comments) to be an object name, so users must specify
1490 * alias for such object names.
1492 * Those special names can be allowed if we care escaped slashes
1493 * and asterisks, but we don't.
1502 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1506 appendStringInfoCharMacro(&buf, *str++);
1511 hint_ereport(str, ("Zero-length delimited string."));
1518 /* Truncate name if it's too long */
1520 truncate_identifier(buf.data, strlen(buf.data), true);
1527 static OuterInnerRels *
1528 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1530 OuterInnerRels *outer_inner;
1532 outer_inner = palloc(sizeof(OuterInnerRels));
1533 outer_inner->relation = name;
1534 outer_inner->outer_inner_pair = outer_inner_list;
1540 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1542 List *outer_inner_pair = NIL;
1544 if ((str = skip_parenthesis(str, '(')) == NULL)
1549 /* Store words in parentheses into outer_inner_list. */
1550 while(*str != ')' && *str != '\0')
1552 OuterInnerRels *outer_inner_rels;
1556 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1564 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1567 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1570 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1575 (str = skip_parenthesis(str, ')')) == NULL)
1577 list_free(outer_inner_pair);
1581 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1587 parse_parentheses_Leading(const char *str, List **name_list,
1588 OuterInnerRels **outer_inner)
1591 bool truncate = true;
1593 if ((str = skip_parenthesis(str, '(')) == NULL)
1599 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1604 /* Store words in parentheses into name_list. */
1605 while(*str != ')' && *str != '\0')
1607 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1609 list_free(*name_list);
1613 *name_list = lappend(*name_list, name);
1618 if ((str = skip_parenthesis(str, ')')) == NULL)
1624 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1627 bool truncate = true;
1629 if ((str = skip_parenthesis(str, '(')) == NULL)
1634 /* Store words in parentheses into name_list. */
1635 while(*str != ')' && *str != '\0')
1637 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1639 list_free(*name_list);
1643 *name_list = lappend(*name_list, name);
1646 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1647 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1648 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1649 keyword == HINT_KEYWORD_SET)
1655 if ((str = skip_parenthesis(str, ')')) == NULL)
1661 parse_hints(HintState *hstate, Query *parse, const char *str)
1666 initStringInfo(&buf);
1667 while (*str != '\0')
1669 const HintParser *parser;
1671 /* in error message, we output the comment including the keyword. */
1672 head = (char *) str;
1674 /* parse only the keyword of the hint. */
1675 resetStringInfo(&buf);
1676 str = parse_keyword(str, &buf);
1678 for (parser = parsers; parser->keyword != NULL; parser++)
1680 char *keyword = parser->keyword;
1683 if (pg_strcasecmp(buf.data, keyword) != 0)
1686 hint = parser->create_func(head, keyword, parser->hint_keyword);
1688 /* parser of each hint does parse in a parenthesis. */
1689 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1691 hint->delete_func(hint);
1697 * Add hint information into all_hints array. If we don't have
1698 * enough space, double the array.
1700 if (hstate->nall_hints == 0)
1702 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1703 hstate->all_hints = (Hint **)
1704 palloc(sizeof(Hint *) * hstate->max_all_hints);
1706 else if (hstate->nall_hints == hstate->max_all_hints)
1708 hstate->max_all_hints *= 2;
1709 hstate->all_hints = (Hint **)
1710 repalloc(hstate->all_hints,
1711 sizeof(Hint *) * hstate->max_all_hints);
1714 hstate->all_hints[hstate->nall_hints] = hint;
1715 hstate->nall_hints++;
1722 if (parser->keyword == NULL)
1725 ("Unrecognized hint keyword \"%s\".", buf.data));
1736 * Get hints from table by client-supplied query string and application name.
1739 get_hints_from_table(const char *client_query, const char *client_application)
1741 const char *search_query =
1743 " FROM hint_plan.hints "
1744 " WHERE norm_query_string = $1 "
1745 " AND ( application_name = $2 "
1746 " OR application_name = '' ) "
1747 " ORDER BY application_name DESC";
1748 static SPIPlanPtr plan = NULL;
1750 Oid argtypes[2] = { TEXTOID, TEXTOID };
1752 char nulls[2] = {' ', ' '};
1758 bool snapshot_set = false;
1760 hint_inhibit_level++;
1762 if (!ActiveSnapshotSet())
1764 PushActiveSnapshot(GetTransactionSnapshot());
1765 snapshot_set = true;
1773 p = SPI_prepare(search_query, 2, argtypes);
1774 plan = SPI_saveplan(p);
1778 qry = cstring_to_text(client_query);
1779 app = cstring_to_text(client_application);
1780 values[0] = PointerGetDatum(qry);
1781 values[1] = PointerGetDatum(app);
1783 SPI_execute_plan(plan, values, nulls, true, 1);
1785 if (SPI_processed > 0)
1789 hints = SPI_getvalue(SPI_tuptable->vals[0],
1790 SPI_tuptable->tupdesc, 1);
1792 * Here we use SPI_palloc to ensure that hints string is valid even
1793 * after SPI_finish call. We can't use simple palloc because it
1794 * allocates memory in SPI's context and that context is deleted in
1797 buf = SPI_palloc(strlen(hints) + 1);
1805 PopActiveSnapshot();
1807 hint_inhibit_level--;
1811 hint_inhibit_level--;
1820 * Get hints from the head block comment in client-supplied query string.
1823 get_hints_from_comment(const char *p)
1825 const char *hint_head;
1833 /* extract query head comment. */
1834 hint_head = strstr(p, HINT_START);
1835 if (hint_head == NULL)
1837 for (;p < hint_head; p++)
1840 * Allow these characters precedes hint comment:
1842 * - alphabets which are in ASCII range
1843 * - space, tabs and new-lines
1844 * - underscores, for identifier
1845 * - commas, for SELECT clause, EXPLAIN and PREPARE
1846 * - parentheses, for EXPLAIN and PREPARE
1848 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1849 * avoid behavior which depends on locale setting.
1851 if (!(*p >= '0' && *p <= '9') &&
1852 !(*p >= 'A' && *p <= 'Z') &&
1853 !(*p >= 'a' && *p <= 'z') &&
1857 *p != '(' && *p != ')')
1861 len = strlen(HINT_START);
1866 /* find hint end keyword. */
1867 if ((tail = strstr(p, HINT_END)) == NULL)
1869 hint_ereport(head, ("Unterminated block comment."));
1873 /* We don't support nested block comments. */
1874 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1876 hint_ereport(head, ("Nested block comments are not supported."));
1880 /* Make a copy of hint. */
1882 head = palloc(len + 1);
1883 memcpy(head, p, len);
1891 * Parse hints that got, create hint struct from parse tree and parse hints.
1894 create_hintstate(Query *parse, const char *hints)
1903 /* -1 means that no Parallel hint is specified. */
1904 max_hint_nworkers = -1;
1907 hstate = HintStateCreate();
1908 hstate->hint_str = (char *) hints;
1910 /* parse each hint. */
1911 parse_hints(hstate, parse, p);
1913 /* When nothing specified a hint, we free HintState and returns NULL. */
1914 if (hstate->nall_hints == 0)
1916 HintStateDelete(hstate);
1920 /* Sort hints in order of original position. */
1921 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1924 /* Count number of hints per hint-type. */
1925 for (i = 0; i < hstate->nall_hints; i++)
1927 Hint *cur_hint = hstate->all_hints[i];
1928 hstate->num_hints[cur_hint->type]++;
1932 * If an object (or a set of objects) has multiple hints of same hint-type,
1933 * only the last hint is valid and others are ignored in planning.
1934 * Hints except the last are marked as 'duplicated' to remember the order.
1936 for (i = 0; i < hstate->nall_hints - 1; i++)
1938 Hint *cur_hint = hstate->all_hints[i];
1939 Hint *next_hint = hstate->all_hints[i + 1];
1942 * Leading hint is marked as 'duplicated' in transform_join_hints.
1944 if (cur_hint->type == HINT_TYPE_LEADING &&
1945 next_hint->type == HINT_TYPE_LEADING)
1949 * Note that we need to pass addresses of hint pointers, because
1950 * HintCmp is designed to sort array of Hint* by qsort.
1952 if (HintCmp(&cur_hint, &next_hint) == 0)
1954 hint_ereport(cur_hint->hint_str,
1955 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1956 cur_hint->state = HINT_STATE_DUPLICATION;
1961 * Make sure that per-type array pointers point proper position in the
1962 * array which consists of all hints.
1964 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1965 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1966 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1967 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1968 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1969 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1970 hstate->num_hints[HINT_TYPE_LEADING]);
1971 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
1972 hstate->num_hints[HINT_TYPE_SET]);
1973 hstate->parallel_hints = (ParallelHint **) (hstate->rows_hints +
1974 hstate->num_hints[HINT_TYPE_ROWS]);
1975 hstate->memoize_hints = (JoinMethodHint **) (hstate->parallel_hints +
1976 hstate->num_hints[HINT_TYPE_PARALLEL]);
1982 * Parse inside of parentheses of scan-method hints.
1985 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1988 const char *keyword = hint->base.keyword;
1989 HintKeyword hint_keyword = hint->base.hint_keyword;
1990 List *name_list = NIL;
1993 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1996 /* Parse relation name and index name(s) if given hint accepts. */
1997 length = list_length(name_list);
1999 /* at least twp parameters required */
2003 ("%s hint requires a relation.", hint->base.keyword));
2004 hint->base.state = HINT_STATE_ERROR;
2008 hint->relname = linitial(name_list);
2009 hint->indexnames = list_delete_first(name_list);
2011 /* check whether the hint accepts index name(s) */
2012 if (length > 1 && !SCAN_HINT_ACCEPTS_INDEX_NAMES(hint_keyword))
2015 ("%s hint accepts only one relation.",
2016 hint->base.keyword));
2017 hint->base.state = HINT_STATE_ERROR;
2021 /* Set a bit for specified hint. */
2022 switch (hint_keyword)
2024 case HINT_KEYWORD_SEQSCAN:
2025 hint->enforce_mask = ENABLE_SEQSCAN;
2027 case HINT_KEYWORD_INDEXSCAN:
2028 hint->enforce_mask = ENABLE_INDEXSCAN;
2030 case HINT_KEYWORD_INDEXSCANREGEXP:
2031 hint->enforce_mask = ENABLE_INDEXSCAN;
2032 hint->regexp = true;
2034 case HINT_KEYWORD_BITMAPSCAN:
2035 hint->enforce_mask = ENABLE_BITMAPSCAN;
2037 case HINT_KEYWORD_BITMAPSCANREGEXP:
2038 hint->enforce_mask = ENABLE_BITMAPSCAN;
2039 hint->regexp = true;
2041 case HINT_KEYWORD_TIDSCAN:
2042 hint->enforce_mask = ENABLE_TIDSCAN;
2044 case HINT_KEYWORD_NOSEQSCAN:
2045 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
2047 case HINT_KEYWORD_NOINDEXSCAN:
2048 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
2050 case HINT_KEYWORD_NOBITMAPSCAN:
2051 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
2053 case HINT_KEYWORD_NOTIDSCAN:
2054 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
2056 case HINT_KEYWORD_INDEXONLYSCAN:
2057 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2059 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
2060 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2061 hint->regexp = true;
2063 case HINT_KEYWORD_NOINDEXONLYSCAN:
2064 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
2067 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2076 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2079 const char *keyword = hint->base.keyword;
2080 HintKeyword hint_keyword = hint->base.hint_keyword;
2081 List *name_list = NIL;
2083 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2086 hint->nrels = list_length(name_list);
2088 if (hint->nrels > 0)
2094 * Transform relation names from list to array to sort them with qsort
2097 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2098 foreach (l, name_list)
2100 hint->relnames[i] = lfirst(l);
2105 list_free(name_list);
2107 /* A join hint requires at least two relations */
2108 if (hint->nrels < 2)
2111 ("%s hint requires at least two relations.",
2112 hint->base.keyword));
2113 hint->base.state = HINT_STATE_ERROR;
2117 /* Sort hints in alphabetical order of relation names. */
2118 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2120 switch (hint_keyword)
2122 case HINT_KEYWORD_NESTLOOP:
2123 hint->enforce_mask = ENABLE_NESTLOOP;
2125 case HINT_KEYWORD_MERGEJOIN:
2126 hint->enforce_mask = ENABLE_MERGEJOIN;
2128 case HINT_KEYWORD_HASHJOIN:
2129 hint->enforce_mask = ENABLE_HASHJOIN;
2131 case HINT_KEYWORD_NONESTLOOP:
2132 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2134 case HINT_KEYWORD_NOMERGEJOIN:
2135 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2137 case HINT_KEYWORD_NOHASHJOIN:
2138 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2140 case HINT_KEYWORD_MEMOIZE:
2141 case HINT_KEYWORD_NOMEMOIZE:
2142 /* nothing to do here */
2145 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2154 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2157 if (outer_inner->outer_inner_pair == NIL)
2159 if (outer_inner->relation)
2165 if (list_length(outer_inner->outer_inner_pair) == 2)
2167 foreach(l, outer_inner->outer_inner_pair)
2169 if (!OuterInnerPairCheck(lfirst(l)))
2180 OuterInnerList(OuterInnerRels *outer_inner)
2182 List *outer_inner_list = NIL;
2184 OuterInnerRels *outer_inner_rels;
2186 foreach(l, outer_inner->outer_inner_pair)
2188 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2190 if (outer_inner_rels->relation != NULL)
2191 outer_inner_list = lappend(outer_inner_list,
2192 outer_inner_rels->relation);
2194 outer_inner_list = list_concat(outer_inner_list,
2195 OuterInnerList(outer_inner_rels));
2197 return outer_inner_list;
2201 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2204 List *name_list = NIL;
2205 OuterInnerRels *outer_inner = NULL;
2207 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2211 if (outer_inner != NULL)
2212 name_list = OuterInnerList(outer_inner);
2214 hint->relations = name_list;
2215 hint->outer_inner = outer_inner;
2217 /* A Leading hint requires at least two relations */
2218 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2220 hint_ereport(hint->base.hint_str,
2221 ("%s hint requires at least two relations.",
2223 hint->base.state = HINT_STATE_ERROR;
2225 else if (hint->outer_inner != NULL &&
2226 !OuterInnerPairCheck(hint->outer_inner))
2228 hint_ereport(hint->base.hint_str,
2229 ("%s hint requires two sets of relations when parentheses nests.",
2231 hint->base.state = HINT_STATE_ERROR;
2238 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2240 List *name_list = NIL;
2242 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2246 hint->words = name_list;
2248 /* We need both name and value to set GUC parameter. */
2249 if (list_length(name_list) == 2)
2251 hint->name = linitial(name_list);
2252 hint->value = lsecond(name_list);
2256 hint_ereport(hint->base.hint_str,
2257 ("%s hint requires name and value of GUC parameter.",
2259 hint->base.state = HINT_STATE_ERROR;
2266 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2269 HintKeyword hint_keyword = hint->base.hint_keyword;
2270 List *name_list = NIL;
2276 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2279 /* Last element must be rows specification */
2280 hint->nrels = list_length(name_list) - 1;
2282 if (hint->nrels < 1)
2285 ("%s hint needs at least one relation followed by one correction term.",
2286 hint->base.keyword));
2287 hint->base.state = HINT_STATE_ERROR;
2294 * Transform relation names from list to array to sort them with qsort
2297 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2298 foreach (l, name_list)
2300 if (hint->nrels <= i)
2302 hint->relnames[i] = lfirst(l);
2306 /* Retieve rows estimation */
2307 rows_str = list_nth(name_list, hint->nrels);
2308 hint->rows_str = rows_str; /* store as-is for error logging */
2309 if (rows_str[0] == '#')
2311 hint->value_type = RVT_ABSOLUTE;
2314 else if (rows_str[0] == '+')
2316 hint->value_type = RVT_ADD;
2319 else if (rows_str[0] == '-')
2321 hint->value_type = RVT_SUB;
2324 else if (rows_str[0] == '*')
2326 hint->value_type = RVT_MULTI;
2331 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2332 hint->base.state = HINT_STATE_ERROR;
2335 hint->rows = strtod(rows_str, &end_ptr);
2338 hint_ereport(rows_str,
2339 ("%s hint requires valid number as rows estimation.",
2340 hint->base.keyword));
2341 hint->base.state = HINT_STATE_ERROR;
2345 /* A join hint requires at least two relations */
2346 if (hint->nrels < 2)
2349 ("%s hint requires at least two relations.",
2350 hint->base.keyword));
2351 hint->base.state = HINT_STATE_ERROR;
2355 list_free(name_list);
2357 /* Sort relnames in alphabetical order. */
2358 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2364 ParallelHintParse(ParallelHint *hint, HintState *hstate, Query *parse,
2367 HintKeyword hint_keyword = hint->base.hint_keyword;
2368 List *name_list = NIL;
2372 bool force_parallel = false;
2374 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2377 /* Parse relation name and index name(s) if given hint accepts. */
2378 length = list_length(name_list);
2380 if (length < 2 || length > 3)
2383 ("wrong number of arguments (%d): %s",
2384 length, hint->base.keyword));
2385 hint->base.state = HINT_STATE_ERROR;
2389 hint->relname = linitial(name_list);
2391 /* The second parameter is number of workers */
2392 hint->nworkers_str = list_nth(name_list, 1);
2393 nworkers = strtod(hint->nworkers_str, &end_ptr);
2394 if (*end_ptr || nworkers < 0 || nworkers > max_worker_processes)
2397 hint_ereport(hint->nworkers_str,
2398 ("number of workers must be a number: %s",
2399 hint->base.keyword));
2400 else if (nworkers < 0)
2401 hint_ereport(hint->nworkers_str,
2402 ("number of workers must be positive: %s",
2403 hint->base.keyword));
2404 else if (nworkers > max_worker_processes)
2405 hint_ereport(hint->nworkers_str,
2406 ("number of workers = %d is larger than max_worker_processes(%d): %s",
2407 nworkers, max_worker_processes, hint->base.keyword));
2409 hint->base.state = HINT_STATE_ERROR;
2412 hint->nworkers = nworkers;
2414 /* optional third parameter is specified */
2417 const char *modeparam = (const char *)list_nth(name_list, 2);
2418 if (pg_strcasecmp(modeparam, "hard") == 0)
2419 force_parallel = true;
2420 else if (pg_strcasecmp(modeparam, "soft") != 0)
2422 hint_ereport(modeparam,
2423 ("enforcement must be soft or hard: %s",
2424 hint->base.keyword));
2425 hint->base.state = HINT_STATE_ERROR;
2429 hint->force_parallel = force_parallel;
2431 if (hint->base.state != HINT_STATE_ERROR &&
2432 nworkers > max_hint_nworkers)
2433 max_hint_nworkers = nworkers;
2439 * set GUC parameter functions
2443 get_current_scan_mask()
2448 mask |= ENABLE_SEQSCAN;
2449 if (enable_indexscan)
2450 mask |= ENABLE_INDEXSCAN;
2451 if (enable_bitmapscan)
2452 mask |= ENABLE_BITMAPSCAN;
2454 mask |= ENABLE_TIDSCAN;
2455 if (enable_indexonlyscan)
2456 mask |= ENABLE_INDEXONLYSCAN;
2462 get_current_join_mask()
2466 if (enable_nestloop)
2467 mask |= ENABLE_NESTLOOP;
2468 if (enable_mergejoin)
2469 mask |= ENABLE_MERGEJOIN;
2470 if (enable_hashjoin)
2471 mask |= ENABLE_HASHJOIN;
2473 mask |= ENABLE_MEMOIZE;
2479 * Sets GUC prameters without throwing exception. Reutrns false if something
2483 set_config_option_noerror(const char *name, const char *value,
2484 GucContext context, GucSource source,
2485 GucAction action, bool changeVal, int elevel)
2488 MemoryContext ccxt = CurrentMemoryContext;
2492 result = set_config_option(name, value, context, source,
2493 action, changeVal, 0, false);
2499 /* Save error info */
2500 MemoryContextSwitchTo(ccxt);
2501 errdata = CopyErrorData();
2505 (errcode(errdata->sqlerrcode),
2506 errmsg("%s", errdata->message),
2507 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2508 errdata->hint ? errhint("%s", errdata->hint) : 0));
2510 FreeErrorData(errdata);
2518 * Sets GUC parameter of int32 type without throwing exceptions. Returns false
2519 * if something wrong.
2522 set_config_int32_option(const char *name, int32 value, GucContext context)
2524 char buf[16]; /* enough for int32 */
2526 if (snprintf(buf, 16, "%d", value) < 0)
2528 ereport(pg_hint_plan_parse_message_level,
2529 (errmsg ("Failed to convert integer to string: %d", value)));
2534 set_config_option_noerror(name, buf, context,
2535 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2536 pg_hint_plan_parse_message_level);
2540 * Sets GUC parameter of double type without throwing exceptions. Returns false
2541 * if something wrong.
2544 set_config_double_option(const char *name, double value, GucContext context)
2546 char *buf = float8out_internal(value);
2549 result = set_config_option_noerror(name, buf, context,
2550 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2551 pg_hint_plan_parse_message_level);
2556 /* setup scan method enforcement according to given options */
2558 setup_guc_enforcement(SetHint **options, int noptions, GucContext context)
2562 for (i = 0; i < noptions; i++)
2564 SetHint *hint = options[i];
2567 if (!hint_state_enabled(hint))
2570 result = set_config_option_noerror(hint->name, hint->value, context,
2571 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2572 pg_hint_plan_parse_message_level);
2574 hint->base.state = HINT_STATE_USED;
2576 hint->base.state = HINT_STATE_ERROR;
2583 * Setup parallel execution environment.
2585 * If hint is not NULL, set up using it, elsewise reset to initial environment.
2588 setup_parallel_plan_enforcement(ParallelHint *hint, HintState *state)
2592 hint->base.state = HINT_STATE_USED;
2593 set_config_int32_option("max_parallel_workers_per_gather",
2594 hint->nworkers, state->context);
2597 set_config_int32_option("max_parallel_workers_per_gather",
2598 state->init_nworkers, state->context);
2600 /* force means that enforce parallel as far as possible */
2601 if (hint && hint->force_parallel && hint->nworkers > 0)
2603 set_config_double_option("parallel_tuple_cost", 0.0, state->context);
2604 set_config_double_option("parallel_setup_cost", 0.0, state->context);
2605 set_config_int32_option("min_parallel_table_scan_size", 0,
2607 set_config_int32_option("min_parallel_index_scan_size", 0,
2612 set_config_double_option("parallel_tuple_cost",
2613 state->init_paratup_cost, state->context);
2614 set_config_double_option("parallel_setup_cost",
2615 state->init_parasetup_cost, state->context);
2616 set_config_int32_option("min_parallel_table_scan_size",
2617 state->init_min_para_tablescan_size,
2619 set_config_int32_option("min_parallel_index_scan_size",
2620 state->init_min_para_indexscan_size,
2625 #define SET_CONFIG_OPTION(name, type_bits) \
2626 set_config_option_noerror((name), \
2627 (mask & (type_bits)) ? "true" : "false", \
2628 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2632 * Setup GUC environment to enforce scan methods. If scanhint is NULL, reset
2633 * GUCs to the saved state in state.
2636 setup_scan_method_enforcement(ScanMethodHint *scanhint, HintState *state)
2638 unsigned char enforce_mask = state->init_scan_mask;
2639 GucContext context = state->context;
2644 enforce_mask = scanhint->enforce_mask;
2645 scanhint->base.state = HINT_STATE_USED;
2648 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2649 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2650 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2652 mask = enforce_mask;
2654 mask = enforce_mask & current_hint_state->init_scan_mask;
2656 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2657 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2658 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2659 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2660 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2664 set_join_config_options(unsigned char enforce_mask, bool set_memoize,
2669 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2670 enforce_mask == ENABLE_HASHJOIN)
2671 mask = enforce_mask;
2673 mask = enforce_mask & current_hint_state->init_join_mask;
2675 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2676 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2677 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2680 SET_CONFIG_OPTION("enable_memoize", ENABLE_MEMOIZE);
2683 * Hash join may be rejected for the reason of estimated memory usage. Try
2684 * getting rid of that limitation.
2686 if (enforce_mask == ENABLE_HASHJOIN)
2691 /* See final_cost_hashjoin(). */
2692 new_multipler = MAX_KILOBYTES / work_mem;
2694 /* See guc.c for the upper limit */
2695 if (new_multipler >= 1000)
2696 new_multipler = 1000;
2698 if (new_multipler > hash_mem_multiplier)
2700 snprintf(buf, sizeof(buf), UINT64_FORMAT, (uint64)new_multipler);
2701 set_config_option_noerror("hash_mem_multiplier", buf,
2702 context, PGC_S_SESSION, GUC_ACTION_SAVE,
2709 * Push a hint into hint stack which is implemented with List struct. Head of
2710 * list is top of stack.
2713 push_hint(HintState *hstate)
2715 /* Prepend new hint to the list means pushing to stack. */
2716 HintStateStack = lcons(hstate, HintStateStack);
2718 /* Pushed hint is the one which should be used hereafter. */
2719 current_hint_state = hstate;
2722 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2726 /* Hint stack must not be empty. */
2727 if(HintStateStack == NIL)
2728 elog(ERROR, "hint stack is empty");
2731 * Take a hint at the head from the list, and free it. Switch
2732 * current_hint_state to point new head (NULL if the list is empty).
2734 HintStateStack = list_delete_first(HintStateStack);
2735 HintStateDelete(current_hint_state);
2736 if(HintStateStack == NIL)
2737 current_hint_state = NULL;
2739 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
2743 * Retrieve and store hint string from given query or from the hint table.
2746 get_current_hint_string(Query *query, const char *query_str)
2748 MemoryContext oldcontext;
2750 /* do nothing while scanning hint table */
2751 if (hint_inhibit_level > 0)
2754 /* Make sure trashing old hint string */
2755 if (current_hint_str)
2757 pfree((void *)current_hint_str);
2758 current_hint_str = NULL;
2761 /* Return if nothing to do. */
2762 if (!pg_hint_plan_enable_hint || !query_str)
2765 /* increment the query number */
2767 if (debug_level > 1)
2768 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2771 /* search the hint table for a hint if requested */
2772 if (pg_hint_plan_enable_hint_table)
2774 JumbleState *jstate;
2776 char *normalized_query;
2778 jstate = JumbleQuery(query, query_str);
2781 * Normalize the query string by replacing constants with '?'
2784 * Search hint string which is stored keyed by query string
2785 * and application name. The query string is normalized to allow
2788 * Adding 1 byte to query_len ensures that the returned string has
2789 * a terminating NULL.
2791 query_len = strlen(query_str) + 1;
2793 generate_normalized_query(jstate, query_str, 0, &query_len);
2796 * find a hint for the normalized query. the result should be in
2799 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2801 get_hints_from_table(normalized_query, application_name);
2802 MemoryContextSwitchTo(oldcontext);
2804 if (debug_level > 1)
2806 if (current_hint_str)
2807 ereport(pg_hint_plan_debug_message_level,
2808 (errmsg("pg_hint_plan[qno=0x%x]: "
2809 "hints from table: \"%s\": "
2810 "normalized_query=\"%s\", "
2811 "application name =\"%s\"",
2812 qno, current_hint_str,
2813 normalized_query, application_name),
2814 errhidestmt(msgqno != qno),
2815 errhidecontext(msgqno != qno)));
2817 ereport(pg_hint_plan_debug_message_level,
2818 (errmsg("pg_hint_plan[qno=0x%x]: "
2819 "no match found in table: "
2820 "application name = \"%s\", "
2821 "normalized_query=\"%s\"",
2822 qno, application_name,
2824 errhidestmt(msgqno != qno),
2825 errhidecontext(msgqno != qno)));
2830 /* retrun if we have hint string here */
2831 if (current_hint_str)
2835 /* get hints from the comment */
2836 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2837 current_hint_str = get_hints_from_comment(query_str);
2838 MemoryContextSwitchTo(oldcontext);
2840 if (debug_level > 1)
2842 if (debug_level == 1 && query_str && debug_query_string &&
2843 strcmp(query_str, debug_query_string))
2844 ereport(pg_hint_plan_debug_message_level,
2845 (errmsg("hints in comment=\"%s\"",
2846 current_hint_str ? current_hint_str : "(none)"),
2847 errhidestmt(msgqno != qno),
2848 errhidecontext(msgqno != qno)));
2850 ereport(pg_hint_plan_debug_message_level,
2851 (errmsg("hints in comment=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2852 current_hint_str ? current_hint_str : "(none)",
2853 query_str ? query_str : "(none)",
2854 debug_query_string ? debug_query_string : "(none)"),
2855 errhidestmt(msgqno != qno),
2856 errhidecontext(msgqno != qno)));
2862 * Read and set up hint information
2864 static PlannedStmt *
2865 pg_hint_plan_planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams)
2868 PlannedStmt *result;
2870 const char *prev_hint_str = NULL;
2873 * Use standard planner if pg_hint_plan is disabled or current nesting
2874 * depth is nesting depth of SPI calls. Other hook functions try to change
2875 * plan with current_hint_state if any, so set it to NULL.
2877 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2879 if (debug_level > 1)
2880 ereport(pg_hint_plan_debug_message_level,
2881 (errmsg ("pg_hint_plan%s: planner: enable_hint=%d,"
2882 " hint_inhibit_level=%d",
2883 qnostr, pg_hint_plan_enable_hint,
2884 hint_inhibit_level),
2885 errhidestmt(msgqno != qno)));
2888 goto standard_planner_proc;
2891 /* always retrieve hint from the top-level query string */
2892 if (plpgsql_recurse_level == 0 && current_hint_str)
2894 pfree((void *)current_hint_str);
2895 current_hint_str = NULL;
2898 get_current_hint_string(parse, query_string);
2900 /* No hint, go the normal way */
2901 if (!current_hint_str)
2902 goto standard_planner_proc;
2904 /* parse the hint into hint state struct */
2905 hstate = create_hintstate(parse, pstrdup(current_hint_str));
2907 /* run standard planner if we're given with no valid hints */
2910 /* forget invalid hint string */
2911 if (current_hint_str)
2913 pfree((void *)current_hint_str);
2914 current_hint_str = NULL;
2917 goto standard_planner_proc;
2921 * Push new hint struct to the hint stack to disable previous hint context.
2925 /* Set scan enforcement here. */
2926 save_nestlevel = NewGUCNestLevel();
2928 /* Apply Set hints, then save it as the initial state */
2929 setup_guc_enforcement(current_hint_state->set_hints,
2930 current_hint_state->num_hints[HINT_TYPE_SET],
2931 current_hint_state->context);
2933 current_hint_state->init_scan_mask = get_current_scan_mask();
2934 current_hint_state->init_join_mask = get_current_join_mask();
2935 current_hint_state->init_min_para_tablescan_size =
2936 min_parallel_table_scan_size;
2937 current_hint_state->init_min_para_indexscan_size =
2938 min_parallel_index_scan_size;
2939 current_hint_state->init_paratup_cost = parallel_tuple_cost;
2940 current_hint_state->init_parasetup_cost = parallel_setup_cost;
2943 * max_parallel_workers_per_gather should be non-zero here if Workers hint
2946 if (max_hint_nworkers > 0 && max_parallel_workers_per_gather < 1)
2947 set_config_int32_option("max_parallel_workers_per_gather",
2948 1, current_hint_state->context);
2949 current_hint_state->init_nworkers = max_parallel_workers_per_gather;
2951 if (debug_level > 1)
2953 ereport(pg_hint_plan_debug_message_level,
2954 (errhidestmt(msgqno != qno),
2955 errmsg("pg_hint_plan%s: planner", qnostr)));
2960 * The planner call below may replace current_hint_str. Store and restore
2961 * it so that the subsequent planning in the upper level doesn't get
2965 prev_hint_str = current_hint_str;
2966 current_hint_str = NULL;
2969 * Use PG_TRY mechanism to recover GUC parameters and current_hint_state to
2970 * the state when this planner started when error occurred in planner.
2975 result = (*prev_planner) (parse, query_string,
2976 cursorOptions, boundParams);
2978 result = standard_planner(parse, query_string,
2979 cursorOptions, boundParams);
2981 current_hint_str = prev_hint_str;
2987 * Rollback changes of GUC parameters, and pop current hint context
2988 * from hint stack to rewind the state.
2990 current_hint_str = prev_hint_str;
2992 AtEOXact_GUC(true, save_nestlevel);
3000 * current_hint_str is useless after planning of the top-level query.
3002 if (recurse_level < 1 && current_hint_str)
3004 pfree((void *)current_hint_str);
3005 current_hint_str = NULL;
3008 /* Print hint in debug mode. */
3009 if (debug_level == 1)
3010 HintStateDump(current_hint_state);
3011 else if (debug_level > 1)
3012 HintStateDump2(current_hint_state);
3015 * Rollback changes of GUC parameters, and pop current hint context from
3016 * hint stack to rewind the state.
3018 AtEOXact_GUC(true, save_nestlevel);
3023 standard_planner_proc:
3024 if (debug_level > 1)
3026 ereport(pg_hint_plan_debug_message_level,
3027 (errhidestmt(msgqno != qno),
3028 errmsg("pg_hint_plan%s: planner: no valid hint",
3032 current_hint_state = NULL;
3034 result = (*prev_planner) (parse, query_string,
3035 cursorOptions, boundParams);
3037 result = standard_planner(parse, query_string,
3038 cursorOptions, boundParams);
3040 /* The upper-level planner still needs the current hint state */
3041 if (HintStateStack != NIL)
3042 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
3048 * Find scan method hint to be applied to the given relation
3051 static ScanMethodHint *
3052 find_scan_hint(PlannerInfo *root, Index relid)
3056 ScanMethodHint *real_name_hint = NULL;
3057 ScanMethodHint *alias_hint = NULL;
3060 /* This should not be a join rel */
3062 rel = root->simple_rel_array[relid];
3065 * This function is called for any RelOptInfo or its inheritance parent if
3066 * any. If we are called from inheritance planner, the RelOptInfo for the
3067 * parent of target child relation is not set in the planner info.
3069 * Otherwise we should check that the reloptinfo is base relation or
3070 * inheritance children.
3073 rel->reloptkind != RELOPT_BASEREL &&
3074 rel->reloptkind != RELOPT_OTHER_MEMBER_REL)
3078 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3080 rte = root->simple_rte_array[relid];
3083 /* We don't hint on other than relation and foreign tables */
3084 if (rte->rtekind != RTE_RELATION ||
3085 rte->relkind == RELKIND_FOREIGN_TABLE)
3088 /* Find scan method hint, which matches given names, from the list. */
3089 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
3091 ScanMethodHint *hint = current_hint_state->scan_hints[i];
3093 /* We ignore disabled hints. */
3094 if (!hint_state_enabled(hint))
3098 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3101 /* check the real name for appendrel children */
3102 if (!real_name_hint &&
3103 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3105 char *realname = get_rel_name(rte->relid);
3107 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3108 real_name_hint = hint;
3111 /* No more match expected, break */
3112 if(alias_hint && real_name_hint)
3116 /* real name match precedes alias match */
3118 return real_name_hint;
3123 static ParallelHint *
3124 find_parallel_hint(PlannerInfo *root, Index relid)
3128 ParallelHint *real_name_hint = NULL;
3129 ParallelHint *alias_hint = NULL;
3132 /* This should not be a join rel */
3134 rel = root->simple_rel_array[relid];
3137 * Parallel planning is appliable only on base relation, which has
3144 * We have set root->glob->parallelModeOK if needed. What we should do here
3145 * is just following the decision of planner.
3147 if (!rel->consider_parallel)
3151 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3153 rte = root->simple_rte_array[relid];
3156 /* Find parallel method hint, which matches given names, from the list. */
3157 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_PARALLEL]; i++)
3159 ParallelHint *hint = current_hint_state->parallel_hints[i];
3161 /* We ignore disabled hints. */
3162 if (!hint_state_enabled(hint))
3166 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3169 /* check the real name for appendrel children */
3170 if (!real_name_hint &&
3171 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3173 char *realname = get_rel_name(rte->relid);
3175 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3176 real_name_hint = hint;
3179 /* No more match expected, break */
3180 if(alias_hint && real_name_hint)
3184 /* real name match precedes alias match */
3186 return real_name_hint;
3194 * Returns TRUE on match, FALSE on no match.
3196 * s1 --- the data to match against
3197 * s2 --- the pattern
3199 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
3202 regexpeq(const char *s1, const char *s2)
3208 strcpy(name.data, s1);
3209 regexp = cstring_to_text(s2);
3211 result = DirectFunctionCall2Coll(nameregexeq,
3212 DEFAULT_COLLATION_OID,
3213 NameGetDatum(&name),
3214 PointerGetDatum(regexp));
3215 return DatumGetBool(result);
3219 /* Remove indexes instructed not to use by hint. */
3221 restrict_indexes(PlannerInfo *root, ScanMethodHint *hint, RelOptInfo *rel,
3222 bool using_parent_hint)
3227 RangeTblEntry *rte = root->simple_rte_array[rel->relid];
3228 Oid relationObjectId = rte->relid;
3231 * We delete all the IndexOptInfo list and prevent you from being usable by
3234 if (hint->enforce_mask == ENABLE_SEQSCAN ||
3235 hint->enforce_mask == ENABLE_TIDSCAN)
3237 list_free_deep(rel->indexlist);
3238 rel->indexlist = NIL;
3239 hint->base.state = HINT_STATE_USED;
3245 * When a list of indexes is not specified, we just use all indexes.
3247 if (hint->indexnames == NIL)
3251 * Leaving only an specified index, we delete it from a IndexOptInfo list
3254 if (debug_level > 0)
3255 initStringInfo(&buf);
3257 for (cell = list_head(rel->indexlist); cell; cell = next)
3259 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
3260 char *indexname = get_rel_name(info->indexoid);
3262 bool use_index = false;
3264 next = lnext(rel->indexlist, cell);
3265 foreach(l, hint->indexnames)
3267 char *hintname = (char *) lfirst(l);
3271 result = regexpeq(indexname, hintname);
3273 result = RelnameCmp(&indexname, &hintname) == 0;
3278 if (debug_level > 0)
3280 appendStringInfoCharMacro(&buf, ' ');
3281 quote_value(&buf, indexname);
3289 * Apply index restriction of parent hint to children. Since index
3290 * inheritance is not explicitly described we should search for an
3291 * children's index with the same definition to that of the parent.
3293 if (using_parent_hint && !use_index)
3295 foreach(l, current_hint_state->parent_index_infos)
3299 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
3302 * we check the 'same' index by comparing uniqueness, access
3303 * method and index key columns.
3305 if (p_info->indisunique != info->unique ||
3306 p_info->method != info->relam ||
3307 list_length(p_info->column_names) != info->ncolumns)
3310 /* Check if index key columns match */
3311 for (i = 0; i < info->ncolumns; i++)
3313 char *c_attname = NULL;
3314 char *p_attname = NULL;
3316 p_attname = list_nth(p_info->column_names, i);
3319 * if both of the key of the same position are expressions,
3320 * ignore them for now and check later.
3322 if (info->indexkeys[i] == 0 && !p_attname)
3325 /* deny if one is expression while another is not */
3326 if (info->indexkeys[i] == 0 || !p_attname)
3329 c_attname = get_attname(relationObjectId,
3330 info->indexkeys[i], false);
3332 /* deny if any of column attributes don't match */
3333 if (strcmp(p_attname, c_attname) != 0 ||
3334 p_info->indcollation[i] != info->indexcollations[i] ||
3335 p_info->opclass[i] != info->opcintype[i]||
3336 ((p_info->indoption[i] & INDOPTION_DESC) != 0)
3337 != info->reverse_sort[i] ||
3338 ((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0)
3339 != info->nulls_first[i])
3343 /* deny this if any difference found */
3344 if (i != info->ncolumns)
3347 /* check on key expressions */
3348 if ((p_info->expression_str && (info->indexprs != NIL)) ||
3349 (p_info->indpred_str && (info->indpred != NIL)))
3351 /* fetch the index of this child */
3352 ht_idx = SearchSysCache1(INDEXRELID,
3353 ObjectIdGetDatum(info->indexoid));
3355 /* check expressions if both expressions are available */
3356 if (p_info->expression_str &&
3357 !heap_attisnull(ht_idx, Anum_pg_index_indexprs, NULL))
3364 * to change the expression's parameter of child's
3367 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3368 Anum_pg_index_indexprs,
3371 result = DirectFunctionCall2(pg_get_expr,
3376 /* deny if expressions don't match */
3377 if (strcmp(p_info->expression_str,
3378 text_to_cstring(DatumGetTextP(result))) != 0)
3381 ReleaseSysCache(ht_idx);
3386 /* compare index predicates */
3387 if (p_info->indpred_str &&
3388 !heap_attisnull(ht_idx, Anum_pg_index_indpred, NULL))
3394 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3395 Anum_pg_index_indpred,
3398 result = DirectFunctionCall2(pg_get_expr,
3403 if (strcmp(p_info->indpred_str,
3404 text_to_cstring(DatumGetTextP(result))) != 0)
3407 ReleaseSysCache(ht_idx);
3413 ReleaseSysCache(ht_idx);
3415 else if (p_info->expression_str || (info->indexprs != NIL))
3417 else if (p_info->indpred_str || (info->indpred != NIL))
3422 /* to log the candidate of index */
3423 if (debug_level > 0)
3425 appendStringInfoCharMacro(&buf, ' ');
3426 quote_value(&buf, indexname);
3435 rel->indexlist = list_delete_cell(rel->indexlist, cell);
3438 * The cells after the deleted cell have been moved towards the
3439 * list head by 1 element. the next iteration should visit the
3440 * cell at the same address if any.
3449 if (debug_level == 1)
3451 StringInfoData rel_buf;
3452 char *disprelname = "";
3455 * If this hint targetted the parent, use the real name of this
3456 * child. Otherwise use hint specification.
3458 if (using_parent_hint)
3459 disprelname = get_rel_name(rte->relid);
3461 disprelname = hint->relname;
3464 initStringInfo(&rel_buf);
3465 quote_value(&rel_buf, disprelname);
3467 ereport(pg_hint_plan_debug_message_level,
3468 (errmsg("available indexes for %s(%s):%s",
3473 pfree(rel_buf.data);
3478 * Return information of index definition.
3480 static ParentIndexInfo *
3481 get_parent_index_info(Oid indexoid, Oid relid)
3483 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3484 Relation indexRelation;
3485 Form_pg_index index;
3489 indexRelation = index_open(indexoid, RowExclusiveLock);
3491 index = indexRelation->rd_index;
3493 p_info->indisunique = index->indisunique;
3494 p_info->method = indexRelation->rd_rel->relam;
3496 p_info->column_names = NIL;
3497 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3498 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3499 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3502 * Collect relation attribute names of index columns for index
3503 * identification, not index attribute names. NULL means expression index
3506 for (i = 0; i < index->indnatts; i++)
3508 attname = get_attname(relid, index->indkey.values[i], true);
3509 p_info->column_names = lappend(p_info->column_names, attname);
3511 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3512 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3513 p_info->indoption[i] = indexRelation->rd_indoption[i];
3517 * to check to match the expression's parameter of index with child indexes
3519 p_info->expression_str = NULL;
3520 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs,
3527 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3528 Anum_pg_index_indexprs, &isnull);
3530 result = DirectFunctionCall2(pg_get_expr,
3532 ObjectIdGetDatum(relid));
3534 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3538 * to check to match the predicate's parameter of index with child indexes
3540 p_info->indpred_str = NULL;
3541 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred,
3548 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3549 Anum_pg_index_indpred, &isnull);
3551 result = DirectFunctionCall2(pg_get_expr,
3553 ObjectIdGetDatum(relid));
3555 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3558 index_close(indexRelation, NoLock);
3564 * cancel hint enforcement
3567 reset_hint_enforcement()
3569 setup_scan_method_enforcement(NULL, current_hint_state);
3570 setup_parallel_plan_enforcement(NULL, current_hint_state);
3574 * Set planner guc parameters according to corresponding scan hints. Returns
3575 * bitmap of HintTypeBitmap. If shint or phint is not NULL, set used hint
3576 * there respectively.
3579 setup_hint_enforcement(PlannerInfo *root, RelOptInfo *rel,
3580 ScanMethodHint **rshint, ParallelHint **rphint)
3582 Index new_parent_relid = 0;
3584 ScanMethodHint *shint = NULL;
3585 ParallelHint *phint = NULL;
3586 bool inhparent = root->simple_rte_array[rel->relid]->inh;
3587 Oid relationObjectId = root->simple_rte_array[rel->relid]->relid;
3590 /* reset returns if requested */
3591 if (rshint != NULL) *rshint = NULL;
3592 if (rphint != NULL) *rphint = NULL;
3595 * We could register the parent relation of the following children here
3596 * when inhparent == true but inheritnce planner doesn't call this function
3597 * for parents. Since we cannot distinguish who called this function we
3598 * cannot do other than always seeking the parent regardless of who called
3603 /* set up only parallel hints for parent relation */
3604 phint = find_parallel_hint(root, rel->relid);
3607 setup_parallel_plan_enforcement(phint, current_hint_state);
3608 if (rphint) *rphint = phint;
3609 ret |= HINT_BM_PARALLEL;
3613 if (debug_level > 1)
3614 ereport(pg_hint_plan_debug_message_level,
3616 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3617 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3618 " current_hint_state=%p, hint_inhibit_level=%d",
3619 qnostr, relationObjectId,
3620 get_rel_name(relationObjectId),
3621 inhparent, current_hint_state, hint_inhibit_level)));
3625 if (bms_num_members(rel->top_parent_relids) == 1)
3627 new_parent_relid = bms_next_member(rel->top_parent_relids, -1);
3628 current_hint_state->current_root = root;
3629 Assert(new_parent_relid > 0);
3633 /* This relation doesn't have a parent. Cancel current_hint_state. */
3634 current_hint_state->parent_relid = 0;
3635 current_hint_state->parent_scan_hint = NULL;
3636 current_hint_state->parent_parallel_hint = NULL;
3639 if (new_parent_relid > 0)
3642 * Here we found a new parent for the current relation. Scan continues
3643 * hint to other childrens of this parent so remember it to avoid
3644 * redundant setup cost.
3646 current_hint_state->parent_relid = new_parent_relid;
3648 /* Find hints for the parent */
3649 current_hint_state->parent_scan_hint =
3650 find_scan_hint(root, current_hint_state->parent_relid);
3652 current_hint_state->parent_parallel_hint =
3653 find_parallel_hint(root, current_hint_state->parent_relid);
3656 * If hint is found for the parent, apply it for this child instead
3659 if (current_hint_state->parent_scan_hint)
3661 ScanMethodHint * pshint = current_hint_state->parent_scan_hint;
3663 pshint->base.state = HINT_STATE_USED;
3665 /* Apply index mask in the same manner to the parent. */
3666 if (pshint->indexnames)
3669 Relation parent_rel;
3672 root->simple_rte_array[current_hint_state->parent_relid]->relid;
3673 parent_rel = table_open(parentrel_oid, NoLock);
3675 /* Search the parent relation for indexes match the hint spec */
3676 foreach(l, RelationGetIndexList(parent_rel))
3678 Oid indexoid = lfirst_oid(l);
3679 char *indexname = get_rel_name(indexoid);
3681 ParentIndexInfo *parent_index_info;
3683 foreach(lc, pshint->indexnames)
3685 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3692 get_parent_index_info(indexoid, parentrel_oid);
3693 current_hint_state->parent_index_infos =
3694 lappend(current_hint_state->parent_index_infos,
3697 table_close(parent_rel, NoLock);
3702 shint = find_scan_hint(root, rel->relid);
3704 shint = current_hint_state->parent_scan_hint;
3708 bool using_parent_hint =
3709 (shint == current_hint_state->parent_scan_hint);
3711 ret |= HINT_BM_SCAN_METHOD;
3713 /* Setup scan enforcement environment */
3714 setup_scan_method_enforcement(shint, current_hint_state);
3716 /* restrict unwanted inexes */
3717 restrict_indexes(root, shint, rel, using_parent_hint);
3719 if (debug_level > 1)
3721 char *additional_message = "";
3723 if (shint == current_hint_state->parent_scan_hint)
3724 additional_message = " by parent hint";
3726 ereport(pg_hint_plan_debug_message_level,
3728 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3729 " index deletion%s:"
3730 " relation=%u(%s), inhparent=%d, "
3731 "current_hint_state=%p,"
3732 " hint_inhibit_level=%d, scanmask=0x%x",
3733 qnostr, additional_message,
3735 get_rel_name(relationObjectId),
3736 inhparent, current_hint_state,
3738 shint->enforce_mask)));
3742 /* Do the same for parallel plan enforcement */
3743 phint = find_parallel_hint(root, rel->relid);
3745 phint = current_hint_state->parent_parallel_hint;
3747 setup_parallel_plan_enforcement(phint, current_hint_state);
3750 ret |= HINT_BM_PARALLEL;
3752 /* Nothing to apply. Reset the scan mask to intial state */
3753 if (!shint && ! phint)
3755 if (debug_level > 1)
3756 ereport(pg_hint_plan_debug_message_level,
3757 (errhidestmt (true),
3758 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3760 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3761 " hint_inhibit_level=%d, scanmask=0x%x",
3762 qnostr, relationObjectId,
3763 get_rel_name(relationObjectId),
3764 inhparent, current_hint_state, hint_inhibit_level,
3765 current_hint_state->init_scan_mask)));
3767 setup_scan_method_enforcement(NULL, current_hint_state);
3772 if (rshint != NULL) *rshint = shint;
3773 if (rphint != NULL) *rphint = phint;
3779 * Return index of relation which matches given aliasname, or 0 if not found.
3780 * If same aliasname was used multiple times in a query, return -1.
3783 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3789 for (i = 1; i < root->simple_rel_array_size; i++)
3793 if (root->simple_rel_array[i] == NULL)
3796 Assert(i == root->simple_rel_array[i]->relid);
3798 if (RelnameCmp(&aliasname,
3799 &root->simple_rte_array[i]->eref->aliasname) != 0)
3802 foreach(l, initial_rels)
3804 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3806 if (rel->reloptkind == RELOPT_BASEREL)
3808 if (rel->relid != i)
3813 Assert(rel->reloptkind == RELOPT_JOINREL);
3815 if (!bms_is_member(i, rel->relids))
3822 ("Relation name \"%s\" is ambiguous.",
3837 * Return join hint which matches given joinrelids.
3839 static JoinMethodHint *
3840 find_join_hint(Relids joinrelids)
3845 join_hint = current_hint_state->join_hint_level[bms_num_members(joinrelids)];
3847 foreach(l, join_hint)
3849 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3851 if (bms_equal(joinrelids, hint->joinrelids))
3860 * Return memoize hint which matches given joinrelids.
3862 static JoinMethodHint *
3863 find_memoize_hint(Relids joinrelids)
3868 join_hint = current_hint_state->memoize_hint_level[bms_num_members(joinrelids)];
3870 foreach(l, join_hint)
3872 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3874 if (bms_equal(joinrelids, hint->joinrelids))
3883 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3884 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3886 OuterInnerRels *outer_rels;
3887 OuterInnerRels *inner_rels;
3888 Relids outer_relids;
3889 Relids inner_relids;
3891 JoinMethodHint *hint;
3893 if (outer_inner->relation != NULL)
3895 return bms_make_singleton(
3896 find_relid_aliasname(root, outer_inner->relation,
3898 leading_hint->base.hint_str));
3901 outer_rels = linitial(outer_inner->outer_inner_pair);
3902 inner_rels = llast(outer_inner->outer_inner_pair);
3904 outer_relids = OuterInnerJoinCreate(outer_rels,
3910 inner_relids = OuterInnerJoinCreate(inner_rels,
3917 join_relids = bms_add_members(outer_relids, inner_relids);
3919 if (bms_num_members(join_relids) > nbaserel)
3923 * If we don't have join method hint, create new one for the
3924 * join combination with all join methods are enabled.
3926 hint = find_join_hint(join_relids);
3930 * Here relnames is not set, since Relids bitmap is sufficient to
3931 * control paths of this query afterward.
3933 hint = (JoinMethodHint *) JoinMethodHintCreate(
3934 leading_hint->base.hint_str,
3936 HINT_KEYWORD_LEADING);
3937 hint->base.state = HINT_STATE_USED;
3938 hint->nrels = bms_num_members(join_relids);
3939 hint->enforce_mask = ENABLE_ALL_JOIN;
3940 hint->joinrelids = bms_copy(join_relids);
3941 hint->inner_nrels = bms_num_members(inner_relids);
3942 hint->inner_joinrelids = bms_copy(inner_relids);
3944 hstate->join_hint_level[hint->nrels] =
3945 lappend(hstate->join_hint_level[hint->nrels], hint);
3949 hint->inner_nrels = bms_num_members(inner_relids);
3950 hint->inner_joinrelids = bms_copy(inner_relids);
3957 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3958 int nrels, char **relnames)
3961 Relids relids = NULL;
3965 for (j = 0; j < nrels; j++)
3967 relname = relnames[j];
3969 relid = find_relid_aliasname(root, relname, initial_rels,
3973 base->state = HINT_STATE_ERROR;
3976 * the aliasname is not found(relid == 0) or same aliasname was used
3977 * multiple times in a query(relid == -1)
3984 if (bms_is_member(relid, relids))
3986 hint_ereport(base->hint_str,
3987 ("Relation name \"%s\" is duplicated.", relname));
3988 base->state = HINT_STATE_ERROR;
3992 relids = bms_add_member(relids, relid);
3997 * Transform join method hint into handy form.
3999 * - create bitmap of relids from alias names, to make it easier to check
4000 * whether a join path matches a join method hint.
4001 * - add join method hints which are necessary to enforce join order
4002 * specified by Leading hint
4005 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
4006 List *initial_rels, JoinMethodHint **join_method_hints)
4014 LeadingHint *lhint = NULL;
4017 * Create bitmap of relids from alias names for each join method hint.
4018 * Bitmaps are more handy than strings in join searching.
4020 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
4022 JoinMethodHint *hint = hstate->join_hints[i];
4024 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4027 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4028 initial_rels, hint->nrels, hint->relnames);
4030 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
4033 hstate->join_hint_level[hint->nrels] =
4034 lappend(hstate->join_hint_level[hint->nrels], hint);
4037 /* ditto for memoize hints */
4038 for (i = 0; i < hstate->num_hints[HINT_TYPE_MEMOIZE]; i++)
4040 JoinMethodHint *hint = hstate->join_hints[i];
4042 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4045 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4046 initial_rels, hint->nrels, hint->relnames);
4048 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
4051 hstate->memoize_hint_level[hint->nrels] =
4052 lappend(hstate->memoize_hint_level[hint->nrels], hint);
4056 * Create bitmap of relids from alias names for each rows hint.
4057 * Bitmaps are more handy than strings in join searching.
4059 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
4061 RowsHint *hint = hstate->rows_hints[i];
4063 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4066 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4067 initial_rels, hint->nrels, hint->relnames);
4070 /* Do nothing if no Leading hint was supplied. */
4071 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
4075 * Decide whether to use Leading hint
4077 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
4079 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
4082 if (leading_hint->base.state == HINT_STATE_ERROR)
4088 foreach(l, leading_hint->relations)
4090 relname = (char *)lfirst(l);;
4092 relid = find_relid_aliasname(root, relname, initial_rels,
4093 leading_hint->base.hint_str);
4095 leading_hint->base.state = HINT_STATE_ERROR;
4100 if (bms_is_member(relid, relids))
4102 hint_ereport(leading_hint->base.hint_str,
4103 ("Relation name \"%s\" is duplicated.", relname));
4104 leading_hint->base.state = HINT_STATE_ERROR;
4108 relids = bms_add_member(relids, relid);
4111 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
4116 hint_ereport(lhint->base.hint_str,
4117 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
4118 lhint->base.state = HINT_STATE_DUPLICATION;
4120 leading_hint->base.state = HINT_STATE_USED;
4121 lhint = leading_hint;
4124 /* check to exist Leading hint marked with 'used'. */
4129 * We need join method hints which fit specified join order in every join
4130 * level. For example, Leading(A B C) virtually requires following join
4131 * method hints, if no join method hint supplied:
4133 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
4134 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
4136 * If we already have join method hint which fits specified join order in
4137 * that join level, we leave it as-is and don't add new hints.
4141 if (lhint->outer_inner == NULL)
4143 foreach(l, lhint->relations)
4145 JoinMethodHint *hint;
4147 relname = (char *)lfirst(l);
4150 * Find relid of the relation which has given name. If we have the
4151 * name given in Leading hint multiple times in the join, nothing to
4154 relid = find_relid_aliasname(root, relname, initial_rels,
4157 /* Create bitmap of relids for current join level. */
4158 joinrelids = bms_add_member(joinrelids, relid);
4161 /* We never have join method hint for single relation. */
4166 * If we don't have join method hint, create new one for the
4167 * join combination with all join methods are enabled.
4169 hint = find_join_hint(joinrelids);
4173 * Here relnames is not set, since Relids bitmap is sufficient
4174 * to control paths of this query afterward.
4176 hint = (JoinMethodHint *) JoinMethodHintCreate(
4177 lhint->base.hint_str,
4179 HINT_KEYWORD_LEADING);
4180 hint->base.state = HINT_STATE_USED;
4181 hint->nrels = njoinrels;
4182 hint->enforce_mask = ENABLE_ALL_JOIN;
4183 hint->joinrelids = bms_copy(joinrelids);
4186 join_method_hints[njoinrels] = hint;
4188 if (njoinrels >= nbaserel)
4191 bms_free(joinrelids);
4197 * Delete all join hints which have different combination from Leading
4200 for (i = 2; i <= njoinrels; i++)
4202 list_free(hstate->join_hint_level[i]);
4204 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
4209 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
4216 njoinrels = bms_num_members(joinrelids);
4217 Assert(njoinrels >= 2);
4220 * Delete all join hints which have different combination from Leading
4223 for (i = 2;i <= njoinrels; i++)
4225 if (hstate->join_hint_level[i] != NIL)
4227 ListCell *next = NULL;
4228 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
4231 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
4233 next = lnext(hstate->join_hint_level[i], l);
4235 if (hint->inner_nrels == 0 &&
4236 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
4237 bms_equal(bms_union(hint->joinrelids, joinrelids),
4240 hstate->join_hint_level[i] =
4241 list_delete_cell(hstate->join_hint_level[i], l);
4243 * The cells after the deleted cell have been moved
4244 * towards the list head by 1 element. the next
4245 * iteration should visit the cell at the same address
4255 bms_free(joinrelids);
4258 if (hint_state_enabled(lhint))
4260 set_join_config_options(DISABLE_ALL_JOIN, false,
4261 current_hint_state->context);
4268 * wrapper of make_join_rel()
4270 * call make_join_rel() after changing enable_* parameters according to given
4274 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
4277 JoinMethodHint *join_hint;
4278 JoinMethodHint *memoize_hint;
4282 joinrelids = bms_union(rel1->relids, rel2->relids);
4283 join_hint = find_join_hint(joinrelids);
4284 memoize_hint = find_memoize_hint(joinrelids);
4285 bms_free(joinrelids);
4287 /* reject non-matching hints */
4288 if (join_hint && join_hint->inner_nrels != 0)
4291 if (memoize_hint && memoize_hint->inner_nrels != 0)
4292 memoize_hint = NULL;
4294 if (join_hint || memoize_hint)
4296 save_nestlevel = NewGUCNestLevel();
4299 set_join_config_options(join_hint->enforce_mask, false,
4300 current_hint_state->context);
4305 memoize_hint->base.hint_keyword == HINT_KEYWORD_MEMOIZE;
4306 set_config_option_noerror("enable_memoize",
4307 memoize ? "true" : "false",
4308 current_hint_state->context,
4309 PGC_S_SESSION, GUC_ACTION_SAVE,
4315 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4317 /* Restore the GUC variables we set above. */
4318 if (join_hint || memoize_hint)
4321 join_hint->base.state = HINT_STATE_USED;
4324 memoize_hint->base.state = HINT_STATE_USED;
4326 AtEOXact_GUC(true, save_nestlevel);
4336 add_paths_to_joinrel_wrapper(PlannerInfo *root,
4337 RelOptInfo *joinrel,
4338 RelOptInfo *outerrel,
4339 RelOptInfo *innerrel,
4341 SpecialJoinInfo *sjinfo,
4345 JoinMethodHint *join_hint;
4346 JoinMethodHint *memoize_hint;
4349 joinrelids = bms_union(outerrel->relids, innerrel->relids);
4350 join_hint = find_join_hint(joinrelids);
4351 memoize_hint = find_memoize_hint(joinrelids);
4352 bms_free(joinrelids);
4354 /* reject the found hints if they don't match this join */
4355 if (join_hint && join_hint->inner_nrels == 0)
4358 if (memoize_hint && memoize_hint->inner_nrels == 0)
4359 memoize_hint = NULL;
4361 /* set up configuration if needed */
4362 if (join_hint || memoize_hint)
4364 save_nestlevel = NewGUCNestLevel();
4368 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
4369 set_join_config_options(join_hint->enforce_mask, false,
4370 current_hint_state->context);
4372 set_join_config_options(DISABLE_ALL_JOIN, false,
4373 current_hint_state->context);
4379 memoize_hint->base.hint_keyword == HINT_KEYWORD_MEMOIZE;
4380 set_config_option_noerror("enable_memoize",
4381 memoize ? "true" : "false",
4382 current_hint_state->context,
4383 PGC_S_SESSION, GUC_ACTION_SAVE,
4388 /* generate paths */
4389 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4390 sjinfo, restrictlist);
4392 /* restore GUC variables */
4393 if (join_hint || memoize_hint)
4396 join_hint->base.state = HINT_STATE_USED;
4399 memoize_hint->base.state = HINT_STATE_USED;
4401 AtEOXact_GUC(true, save_nestlevel);
4406 get_num_baserels(List *initial_rels)
4411 foreach(l, initial_rels)
4413 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
4415 if (rel->reloptkind == RELOPT_BASEREL)
4417 else if (rel->reloptkind ==RELOPT_JOINREL)
4418 nbaserel+= bms_num_members(rel->relids);
4421 /* other values not expected here */
4422 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
4430 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
4433 JoinMethodHint **join_method_hints;
4437 bool leading_hint_enable;
4440 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
4441 * valid hint is supplied or current nesting depth is nesting depth of SPI
4444 if (!current_hint_state || hint_inhibit_level > 0)
4446 if (prev_join_search)
4447 return (*prev_join_search) (root, levels_needed, initial_rels);
4448 else if (enable_geqo && levels_needed >= geqo_threshold)
4449 return geqo(root, levels_needed, initial_rels);
4451 return standard_join_search(root, levels_needed, initial_rels);
4455 * In the case using GEQO, only scan method hints and Set hints have
4456 * effect. Join method and join order is not controllable by hints.
4458 if (enable_geqo && levels_needed >= geqo_threshold)
4459 return geqo(root, levels_needed, initial_rels);
4461 nbaserel = get_num_baserels(initial_rels);
4462 current_hint_state->join_hint_level =
4463 palloc0(sizeof(List *) * (nbaserel + 1));
4464 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4465 current_hint_state->memoize_hint_level =
4466 palloc0(sizeof(List *) * (nbaserel + 1));
4468 leading_hint_enable = transform_join_hints(current_hint_state,
4470 initial_rels, join_method_hints);
4472 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4475 * Adjust number of parallel workers of the result rel to the largest
4476 * number of the component paths.
4478 if (current_hint_state->num_hints[HINT_TYPE_PARALLEL] > 0)
4483 foreach (lc, initial_rels)
4486 RelOptInfo *rel = (RelOptInfo *) lfirst(lc);
4488 foreach (lcp, rel->partial_pathlist)
4490 Path *path = (Path *) lfirst(lcp);
4492 if (nworkers < path-> parallel_workers)
4493 nworkers = path-> parallel_workers;
4497 foreach (lc, rel->partial_pathlist)
4499 Path *path = (Path *) lfirst(lc);
4501 if (path->parallel_safe && path->parallel_workers < nworkers)
4502 path->parallel_workers = nworkers;
4506 for (i = 2; i <= nbaserel; i++)
4508 list_free(current_hint_state->join_hint_level[i]);
4510 /* free Leading hint only */
4511 if (join_method_hints[i] != NULL &&
4512 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4513 JoinMethodHintDelete(join_method_hints[i]);
4515 pfree(current_hint_state->join_hint_level);
4516 pfree(join_method_hints);
4518 if (leading_hint_enable)
4519 set_join_config_options(current_hint_state->init_join_mask, true,
4520 current_hint_state->context);
4526 * Force number of wokers if instructed by hint
4529 pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
4530 Index rti, RangeTblEntry *rte)
4532 ParallelHint *phint;
4536 /* call the previous hook */
4537 if (prev_set_rel_pathlist)
4538 prev_set_rel_pathlist(root, rel, rti, rte);
4540 /* Nothing to do if no hint available */
4541 if (current_hint_state == NULL)
4544 /* Don't touch dummy rels. */
4545 if (IS_DUMMY_REL(rel))
4549 * We can accept only plain relations, foreign tables and table saples are
4550 * also unacceptable. See set_rel_pathlist.
4552 if ((rel->rtekind != RTE_RELATION &&
4553 rel->rtekind != RTE_SUBQUERY)||
4554 rte->relkind == RELKIND_FOREIGN_TABLE ||
4555 rte->tablesample != NULL)
4559 * Even though UNION ALL node doesn't have particular name so usually it is
4560 * unhintable, turn on parallel when it contains parallel nodes.
4562 if (rel->rtekind == RTE_SUBQUERY)
4565 bool inhibit_nonparallel = false;
4567 if (rel->partial_pathlist == NIL)
4570 foreach(lc, rel->partial_pathlist)
4573 AppendPath *apath = (AppendPath *) lfirst(lc);
4574 int parallel_workers = 0;
4576 if (!IsA(apath, AppendPath))
4579 foreach (lcp, apath->subpaths)
4581 Path *spath = (Path *) lfirst(lcp);
4583 if (spath->parallel_aware &&
4584 parallel_workers < spath->parallel_workers)
4585 parallel_workers = spath->parallel_workers;
4588 apath->path.parallel_workers = parallel_workers;
4589 inhibit_nonparallel = true;
4592 if (inhibit_nonparallel)
4596 foreach(lc, rel->pathlist)
4598 Path *path = (Path *) lfirst(lc);
4600 if (path->startup_cost < disable_cost)
4602 path->startup_cost += disable_cost;
4603 path->total_cost += disable_cost;
4611 /* We cannot handle if this requires an outer */
4612 if (rel->lateral_relids)
4615 /* Return if this relation gets no enfocement */
4616 if ((found_hints = setup_hint_enforcement(root, rel, NULL, &phint)) == 0)
4619 /* Here, we regenerate paths with the current hint restriction */
4620 if (found_hints & HINT_BM_SCAN_METHOD || found_hints & HINT_BM_PARALLEL)
4623 * When hint is specified on non-parent relations, discard existing
4624 * paths and regenerate based on the hint considered. Otherwise we
4625 * already have hinted childx paths then just adjust the number of
4626 * planned number of workers.
4628 if (root->simple_rte_array[rel->relid]->inh)
4630 /* enforce number of workers if requested */
4631 if (phint && phint->force_parallel)
4633 if (phint->nworkers == 0)
4635 list_free_deep(rel->partial_pathlist);
4636 rel->partial_pathlist = NIL;
4640 /* prioritize partial paths */
4641 foreach (l, rel->partial_pathlist)
4643 Path *ppath = (Path *) lfirst(l);
4645 if (ppath->parallel_safe)
4647 ppath->parallel_workers = phint->nworkers;
4648 ppath->startup_cost = 0;
4649 ppath->total_cost = 0;
4653 /* disable non-partial paths */
4654 foreach (l, rel->pathlist)
4656 Path *ppath = (Path *) lfirst(l);
4658 if (ppath->startup_cost < disable_cost)
4660 ppath->startup_cost += disable_cost;
4661 ppath->total_cost += disable_cost;
4669 /* Just discard all the paths considered so far */
4670 list_free_deep(rel->pathlist);
4671 rel->pathlist = NIL;
4672 list_free_deep(rel->partial_pathlist);
4673 rel->partial_pathlist = NIL;
4675 /* Regenerate paths with the current enforcement */
4676 set_plain_rel_pathlist(root, rel, rte);
4678 /* Additional work to enforce parallel query execution */
4679 if (phint && phint->nworkers > 0)
4682 * For Parallel Append to be planned properly, we shouldn't set
4683 * the costs of non-partial paths to disable-value. Lower the
4684 * priority of non-parallel paths by setting partial path costs
4687 foreach (l, rel->partial_pathlist)
4689 Path *path = (Path *) lfirst(l);
4691 path->startup_cost = 0;
4692 path->total_cost = 0;
4695 /* enforce number of workers if requested */
4696 if (phint->force_parallel)
4698 foreach (l, rel->partial_pathlist)
4700 Path *ppath = (Path *) lfirst(l);
4702 if (ppath->parallel_safe)
4703 ppath->parallel_workers = phint->nworkers;
4707 /* Generate gather paths */
4708 if (rel->reloptkind == RELOPT_BASEREL &&
4709 bms_membership(root->all_baserels) != BMS_SINGLETON)
4710 generate_gather_paths(root, rel, false);
4715 reset_hint_enforcement();
4719 * stmt_beg callback is called when each query in PL/pgSQL function is about
4720 * to be executed. At that timing, we save query string in the global variable
4721 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4722 * variable for the purpose, because its content is only necessary until
4723 * planner hook is called for the query, so recursive PL/pgSQL function calls
4724 * don't harm this mechanism.
4727 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4729 plpgsql_recurse_level++;
4733 * stmt_end callback is called then each query in PL/pgSQL function has
4734 * finished. At that timing, we clear plpgsql_query_string to tell planner
4735 * hook that next call is not for a query written in PL/pgSQL block.
4738 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4740 plpgsql_recurse_level--;
4743 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4748 if (!isTopLevel || phase != RESOURCE_RELEASE_AFTER_LOCKS)
4750 /* Cancel plpgsql nest level*/
4751 plpgsql_recurse_level = 0;
4755 /* include core static functions */
4756 static void populate_joinrel_with_paths(PlannerInfo *root, RelOptInfo *rel1,
4757 RelOptInfo *rel2, RelOptInfo *joinrel,
4758 SpecialJoinInfo *sjinfo, List *restrictlist);
4759 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4760 Index rti, RangeTblEntry *rte);
4762 #define standard_join_search pg_hint_plan_standard_join_search
4763 #define join_search_one_level pg_hint_plan_join_search_one_level
4764 #define make_join_rel make_join_rel_wrapper
4767 #undef make_join_rel
4768 #define make_join_rel pg_hint_plan_make_join_rel
4769 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4770 #include "make_join_rel.c"
4772 #include "pg_stat_statements.c"