1 /*-------------------------------------------------------------------------
4 * hinting on how to execute a query for PostgreSQL
6 * Copyright (c) 2012-2020, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
8 *-------------------------------------------------------------------------
13 #include "catalog/pg_collation.h"
14 #include "catalog/pg_index.h"
15 #include "commands/prepare.h"
16 #include "mb/pg_wchar.h"
17 #include "miscadmin.h"
18 #include "nodes/nodeFuncs.h"
19 #include "nodes/params.h"
20 #include "nodes/relation.h"
21 #include "optimizer/clauses.h"
22 #include "optimizer/cost.h"
23 #include "optimizer/geqo.h"
24 #include "optimizer/joininfo.h"
25 #include "optimizer/pathnode.h"
26 #include "optimizer/paths.h"
27 #include "optimizer/plancat.h"
28 #include "optimizer/planner.h"
29 #include "optimizer/prep.h"
30 #include "optimizer/restrictinfo.h"
31 #include "parser/analyze.h"
32 #include "parser/parsetree.h"
33 #include "parser/scansup.h"
34 #include "partitioning/partbounds.h"
35 #include "tcop/utility.h"
36 #include "utils/builtins.h"
37 #include "utils/lsyscache.h"
38 #include "utils/memutils.h"
39 #include "utils/rel.h"
40 #include "utils/snapmgr.h"
41 #include "utils/syscache.h"
42 #include "utils/resowner.h"
44 #include "catalog/pg_class.h"
46 #include "executor/spi.h"
47 #include "catalog/pg_type.h"
51 /* partially copied from pg_stat_statements */
52 #include "normalize_query.h"
55 #include "access/htup_details.h"
57 #ifdef PG_MODULE_MAGIC
61 #define BLOCK_COMMENT_START "/*"
62 #define BLOCK_COMMENT_END "*/"
63 #define HINT_COMMENT_KEYWORD "+"
64 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
65 #define HINT_END BLOCK_COMMENT_END
68 #define HINT_SEQSCAN "SeqScan"
69 #define HINT_INDEXSCAN "IndexScan"
70 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
71 #define HINT_BITMAPSCAN "BitmapScan"
72 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
73 #define HINT_TIDSCAN "TidScan"
74 #define HINT_NOSEQSCAN "NoSeqScan"
75 #define HINT_NOINDEXSCAN "NoIndexScan"
76 #define HINT_NOBITMAPSCAN "NoBitmapScan"
77 #define HINT_NOTIDSCAN "NoTidScan"
78 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
79 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
80 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
81 #define HINT_PARALLEL "Parallel"
83 #define HINT_NESTLOOP "NestLoop"
84 #define HINT_MERGEJOIN "MergeJoin"
85 #define HINT_HASHJOIN "HashJoin"
86 #define HINT_NONESTLOOP "NoNestLoop"
87 #define HINT_NOMERGEJOIN "NoMergeJoin"
88 #define HINT_NOHASHJOIN "NoHashJoin"
89 #define HINT_LEADING "Leading"
90 #define HINT_SET "Set"
91 #define HINT_ROWS "Rows"
93 #define HINT_ARRAY_DEFAULT_INITSIZE 8
95 #define hint_ereport(str, detail) hint_parse_ereport(str, detail)
96 #define hint_parse_ereport(str, detail) \
98 ereport(pg_hint_plan_parse_message_level, \
99 (errmsg("pg_hint_plan: hint syntax error at or near \"%s\"", (str)), \
100 errdetail detail)); \
103 #define skip_space(str) \
104 while (isspace(*str)) \
109 ENABLE_SEQSCAN = 0x01,
110 ENABLE_INDEXSCAN = 0x02,
111 ENABLE_BITMAPSCAN = 0x04,
112 ENABLE_TIDSCAN = 0x08,
113 ENABLE_INDEXONLYSCAN = 0x10
118 ENABLE_NESTLOOP = 0x01,
119 ENABLE_MERGEJOIN = 0x02,
120 ENABLE_HASHJOIN = 0x04
123 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
124 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
125 ENABLE_INDEXONLYSCAN)
126 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
127 #define DISABLE_ALL_SCAN 0
128 #define DISABLE_ALL_JOIN 0
130 /* hint keyword of enum type*/
131 typedef enum HintKeyword
133 HINT_KEYWORD_SEQSCAN,
134 HINT_KEYWORD_INDEXSCAN,
135 HINT_KEYWORD_INDEXSCANREGEXP,
136 HINT_KEYWORD_BITMAPSCAN,
137 HINT_KEYWORD_BITMAPSCANREGEXP,
138 HINT_KEYWORD_TIDSCAN,
139 HINT_KEYWORD_NOSEQSCAN,
140 HINT_KEYWORD_NOINDEXSCAN,
141 HINT_KEYWORD_NOBITMAPSCAN,
142 HINT_KEYWORD_NOTIDSCAN,
143 HINT_KEYWORD_INDEXONLYSCAN,
144 HINT_KEYWORD_INDEXONLYSCANREGEXP,
145 HINT_KEYWORD_NOINDEXONLYSCAN,
147 HINT_KEYWORD_NESTLOOP,
148 HINT_KEYWORD_MERGEJOIN,
149 HINT_KEYWORD_HASHJOIN,
150 HINT_KEYWORD_NONESTLOOP,
151 HINT_KEYWORD_NOMERGEJOIN,
152 HINT_KEYWORD_NOHASHJOIN,
154 HINT_KEYWORD_LEADING,
157 HINT_KEYWORD_PARALLEL,
159 HINT_KEYWORD_UNRECOGNIZED
162 #define SCAN_HINT_ACCEPTS_INDEX_NAMES(kw) \
163 (kw == HINT_KEYWORD_INDEXSCAN || \
164 kw == HINT_KEYWORD_INDEXSCANREGEXP || \
165 kw == HINT_KEYWORD_INDEXONLYSCAN || \
166 kw == HINT_KEYWORD_INDEXONLYSCANREGEXP || \
167 kw == HINT_KEYWORD_BITMAPSCAN || \
168 kw == HINT_KEYWORD_BITMAPSCANREGEXP)
171 typedef struct Hint Hint;
172 typedef struct HintState HintState;
174 typedef Hint *(*HintCreateFunction) (const char *hint_str,
176 HintKeyword hint_keyword);
177 typedef void (*HintDeleteFunction) (Hint *hint);
178 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf, bool nolf);
179 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
180 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
181 Query *parse, const char *str);
184 #define NUM_HINT_TYPE 6
185 typedef enum HintType
187 HINT_TYPE_SCAN_METHOD,
188 HINT_TYPE_JOIN_METHOD,
195 typedef enum HintTypeBitmap
197 HINT_BM_SCAN_METHOD = 1,
201 static const char *HintTypeName[] = {
211 typedef enum HintStatus
213 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
214 HINT_STATE_USED, /* hint is used */
215 HINT_STATE_DUPLICATION, /* specified hint duplication */
216 HINT_STATE_ERROR /* execute error (parse error does not include
220 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
221 (hint)->base.state == HINT_STATE_USED)
223 static unsigned int qno = 0;
224 static unsigned int msgqno = 0;
225 static char qnostr[32];
226 static const char *current_hint_str = NULL;
229 * However we usually take a hint stirng in post_parse_analyze_hook, we still
230 * need to do so in planner_hook when client starts query execution from the
231 * bind message on a prepared query. This variable prevent duplicate and
232 * sometimes harmful hint string retrieval.
234 static bool current_hint_retrieved = false;
236 /* common data for all hints. */
239 const char *hint_str; /* must not do pfree */
240 const char *keyword; /* must not do pfree */
241 HintKeyword hint_keyword;
244 HintDeleteFunction delete_func;
245 HintDescFunction desc_func;
246 HintCmpFunction cmp_func;
247 HintParseFunction parse_func;
250 /* scan method hints */
251 typedef struct ScanMethodHint
257 unsigned char enforce_mask;
260 typedef struct ParentIndexInfo
265 char *expression_str;
272 /* join method hints */
273 typedef struct JoinMethodHint
279 unsigned char enforce_mask;
281 Relids inner_joinrelids;
284 /* join order hints */
285 typedef struct OuterInnerRels
288 List *outer_inner_pair;
291 typedef struct LeadingHint
294 List *relations; /* relation names specified in Leading hint */
295 OuterInnerRels *outer_inner;
298 /* change a run-time parameter hints */
299 typedef struct SetHint
302 char *name; /* name of variable */
308 typedef enum RowsValueType {
309 RVT_ABSOLUTE, /* Rows(... #1000) */
310 RVT_ADD, /* Rows(... +1000) */
311 RVT_SUB, /* Rows(... -1000) */
312 RVT_MULTI, /* Rows(... *1.2) */
314 typedef struct RowsHint
321 Relids inner_joinrelids;
323 RowsValueType value_type;
328 typedef struct ParallelHint
332 char *nworkers_str; /* original string of nworkers */
333 int nworkers; /* num of workers specified by Worker */
334 bool force_parallel; /* force parallel scan */
338 * Describes a context of hint processing.
342 char *hint_str; /* original hint string */
345 int nall_hints; /* # of valid all hints */
346 int max_all_hints; /* # of slots for all hints */
347 Hint **all_hints; /* parsed all hints */
349 /* # of each hints */
350 int num_hints[NUM_HINT_TYPE];
352 /* for scan method hints */
353 ScanMethodHint **scan_hints; /* parsed scan hints */
355 /* Initial values of parameters */
356 int init_scan_mask; /* enable_* mask */
357 int init_nworkers; /* max_parallel_workers_per_gather */
358 /* min_parallel_table_scan_size*/
359 int init_min_para_tablescan_size;
360 /* min_parallel_index_scan_size*/
361 int init_min_para_indexscan_size;
362 double init_paratup_cost; /* parallel_tuple_cost */
363 double init_parasetup_cost;/* parallel_setup_cost */
365 PlannerInfo *current_root; /* PlannerInfo for the followings */
366 Index parent_relid; /* inherit parent of table relid */
367 ScanMethodHint *parent_scan_hint; /* scan hint for the parent */
368 ParallelHint *parent_parallel_hint; /* parallel hint for the parent */
369 List *parent_index_infos; /* list of parent table's index */
371 JoinMethodHint **join_hints; /* parsed join hints */
372 int init_join_mask; /* initial value join parameter */
373 List **join_hint_level;
374 LeadingHint **leading_hint; /* parsed Leading hints */
375 SetHint **set_hints; /* parsed Set hints */
376 GucContext context; /* which GUC parameters can we set? */
377 RowsHint **rows_hints; /* parsed Rows hints */
378 ParallelHint **parallel_hints; /* parsed Parallel hints */
382 * Describes a hint parser module which is bound with particular hint keyword.
384 typedef struct HintParser
387 HintCreateFunction create_func;
388 HintKeyword hint_keyword;
391 /* Module callbacks */
395 static void push_hint(HintState *hstate);
396 static void pop_hint(void);
398 static void pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query);
399 static void pg_hint_plan_ProcessUtility(PlannedStmt *pstmt,
400 const char *queryString,
401 ProcessUtilityContext context,
402 ParamListInfo params, QueryEnvironment *queryEnv,
403 DestReceiver *dest, char *completionTag);
404 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
405 ParamListInfo boundParams);
406 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
410 /* Scan method hint callbacks */
411 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
412 HintKeyword hint_keyword);
413 static void ScanMethodHintDelete(ScanMethodHint *hint);
414 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
415 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
416 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
417 Query *parse, const char *str);
419 /* Join method hint callbacks */
420 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
421 HintKeyword hint_keyword);
422 static void JoinMethodHintDelete(JoinMethodHint *hint);
423 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
424 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
425 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
426 Query *parse, const char *str);
428 /* Leading hint callbacks */
429 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
430 HintKeyword hint_keyword);
431 static void LeadingHintDelete(LeadingHint *hint);
432 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
433 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
434 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
435 Query *parse, const char *str);
437 /* Set hint callbacks */
438 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
439 HintKeyword hint_keyword);
440 static void SetHintDelete(SetHint *hint);
441 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
442 static int SetHintCmp(const SetHint *a, const SetHint *b);
443 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
446 /* Rows hint callbacks */
447 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
448 HintKeyword hint_keyword);
449 static void RowsHintDelete(RowsHint *hint);
450 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
451 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
452 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
453 Query *parse, const char *str);
455 /* Parallel hint callbacks */
456 static Hint *ParallelHintCreate(const char *hint_str, const char *keyword,
457 HintKeyword hint_keyword);
458 static void ParallelHintDelete(ParallelHint *hint);
459 static void ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf);
460 static int ParallelHintCmp(const ParallelHint *a, const ParallelHint *b);
461 static const char *ParallelHintParse(ParallelHint *hint, HintState *hstate,
462 Query *parse, const char *str);
464 static void quote_value(StringInfo buf, const char *value);
466 static const char *parse_quoted_value(const char *str, char **word,
469 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
472 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
473 void pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
474 Index rti, RangeTblEntry *rte);
475 static void create_plain_partial_paths(PlannerInfo *root,
477 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
478 ListCell *other_rels);
479 static void make_rels_by_clauseless_joins(PlannerInfo *root,
481 ListCell *other_rels);
482 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
483 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
485 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
486 Index rti, RangeTblEntry *rte);
487 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
490 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
492 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
494 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
498 static int set_config_option_noerror(const char *name, const char *value,
499 GucContext context, GucSource source,
500 GucAction action, bool changeVal, int elevel);
501 static void setup_scan_method_enforcement(ScanMethodHint *scanhint,
503 static int set_config_int32_option(const char *name, int32 value,
505 static int set_config_double_option(const char *name, double value,
509 static bool pg_hint_plan_enable_hint = true;
510 static int debug_level = 0;
511 static int pg_hint_plan_parse_message_level = INFO;
512 static int pg_hint_plan_debug_message_level = LOG;
513 /* Default is off, to keep backward compatibility. */
514 static bool pg_hint_plan_enable_hint_table = false;
516 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
517 static int recurse_level = 0; /* recursion level incl. direct SPI calls */
518 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
519 /* (This could not be above 1) */
520 static int max_hint_nworkers = -1; /* Maximum nworkers of Workers hints */
522 static const struct config_enum_entry parse_messages_level_options[] = {
523 {"debug", DEBUG2, true},
524 {"debug5", DEBUG5, false},
525 {"debug4", DEBUG4, false},
526 {"debug3", DEBUG3, false},
527 {"debug2", DEBUG2, false},
528 {"debug1", DEBUG1, false},
530 {"info", INFO, false},
531 {"notice", NOTICE, false},
532 {"warning", WARNING, false},
533 {"error", ERROR, false},
535 * {"fatal", FATAL, true},
536 * {"panic", PANIC, true},
541 static const struct config_enum_entry parse_debug_level_options[] = {
544 {"detailed", 2, false},
545 {"verbose", 3, false},
557 /* Saved hook values in case of unload */
558 static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
559 static planner_hook_type prev_planner = NULL;
560 static join_search_hook_type prev_join_search = NULL;
561 static set_rel_pathlist_hook_type prev_set_rel_pathlist = NULL;
562 static ProcessUtility_hook_type prev_ProcessUtility_hook = NULL;
564 /* Hold reference to currently active hint */
565 static HintState *current_hint_state = NULL;
568 * List of hint contexts. We treat the head of the list as the Top of the
569 * context stack, so current_hint_state always points the first element of this
572 static List *HintStateStack = NIL;
574 static const HintParser parsers[] = {
575 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
576 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
577 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
578 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
579 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
580 HINT_KEYWORD_BITMAPSCANREGEXP},
581 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
582 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
583 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
584 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
585 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
586 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
587 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
588 HINT_KEYWORD_INDEXONLYSCANREGEXP},
589 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
591 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
592 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
593 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
594 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
595 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
596 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
598 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
599 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
600 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
601 {HINT_PARALLEL, ParallelHintCreate, HINT_KEYWORD_PARALLEL},
603 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
606 PLpgSQL_plugin plugin_funcs = {
610 pg_hint_plan_plpgsql_stmt_beg,
611 pg_hint_plan_plpgsql_stmt_end,
617 * Module load callbacks
622 PLpgSQL_plugin **var_ptr;
624 /* Define custom GUC variables. */
625 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
626 "Force planner to use plans specified in the hint comment preceding to the query.",
628 &pg_hint_plan_enable_hint,
636 DefineCustomEnumVariable("pg_hint_plan.debug_print",
637 "Logs results of hint parsing.",
641 parse_debug_level_options,
648 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
649 "Message level of parse errors.",
651 &pg_hint_plan_parse_message_level,
653 parse_messages_level_options,
660 DefineCustomEnumVariable("pg_hint_plan.message_level",
661 "Message level of debug messages.",
663 &pg_hint_plan_debug_message_level,
665 parse_messages_level_options,
672 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
673 "Let pg_hint_plan look up the hint table.",
675 &pg_hint_plan_enable_hint_table,
684 prev_post_parse_analyze_hook = post_parse_analyze_hook;
685 post_parse_analyze_hook = pg_hint_plan_post_parse_analyze;
686 prev_planner = planner_hook;
687 planner_hook = pg_hint_plan_planner;
688 prev_join_search = join_search_hook;
689 join_search_hook = pg_hint_plan_join_search;
690 prev_set_rel_pathlist = set_rel_pathlist_hook;
691 set_rel_pathlist_hook = pg_hint_plan_set_rel_pathlist;
692 prev_ProcessUtility_hook = ProcessUtility_hook;
693 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
695 /* setup PL/pgSQL plugin hook */
696 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
697 *var_ptr = &plugin_funcs;
699 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
703 * Module unload callback
709 PLpgSQL_plugin **var_ptr;
711 /* Uninstall hooks. */
712 post_parse_analyze_hook = prev_post_parse_analyze_hook;
713 planner_hook = prev_planner;
714 join_search_hook = prev_join_search;
715 set_rel_pathlist_hook = prev_set_rel_pathlist;
716 ProcessUtility_hook = prev_ProcessUtility_hook;
718 /* uninstall PL/pgSQL plugin hook */
719 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
724 * create and delete functions the hint object
728 ScanMethodHintCreate(const char *hint_str, const char *keyword,
729 HintKeyword hint_keyword)
731 ScanMethodHint *hint;
733 hint = palloc(sizeof(ScanMethodHint));
734 hint->base.hint_str = hint_str;
735 hint->base.keyword = keyword;
736 hint->base.hint_keyword = hint_keyword;
737 hint->base.type = HINT_TYPE_SCAN_METHOD;
738 hint->base.state = HINT_STATE_NOTUSED;
739 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
740 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
741 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
742 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
743 hint->relname = NULL;
744 hint->indexnames = NIL;
745 hint->regexp = false;
746 hint->enforce_mask = 0;
748 return (Hint *) hint;
752 ScanMethodHintDelete(ScanMethodHint *hint)
758 pfree(hint->relname);
759 list_free_deep(hint->indexnames);
764 JoinMethodHintCreate(const char *hint_str, const char *keyword,
765 HintKeyword hint_keyword)
767 JoinMethodHint *hint;
769 hint = palloc(sizeof(JoinMethodHint));
770 hint->base.hint_str = hint_str;
771 hint->base.keyword = keyword;
772 hint->base.hint_keyword = hint_keyword;
773 hint->base.type = HINT_TYPE_JOIN_METHOD;
774 hint->base.state = HINT_STATE_NOTUSED;
775 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
776 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
777 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
778 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
780 hint->inner_nrels = 0;
781 hint->relnames = NULL;
782 hint->enforce_mask = 0;
783 hint->joinrelids = NULL;
784 hint->inner_joinrelids = NULL;
786 return (Hint *) hint;
790 JoinMethodHintDelete(JoinMethodHint *hint)
799 for (i = 0; i < hint->nrels; i++)
800 pfree(hint->relnames[i]);
801 pfree(hint->relnames);
804 bms_free(hint->joinrelids);
805 bms_free(hint->inner_joinrelids);
810 LeadingHintCreate(const char *hint_str, const char *keyword,
811 HintKeyword hint_keyword)
815 hint = palloc(sizeof(LeadingHint));
816 hint->base.hint_str = hint_str;
817 hint->base.keyword = keyword;
818 hint->base.hint_keyword = hint_keyword;
819 hint->base.type = HINT_TYPE_LEADING;
820 hint->base.state = HINT_STATE_NOTUSED;
821 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
822 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
823 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
824 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
825 hint->relations = NIL;
826 hint->outer_inner = NULL;
828 return (Hint *) hint;
832 LeadingHintDelete(LeadingHint *hint)
837 list_free_deep(hint->relations);
838 if (hint->outer_inner)
839 pfree(hint->outer_inner);
844 SetHintCreate(const char *hint_str, const char *keyword,
845 HintKeyword hint_keyword)
849 hint = palloc(sizeof(SetHint));
850 hint->base.hint_str = hint_str;
851 hint->base.keyword = keyword;
852 hint->base.hint_keyword = hint_keyword;
853 hint->base.type = HINT_TYPE_SET;
854 hint->base.state = HINT_STATE_NOTUSED;
855 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
856 hint->base.desc_func = (HintDescFunction) SetHintDesc;
857 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
858 hint->base.parse_func = (HintParseFunction) SetHintParse;
863 return (Hint *) hint;
867 SetHintDelete(SetHint *hint)
877 list_free(hint->words);
882 RowsHintCreate(const char *hint_str, const char *keyword,
883 HintKeyword hint_keyword)
887 hint = palloc(sizeof(RowsHint));
888 hint->base.hint_str = hint_str;
889 hint->base.keyword = keyword;
890 hint->base.hint_keyword = hint_keyword;
891 hint->base.type = HINT_TYPE_ROWS;
892 hint->base.state = HINT_STATE_NOTUSED;
893 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
894 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
895 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
896 hint->base.parse_func = (HintParseFunction) RowsHintParse;
898 hint->inner_nrels = 0;
899 hint->relnames = NULL;
900 hint->joinrelids = NULL;
901 hint->inner_joinrelids = NULL;
902 hint->rows_str = NULL;
903 hint->value_type = RVT_ABSOLUTE;
906 return (Hint *) hint;
910 RowsHintDelete(RowsHint *hint)
919 for (i = 0; i < hint->nrels; i++)
920 pfree(hint->relnames[i]);
921 pfree(hint->relnames);
924 bms_free(hint->joinrelids);
925 bms_free(hint->inner_joinrelids);
930 ParallelHintCreate(const char *hint_str, const char *keyword,
931 HintKeyword hint_keyword)
935 hint = palloc(sizeof(ParallelHint));
936 hint->base.hint_str = hint_str;
937 hint->base.keyword = keyword;
938 hint->base.hint_keyword = hint_keyword;
939 hint->base.type = HINT_TYPE_PARALLEL;
940 hint->base.state = HINT_STATE_NOTUSED;
941 hint->base.delete_func = (HintDeleteFunction) ParallelHintDelete;
942 hint->base.desc_func = (HintDescFunction) ParallelHintDesc;
943 hint->base.cmp_func = (HintCmpFunction) ParallelHintCmp;
944 hint->base.parse_func = (HintParseFunction) ParallelHintParse;
945 hint->relname = NULL;
947 hint->nworkers_str = "0";
949 return (Hint *) hint;
953 ParallelHintDelete(ParallelHint *hint)
959 pfree(hint->relname);
965 HintStateCreate(void)
969 hstate = palloc(sizeof(HintState));
970 hstate->hint_str = NULL;
971 hstate->nall_hints = 0;
972 hstate->max_all_hints = 0;
973 hstate->all_hints = NULL;
974 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
975 hstate->scan_hints = NULL;
976 hstate->init_scan_mask = 0;
977 hstate->init_nworkers = 0;
978 hstate->init_min_para_tablescan_size = 0;
979 hstate->init_min_para_indexscan_size = 0;
980 hstate->init_paratup_cost = 0;
981 hstate->init_parasetup_cost = 0;
982 hstate->current_root = NULL;
983 hstate->parent_relid = 0;
984 hstate->parent_scan_hint = NULL;
985 hstate->parent_parallel_hint = NULL;
986 hstate->parent_index_infos = NIL;
987 hstate->join_hints = NULL;
988 hstate->init_join_mask = 0;
989 hstate->join_hint_level = NULL;
990 hstate->leading_hint = NULL;
991 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
992 hstate->set_hints = NULL;
993 hstate->rows_hints = NULL;
994 hstate->parallel_hints = NULL;
1000 HintStateDelete(HintState *hstate)
1007 if (hstate->hint_str)
1008 pfree(hstate->hint_str);
1010 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1011 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
1012 if (hstate->all_hints)
1013 pfree(hstate->all_hints);
1014 if (hstate->parent_index_infos)
1015 list_free(hstate->parent_index_infos);
1019 * Copy given value into buf, with quoting with '"' if necessary.
1022 quote_value(StringInfo buf, const char *value)
1024 bool need_quote = false;
1027 for (str = value; *str != '\0'; str++)
1029 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
1032 appendStringInfoCharMacro(buf, '"');
1037 for (str = value; *str != '\0'; str++)
1040 appendStringInfoCharMacro(buf, '"');
1042 appendStringInfoCharMacro(buf, *str);
1046 appendStringInfoCharMacro(buf, '"');
1050 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
1054 appendStringInfo(buf, "%s(", hint->base.keyword);
1055 if (hint->relname != NULL)
1057 quote_value(buf, hint->relname);
1058 foreach(l, hint->indexnames)
1060 appendStringInfoCharMacro(buf, ' ');
1061 quote_value(buf, (char *) lfirst(l));
1064 appendStringInfoString(buf, ")");
1066 appendStringInfoChar(buf, '\n');
1070 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
1074 appendStringInfo(buf, "%s(", hint->base.keyword);
1075 if (hint->relnames != NULL)
1077 quote_value(buf, hint->relnames[0]);
1078 for (i = 1; i < hint->nrels; i++)
1080 appendStringInfoCharMacro(buf, ' ');
1081 quote_value(buf, hint->relnames[i]);
1084 appendStringInfoString(buf, ")");
1086 appendStringInfoChar(buf, '\n');
1090 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
1092 if (outer_inner->relation == NULL)
1099 appendStringInfoCharMacro(buf, '(');
1100 foreach(l, outer_inner->outer_inner_pair)
1105 appendStringInfoCharMacro(buf, ' ');
1107 OuterInnerDesc(lfirst(l), buf);
1110 appendStringInfoCharMacro(buf, ')');
1113 quote_value(buf, outer_inner->relation);
1117 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
1119 appendStringInfo(buf, "%s(", HINT_LEADING);
1120 if (hint->outer_inner == NULL)
1127 foreach(l, hint->relations)
1132 appendStringInfoCharMacro(buf, ' ');
1134 quote_value(buf, (char *) lfirst(l));
1138 OuterInnerDesc(hint->outer_inner, buf);
1140 appendStringInfoString(buf, ")");
1142 appendStringInfoChar(buf, '\n');
1146 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1148 bool is_first = true;
1151 appendStringInfo(buf, "%s(", HINT_SET);
1152 foreach(l, hint->words)
1157 appendStringInfoCharMacro(buf, ' ');
1159 quote_value(buf, (char *) lfirst(l));
1161 appendStringInfo(buf, ")");
1163 appendStringInfoChar(buf, '\n');
1167 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1171 appendStringInfo(buf, "%s(", hint->base.keyword);
1172 if (hint->relnames != NULL)
1174 quote_value(buf, hint->relnames[0]);
1175 for (i = 1; i < hint->nrels; i++)
1177 appendStringInfoCharMacro(buf, ' ');
1178 quote_value(buf, hint->relnames[i]);
1181 if (hint->rows_str != NULL)
1182 appendStringInfo(buf, " %s", hint->rows_str);
1183 appendStringInfoString(buf, ")");
1185 appendStringInfoChar(buf, '\n');
1189 ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf)
1191 appendStringInfo(buf, "%s(", hint->base.keyword);
1192 if (hint->relname != NULL)
1194 quote_value(buf, hint->relname);
1196 /* number of workers */
1197 appendStringInfoCharMacro(buf, ' ');
1198 quote_value(buf, hint->nworkers_str);
1199 /* application mode of num of workers */
1200 appendStringInfoCharMacro(buf, ' ');
1201 appendStringInfoString(buf,
1202 (hint->force_parallel ? "hard" : "soft"));
1204 appendStringInfoString(buf, ")");
1206 appendStringInfoChar(buf, '\n');
1210 * Append string which represents all hints in a given state to buf, with
1211 * preceding title with them.
1214 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1215 HintStatus state, bool nolf)
1219 appendStringInfo(buf, "%s:", title);
1221 appendStringInfoChar(buf, '\n');
1224 for (i = 0; i < hstate->nall_hints; i++)
1226 if (hstate->all_hints[i]->state != state)
1229 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1233 if (nolf && nshown == 0)
1234 appendStringInfoString(buf, "(none)");
1238 * Dump contents of given hstate to server log with log level LOG.
1241 HintStateDump(HintState *hstate)
1247 elog(pg_hint_plan_debug_message_level, "pg_hint_plan:\nno hint");
1251 initStringInfo(&buf);
1253 appendStringInfoString(&buf, "pg_hint_plan:\n");
1254 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1255 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1256 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1257 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1259 ereport(pg_hint_plan_debug_message_level,
1260 (errmsg ("%s", buf.data)));
1266 HintStateDump2(HintState *hstate)
1272 elog(pg_hint_plan_debug_message_level,
1273 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1277 initStringInfo(&buf);
1278 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1279 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1280 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1281 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1282 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1283 appendStringInfoChar(&buf, '}');
1285 ereport(pg_hint_plan_debug_message_level,
1286 (errmsg("%s", buf.data),
1288 errhidecontext(true)));
1298 RelnameCmp(const void *a, const void *b)
1300 const char *relnamea = *((const char **) a);
1301 const char *relnameb = *((const char **) b);
1303 return strcmp(relnamea, relnameb);
1307 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1309 return RelnameCmp(&a->relname, &b->relname);
1313 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1317 if (a->nrels != b->nrels)
1318 return a->nrels - b->nrels;
1320 for (i = 0; i < a->nrels; i++)
1323 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1331 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1337 SetHintCmp(const SetHint *a, const SetHint *b)
1339 return strcmp(a->name, b->name);
1343 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1347 if (a->nrels != b->nrels)
1348 return a->nrels - b->nrels;
1350 for (i = 0; i < a->nrels; i++)
1353 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1361 ParallelHintCmp(const ParallelHint *a, const ParallelHint *b)
1363 return RelnameCmp(&a->relname, &b->relname);
1367 HintCmp(const void *a, const void *b)
1369 const Hint *hinta = *((const Hint **) a);
1370 const Hint *hintb = *((const Hint **) b);
1372 if (hinta->type != hintb->type)
1373 return hinta->type - hintb->type;
1374 if (hinta->state == HINT_STATE_ERROR)
1376 if (hintb->state == HINT_STATE_ERROR)
1378 return hinta->cmp_func(hinta, hintb);
1382 * Returns byte offset of hint b from hint a. If hint a was specified before
1383 * b, positive value is returned.
1386 HintCmpWithPos(const void *a, const void *b)
1388 const Hint *hinta = *((const Hint **) a);
1389 const Hint *hintb = *((const Hint **) b);
1392 result = HintCmp(a, b);
1394 result = hinta->hint_str - hintb->hint_str;
1403 parse_keyword(const char *str, StringInfo buf)
1407 while (!isspace(*str) && *str != '(' && *str != '\0')
1408 appendStringInfoCharMacro(buf, *str++);
1414 skip_parenthesis(const char *str, char parenthesis)
1418 if (*str != parenthesis)
1420 if (parenthesis == '(')
1421 hint_ereport(str, ("Opening parenthesis is necessary."));
1422 else if (parenthesis == ')')
1423 hint_ereport(str, ("Closing parenthesis is necessary."));
1434 * Parse a token from str, and store malloc'd copy into word. A token can be
1435 * quoted with '"'. Return value is pointer to unparsed portion of original
1436 * string, or NULL if an error occurred.
1438 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1441 parse_quoted_value(const char *str, char **word, bool truncate)
1446 /* Skip leading spaces. */
1449 initStringInfo(&buf);
1462 /* Double quotation must be closed. */
1466 hint_ereport(str, ("Unterminated quoted string."));
1471 * Skip escaped double quotation.
1473 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1474 * block comments) to be an object name, so users must specify
1475 * alias for such object names.
1477 * Those special names can be allowed if we care escaped slashes
1478 * and asterisks, but we don't.
1487 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1491 appendStringInfoCharMacro(&buf, *str++);
1496 hint_ereport(str, ("Zero-length delimited string."));
1503 /* Truncate name if it's too long */
1505 truncate_identifier(buf.data, strlen(buf.data), true);
1512 static OuterInnerRels *
1513 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1515 OuterInnerRels *outer_inner;
1517 outer_inner = palloc(sizeof(OuterInnerRels));
1518 outer_inner->relation = name;
1519 outer_inner->outer_inner_pair = outer_inner_list;
1525 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1527 List *outer_inner_pair = NIL;
1529 if ((str = skip_parenthesis(str, '(')) == NULL)
1534 /* Store words in parentheses into outer_inner_list. */
1535 while(*str != ')' && *str != '\0')
1537 OuterInnerRels *outer_inner_rels;
1541 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1549 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1552 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1555 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1560 (str = skip_parenthesis(str, ')')) == NULL)
1562 list_free(outer_inner_pair);
1566 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1572 parse_parentheses_Leading(const char *str, List **name_list,
1573 OuterInnerRels **outer_inner)
1576 bool truncate = true;
1578 if ((str = skip_parenthesis(str, '(')) == NULL)
1584 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1589 /* Store words in parentheses into name_list. */
1590 while(*str != ')' && *str != '\0')
1592 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1594 list_free(*name_list);
1598 *name_list = lappend(*name_list, name);
1603 if ((str = skip_parenthesis(str, ')')) == NULL)
1609 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1612 bool truncate = true;
1614 if ((str = skip_parenthesis(str, '(')) == NULL)
1619 /* Store words in parentheses into name_list. */
1620 while(*str != ')' && *str != '\0')
1622 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1624 list_free(*name_list);
1628 *name_list = lappend(*name_list, name);
1631 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1632 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1633 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1634 keyword == HINT_KEYWORD_SET)
1640 if ((str = skip_parenthesis(str, ')')) == NULL)
1646 parse_hints(HintState *hstate, Query *parse, const char *str)
1651 initStringInfo(&buf);
1652 while (*str != '\0')
1654 const HintParser *parser;
1656 /* in error message, we output the comment including the keyword. */
1657 head = (char *) str;
1659 /* parse only the keyword of the hint. */
1660 resetStringInfo(&buf);
1661 str = parse_keyword(str, &buf);
1663 for (parser = parsers; parser->keyword != NULL; parser++)
1665 char *keyword = parser->keyword;
1668 if (pg_strcasecmp(buf.data, keyword) != 0)
1671 hint = parser->create_func(head, keyword, parser->hint_keyword);
1673 /* parser of each hint does parse in a parenthesis. */
1674 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1676 hint->delete_func(hint);
1682 * Add hint information into all_hints array. If we don't have
1683 * enough space, double the array.
1685 if (hstate->nall_hints == 0)
1687 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1688 hstate->all_hints = (Hint **)
1689 palloc(sizeof(Hint *) * hstate->max_all_hints);
1691 else if (hstate->nall_hints == hstate->max_all_hints)
1693 hstate->max_all_hints *= 2;
1694 hstate->all_hints = (Hint **)
1695 repalloc(hstate->all_hints,
1696 sizeof(Hint *) * hstate->max_all_hints);
1699 hstate->all_hints[hstate->nall_hints] = hint;
1700 hstate->nall_hints++;
1707 if (parser->keyword == NULL)
1710 ("Unrecognized hint keyword \"%s\".", buf.data));
1721 * Get hints from table by client-supplied query string and application name.
1724 get_hints_from_table(const char *client_query, const char *client_application)
1726 const char *search_query =
1728 " FROM hint_plan.hints "
1729 " WHERE norm_query_string = $1 "
1730 " AND ( application_name = $2 "
1731 " OR application_name = '' ) "
1732 " ORDER BY application_name DESC";
1733 static SPIPlanPtr plan = NULL;
1735 Oid argtypes[2] = { TEXTOID, TEXTOID };
1737 char nulls[2] = {' ', ' '};
1743 bool snapshot_set = false;
1745 hint_inhibit_level++;
1747 if (!ActiveSnapshotSet())
1749 PushActiveSnapshot(GetTransactionSnapshot());
1750 snapshot_set = true;
1758 p = SPI_prepare(search_query, 2, argtypes);
1759 plan = SPI_saveplan(p);
1763 qry = cstring_to_text(client_query);
1764 app = cstring_to_text(client_application);
1765 values[0] = PointerGetDatum(qry);
1766 values[1] = PointerGetDatum(app);
1768 SPI_execute_plan(plan, values, nulls, true, 1);
1770 if (SPI_processed > 0)
1774 hints = SPI_getvalue(SPI_tuptable->vals[0],
1775 SPI_tuptable->tupdesc, 1);
1777 * Here we use SPI_palloc to ensure that hints string is valid even
1778 * after SPI_finish call. We can't use simple palloc because it
1779 * allocates memory in SPI's context and that context is deleted in
1782 buf = SPI_palloc(strlen(hints) + 1);
1790 PopActiveSnapshot();
1792 hint_inhibit_level--;
1796 hint_inhibit_level--;
1805 * Get client-supplied query string. Addtion to that the jumbled query is
1806 * supplied if the caller requested. From the restriction of JumbleQuery, some
1807 * kind of query needs special amendments. Reutrns NULL if this query doesn't
1808 * change the current hint. This function returns NULL also when something
1809 * wrong has happend and let the caller continue using the current hints.
1812 get_query_string(ParseState *pstate, Query *query, Query **jumblequery)
1814 const char *p = debug_query_string;
1817 * If debug_query_string is set, it is the top level statement. But in some
1818 * cases we reach here with debug_query_string set NULL for example in the
1819 * case of DESCRIBE message handling or EXECUTE command. We may still see a
1820 * candidate top-level query in pstate in the case.
1822 if (pstate && pstate->p_sourcetext)
1823 p = pstate->p_sourcetext;
1825 /* We don't see a query string, return NULL */
1829 if (jumblequery != NULL)
1830 *jumblequery = query;
1832 if (query->commandType == CMD_UTILITY)
1834 Query *target_query = (Query *)query->utilityStmt;
1837 * Some CMD_UTILITY statements have a subquery that we can hint on.
1838 * Since EXPLAIN can be placed before other kind of utility statements
1839 * and EXECUTE can be contained other kind of utility statements, these
1840 * conditions are not mutually exclusive and should be considered in
1843 if (IsA(target_query, ExplainStmt))
1845 ExplainStmt *stmt = (ExplainStmt *)target_query;
1847 Assert(IsA(stmt->query, Query));
1848 target_query = (Query *)stmt->query;
1850 /* strip out the top-level query for further processing */
1851 if (target_query->commandType == CMD_UTILITY &&
1852 target_query->utilityStmt != NULL)
1853 target_query = (Query *)target_query->utilityStmt;
1856 if (IsA(target_query, DeclareCursorStmt))
1858 DeclareCursorStmt *stmt = (DeclareCursorStmt *)target_query;
1859 Query *query = (Query *)stmt->query;
1861 /* the target must be CMD_SELECT in this case */
1862 Assert(IsA(query, Query) && query->commandType == CMD_SELECT);
1863 target_query = query;
1866 if (IsA(target_query, CreateTableAsStmt))
1868 CreateTableAsStmt *stmt = (CreateTableAsStmt *) target_query;
1870 Assert(IsA(stmt->query, Query));
1871 target_query = (Query *) stmt->query;
1873 /* strip out the top-level query for further processing */
1874 if (target_query->commandType == CMD_UTILITY &&
1875 target_query->utilityStmt != NULL)
1876 target_query = (Query *)target_query->utilityStmt;
1879 if (IsA(target_query, ExecuteStmt))
1882 * Use the prepared query for EXECUTE. The Query for jumble
1883 * also replaced with the corresponding one.
1885 ExecuteStmt *stmt = (ExecuteStmt *)target_query;
1886 PreparedStatement *entry;
1888 entry = FetchPreparedStatement(stmt->name, true);
1890 if (entry->plansource->is_valid)
1892 p = entry->plansource->query_string;
1893 target_query = (Query *) linitial (entry->plansource->query_list);
1897 /* igonre the hint for EXECUTE if invalidated */
1899 target_query = NULL;
1903 /* JumbleQuery accespts only a non-utility Query */
1905 (!IsA(target_query, Query) ||
1906 target_query->utilityStmt != NULL))
1907 target_query = NULL;
1910 *jumblequery = target_query;
1913 * Return NULL if pstate is not of top-level query. We don't need this
1914 * when jumble info is not requested or cannot do this when pstate is NULL.
1916 else if (!jumblequery && pstate && pstate->p_sourcetext != p &&
1917 strcmp(pstate->p_sourcetext, p) != 0)
1924 * Get hints from the head block comment in client-supplied query string.
1927 get_hints_from_comment(const char *p)
1929 const char *hint_head;
1937 /* extract query head comment. */
1938 hint_head = strstr(p, HINT_START);
1939 if (hint_head == NULL)
1941 for (;p < hint_head; p++)
1944 * Allow these characters precedes hint comment:
1946 * - alphabets which are in ASCII range
1947 * - space, tabs and new-lines
1948 * - underscores, for identifier
1949 * - commas, for SELECT clause, EXPLAIN and PREPARE
1950 * - parentheses, for EXPLAIN and PREPARE
1952 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1953 * avoid behavior which depends on locale setting.
1955 if (!(*p >= '0' && *p <= '9') &&
1956 !(*p >= 'A' && *p <= 'Z') &&
1957 !(*p >= 'a' && *p <= 'z') &&
1961 *p != '(' && *p != ')')
1965 len = strlen(HINT_START);
1970 /* find hint end keyword. */
1971 if ((tail = strstr(p, HINT_END)) == NULL)
1973 hint_ereport(head, ("Unterminated block comment."));
1977 /* We don't support nested block comments. */
1978 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1980 hint_ereport(head, ("Nested block comments are not supported."));
1984 /* Make a copy of hint. */
1986 head = palloc(len + 1);
1987 memcpy(head, p, len);
1995 * Parse hints that got, create hint struct from parse tree and parse hints.
1998 create_hintstate(Query *parse, const char *hints)
2007 /* -1 means that no Parallel hint is specified. */
2008 max_hint_nworkers = -1;
2011 hstate = HintStateCreate();
2012 hstate->hint_str = (char *) hints;
2014 /* parse each hint. */
2015 parse_hints(hstate, parse, p);
2017 /* When nothing specified a hint, we free HintState and returns NULL. */
2018 if (hstate->nall_hints == 0)
2020 HintStateDelete(hstate);
2024 /* Sort hints in order of original position. */
2025 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
2028 /* Count number of hints per hint-type. */
2029 for (i = 0; i < hstate->nall_hints; i++)
2031 Hint *cur_hint = hstate->all_hints[i];
2032 hstate->num_hints[cur_hint->type]++;
2036 * If an object (or a set of objects) has multiple hints of same hint-type,
2037 * only the last hint is valid and others are ignored in planning.
2038 * Hints except the last are marked as 'duplicated' to remember the order.
2040 for (i = 0; i < hstate->nall_hints - 1; i++)
2042 Hint *cur_hint = hstate->all_hints[i];
2043 Hint *next_hint = hstate->all_hints[i + 1];
2046 * Leading hint is marked as 'duplicated' in transform_join_hints.
2048 if (cur_hint->type == HINT_TYPE_LEADING &&
2049 next_hint->type == HINT_TYPE_LEADING)
2053 * Note that we need to pass addresses of hint pointers, because
2054 * HintCmp is designed to sort array of Hint* by qsort.
2056 if (HintCmp(&cur_hint, &next_hint) == 0)
2058 hint_ereport(cur_hint->hint_str,
2059 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
2060 cur_hint->state = HINT_STATE_DUPLICATION;
2065 * Make sure that per-type array pointers point proper position in the
2066 * array which consists of all hints.
2068 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
2069 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
2070 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
2071 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
2072 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
2073 hstate->set_hints = (SetHint **) (hstate->leading_hint +
2074 hstate->num_hints[HINT_TYPE_LEADING]);
2075 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
2076 hstate->num_hints[HINT_TYPE_SET]);
2077 hstate->parallel_hints = (ParallelHint **) (hstate->rows_hints +
2078 hstate->num_hints[HINT_TYPE_ROWS]);
2084 * Parse inside of parentheses of scan-method hints.
2087 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
2090 const char *keyword = hint->base.keyword;
2091 HintKeyword hint_keyword = hint->base.hint_keyword;
2092 List *name_list = NIL;
2095 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2098 /* Parse relation name and index name(s) if given hint accepts. */
2099 length = list_length(name_list);
2101 /* at least twp parameters required */
2105 ("%s hint requires a relation.", hint->base.keyword));
2106 hint->base.state = HINT_STATE_ERROR;
2110 hint->relname = linitial(name_list);
2111 hint->indexnames = list_delete_first(name_list);
2113 /* check whether the hint accepts index name(s) */
2114 if (length > 1 && !SCAN_HINT_ACCEPTS_INDEX_NAMES(hint_keyword))
2117 ("%s hint accepts only one relation.",
2118 hint->base.keyword));
2119 hint->base.state = HINT_STATE_ERROR;
2123 /* Set a bit for specified hint. */
2124 switch (hint_keyword)
2126 case HINT_KEYWORD_SEQSCAN:
2127 hint->enforce_mask = ENABLE_SEQSCAN;
2129 case HINT_KEYWORD_INDEXSCAN:
2130 hint->enforce_mask = ENABLE_INDEXSCAN;
2132 case HINT_KEYWORD_INDEXSCANREGEXP:
2133 hint->enforce_mask = ENABLE_INDEXSCAN;
2134 hint->regexp = true;
2136 case HINT_KEYWORD_BITMAPSCAN:
2137 hint->enforce_mask = ENABLE_BITMAPSCAN;
2139 case HINT_KEYWORD_BITMAPSCANREGEXP:
2140 hint->enforce_mask = ENABLE_BITMAPSCAN;
2141 hint->regexp = true;
2143 case HINT_KEYWORD_TIDSCAN:
2144 hint->enforce_mask = ENABLE_TIDSCAN;
2146 case HINT_KEYWORD_NOSEQSCAN:
2147 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
2149 case HINT_KEYWORD_NOINDEXSCAN:
2150 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
2152 case HINT_KEYWORD_NOBITMAPSCAN:
2153 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
2155 case HINT_KEYWORD_NOTIDSCAN:
2156 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
2158 case HINT_KEYWORD_INDEXONLYSCAN:
2159 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2161 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
2162 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2163 hint->regexp = true;
2165 case HINT_KEYWORD_NOINDEXONLYSCAN:
2166 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
2169 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2178 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2181 const char *keyword = hint->base.keyword;
2182 HintKeyword hint_keyword = hint->base.hint_keyword;
2183 List *name_list = NIL;
2185 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2188 hint->nrels = list_length(name_list);
2190 if (hint->nrels > 0)
2196 * Transform relation names from list to array to sort them with qsort
2199 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2200 foreach (l, name_list)
2202 hint->relnames[i] = lfirst(l);
2207 list_free(name_list);
2209 /* A join hint requires at least two relations */
2210 if (hint->nrels < 2)
2213 ("%s hint requires at least two relations.",
2214 hint->base.keyword));
2215 hint->base.state = HINT_STATE_ERROR;
2219 /* Sort hints in alphabetical order of relation names. */
2220 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2222 switch (hint_keyword)
2224 case HINT_KEYWORD_NESTLOOP:
2225 hint->enforce_mask = ENABLE_NESTLOOP;
2227 case HINT_KEYWORD_MERGEJOIN:
2228 hint->enforce_mask = ENABLE_MERGEJOIN;
2230 case HINT_KEYWORD_HASHJOIN:
2231 hint->enforce_mask = ENABLE_HASHJOIN;
2233 case HINT_KEYWORD_NONESTLOOP:
2234 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2236 case HINT_KEYWORD_NOMERGEJOIN:
2237 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2239 case HINT_KEYWORD_NOHASHJOIN:
2240 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2243 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2252 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2255 if (outer_inner->outer_inner_pair == NIL)
2257 if (outer_inner->relation)
2263 if (list_length(outer_inner->outer_inner_pair) == 2)
2265 foreach(l, outer_inner->outer_inner_pair)
2267 if (!OuterInnerPairCheck(lfirst(l)))
2278 OuterInnerList(OuterInnerRels *outer_inner)
2280 List *outer_inner_list = NIL;
2282 OuterInnerRels *outer_inner_rels;
2284 foreach(l, outer_inner->outer_inner_pair)
2286 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2288 if (outer_inner_rels->relation != NULL)
2289 outer_inner_list = lappend(outer_inner_list,
2290 outer_inner_rels->relation);
2292 outer_inner_list = list_concat(outer_inner_list,
2293 OuterInnerList(outer_inner_rels));
2295 return outer_inner_list;
2299 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2302 List *name_list = NIL;
2303 OuterInnerRels *outer_inner = NULL;
2305 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2309 if (outer_inner != NULL)
2310 name_list = OuterInnerList(outer_inner);
2312 hint->relations = name_list;
2313 hint->outer_inner = outer_inner;
2315 /* A Leading hint requires at least two relations */
2316 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2318 hint_ereport(hint->base.hint_str,
2319 ("%s hint requires at least two relations.",
2321 hint->base.state = HINT_STATE_ERROR;
2323 else if (hint->outer_inner != NULL &&
2324 !OuterInnerPairCheck(hint->outer_inner))
2326 hint_ereport(hint->base.hint_str,
2327 ("%s hint requires two sets of relations when parentheses nests.",
2329 hint->base.state = HINT_STATE_ERROR;
2336 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2338 List *name_list = NIL;
2340 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2344 hint->words = name_list;
2346 /* We need both name and value to set GUC parameter. */
2347 if (list_length(name_list) == 2)
2349 hint->name = linitial(name_list);
2350 hint->value = lsecond(name_list);
2354 hint_ereport(hint->base.hint_str,
2355 ("%s hint requires name and value of GUC parameter.",
2357 hint->base.state = HINT_STATE_ERROR;
2364 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2367 HintKeyword hint_keyword = hint->base.hint_keyword;
2368 List *name_list = NIL;
2374 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2377 /* Last element must be rows specification */
2378 hint->nrels = list_length(name_list) - 1;
2380 if (hint->nrels < 1)
2383 ("%s hint needs at least one relation followed by one correction term.",
2384 hint->base.keyword));
2385 hint->base.state = HINT_STATE_ERROR;
2392 * Transform relation names from list to array to sort them with qsort
2395 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2396 foreach (l, name_list)
2398 if (hint->nrels <= i)
2400 hint->relnames[i] = lfirst(l);
2404 /* Retieve rows estimation */
2405 rows_str = list_nth(name_list, hint->nrels);
2406 hint->rows_str = rows_str; /* store as-is for error logging */
2407 if (rows_str[0] == '#')
2409 hint->value_type = RVT_ABSOLUTE;
2412 else if (rows_str[0] == '+')
2414 hint->value_type = RVT_ADD;
2417 else if (rows_str[0] == '-')
2419 hint->value_type = RVT_SUB;
2422 else if (rows_str[0] == '*')
2424 hint->value_type = RVT_MULTI;
2429 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2430 hint->base.state = HINT_STATE_ERROR;
2433 hint->rows = strtod(rows_str, &end_ptr);
2436 hint_ereport(rows_str,
2437 ("%s hint requires valid number as rows estimation.",
2438 hint->base.keyword));
2439 hint->base.state = HINT_STATE_ERROR;
2443 /* A join hint requires at least two relations */
2444 if (hint->nrels < 2)
2447 ("%s hint requires at least two relations.",
2448 hint->base.keyword));
2449 hint->base.state = HINT_STATE_ERROR;
2453 list_free(name_list);
2455 /* Sort relnames in alphabetical order. */
2456 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2462 ParallelHintParse(ParallelHint *hint, HintState *hstate, Query *parse,
2465 HintKeyword hint_keyword = hint->base.hint_keyword;
2466 List *name_list = NIL;
2470 bool force_parallel = false;
2472 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2475 /* Parse relation name and index name(s) if given hint accepts. */
2476 length = list_length(name_list);
2478 if (length < 2 || length > 3)
2481 ("wrong number of arguments (%d): %s",
2482 length, hint->base.keyword));
2483 hint->base.state = HINT_STATE_ERROR;
2487 hint->relname = linitial(name_list);
2489 /* The second parameter is number of workers */
2490 hint->nworkers_str = list_nth(name_list, 1);
2491 nworkers = strtod(hint->nworkers_str, &end_ptr);
2492 if (*end_ptr || nworkers < 0 || nworkers > max_worker_processes)
2495 hint_ereport(hint->nworkers_str,
2496 ("number of workers must be a number: %s",
2497 hint->base.keyword));
2498 else if (nworkers < 0)
2499 hint_ereport(hint->nworkers_str,
2500 ("number of workers must be positive: %s",
2501 hint->base.keyword));
2502 else if (nworkers > max_worker_processes)
2503 hint_ereport(hint->nworkers_str,
2504 ("number of workers = %d is larger than max_worker_processes(%d): %s",
2505 nworkers, max_worker_processes, hint->base.keyword));
2507 hint->base.state = HINT_STATE_ERROR;
2510 hint->nworkers = nworkers;
2512 /* optional third parameter is specified */
2515 const char *modeparam = (const char *)list_nth(name_list, 2);
2516 if (pg_strcasecmp(modeparam, "hard") == 0)
2517 force_parallel = true;
2518 else if (pg_strcasecmp(modeparam, "soft") != 0)
2520 hint_ereport(modeparam,
2521 ("enforcement must be soft or hard: %s",
2522 hint->base.keyword));
2523 hint->base.state = HINT_STATE_ERROR;
2527 hint->force_parallel = force_parallel;
2529 if (hint->base.state != HINT_STATE_ERROR &&
2530 nworkers > max_hint_nworkers)
2531 max_hint_nworkers = nworkers;
2537 * set GUC parameter functions
2541 get_current_scan_mask()
2546 mask |= ENABLE_SEQSCAN;
2547 if (enable_indexscan)
2548 mask |= ENABLE_INDEXSCAN;
2549 if (enable_bitmapscan)
2550 mask |= ENABLE_BITMAPSCAN;
2552 mask |= ENABLE_TIDSCAN;
2553 if (enable_indexonlyscan)
2554 mask |= ENABLE_INDEXONLYSCAN;
2560 get_current_join_mask()
2564 if (enable_nestloop)
2565 mask |= ENABLE_NESTLOOP;
2566 if (enable_mergejoin)
2567 mask |= ENABLE_MERGEJOIN;
2568 if (enable_hashjoin)
2569 mask |= ENABLE_HASHJOIN;
2575 * Sets GUC prameters without throwing exception. Reutrns false if something
2579 set_config_option_noerror(const char *name, const char *value,
2580 GucContext context, GucSource source,
2581 GucAction action, bool changeVal, int elevel)
2584 MemoryContext ccxt = CurrentMemoryContext;
2588 result = set_config_option(name, value, context, source,
2589 action, changeVal, 0, false);
2595 /* Save error info */
2596 MemoryContextSwitchTo(ccxt);
2597 errdata = CopyErrorData();
2601 (errcode(errdata->sqlerrcode),
2602 errmsg("%s", errdata->message),
2603 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2604 errdata->hint ? errhint("%s", errdata->hint) : 0));
2606 FreeErrorData(errdata);
2614 * Sets GUC parameter of int32 type without throwing exceptions. Returns false
2615 * if something wrong.
2618 set_config_int32_option(const char *name, int32 value, GucContext context)
2620 char buf[16]; /* enough for int32 */
2622 if (snprintf(buf, 16, "%d", value) < 0)
2624 ereport(pg_hint_plan_parse_message_level,
2625 (errmsg ("Failed to convert integer to string: %d", value)));
2630 set_config_option_noerror(name, buf, context,
2631 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2632 pg_hint_plan_parse_message_level);
2636 * Sets GUC parameter of double type without throwing exceptions. Returns false
2637 * if something wrong.
2640 set_config_double_option(const char *name, double value, GucContext context)
2642 char *buf = float8out_internal(value);
2645 result = set_config_option_noerror(name, buf, context,
2646 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2647 pg_hint_plan_parse_message_level);
2652 /* setup scan method enforcement according to given options */
2654 setup_guc_enforcement(SetHint **options, int noptions, GucContext context)
2658 for (i = 0; i < noptions; i++)
2660 SetHint *hint = options[i];
2663 if (!hint_state_enabled(hint))
2666 result = set_config_option_noerror(hint->name, hint->value, context,
2667 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2668 pg_hint_plan_parse_message_level);
2670 hint->base.state = HINT_STATE_USED;
2672 hint->base.state = HINT_STATE_ERROR;
2679 * Setup parallel execution environment.
2681 * If hint is not NULL, set up using it, elsewise reset to initial environment.
2684 setup_parallel_plan_enforcement(ParallelHint *hint, HintState *state)
2688 hint->base.state = HINT_STATE_USED;
2689 set_config_int32_option("max_parallel_workers_per_gather",
2690 hint->nworkers, state->context);
2693 set_config_int32_option("max_parallel_workers_per_gather",
2694 state->init_nworkers, state->context);
2696 /* force means that enforce parallel as far as possible */
2697 if (hint && hint->force_parallel && hint->nworkers > 0)
2699 set_config_double_option("parallel_tuple_cost", 0.0, state->context);
2700 set_config_double_option("parallel_setup_cost", 0.0, state->context);
2701 set_config_int32_option("min_parallel_table_scan_size", 0,
2703 set_config_int32_option("min_parallel_index_scan_size", 0,
2708 set_config_double_option("parallel_tuple_cost",
2709 state->init_paratup_cost, state->context);
2710 set_config_double_option("parallel_setup_cost",
2711 state->init_parasetup_cost, state->context);
2712 set_config_int32_option("min_parallel_table_scan_size",
2713 state->init_min_para_tablescan_size,
2715 set_config_int32_option("min_parallel_index_scan_size",
2716 state->init_min_para_indexscan_size,
2721 #define SET_CONFIG_OPTION(name, type_bits) \
2722 set_config_option_noerror((name), \
2723 (mask & (type_bits)) ? "true" : "false", \
2724 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2728 * Setup GUC environment to enforce scan methods. If scanhint is NULL, reset
2729 * GUCs to the saved state in state.
2732 setup_scan_method_enforcement(ScanMethodHint *scanhint, HintState *state)
2734 unsigned char enforce_mask = state->init_scan_mask;
2735 GucContext context = state->context;
2740 enforce_mask = scanhint->enforce_mask;
2741 scanhint->base.state = HINT_STATE_USED;
2744 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2745 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2746 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2748 mask = enforce_mask;
2750 mask = enforce_mask & current_hint_state->init_scan_mask;
2752 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2753 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2754 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2755 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2756 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2760 set_join_config_options(unsigned char enforce_mask, GucContext context)
2764 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2765 enforce_mask == ENABLE_HASHJOIN)
2766 mask = enforce_mask;
2768 mask = enforce_mask & current_hint_state->init_join_mask;
2770 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2771 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2772 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2776 * Push a hint into hint stack which is implemented with List struct. Head of
2777 * list is top of stack.
2780 push_hint(HintState *hstate)
2782 /* Prepend new hint to the list means pushing to stack. */
2783 HintStateStack = lcons(hstate, HintStateStack);
2785 /* Pushed hint is the one which should be used hereafter. */
2786 current_hint_state = hstate;
2789 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2793 /* Hint stack must not be empty. */
2794 if(HintStateStack == NIL)
2795 elog(ERROR, "hint stack is empty");
2798 * Take a hint at the head from the list, and free it. Switch
2799 * current_hint_state to point new head (NULL if the list is empty).
2801 HintStateStack = list_delete_first(HintStateStack);
2802 HintStateDelete(current_hint_state);
2803 if(HintStateStack == NIL)
2804 current_hint_state = NULL;
2806 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
2810 * Retrieve and store hint string from given query or from the hint table.
2813 get_current_hint_string(ParseState *pstate, Query *query)
2815 const char *query_str;
2816 MemoryContext oldcontext;
2818 /* do nothing under hint table search */
2819 if (hint_inhibit_level > 0)
2822 /* We alredy have one, don't parse it again. */
2823 if (current_hint_retrieved)
2826 /* Don't parse the current query hereafter */
2827 current_hint_retrieved = true;
2829 if (!pg_hint_plan_enable_hint)
2831 if (current_hint_str)
2833 pfree((void *)current_hint_str);
2834 current_hint_str = NULL;
2839 /* increment the query number */
2841 if (debug_level > 1)
2842 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2845 /* search the hint table for a hint if requested */
2846 if (pg_hint_plan_enable_hint_table)
2849 pgssJumbleState jstate;
2851 char *normalized_query = NULL;
2853 query_str = get_query_string(pstate, query, &jumblequery);
2855 /* If this query is not for hint, just return */
2859 /* clear the previous hint string */
2860 if (current_hint_str)
2862 pfree((void *)current_hint_str);
2863 current_hint_str = NULL;
2869 * XXX: normalization code is copied from pg_stat_statements.c.
2870 * Make sure to keep up-to-date with it.
2872 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2873 jstate.jumble_len = 0;
2874 jstate.clocations_buf_size = 32;
2875 jstate.clocations = (pgssLocationLen *)
2876 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2877 jstate.clocations_count = 0;
2879 JumbleQuery(&jstate, jumblequery);
2882 * Normalize the query string by replacing constants with '?'
2885 * Search hint string which is stored keyed by query string
2886 * and application name. The query string is normalized to allow
2889 * Adding 1 byte to query_len ensures that the returned string has
2890 * a terminating NULL.
2892 query_len = strlen(query_str) + 1;
2894 generate_normalized_query(&jstate, query_str, 0, &query_len,
2895 GetDatabaseEncoding());
2898 * find a hint for the normalized query. the result should be in
2901 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2903 get_hints_from_table(normalized_query, application_name);
2904 MemoryContextSwitchTo(oldcontext);
2906 if (debug_level > 1)
2908 if (current_hint_str)
2909 ereport(pg_hint_plan_debug_message_level,
2910 (errmsg("pg_hint_plan[qno=0x%x]: "
2911 "post_parse_analyze_hook: "
2912 "hints from table: \"%s\": "
2913 "normalized_query=\"%s\", "
2914 "application name =\"%s\"",
2915 qno, current_hint_str,
2916 normalized_query, application_name),
2917 errhidestmt(msgqno != qno),
2918 errhidecontext(msgqno != qno)));
2920 ereport(pg_hint_plan_debug_message_level,
2921 (errmsg("pg_hint_plan[qno=0x%x]: "
2922 "no match found in table: "
2923 "application name = \"%s\", "
2924 "normalized_query=\"%s\"",
2925 qno, application_name,
2927 errhidestmt(msgqno != qno),
2928 errhidecontext(msgqno != qno)));
2934 /* retrun if we have hint here */
2935 if (current_hint_str)
2939 query_str = get_query_string(pstate, query, NULL);
2944 * get hints from the comment. However we may have the same query
2945 * string with the previous call, but the extra comparison seems no
2948 if (current_hint_str)
2949 pfree((void *)current_hint_str);
2951 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2952 current_hint_str = get_hints_from_comment(query_str);
2953 MemoryContextSwitchTo(oldcontext);
2958 * Failed to get query. We would be in fetching invalidated
2959 * plancache. Try the next chance.
2961 current_hint_retrieved = false;
2964 if (debug_level > 1)
2966 if (debug_level == 1 && query_str && debug_query_string &&
2967 strcmp(query_str, debug_query_string))
2968 ereport(pg_hint_plan_debug_message_level,
2969 (errmsg("hints in comment=\"%s\"",
2970 current_hint_str ? current_hint_str : "(none)"),
2971 errhidestmt(msgqno != qno),
2972 errhidecontext(msgqno != qno)));
2974 ereport(pg_hint_plan_debug_message_level,
2975 (errmsg("hints in comment=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2976 current_hint_str ? current_hint_str : "(none)",
2977 query_str ? query_str : "(none)",
2978 debug_query_string ? debug_query_string : "(none)"),
2979 errhidestmt(msgqno != qno),
2980 errhidecontext(msgqno != qno)));
2986 * Retrieve hint string from the current query.
2989 pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query)
2991 if (prev_post_parse_analyze_hook)
2992 prev_post_parse_analyze_hook(pstate, query);
2994 /* always retrieve hint from the top-level query string */
2995 if (plpgsql_recurse_level == 0)
2996 current_hint_retrieved = false;
2998 get_current_hint_string(pstate, query);
3002 * We need to reset current_hint_retrieved flag always when a command execution
3003 * is finished. This is true even for a pure utility command that doesn't
3004 * involve planning phase.
3007 pg_hint_plan_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
3008 ProcessUtilityContext context,
3009 ParamListInfo params, QueryEnvironment *queryEnv,
3010 DestReceiver *dest, char *completionTag)
3012 if (prev_ProcessUtility_hook)
3013 prev_ProcessUtility_hook(pstmt, queryString, context, params, queryEnv,
3014 dest, completionTag);
3016 standard_ProcessUtility(pstmt, queryString, context, params, queryEnv,
3017 dest, completionTag);
3019 if (plpgsql_recurse_level == 0)
3020 current_hint_retrieved = false;
3024 * Read and set up hint information
3026 static PlannedStmt *
3027 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
3030 PlannedStmt *result;
3032 const char *prev_hint_str = NULL;
3035 * Use standard planner if pg_hint_plan is disabled or current nesting
3036 * depth is nesting depth of SPI calls. Other hook functions try to change
3037 * plan with current_hint_state if any, so set it to NULL.
3039 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
3041 if (debug_level > 1)
3042 ereport(pg_hint_plan_debug_message_level,
3043 (errmsg ("pg_hint_plan%s: planner: enable_hint=%d,"
3044 " hint_inhibit_level=%d",
3045 qnostr, pg_hint_plan_enable_hint,
3046 hint_inhibit_level),
3047 errhidestmt(msgqno != qno)));
3050 goto standard_planner_proc;
3054 * Support for nested plpgsql functions. This is quite ugly but this is the
3055 * only point I could find where I can get the query string.
3057 if (plpgsql_recurse_level > 0 &&
3058 error_context_stack && error_context_stack->arg)
3060 MemoryContext oldcontext;
3062 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
3064 get_hints_from_comment((char *)error_context_stack->arg);
3065 MemoryContextSwitchTo(oldcontext);
3069 * Query execution in extended protocol can be started without the analyze
3070 * phase. In the case retrieve hint string here.
3072 if (!current_hint_str)
3073 get_current_hint_string(NULL, parse);
3075 /* No hint, go the normal way */
3076 if (!current_hint_str)
3077 goto standard_planner_proc;
3079 /* parse the hint into hint state struct */
3080 hstate = create_hintstate(parse, pstrdup(current_hint_str));
3082 /* run standard planner if the statement has not valid hint */
3084 goto standard_planner_proc;
3087 * Push new hint struct to the hint stack to disable previous hint context.
3091 /* Set scan enforcement here. */
3092 save_nestlevel = NewGUCNestLevel();
3094 /* Apply Set hints, then save it as the initial state */
3095 setup_guc_enforcement(current_hint_state->set_hints,
3096 current_hint_state->num_hints[HINT_TYPE_SET],
3097 current_hint_state->context);
3099 current_hint_state->init_scan_mask = get_current_scan_mask();
3100 current_hint_state->init_join_mask = get_current_join_mask();
3101 current_hint_state->init_min_para_tablescan_size =
3102 min_parallel_table_scan_size;
3103 current_hint_state->init_min_para_indexscan_size =
3104 min_parallel_index_scan_size;
3105 current_hint_state->init_paratup_cost = parallel_tuple_cost;
3106 current_hint_state->init_parasetup_cost = parallel_setup_cost;
3109 * max_parallel_workers_per_gather should be non-zero here if Workers hint
3112 if (max_hint_nworkers > 0 && max_parallel_workers_per_gather < 1)
3113 set_config_int32_option("max_parallel_workers_per_gather",
3114 1, current_hint_state->context);
3115 current_hint_state->init_nworkers = max_parallel_workers_per_gather;
3117 if (debug_level > 1)
3119 ereport(pg_hint_plan_debug_message_level,
3120 (errhidestmt(msgqno != qno),
3121 errmsg("pg_hint_plan%s: planner", qnostr)));
3126 * The planner call below may replace current_hint_str. Store and restore
3127 * it so that the subsequent planning in the upper level doesn't get
3131 prev_hint_str = current_hint_str;
3132 current_hint_str = NULL;
3135 * Use PG_TRY mechanism to recover GUC parameters and current_hint_state to
3136 * the state when this planner started when error occurred in planner.
3141 result = (*prev_planner) (parse, cursorOptions, boundParams);
3143 result = standard_planner(parse, cursorOptions, boundParams);
3145 current_hint_str = prev_hint_str;
3151 * Rollback changes of GUC parameters, and pop current hint context
3152 * from hint stack to rewind the state.
3154 current_hint_str = prev_hint_str;
3156 AtEOXact_GUC(true, save_nestlevel);
3164 * current_hint_str is useless after planning of the top-level query.
3166 if (recurse_level < 1 && current_hint_str)
3168 pfree((void *)current_hint_str);
3169 current_hint_str = NULL;
3170 current_hint_retrieved = false;
3173 /* Print hint in debug mode. */
3174 if (debug_level == 1)
3175 HintStateDump(current_hint_state);
3176 else if (debug_level > 1)
3177 HintStateDump2(current_hint_state);
3180 * Rollback changes of GUC parameters, and pop current hint context from
3181 * hint stack to rewind the state.
3183 AtEOXact_GUC(true, save_nestlevel);
3188 standard_planner_proc:
3189 if (debug_level > 1)
3191 ereport(pg_hint_plan_debug_message_level,
3192 (errhidestmt(msgqno != qno),
3193 errmsg("pg_hint_plan%s: planner: no valid hint",
3197 current_hint_state = NULL;
3199 result = (*prev_planner) (parse, cursorOptions, boundParams);
3201 result = standard_planner(parse, cursorOptions, boundParams);
3203 /* The upper-level planner still needs the current hint state */
3204 if (HintStateStack != NIL)
3205 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
3211 * Find scan method hint to be applied to the given relation
3214 static ScanMethodHint *
3215 find_scan_hint(PlannerInfo *root, Index relid)
3219 ScanMethodHint *real_name_hint = NULL;
3220 ScanMethodHint *alias_hint = NULL;
3223 /* This should not be a join rel */
3225 rel = root->simple_rel_array[relid];
3228 * This function is called for any RelOptInfo or its inheritance parent if
3229 * any. If we are called from inheritance planner, the RelOptInfo for the
3230 * parent of target child relation is not set in the planner info.
3232 * Otherwise we should check that the reloptinfo is base relation or
3233 * inheritance children.
3236 rel->reloptkind != RELOPT_BASEREL &&
3237 rel->reloptkind != RELOPT_OTHER_MEMBER_REL)
3241 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3243 rte = root->simple_rte_array[relid];
3246 /* We don't hint on other than relation and foreign tables */
3247 if (rte->rtekind != RTE_RELATION ||
3248 rte->relkind == RELKIND_FOREIGN_TABLE)
3251 /* Find scan method hint, which matches given names, from the list. */
3252 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
3254 ScanMethodHint *hint = current_hint_state->scan_hints[i];
3256 /* We ignore disabled hints. */
3257 if (!hint_state_enabled(hint))
3261 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3264 /* check the real name for appendrel children */
3265 if (!real_name_hint &&
3266 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3268 char *realname = get_rel_name(rte->relid);
3270 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3271 real_name_hint = hint;
3274 /* No more match expected, break */
3275 if(alias_hint && real_name_hint)
3279 /* real name match precedes alias match */
3281 return real_name_hint;
3286 static ParallelHint *
3287 find_parallel_hint(PlannerInfo *root, Index relid)
3291 ParallelHint *real_name_hint = NULL;
3292 ParallelHint *alias_hint = NULL;
3295 /* This should not be a join rel */
3297 rel = root->simple_rel_array[relid];
3300 * Parallel planning is appliable only on base relation, which has
3307 * We have set root->glob->parallelModeOK if needed. What we should do here
3308 * is just following the decision of planner.
3310 if (!rel->consider_parallel)
3314 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3316 rte = root->simple_rte_array[relid];
3319 /* Find parallel method hint, which matches given names, from the list. */
3320 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_PARALLEL]; i++)
3322 ParallelHint *hint = current_hint_state->parallel_hints[i];
3324 /* We ignore disabled hints. */
3325 if (!hint_state_enabled(hint))
3329 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3332 /* check the real name for appendrel children */
3333 if (!real_name_hint &&
3334 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3336 char *realname = get_rel_name(rte->relid);
3338 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3339 real_name_hint = hint;
3342 /* No more match expected, break */
3343 if(alias_hint && real_name_hint)
3347 /* real name match precedes alias match */
3349 return real_name_hint;
3357 * Returns TRUE on match, FALSE on no match.
3359 * s1 --- the data to match against
3360 * s2 --- the pattern
3362 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
3365 regexpeq(const char *s1, const char *s2)
3371 strcpy(name.data, s1);
3372 regexp = cstring_to_text(s2);
3374 result = DirectFunctionCall2Coll(nameregexeq,
3375 DEFAULT_COLLATION_OID,
3376 NameGetDatum(&name),
3377 PointerGetDatum(regexp));
3378 return DatumGetBool(result);
3382 /* Remove indexes instructed not to use by hint. */
3384 restrict_indexes(PlannerInfo *root, ScanMethodHint *hint, RelOptInfo *rel,
3385 bool using_parent_hint)
3391 RangeTblEntry *rte = root->simple_rte_array[rel->relid];
3392 Oid relationObjectId = rte->relid;
3395 * We delete all the IndexOptInfo list and prevent you from being usable by
3398 if (hint->enforce_mask == ENABLE_SEQSCAN ||
3399 hint->enforce_mask == ENABLE_TIDSCAN)
3401 list_free_deep(rel->indexlist);
3402 rel->indexlist = NIL;
3403 hint->base.state = HINT_STATE_USED;
3409 * When a list of indexes is not specified, we just use all indexes.
3411 if (hint->indexnames == NIL)
3415 * Leaving only an specified index, we delete it from a IndexOptInfo list
3419 if (debug_level > 0)
3420 initStringInfo(&buf);
3422 for (cell = list_head(rel->indexlist); cell; cell = next)
3424 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
3425 char *indexname = get_rel_name(info->indexoid);
3427 bool use_index = false;
3431 foreach(l, hint->indexnames)
3433 char *hintname = (char *) lfirst(l);
3437 result = regexpeq(indexname, hintname);
3439 result = RelnameCmp(&indexname, &hintname) == 0;
3444 if (debug_level > 0)
3446 appendStringInfoCharMacro(&buf, ' ');
3447 quote_value(&buf, indexname);
3455 * Apply index restriction of parent hint to children. Since index
3456 * inheritance is not explicitly described we should search for an
3457 * children's index with the same definition to that of the parent.
3459 if (using_parent_hint && !use_index)
3461 foreach(l, current_hint_state->parent_index_infos)
3465 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
3468 * we check the 'same' index by comparing uniqueness, access
3469 * method and index key columns.
3471 if (p_info->indisunique != info->unique ||
3472 p_info->method != info->relam ||
3473 list_length(p_info->column_names) != info->ncolumns)
3476 /* Check if index key columns match */
3477 for (i = 0; i < info->ncolumns; i++)
3479 char *c_attname = NULL;
3480 char *p_attname = NULL;
3482 p_attname = list_nth(p_info->column_names, i);
3485 * if both of the key of the same position are expressions,
3486 * ignore them for now and check later.
3488 if (info->indexkeys[i] == 0 && !p_attname)
3491 /* deny if one is expression while another is not */
3492 if (info->indexkeys[i] == 0 || !p_attname)
3495 c_attname = get_attname(relationObjectId,
3496 info->indexkeys[i], false);
3498 /* deny if any of column attributes don't match */
3499 if (strcmp(p_attname, c_attname) != 0 ||
3500 p_info->indcollation[i] != info->indexcollations[i] ||
3501 p_info->opclass[i] != info->opcintype[i]||
3502 ((p_info->indoption[i] & INDOPTION_DESC) != 0)
3503 != info->reverse_sort[i] ||
3504 ((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0)
3505 != info->nulls_first[i])
3509 /* deny this if any difference found */
3510 if (i != info->ncolumns)
3513 /* check on key expressions */
3514 if ((p_info->expression_str && (info->indexprs != NIL)) ||
3515 (p_info->indpred_str && (info->indpred != NIL)))
3517 /* fetch the index of this child */
3518 ht_idx = SearchSysCache1(INDEXRELID,
3519 ObjectIdGetDatum(info->indexoid));
3521 /* check expressions if both expressions are available */
3522 if (p_info->expression_str &&
3523 !heap_attisnull(ht_idx, Anum_pg_index_indexprs, NULL))
3530 * to change the expression's parameter of child's
3533 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3534 Anum_pg_index_indexprs,
3537 result = DirectFunctionCall2(pg_get_expr,
3542 /* deny if expressions don't match */
3543 if (strcmp(p_info->expression_str,
3544 text_to_cstring(DatumGetTextP(result))) != 0)
3547 ReleaseSysCache(ht_idx);
3552 /* compare index predicates */
3553 if (p_info->indpred_str &&
3554 !heap_attisnull(ht_idx, Anum_pg_index_indpred, NULL))
3560 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3561 Anum_pg_index_indpred,
3564 result = DirectFunctionCall2(pg_get_expr,
3569 if (strcmp(p_info->indpred_str,
3570 text_to_cstring(DatumGetTextP(result))) != 0)
3573 ReleaseSysCache(ht_idx);
3579 ReleaseSysCache(ht_idx);
3581 else if (p_info->expression_str || (info->indexprs != NIL))
3583 else if (p_info->indpred_str || (info->indpred != NIL))
3588 /* to log the candidate of index */
3589 if (debug_level > 0)
3591 appendStringInfoCharMacro(&buf, ' ');
3592 quote_value(&buf, indexname);
3600 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
3607 if (debug_level == 1)
3609 StringInfoData rel_buf;
3610 char *disprelname = "";
3613 * If this hint targetted the parent, use the real name of this
3614 * child. Otherwise use hint specification.
3616 if (using_parent_hint)
3617 disprelname = get_rel_name(rte->relid);
3619 disprelname = hint->relname;
3622 initStringInfo(&rel_buf);
3623 quote_value(&rel_buf, disprelname);
3625 ereport(pg_hint_plan_debug_message_level,
3626 (errmsg("available indexes for %s(%s):%s",
3631 pfree(rel_buf.data);
3636 * Return information of index definition.
3638 static ParentIndexInfo *
3639 get_parent_index_info(Oid indexoid, Oid relid)
3641 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3642 Relation indexRelation;
3643 Form_pg_index index;
3647 indexRelation = index_open(indexoid, RowExclusiveLock);
3649 index = indexRelation->rd_index;
3651 p_info->indisunique = index->indisunique;
3652 p_info->method = indexRelation->rd_rel->relam;
3654 p_info->column_names = NIL;
3655 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3656 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3657 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3660 * Collect relation attribute names of index columns for index
3661 * identification, not index attribute names. NULL means expression index
3664 for (i = 0; i < index->indnatts; i++)
3666 attname = get_attname(relid, index->indkey.values[i], true);
3667 p_info->column_names = lappend(p_info->column_names, attname);
3669 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3670 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3671 p_info->indoption[i] = indexRelation->rd_indoption[i];
3675 * to check to match the expression's parameter of index with child indexes
3677 p_info->expression_str = NULL;
3678 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs,
3685 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3686 Anum_pg_index_indexprs, &isnull);
3688 result = DirectFunctionCall2(pg_get_expr,
3690 ObjectIdGetDatum(relid));
3692 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3696 * to check to match the predicate's parameter of index with child indexes
3698 p_info->indpred_str = NULL;
3699 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred,
3706 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3707 Anum_pg_index_indpred, &isnull);
3709 result = DirectFunctionCall2(pg_get_expr,
3711 ObjectIdGetDatum(relid));
3713 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3716 index_close(indexRelation, NoLock);
3722 * cancel hint enforcement
3725 reset_hint_enforcement()
3727 setup_scan_method_enforcement(NULL, current_hint_state);
3728 setup_parallel_plan_enforcement(NULL, current_hint_state);
3732 * Set planner guc parameters according to corresponding scan hints. Returns
3733 * bitmap of HintTypeBitmap. If shint or phint is not NULL, set used hint
3734 * there respectively.
3737 setup_hint_enforcement(PlannerInfo *root, RelOptInfo *rel,
3738 ScanMethodHint **rshint, ParallelHint **rphint)
3740 Index new_parent_relid = 0;
3742 ScanMethodHint *shint = NULL;
3743 ParallelHint *phint = NULL;
3744 bool inhparent = root->simple_rte_array[rel->relid]->inh;
3745 Oid relationObjectId = root->simple_rte_array[rel->relid]->relid;
3748 /* reset returns if requested */
3749 if (rshint != NULL) *rshint = NULL;
3750 if (rphint != NULL) *rphint = NULL;
3753 * We could register the parent relation of the following children here
3754 * when inhparent == true but inheritnce planner doesn't call this function
3755 * for parents. Since we cannot distinguish who called this function we
3756 * cannot do other than always seeking the parent regardless of who called
3761 /* set up only parallel hints for parent relation */
3762 phint = find_parallel_hint(root, rel->relid);
3765 setup_parallel_plan_enforcement(phint, current_hint_state);
3766 if (rphint) *rphint = phint;
3767 ret |= HINT_BM_PARALLEL;
3771 if (debug_level > 1)
3772 ereport(pg_hint_plan_debug_message_level,
3774 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3775 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3776 " current_hint_state=%p, hint_inhibit_level=%d",
3777 qnostr, relationObjectId,
3778 get_rel_name(relationObjectId),
3779 inhparent, current_hint_state, hint_inhibit_level)));
3783 /* Forget about the parent of another subquery */
3784 if (root != current_hint_state->current_root)
3785 current_hint_state->parent_relid = 0;
3787 /* Find the parent for this relation other than the registered parent */
3788 foreach (l, root->append_rel_list)
3790 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3792 if (appinfo->child_relid == rel->relid)
3794 if (current_hint_state->parent_relid != appinfo->parent_relid)
3796 new_parent_relid = appinfo->parent_relid;
3797 current_hint_state->current_root = root;
3805 /* This relation doesn't have a parent. Cancel current_hint_state. */
3806 current_hint_state->parent_relid = 0;
3807 current_hint_state->parent_scan_hint = NULL;
3808 current_hint_state->parent_parallel_hint = NULL;
3811 if (new_parent_relid > 0)
3814 * Here we found a new parent for the current relation. Scan continues
3815 * hint to other childrens of this parent so remember it to avoid
3816 * redundant setup cost.
3818 current_hint_state->parent_relid = new_parent_relid;
3820 /* Find hints for the parent */
3821 current_hint_state->parent_scan_hint =
3822 find_scan_hint(root, current_hint_state->parent_relid);
3824 current_hint_state->parent_parallel_hint =
3825 find_parallel_hint(root, current_hint_state->parent_relid);
3828 * If hint is found for the parent, apply it for this child instead
3831 if (current_hint_state->parent_scan_hint)
3833 ScanMethodHint * pshint = current_hint_state->parent_scan_hint;
3835 pshint->base.state = HINT_STATE_USED;
3837 /* Apply index mask in the same manner to the parent. */
3838 if (pshint->indexnames)
3841 Relation parent_rel;
3844 root->simple_rte_array[current_hint_state->parent_relid]->relid;
3845 parent_rel = heap_open(parentrel_oid, NoLock);
3847 /* Search the parent relation for indexes match the hint spec */
3848 foreach(l, RelationGetIndexList(parent_rel))
3850 Oid indexoid = lfirst_oid(l);
3851 char *indexname = get_rel_name(indexoid);
3853 ParentIndexInfo *parent_index_info;
3855 foreach(lc, pshint->indexnames)
3857 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3864 get_parent_index_info(indexoid, parentrel_oid);
3865 current_hint_state->parent_index_infos =
3866 lappend(current_hint_state->parent_index_infos,
3869 heap_close(parent_rel, NoLock);
3874 shint = find_scan_hint(root, rel->relid);
3876 shint = current_hint_state->parent_scan_hint;
3880 bool using_parent_hint =
3881 (shint == current_hint_state->parent_scan_hint);
3883 ret |= HINT_BM_SCAN_METHOD;
3885 /* Setup scan enforcement environment */
3886 setup_scan_method_enforcement(shint, current_hint_state);
3888 /* restrict unwanted inexes */
3889 restrict_indexes(root, shint, rel, using_parent_hint);
3891 if (debug_level > 1)
3893 char *additional_message = "";
3895 if (shint == current_hint_state->parent_scan_hint)
3896 additional_message = " by parent hint";
3898 ereport(pg_hint_plan_debug_message_level,
3900 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3901 " index deletion%s:"
3902 " relation=%u(%s), inhparent=%d, "
3903 "current_hint_state=%p,"
3904 " hint_inhibit_level=%d, scanmask=0x%x",
3905 qnostr, additional_message,
3907 get_rel_name(relationObjectId),
3908 inhparent, current_hint_state,
3910 shint->enforce_mask)));
3914 /* Do the same for parallel plan enforcement */
3915 phint = find_parallel_hint(root, rel->relid);
3917 phint = current_hint_state->parent_parallel_hint;
3919 setup_parallel_plan_enforcement(phint, current_hint_state);
3922 ret |= HINT_BM_PARALLEL;
3924 /* Nothing to apply. Reset the scan mask to intial state */
3925 if (!shint && ! phint)
3927 if (debug_level > 1)
3928 ereport(pg_hint_plan_debug_message_level,
3929 (errhidestmt (true),
3930 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3932 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3933 " hint_inhibit_level=%d, scanmask=0x%x",
3934 qnostr, relationObjectId,
3935 get_rel_name(relationObjectId),
3936 inhparent, current_hint_state, hint_inhibit_level,
3937 current_hint_state->init_scan_mask)));
3939 setup_scan_method_enforcement(NULL, current_hint_state);
3944 if (rshint != NULL) *rshint = shint;
3945 if (rphint != NULL) *rphint = phint;
3951 * Return index of relation which matches given aliasname, or 0 if not found.
3952 * If same aliasname was used multiple times in a query, return -1.
3955 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3961 for (i = 1; i < root->simple_rel_array_size; i++)
3965 if (root->simple_rel_array[i] == NULL)
3968 Assert(i == root->simple_rel_array[i]->relid);
3970 if (RelnameCmp(&aliasname,
3971 &root->simple_rte_array[i]->eref->aliasname) != 0)
3974 foreach(l, initial_rels)
3976 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3978 if (rel->reloptkind == RELOPT_BASEREL)
3980 if (rel->relid != i)
3985 Assert(rel->reloptkind == RELOPT_JOINREL);
3987 if (!bms_is_member(i, rel->relids))
3994 ("Relation name \"%s\" is ambiguous.",
4009 * Return join hint which matches given joinrelids.
4011 static JoinMethodHint *
4012 find_join_hint(Relids joinrelids)
4017 join_hint = current_hint_state->join_hint_level[bms_num_members(joinrelids)];
4019 foreach(l, join_hint)
4021 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
4023 if (bms_equal(joinrelids, hint->joinrelids))
4031 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
4032 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
4034 OuterInnerRels *outer_rels;
4035 OuterInnerRels *inner_rels;
4036 Relids outer_relids;
4037 Relids inner_relids;
4039 JoinMethodHint *hint;
4041 if (outer_inner->relation != NULL)
4043 return bms_make_singleton(
4044 find_relid_aliasname(root, outer_inner->relation,
4046 leading_hint->base.hint_str));
4049 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
4050 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
4052 outer_relids = OuterInnerJoinCreate(outer_rels,
4058 inner_relids = OuterInnerJoinCreate(inner_rels,
4065 join_relids = bms_add_members(outer_relids, inner_relids);
4067 if (bms_num_members(join_relids) > nbaserel)
4071 * If we don't have join method hint, create new one for the
4072 * join combination with all join methods are enabled.
4074 hint = find_join_hint(join_relids);
4078 * Here relnames is not set, since Relids bitmap is sufficient to
4079 * control paths of this query afterward.
4081 hint = (JoinMethodHint *) JoinMethodHintCreate(
4082 leading_hint->base.hint_str,
4084 HINT_KEYWORD_LEADING);
4085 hint->base.state = HINT_STATE_USED;
4086 hint->nrels = bms_num_members(join_relids);
4087 hint->enforce_mask = ENABLE_ALL_JOIN;
4088 hint->joinrelids = bms_copy(join_relids);
4089 hint->inner_nrels = bms_num_members(inner_relids);
4090 hint->inner_joinrelids = bms_copy(inner_relids);
4092 hstate->join_hint_level[hint->nrels] =
4093 lappend(hstate->join_hint_level[hint->nrels], hint);
4097 hint->inner_nrels = bms_num_members(inner_relids);
4098 hint->inner_joinrelids = bms_copy(inner_relids);
4105 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
4106 int nrels, char **relnames)
4109 Relids relids = NULL;
4113 for (j = 0; j < nrels; j++)
4115 relname = relnames[j];
4117 relid = find_relid_aliasname(root, relname, initial_rels,
4121 base->state = HINT_STATE_ERROR;
4124 * the aliasname is not found(relid == 0) or same aliasname was used
4125 * multiple times in a query(relid == -1)
4132 if (bms_is_member(relid, relids))
4134 hint_ereport(base->hint_str,
4135 ("Relation name \"%s\" is duplicated.", relname));
4136 base->state = HINT_STATE_ERROR;
4140 relids = bms_add_member(relids, relid);
4145 * Transform join method hint into handy form.
4147 * - create bitmap of relids from alias names, to make it easier to check
4148 * whether a join path matches a join method hint.
4149 * - add join method hints which are necessary to enforce join order
4150 * specified by Leading hint
4153 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
4154 List *initial_rels, JoinMethodHint **join_method_hints)
4162 LeadingHint *lhint = NULL;
4165 * Create bitmap of relids from alias names for each join method hint.
4166 * Bitmaps are more handy than strings in join searching.
4168 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
4170 JoinMethodHint *hint = hstate->join_hints[i];
4172 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4175 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4176 initial_rels, hint->nrels, hint->relnames);
4178 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
4181 hstate->join_hint_level[hint->nrels] =
4182 lappend(hstate->join_hint_level[hint->nrels], hint);
4186 * Create bitmap of relids from alias names for each rows hint.
4187 * Bitmaps are more handy than strings in join searching.
4189 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
4191 RowsHint *hint = hstate->rows_hints[i];
4193 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4196 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4197 initial_rels, hint->nrels, hint->relnames);
4200 /* Do nothing if no Leading hint was supplied. */
4201 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
4205 * Decide whether to use Leading hint
4207 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
4209 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
4212 if (leading_hint->base.state == HINT_STATE_ERROR)
4218 foreach(l, leading_hint->relations)
4220 relname = (char *)lfirst(l);;
4222 relid = find_relid_aliasname(root, relname, initial_rels,
4223 leading_hint->base.hint_str);
4225 leading_hint->base.state = HINT_STATE_ERROR;
4230 if (bms_is_member(relid, relids))
4232 hint_ereport(leading_hint->base.hint_str,
4233 ("Relation name \"%s\" is duplicated.", relname));
4234 leading_hint->base.state = HINT_STATE_ERROR;
4238 relids = bms_add_member(relids, relid);
4241 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
4246 hint_ereport(lhint->base.hint_str,
4247 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
4248 lhint->base.state = HINT_STATE_DUPLICATION;
4250 leading_hint->base.state = HINT_STATE_USED;
4251 lhint = leading_hint;
4254 /* check to exist Leading hint marked with 'used'. */
4259 * We need join method hints which fit specified join order in every join
4260 * level. For example, Leading(A B C) virtually requires following join
4261 * method hints, if no join method hint supplied:
4263 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
4264 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
4266 * If we already have join method hint which fits specified join order in
4267 * that join level, we leave it as-is and don't add new hints.
4271 if (lhint->outer_inner == NULL)
4273 foreach(l, lhint->relations)
4275 JoinMethodHint *hint;
4277 relname = (char *)lfirst(l);
4280 * Find relid of the relation which has given name. If we have the
4281 * name given in Leading hint multiple times in the join, nothing to
4284 relid = find_relid_aliasname(root, relname, initial_rels,
4287 /* Create bitmap of relids for current join level. */
4288 joinrelids = bms_add_member(joinrelids, relid);
4291 /* We never have join method hint for single relation. */
4296 * If we don't have join method hint, create new one for the
4297 * join combination with all join methods are enabled.
4299 hint = find_join_hint(joinrelids);
4303 * Here relnames is not set, since Relids bitmap is sufficient
4304 * to control paths of this query afterward.
4306 hint = (JoinMethodHint *) JoinMethodHintCreate(
4307 lhint->base.hint_str,
4309 HINT_KEYWORD_LEADING);
4310 hint->base.state = HINT_STATE_USED;
4311 hint->nrels = njoinrels;
4312 hint->enforce_mask = ENABLE_ALL_JOIN;
4313 hint->joinrelids = bms_copy(joinrelids);
4316 join_method_hints[njoinrels] = hint;
4318 if (njoinrels >= nbaserel)
4321 bms_free(joinrelids);
4327 * Delete all join hints which have different combination from Leading
4330 for (i = 2; i <= njoinrels; i++)
4332 list_free(hstate->join_hint_level[i]);
4334 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
4339 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
4346 njoinrels = bms_num_members(joinrelids);
4347 Assert(njoinrels >= 2);
4350 * Delete all join hints which have different combination from Leading
4353 for (i = 2;i <= njoinrels; i++)
4355 if (hstate->join_hint_level[i] != NIL)
4357 ListCell *prev = NULL;
4358 ListCell *next = NULL;
4359 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
4362 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
4366 if (hint->inner_nrels == 0 &&
4367 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
4368 bms_equal(bms_union(hint->joinrelids, joinrelids),
4371 hstate->join_hint_level[i] =
4372 list_delete_cell(hstate->join_hint_level[i], l,
4381 bms_free(joinrelids);
4384 if (hint_state_enabled(lhint))
4386 set_join_config_options(DISABLE_ALL_JOIN, current_hint_state->context);
4393 * wrapper of make_join_rel()
4395 * call make_join_rel() after changing enable_* parameters according to given
4399 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
4402 JoinMethodHint *hint;
4406 joinrelids = bms_union(rel1->relids, rel2->relids);
4407 hint = find_join_hint(joinrelids);
4408 bms_free(joinrelids);
4411 return pg_hint_plan_make_join_rel(root, rel1, rel2);
4413 if (hint->inner_nrels == 0)
4415 save_nestlevel = NewGUCNestLevel();
4417 set_join_config_options(hint->enforce_mask,
4418 current_hint_state->context);
4420 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4421 hint->base.state = HINT_STATE_USED;
4424 * Restore the GUC variables we set above.
4426 AtEOXact_GUC(true, save_nestlevel);
4429 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4438 add_paths_to_joinrel_wrapper(PlannerInfo *root,
4439 RelOptInfo *joinrel,
4440 RelOptInfo *outerrel,
4441 RelOptInfo *innerrel,
4443 SpecialJoinInfo *sjinfo,
4447 JoinMethodHint *join_hint;
4450 joinrelids = bms_union(outerrel->relids, innerrel->relids);
4451 join_hint = find_join_hint(joinrelids);
4452 bms_free(joinrelids);
4454 if (join_hint && join_hint->inner_nrels != 0)
4456 save_nestlevel = NewGUCNestLevel();
4458 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
4461 set_join_config_options(join_hint->enforce_mask,
4462 current_hint_state->context);
4464 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4465 sjinfo, restrictlist);
4466 join_hint->base.state = HINT_STATE_USED;
4470 set_join_config_options(DISABLE_ALL_JOIN,
4471 current_hint_state->context);
4472 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4473 sjinfo, restrictlist);
4477 * Restore the GUC variables we set above.
4479 AtEOXact_GUC(true, save_nestlevel);
4482 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4483 sjinfo, restrictlist);
4487 get_num_baserels(List *initial_rels)
4492 foreach(l, initial_rels)
4494 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
4496 if (rel->reloptkind == RELOPT_BASEREL)
4498 else if (rel->reloptkind ==RELOPT_JOINREL)
4499 nbaserel+= bms_num_members(rel->relids);
4502 /* other values not expected here */
4503 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
4511 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
4514 JoinMethodHint **join_method_hints;
4518 bool leading_hint_enable;
4521 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
4522 * valid hint is supplied or current nesting depth is nesting depth of SPI
4525 if (!current_hint_state || hint_inhibit_level > 0)
4527 if (prev_join_search)
4528 return (*prev_join_search) (root, levels_needed, initial_rels);
4529 else if (enable_geqo && levels_needed >= geqo_threshold)
4530 return geqo(root, levels_needed, initial_rels);
4532 return standard_join_search(root, levels_needed, initial_rels);
4536 * In the case using GEQO, only scan method hints and Set hints have
4537 * effect. Join method and join order is not controllable by hints.
4539 if (enable_geqo && levels_needed >= geqo_threshold)
4540 return geqo(root, levels_needed, initial_rels);
4542 nbaserel = get_num_baserels(initial_rels);
4543 current_hint_state->join_hint_level =
4544 palloc0(sizeof(List *) * (nbaserel + 1));
4545 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4547 leading_hint_enable = transform_join_hints(current_hint_state,
4549 initial_rels, join_method_hints);
4551 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4554 * Adjust number of parallel workers of the result rel to the largest
4555 * number of the component paths.
4557 if (current_hint_state->num_hints[HINT_TYPE_PARALLEL] > 0)
4562 foreach (lc, initial_rels)
4565 RelOptInfo *rel = (RelOptInfo *) lfirst(lc);
4567 foreach (lcp, rel->partial_pathlist)
4569 Path *path = (Path *) lfirst(lcp);
4571 if (nworkers < path-> parallel_workers)
4572 nworkers = path-> parallel_workers;
4576 foreach (lc, rel->partial_pathlist)
4578 Path *path = (Path *) lfirst(lc);
4580 if (path->parallel_safe && path->parallel_workers < nworkers)
4581 path->parallel_workers = nworkers;
4585 for (i = 2; i <= nbaserel; i++)
4587 list_free(current_hint_state->join_hint_level[i]);
4589 /* free Leading hint only */
4590 if (join_method_hints[i] != NULL &&
4591 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4592 JoinMethodHintDelete(join_method_hints[i]);
4594 pfree(current_hint_state->join_hint_level);
4595 pfree(join_method_hints);
4597 if (leading_hint_enable)
4598 set_join_config_options(current_hint_state->init_join_mask,
4599 current_hint_state->context);
4605 * Force number of wokers if instructed by hint
4608 pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
4609 Index rti, RangeTblEntry *rte)
4611 ParallelHint *phint;
4615 /* call the previous hook */
4616 if (prev_set_rel_pathlist)
4617 prev_set_rel_pathlist(root, rel, rti, rte);
4619 /* Nothing to do if no hint available */
4620 if (current_hint_state == NULL)
4623 /* Don't touch dummy rels. */
4624 if (IS_DUMMY_REL(rel))
4628 * We can accept only plain relations, foreign tables and table saples are
4629 * also unacceptable. See set_rel_pathlist.
4631 if ((rel->rtekind != RTE_RELATION &&
4632 rel->rtekind != RTE_SUBQUERY)||
4633 rte->relkind == RELKIND_FOREIGN_TABLE ||
4634 rte->tablesample != NULL)
4638 * Even though UNION ALL node doesn't have particular name so usually it is
4639 * unhintable, turn on parallel when it contains parallel nodes.
4641 if (rel->rtekind == RTE_SUBQUERY)
4644 bool inhibit_nonparallel = false;
4646 if (rel->partial_pathlist == NIL)
4649 foreach(lc, rel->partial_pathlist)
4652 AppendPath *apath = (AppendPath *) lfirst(lc);
4653 int parallel_workers = 0;
4655 if (!IsA(apath, AppendPath))
4658 foreach (lcp, apath->subpaths)
4660 Path *spath = (Path *) lfirst(lcp);
4662 if (spath->parallel_aware &&
4663 parallel_workers < spath->parallel_workers)
4664 parallel_workers = spath->parallel_workers;
4667 apath->path.parallel_workers = parallel_workers;
4668 inhibit_nonparallel = true;
4671 if (inhibit_nonparallel)
4675 foreach(lc, rel->pathlist)
4677 Path *path = (Path *) lfirst(lc);
4679 if (path->startup_cost < disable_cost)
4681 path->startup_cost += disable_cost;
4682 path->total_cost += disable_cost;
4690 /* We cannot handle if this requires an outer */
4691 if (rel->lateral_relids)
4694 /* Return if this relation gets no enfocement */
4695 if ((found_hints = setup_hint_enforcement(root, rel, NULL, &phint)) == 0)
4698 /* Here, we regenerate paths with the current hint restriction */
4699 if (found_hints & HINT_BM_SCAN_METHOD || found_hints & HINT_BM_PARALLEL)
4702 * When hint is specified on non-parent relations, discard existing
4703 * paths and regenerate based on the hint considered. Otherwise we
4704 * already have hinted child paths then just adjust the number of
4705 * planned number of workers.
4707 if (root->simple_rte_array[rel->relid]->inh)
4709 /* enforce number of workers if requested */
4710 if (phint && phint->force_parallel)
4712 if (phint->nworkers == 0)
4714 list_free_deep(rel->partial_pathlist);
4715 rel->partial_pathlist = NIL;
4719 /* prioritize partial paths */
4720 foreach (l, rel->partial_pathlist)
4722 Path *ppath = (Path *) lfirst(l);
4724 if (ppath->parallel_safe)
4726 ppath->parallel_workers = phint->nworkers;
4727 ppath->startup_cost = 0;
4728 ppath->total_cost = 0;
4732 /* disable non-partial paths */
4733 foreach (l, rel->pathlist)
4735 Path *ppath = (Path *) lfirst(l);
4737 if (ppath->startup_cost < disable_cost)
4739 ppath->startup_cost += disable_cost;
4740 ppath->total_cost += disable_cost;
4748 /* Just discard all the paths considered so far */
4749 list_free_deep(rel->pathlist);
4750 rel->pathlist = NIL;
4751 list_free_deep(rel->partial_pathlist);
4752 rel->partial_pathlist = NIL;
4754 /* Regenerate paths with the current enforcement */
4755 set_plain_rel_pathlist(root, rel, rte);
4757 /* Additional work to enforce parallel query execution */
4758 if (phint && phint->nworkers > 0)
4761 * For Parallel Append to be planned properly, we shouldn't set
4762 * the costs of non-partial paths to disable-value. Lower the
4763 * priority of non-parallel paths by setting partial path costs
4766 foreach (l, rel->partial_pathlist)
4768 Path *path = (Path *) lfirst(l);
4770 path->startup_cost = 0;
4771 path->total_cost = 0;
4774 /* enforce number of workers if requested */
4775 if (phint->force_parallel)
4777 foreach (l, rel->partial_pathlist)
4779 Path *ppath = (Path *) lfirst(l);
4781 if (ppath->parallel_safe)
4782 ppath->parallel_workers = phint->nworkers;
4786 /* Generate gather paths */
4787 if (rel->reloptkind == RELOPT_BASEREL &&
4788 bms_membership(root->all_baserels) != BMS_SINGLETON)
4789 generate_gather_paths(root, rel, false);
4794 reset_hint_enforcement();
4799 * Build access paths for a base relation
4801 * This function was copied and edited from set_rel_pathlist() in
4802 * src/backend/optimizer/path/allpaths.c in order not to copy other static
4803 * functions not required here.
4806 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4807 Index rti, RangeTblEntry *rte)
4809 if (IS_DUMMY_REL(rel))
4811 /* We already proved the relation empty, so nothing more to do */
4815 /* It's an "append relation", process accordingly */
4816 set_append_rel_pathlist(root, rel, rti, rte);
4820 if (rel->rtekind == RTE_RELATION)
4822 if (rte->relkind == RELKIND_RELATION)
4824 if(rte->tablesample != NULL)
4825 elog(ERROR, "sampled relation is not supported");
4827 /* Plain relation */
4828 set_plain_rel_pathlist(root, rel, rte);
4831 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4834 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4838 * Allow a plugin to editorialize on the set of Paths for this base
4839 * relation. It could add new paths (such as CustomPaths) by calling
4840 * add_path(), or delete or modify paths added by the core code.
4842 if (set_rel_pathlist_hook)
4843 (*set_rel_pathlist_hook) (root, rel, rti, rte);
4845 /* Now find the cheapest of the paths for this rel */
4850 * stmt_beg callback is called when each query in PL/pgSQL function is about
4851 * to be executed. At that timing, we save query string in the global variable
4852 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4853 * variable for the purpose, because its content is only necessary until
4854 * planner hook is called for the query, so recursive PL/pgSQL function calls
4855 * don't harm this mechanism.
4858 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4860 plpgsql_recurse_level++;
4864 * stmt_end callback is called then each query in PL/pgSQL function has
4865 * finished. At that timing, we clear plpgsql_query_string to tell planner
4866 * hook that next call is not for a query written in PL/pgSQL block.
4869 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4871 plpgsql_recurse_level--;
4874 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4879 if (!isTopLevel || phase != RESOURCE_RELEASE_AFTER_LOCKS)
4881 /* Cancel plpgsql nest level*/
4882 plpgsql_recurse_level = 0;
4885 #define standard_join_search pg_hint_plan_standard_join_search
4886 #define join_search_one_level pg_hint_plan_join_search_one_level
4887 #define make_join_rel make_join_rel_wrapper
4890 #undef make_join_rel
4891 #define make_join_rel pg_hint_plan_make_join_rel
4892 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4893 #include "make_join_rel.c"
4895 #include "pg_stat_statements.c"