1 /*-------------------------------------------------------------------------
4 * hinting on how to execute a query for PostgreSQL
6 * Copyright (c) 2012-2018, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
8 *-------------------------------------------------------------------------
13 #include "catalog/pg_collation.h"
14 #include "catalog/pg_index.h"
15 #include "commands/prepare.h"
16 #include "mb/pg_wchar.h"
17 #include "miscadmin.h"
18 #include "nodes/nodeFuncs.h"
19 #include "nodes/params.h"
20 #include "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;
228 /* common data for all hints. */
231 const char *hint_str; /* must not do pfree */
232 const char *keyword; /* must not do pfree */
233 HintKeyword hint_keyword;
236 HintDeleteFunction delete_func;
237 HintDescFunction desc_func;
238 HintCmpFunction cmp_func;
239 HintParseFunction parse_func;
242 /* scan method hints */
243 typedef struct ScanMethodHint
249 unsigned char enforce_mask;
252 typedef struct ParentIndexInfo
257 char *expression_str;
264 /* join method hints */
265 typedef struct JoinMethodHint
271 unsigned char enforce_mask;
273 Relids inner_joinrelids;
276 /* join order hints */
277 typedef struct OuterInnerRels
280 List *outer_inner_pair;
283 typedef struct LeadingHint
286 List *relations; /* relation names specified in Leading hint */
287 OuterInnerRels *outer_inner;
290 /* change a run-time parameter hints */
291 typedef struct SetHint
294 char *name; /* name of variable */
300 typedef enum RowsValueType {
301 RVT_ABSOLUTE, /* Rows(... #1000) */
302 RVT_ADD, /* Rows(... +1000) */
303 RVT_SUB, /* Rows(... -1000) */
304 RVT_MULTI, /* Rows(... *1.2) */
306 typedef struct RowsHint
313 Relids inner_joinrelids;
315 RowsValueType value_type;
320 typedef struct ParallelHint
324 char *nworkers_str; /* original string of nworkers */
325 int nworkers; /* num of workers specified by Worker */
326 bool force_parallel; /* force parallel scan */
330 * Describes a context of hint processing.
334 char *hint_str; /* original hint string */
337 int nall_hints; /* # of valid all hints */
338 int max_all_hints; /* # of slots for all hints */
339 Hint **all_hints; /* parsed all hints */
341 /* # of each hints */
342 int num_hints[NUM_HINT_TYPE];
344 /* for scan method hints */
345 ScanMethodHint **scan_hints; /* parsed scan hints */
347 /* Initial values of parameters */
348 int init_scan_mask; /* enable_* mask */
349 int init_nworkers; /* max_parallel_workers_per_gather */
350 /* min_parallel_table_scan_size*/
351 int init_min_para_tablescan_size;
352 /* min_parallel_index_scan_size*/
353 int init_min_para_indexscan_size;
354 int init_paratup_cost; /* parallel_tuple_cost */
355 int init_parasetup_cost;/* parallel_setup_cost */
357 PlannerInfo *current_root; /* PlannerInfo for the followings */
358 Index parent_relid; /* inherit parent of table relid */
359 ScanMethodHint *parent_scan_hint; /* scan hint for the parent */
360 ParallelHint *parent_parallel_hint; /* parallel hint for the parent */
361 List *parent_index_infos; /* list of parent table's index */
363 JoinMethodHint **join_hints; /* parsed join hints */
364 int init_join_mask; /* initial value join parameter */
365 List **join_hint_level;
366 LeadingHint **leading_hint; /* parsed Leading hints */
367 SetHint **set_hints; /* parsed Set hints */
368 GucContext context; /* which GUC parameters can we set? */
369 RowsHint **rows_hints; /* parsed Rows hints */
370 ParallelHint **parallel_hints; /* parsed Parallel hints */
374 * Describes a hint parser module which is bound with particular hint keyword.
376 typedef struct HintParser
379 HintCreateFunction create_func;
380 HintKeyword hint_keyword;
383 /* Module callbacks */
387 static void push_hint(HintState *hstate);
388 static void pop_hint(void);
390 static void pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query);
391 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
392 ParamListInfo boundParams);
393 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
397 /* Scan method hint callbacks */
398 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
399 HintKeyword hint_keyword);
400 static void ScanMethodHintDelete(ScanMethodHint *hint);
401 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
402 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
403 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
404 Query *parse, const char *str);
406 /* Join method hint callbacks */
407 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
408 HintKeyword hint_keyword);
409 static void JoinMethodHintDelete(JoinMethodHint *hint);
410 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
411 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
412 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
413 Query *parse, const char *str);
415 /* Leading hint callbacks */
416 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
417 HintKeyword hint_keyword);
418 static void LeadingHintDelete(LeadingHint *hint);
419 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
420 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
421 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
422 Query *parse, const char *str);
424 /* Set hint callbacks */
425 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
426 HintKeyword hint_keyword);
427 static void SetHintDelete(SetHint *hint);
428 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
429 static int SetHintCmp(const SetHint *a, const SetHint *b);
430 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
433 /* Rows hint callbacks */
434 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
435 HintKeyword hint_keyword);
436 static void RowsHintDelete(RowsHint *hint);
437 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
438 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
439 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
440 Query *parse, const char *str);
442 /* Parallel hint callbacks */
443 static Hint *ParallelHintCreate(const char *hint_str, const char *keyword,
444 HintKeyword hint_keyword);
445 static void ParallelHintDelete(ParallelHint *hint);
446 static void ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf);
447 static int ParallelHintCmp(const ParallelHint *a, const ParallelHint *b);
448 static const char *ParallelHintParse(ParallelHint *hint, HintState *hstate,
449 Query *parse, const char *str);
451 static void quote_value(StringInfo buf, const char *value);
453 static const char *parse_quoted_value(const char *str, char **word,
456 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
459 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
460 void pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
461 Index rti, RangeTblEntry *rte);
462 static void create_plain_partial_paths(PlannerInfo *root,
464 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
465 ListCell *other_rels);
466 static void make_rels_by_clauseless_joins(PlannerInfo *root,
468 ListCell *other_rels);
469 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
470 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
472 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
473 Index rti, RangeTblEntry *rte);
474 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
477 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
479 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
481 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
485 static int set_config_option_noerror(const char *name, const char *value,
486 GucContext context, GucSource source,
487 GucAction action, bool changeVal, int elevel);
488 static void setup_scan_method_enforcement(ScanMethodHint *scanhint,
490 static int set_config_int32_option(const char *name, int32 value,
494 static bool pg_hint_plan_enable_hint = true;
495 static int debug_level = 0;
496 static int pg_hint_plan_parse_message_level = INFO;
497 static int pg_hint_plan_debug_message_level = LOG;
498 /* Default is off, to keep backward compatibility. */
499 static bool pg_hint_plan_enable_hint_table = false;
501 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
502 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
503 /* (This could not be above 1) */
504 static int max_hint_nworkers = -1; /* Maximum nworkers of Workers hints */
506 static const struct config_enum_entry parse_messages_level_options[] = {
507 {"debug", DEBUG2, true},
508 {"debug5", DEBUG5, false},
509 {"debug4", DEBUG4, false},
510 {"debug3", DEBUG3, false},
511 {"debug2", DEBUG2, false},
512 {"debug1", DEBUG1, false},
514 {"info", INFO, false},
515 {"notice", NOTICE, false},
516 {"warning", WARNING, false},
517 {"error", ERROR, false},
519 * {"fatal", FATAL, true},
520 * {"panic", PANIC, true},
525 static const struct config_enum_entry parse_debug_level_options[] = {
528 {"detailed", 2, false},
529 {"verbose", 3, false},
541 /* Saved hook values in case of unload */
542 static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
543 static planner_hook_type prev_planner = NULL;
544 static join_search_hook_type prev_join_search = NULL;
545 static set_rel_pathlist_hook_type prev_set_rel_pathlist = NULL;
547 /* Hold reference to currently active hint */
548 static HintState *current_hint_state = NULL;
551 * List of hint contexts. We treat the head of the list as the Top of the
552 * context stack, so current_hint_state always points the first element of this
555 static List *HintStateStack = NIL;
558 * Holds statement name during executing EXECUTE command. NULL for other
561 static char *stmt_name = NULL;
563 static const HintParser parsers[] = {
564 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
565 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
566 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
567 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
568 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
569 HINT_KEYWORD_BITMAPSCANREGEXP},
570 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
571 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
572 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
573 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
574 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
575 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
576 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
577 HINT_KEYWORD_INDEXONLYSCANREGEXP},
578 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
580 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
581 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
582 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
583 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
584 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
585 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
587 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
588 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
589 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
590 {HINT_PARALLEL, ParallelHintCreate, HINT_KEYWORD_PARALLEL},
592 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
595 PLpgSQL_plugin plugin_funcs = {
599 pg_hint_plan_plpgsql_stmt_beg,
600 pg_hint_plan_plpgsql_stmt_end,
606 * Module load callbacks
611 PLpgSQL_plugin **var_ptr;
613 /* Define custom GUC variables. */
614 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
615 "Force planner to use plans specified in the hint comment preceding to the query.",
617 &pg_hint_plan_enable_hint,
625 DefineCustomEnumVariable("pg_hint_plan.debug_print",
626 "Logs results of hint parsing.",
630 parse_debug_level_options,
637 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
638 "Message level of parse errors.",
640 &pg_hint_plan_parse_message_level,
642 parse_messages_level_options,
649 DefineCustomEnumVariable("pg_hint_plan.message_level",
650 "Message level of debug messages.",
652 &pg_hint_plan_debug_message_level,
654 parse_messages_level_options,
661 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
662 "Let pg_hint_plan look up the hint table.",
664 &pg_hint_plan_enable_hint_table,
673 prev_post_parse_analyze_hook = post_parse_analyze_hook;
674 post_parse_analyze_hook = pg_hint_plan_post_parse_analyze;
675 prev_planner = planner_hook;
676 planner_hook = pg_hint_plan_planner;
677 prev_join_search = join_search_hook;
678 join_search_hook = pg_hint_plan_join_search;
679 prev_set_rel_pathlist = set_rel_pathlist_hook;
680 set_rel_pathlist_hook = pg_hint_plan_set_rel_pathlist;
682 /* setup PL/pgSQL plugin hook */
683 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
684 *var_ptr = &plugin_funcs;
686 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
690 * Module unload callback
696 PLpgSQL_plugin **var_ptr;
698 /* Uninstall hooks. */
699 post_parse_analyze_hook = prev_post_parse_analyze_hook;
700 planner_hook = prev_planner;
701 join_search_hook = prev_join_search;
702 set_rel_pathlist_hook = prev_set_rel_pathlist;
704 /* uninstall PL/pgSQL plugin hook */
705 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
710 * create and delete functions the hint object
714 ScanMethodHintCreate(const char *hint_str, const char *keyword,
715 HintKeyword hint_keyword)
717 ScanMethodHint *hint;
719 hint = palloc(sizeof(ScanMethodHint));
720 hint->base.hint_str = hint_str;
721 hint->base.keyword = keyword;
722 hint->base.hint_keyword = hint_keyword;
723 hint->base.type = HINT_TYPE_SCAN_METHOD;
724 hint->base.state = HINT_STATE_NOTUSED;
725 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
726 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
727 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
728 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
729 hint->relname = NULL;
730 hint->indexnames = NIL;
731 hint->regexp = false;
732 hint->enforce_mask = 0;
734 return (Hint *) hint;
738 ScanMethodHintDelete(ScanMethodHint *hint)
744 pfree(hint->relname);
745 list_free_deep(hint->indexnames);
750 JoinMethodHintCreate(const char *hint_str, const char *keyword,
751 HintKeyword hint_keyword)
753 JoinMethodHint *hint;
755 hint = palloc(sizeof(JoinMethodHint));
756 hint->base.hint_str = hint_str;
757 hint->base.keyword = keyword;
758 hint->base.hint_keyword = hint_keyword;
759 hint->base.type = HINT_TYPE_JOIN_METHOD;
760 hint->base.state = HINT_STATE_NOTUSED;
761 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
762 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
763 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
764 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
766 hint->inner_nrels = 0;
767 hint->relnames = NULL;
768 hint->enforce_mask = 0;
769 hint->joinrelids = NULL;
770 hint->inner_joinrelids = NULL;
772 return (Hint *) hint;
776 JoinMethodHintDelete(JoinMethodHint *hint)
785 for (i = 0; i < hint->nrels; i++)
786 pfree(hint->relnames[i]);
787 pfree(hint->relnames);
790 bms_free(hint->joinrelids);
791 bms_free(hint->inner_joinrelids);
796 LeadingHintCreate(const char *hint_str, const char *keyword,
797 HintKeyword hint_keyword)
801 hint = palloc(sizeof(LeadingHint));
802 hint->base.hint_str = hint_str;
803 hint->base.keyword = keyword;
804 hint->base.hint_keyword = hint_keyword;
805 hint->base.type = HINT_TYPE_LEADING;
806 hint->base.state = HINT_STATE_NOTUSED;
807 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
808 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
809 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
810 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
811 hint->relations = NIL;
812 hint->outer_inner = NULL;
814 return (Hint *) hint;
818 LeadingHintDelete(LeadingHint *hint)
823 list_free_deep(hint->relations);
824 if (hint->outer_inner)
825 pfree(hint->outer_inner);
830 SetHintCreate(const char *hint_str, const char *keyword,
831 HintKeyword hint_keyword)
835 hint = palloc(sizeof(SetHint));
836 hint->base.hint_str = hint_str;
837 hint->base.keyword = keyword;
838 hint->base.hint_keyword = hint_keyword;
839 hint->base.type = HINT_TYPE_SET;
840 hint->base.state = HINT_STATE_NOTUSED;
841 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
842 hint->base.desc_func = (HintDescFunction) SetHintDesc;
843 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
844 hint->base.parse_func = (HintParseFunction) SetHintParse;
849 return (Hint *) hint;
853 SetHintDelete(SetHint *hint)
863 list_free(hint->words);
868 RowsHintCreate(const char *hint_str, const char *keyword,
869 HintKeyword hint_keyword)
873 hint = palloc(sizeof(RowsHint));
874 hint->base.hint_str = hint_str;
875 hint->base.keyword = keyword;
876 hint->base.hint_keyword = hint_keyword;
877 hint->base.type = HINT_TYPE_ROWS;
878 hint->base.state = HINT_STATE_NOTUSED;
879 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
880 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
881 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
882 hint->base.parse_func = (HintParseFunction) RowsHintParse;
884 hint->inner_nrels = 0;
885 hint->relnames = NULL;
886 hint->joinrelids = NULL;
887 hint->inner_joinrelids = NULL;
888 hint->rows_str = NULL;
889 hint->value_type = RVT_ABSOLUTE;
892 return (Hint *) hint;
896 RowsHintDelete(RowsHint *hint)
905 for (i = 0; i < hint->nrels; i++)
906 pfree(hint->relnames[i]);
907 pfree(hint->relnames);
910 bms_free(hint->joinrelids);
911 bms_free(hint->inner_joinrelids);
916 ParallelHintCreate(const char *hint_str, const char *keyword,
917 HintKeyword hint_keyword)
921 hint = palloc(sizeof(ScanMethodHint));
922 hint->base.hint_str = hint_str;
923 hint->base.keyword = keyword;
924 hint->base.hint_keyword = hint_keyword;
925 hint->base.type = HINT_TYPE_PARALLEL;
926 hint->base.state = HINT_STATE_NOTUSED;
927 hint->base.delete_func = (HintDeleteFunction) ParallelHintDelete;
928 hint->base.desc_func = (HintDescFunction) ParallelHintDesc;
929 hint->base.cmp_func = (HintCmpFunction) ParallelHintCmp;
930 hint->base.parse_func = (HintParseFunction) ParallelHintParse;
931 hint->relname = NULL;
933 hint->nworkers_str = "0";
935 return (Hint *) hint;
939 ParallelHintDelete(ParallelHint *hint)
945 pfree(hint->relname);
951 HintStateCreate(void)
955 hstate = palloc(sizeof(HintState));
956 hstate->hint_str = NULL;
957 hstate->nall_hints = 0;
958 hstate->max_all_hints = 0;
959 hstate->all_hints = NULL;
960 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
961 hstate->scan_hints = NULL;
962 hstate->init_scan_mask = 0;
963 hstate->init_nworkers = 0;
964 hstate->init_min_para_tablescan_size = 0;
965 hstate->init_min_para_indexscan_size = 0;
966 hstate->init_paratup_cost = 0;
967 hstate->init_parasetup_cost = 0;
968 hstate->current_root = NULL;
969 hstate->parent_relid = 0;
970 hstate->parent_scan_hint = NULL;
971 hstate->parent_parallel_hint = NULL;
972 hstate->parent_index_infos = NIL;
973 hstate->join_hints = NULL;
974 hstate->init_join_mask = 0;
975 hstate->join_hint_level = NULL;
976 hstate->leading_hint = NULL;
977 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
978 hstate->set_hints = NULL;
979 hstate->rows_hints = NULL;
980 hstate->parallel_hints = NULL;
986 HintStateDelete(HintState *hstate)
993 if (hstate->hint_str)
994 pfree(hstate->hint_str);
996 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
997 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
998 if (hstate->all_hints)
999 pfree(hstate->all_hints);
1000 if (hstate->parent_index_infos)
1001 list_free(hstate->parent_index_infos);
1005 * Copy given value into buf, with quoting with '"' if necessary.
1008 quote_value(StringInfo buf, const char *value)
1010 bool need_quote = false;
1013 for (str = value; *str != '\0'; str++)
1015 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
1018 appendStringInfoCharMacro(buf, '"');
1023 for (str = value; *str != '\0'; str++)
1026 appendStringInfoCharMacro(buf, '"');
1028 appendStringInfoCharMacro(buf, *str);
1032 appendStringInfoCharMacro(buf, '"');
1036 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
1040 appendStringInfo(buf, "%s(", hint->base.keyword);
1041 if (hint->relname != NULL)
1043 quote_value(buf, hint->relname);
1044 foreach(l, hint->indexnames)
1046 appendStringInfoCharMacro(buf, ' ');
1047 quote_value(buf, (char *) lfirst(l));
1050 appendStringInfoString(buf, ")");
1052 appendStringInfoChar(buf, '\n');
1056 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
1060 appendStringInfo(buf, "%s(", hint->base.keyword);
1061 if (hint->relnames != NULL)
1063 quote_value(buf, hint->relnames[0]);
1064 for (i = 1; i < hint->nrels; i++)
1066 appendStringInfoCharMacro(buf, ' ');
1067 quote_value(buf, hint->relnames[i]);
1070 appendStringInfoString(buf, ")");
1072 appendStringInfoChar(buf, '\n');
1076 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
1078 if (outer_inner->relation == NULL)
1085 appendStringInfoCharMacro(buf, '(');
1086 foreach(l, outer_inner->outer_inner_pair)
1091 appendStringInfoCharMacro(buf, ' ');
1093 OuterInnerDesc(lfirst(l), buf);
1096 appendStringInfoCharMacro(buf, ')');
1099 quote_value(buf, outer_inner->relation);
1103 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
1105 appendStringInfo(buf, "%s(", HINT_LEADING);
1106 if (hint->outer_inner == NULL)
1113 foreach(l, hint->relations)
1118 appendStringInfoCharMacro(buf, ' ');
1120 quote_value(buf, (char *) lfirst(l));
1124 OuterInnerDesc(hint->outer_inner, buf);
1126 appendStringInfoString(buf, ")");
1128 appendStringInfoChar(buf, '\n');
1132 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1134 bool is_first = true;
1137 appendStringInfo(buf, "%s(", HINT_SET);
1138 foreach(l, hint->words)
1143 appendStringInfoCharMacro(buf, ' ');
1145 quote_value(buf, (char *) lfirst(l));
1147 appendStringInfo(buf, ")");
1149 appendStringInfoChar(buf, '\n');
1153 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1157 appendStringInfo(buf, "%s(", hint->base.keyword);
1158 if (hint->relnames != NULL)
1160 quote_value(buf, hint->relnames[0]);
1161 for (i = 1; i < hint->nrels; i++)
1163 appendStringInfoCharMacro(buf, ' ');
1164 quote_value(buf, hint->relnames[i]);
1167 appendStringInfo(buf, " %s", hint->rows_str);
1168 appendStringInfoString(buf, ")");
1170 appendStringInfoChar(buf, '\n');
1174 ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf)
1176 appendStringInfo(buf, "%s(", hint->base.keyword);
1177 if (hint->relname != NULL)
1179 quote_value(buf, hint->relname);
1181 /* number of workers */
1182 appendStringInfoCharMacro(buf, ' ');
1183 quote_value(buf, hint->nworkers_str);
1184 /* application mode of num of workers */
1185 appendStringInfoCharMacro(buf, ' ');
1186 appendStringInfoString(buf,
1187 (hint->force_parallel ? "hard" : "soft"));
1189 appendStringInfoString(buf, ")");
1191 appendStringInfoChar(buf, '\n');
1195 * Append string which represents all hints in a given state to buf, with
1196 * preceding title with them.
1199 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1200 HintStatus state, bool nolf)
1204 appendStringInfo(buf, "%s:", title);
1206 appendStringInfoChar(buf, '\n');
1209 for (i = 0; i < hstate->nall_hints; i++)
1211 if (hstate->all_hints[i]->state != state)
1214 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1218 if (nolf && nshown == 0)
1219 appendStringInfoString(buf, "(none)");
1223 * Dump contents of given hstate to server log with log level LOG.
1226 HintStateDump(HintState *hstate)
1232 elog(pg_hint_plan_debug_message_level, "pg_hint_plan:\nno hint");
1236 initStringInfo(&buf);
1238 appendStringInfoString(&buf, "pg_hint_plan:\n");
1239 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1240 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1241 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1242 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1244 ereport(pg_hint_plan_debug_message_level,
1245 (errmsg ("%s", buf.data)));
1251 HintStateDump2(HintState *hstate)
1257 elog(pg_hint_plan_debug_message_level,
1258 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1262 initStringInfo(&buf);
1263 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1264 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1265 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1266 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1267 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1268 appendStringInfoChar(&buf, '}');
1270 ereport(pg_hint_plan_debug_message_level,
1271 (errmsg("%s", buf.data),
1273 errhidecontext(true)));
1283 RelnameCmp(const void *a, const void *b)
1285 const char *relnamea = *((const char **) a);
1286 const char *relnameb = *((const char **) b);
1288 return strcmp(relnamea, relnameb);
1292 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1294 return RelnameCmp(&a->relname, &b->relname);
1298 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1302 if (a->nrels != b->nrels)
1303 return a->nrels - b->nrels;
1305 for (i = 0; i < a->nrels; i++)
1308 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1316 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1322 SetHintCmp(const SetHint *a, const SetHint *b)
1324 return strcmp(a->name, b->name);
1328 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1332 if (a->nrels != b->nrels)
1333 return a->nrels - b->nrels;
1335 for (i = 0; i < a->nrels; i++)
1338 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1346 ParallelHintCmp(const ParallelHint *a, const ParallelHint *b)
1348 return RelnameCmp(&a->relname, &b->relname);
1352 HintCmp(const void *a, const void *b)
1354 const Hint *hinta = *((const Hint **) a);
1355 const Hint *hintb = *((const Hint **) b);
1357 if (hinta->type != hintb->type)
1358 return hinta->type - hintb->type;
1359 if (hinta->state == HINT_STATE_ERROR)
1361 if (hintb->state == HINT_STATE_ERROR)
1363 return hinta->cmp_func(hinta, hintb);
1367 * Returns byte offset of hint b from hint a. If hint a was specified before
1368 * b, positive value is returned.
1371 HintCmpWithPos(const void *a, const void *b)
1373 const Hint *hinta = *((const Hint **) a);
1374 const Hint *hintb = *((const Hint **) b);
1377 result = HintCmp(a, b);
1379 result = hinta->hint_str - hintb->hint_str;
1388 parse_keyword(const char *str, StringInfo buf)
1392 while (!isspace(*str) && *str != '(' && *str != '\0')
1393 appendStringInfoCharMacro(buf, *str++);
1399 skip_parenthesis(const char *str, char parenthesis)
1403 if (*str != parenthesis)
1405 if (parenthesis == '(')
1406 hint_ereport(str, ("Opening parenthesis is necessary."));
1407 else if (parenthesis == ')')
1408 hint_ereport(str, ("Closing parenthesis is necessary."));
1419 * Parse a token from str, and store malloc'd copy into word. A token can be
1420 * quoted with '"'. Return value is pointer to unparsed portion of original
1421 * string, or NULL if an error occurred.
1423 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1426 parse_quoted_value(const char *str, char **word, bool truncate)
1431 /* Skip leading spaces. */
1434 initStringInfo(&buf);
1447 /* Double quotation must be closed. */
1451 hint_ereport(str, ("Unterminated quoted string."));
1456 * Skip escaped double quotation.
1458 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1459 * block comments) to be an object name, so users must specify
1460 * alias for such object names.
1462 * Those special names can be allowed if we care escaped slashes
1463 * and asterisks, but we don't.
1472 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1476 appendStringInfoCharMacro(&buf, *str++);
1481 hint_ereport(str, ("Zero-length delimited string."));
1488 /* Truncate name if it's too long */
1490 truncate_identifier(buf.data, strlen(buf.data), true);
1497 static OuterInnerRels *
1498 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1500 OuterInnerRels *outer_inner;
1502 outer_inner = palloc(sizeof(OuterInnerRels));
1503 outer_inner->relation = name;
1504 outer_inner->outer_inner_pair = outer_inner_list;
1510 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1512 List *outer_inner_pair = NIL;
1514 if ((str = skip_parenthesis(str, '(')) == NULL)
1519 /* Store words in parentheses into outer_inner_list. */
1520 while(*str != ')' && *str != '\0')
1522 OuterInnerRels *outer_inner_rels;
1526 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1534 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1537 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1540 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1545 (str = skip_parenthesis(str, ')')) == NULL)
1547 list_free(outer_inner_pair);
1551 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1557 parse_parentheses_Leading(const char *str, List **name_list,
1558 OuterInnerRels **outer_inner)
1561 bool truncate = true;
1563 if ((str = skip_parenthesis(str, '(')) == NULL)
1569 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1574 /* Store words in parentheses into name_list. */
1575 while(*str != ')' && *str != '\0')
1577 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1579 list_free(*name_list);
1583 *name_list = lappend(*name_list, name);
1588 if ((str = skip_parenthesis(str, ')')) == NULL)
1594 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1597 bool truncate = true;
1599 if ((str = skip_parenthesis(str, '(')) == NULL)
1604 /* Store words in parentheses into name_list. */
1605 while(*str != ')' && *str != '\0')
1607 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1609 list_free(*name_list);
1613 *name_list = lappend(*name_list, name);
1616 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1617 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1618 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1619 keyword == HINT_KEYWORD_SET)
1625 if ((str = skip_parenthesis(str, ')')) == NULL)
1631 parse_hints(HintState *hstate, Query *parse, const char *str)
1636 initStringInfo(&buf);
1637 while (*str != '\0')
1639 const HintParser *parser;
1641 /* in error message, we output the comment including the keyword. */
1642 head = (char *) str;
1644 /* parse only the keyword of the hint. */
1645 resetStringInfo(&buf);
1646 str = parse_keyword(str, &buf);
1648 for (parser = parsers; parser->keyword != NULL; parser++)
1650 char *keyword = parser->keyword;
1653 if (pg_strcasecmp(buf.data, keyword) != 0)
1656 hint = parser->create_func(head, keyword, parser->hint_keyword);
1658 /* parser of each hint does parse in a parenthesis. */
1659 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1661 hint->delete_func(hint);
1667 * Add hint information into all_hints array. If we don't have
1668 * enough space, double the array.
1670 if (hstate->nall_hints == 0)
1672 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1673 hstate->all_hints = (Hint **)
1674 palloc(sizeof(Hint *) * hstate->max_all_hints);
1676 else if (hstate->nall_hints == hstate->max_all_hints)
1678 hstate->max_all_hints *= 2;
1679 hstate->all_hints = (Hint **)
1680 repalloc(hstate->all_hints,
1681 sizeof(Hint *) * hstate->max_all_hints);
1684 hstate->all_hints[hstate->nall_hints] = hint;
1685 hstate->nall_hints++;
1692 if (parser->keyword == NULL)
1695 ("Unrecognized hint keyword \"%s\".", buf.data));
1706 * Get hints from table by client-supplied query string and application name.
1709 get_hints_from_table(const char *client_query, const char *client_application)
1711 const char *search_query =
1713 " FROM hint_plan.hints "
1714 " WHERE norm_query_string = $1 "
1715 " AND ( application_name = $2 "
1716 " OR application_name = '' ) "
1717 " ORDER BY application_name DESC";
1718 static SPIPlanPtr plan = NULL;
1720 Oid argtypes[2] = { TEXTOID, TEXTOID };
1722 char nulls[2] = {' ', ' '};
1728 bool snapshot_set = false;
1730 hint_inhibit_level++;
1732 if (!ActiveSnapshotSet())
1734 PushActiveSnapshot(GetTransactionSnapshot());
1735 snapshot_set = true;
1743 p = SPI_prepare(search_query, 2, argtypes);
1744 plan = SPI_saveplan(p);
1748 qry = cstring_to_text(client_query);
1749 app = cstring_to_text(client_application);
1750 values[0] = PointerGetDatum(qry);
1751 values[1] = PointerGetDatum(app);
1753 SPI_execute_plan(plan, values, nulls, true, 1);
1755 if (SPI_processed > 0)
1759 hints = SPI_getvalue(SPI_tuptable->vals[0],
1760 SPI_tuptable->tupdesc, 1);
1762 * Here we use SPI_palloc to ensure that hints string is valid even
1763 * after SPI_finish call. We can't use simple palloc because it
1764 * allocates memory in SPI's context and that context is deleted in
1767 buf = SPI_palloc(strlen(hints) + 1);
1775 PopActiveSnapshot();
1777 hint_inhibit_level--;
1781 hint_inhibit_level--;
1790 * Get client-supplied query string. Addtion to that the jumbled query is
1791 * supplied if the caller requested. From the restriction of JumbleQuery, some
1792 * kind of query needs special amendments. Reutrns NULL if this query doesn't
1793 * change the current hint. This function returns NULL also when something
1794 * wrong has happend and let the caller continue using the current hints.
1797 get_query_string(ParseState *pstate, Query *query, Query **jumblequery)
1799 const char *p = debug_query_string;
1802 * If debug_query_string is set, it is the top level statement. But in some
1803 * cases we reach here with debug_query_string set NULL for example in the
1804 * case of DESCRIBE message handling. We may still see a candidate
1805 * top-level query in pstate in the case.
1809 /* We don't see a query string, return NULL */
1810 if (!pstate->p_sourcetext)
1813 p = pstate->p_sourcetext;
1816 if (jumblequery != NULL)
1817 *jumblequery = query;
1819 if (query->commandType == CMD_UTILITY)
1821 Query *target_query = (Query *)query->utilityStmt;
1824 * Some CMD_UTILITY statements have a subquery that we can hint on.
1825 * Since EXPLAIN can be placed before other kind of utility statements
1826 * and EXECUTE can be contained other kind of utility statements, these
1827 * conditions are not mutually exclusive and should be considered in
1830 if (IsA(target_query, ExplainStmt))
1832 ExplainStmt *stmt = (ExplainStmt *)target_query;
1834 Assert(IsA(stmt->query, Query));
1835 target_query = (Query *)stmt->query;
1837 /* strip out the top-level query for further processing */
1838 if (target_query->commandType == CMD_UTILITY &&
1839 target_query->utilityStmt != NULL)
1840 target_query = (Query *)target_query->utilityStmt;
1843 if (IsA(target_query, DeclareCursorStmt))
1845 DeclareCursorStmt *stmt = (DeclareCursorStmt *)target_query;
1846 Query *query = (Query *)stmt->query;
1848 /* the target must be CMD_SELECT in this case */
1849 Assert(IsA(query, Query) && query->commandType == CMD_SELECT);
1850 target_query = query;
1853 if (IsA(target_query, CreateTableAsStmt))
1855 CreateTableAsStmt *stmt = (CreateTableAsStmt *) target_query;
1857 Assert(IsA(stmt->query, Query));
1858 target_query = (Query *) stmt->query;
1860 /* strip out the top-level query for further processing */
1861 if (target_query->commandType == CMD_UTILITY &&
1862 target_query->utilityStmt != NULL)
1863 target_query = (Query *)target_query->utilityStmt;
1866 if (IsA(target_query, ExecuteStmt))
1869 * Use the prepared query for EXECUTE. The Query for jumble
1870 * also replaced with the corresponding one.
1872 ExecuteStmt *stmt = (ExecuteStmt *)target_query;
1873 PreparedStatement *entry;
1875 entry = FetchPreparedStatement(stmt->name, true);
1876 p = entry->plansource->query_string;
1877 target_query = (Query *) linitial (entry->plansource->query_list);
1880 /* JumbleQuery accespts only a non-utility Query */
1881 if (!IsA(target_query, Query) ||
1882 target_query->utilityStmt != NULL)
1883 target_query = NULL;
1886 *jumblequery = target_query;
1888 /* Return NULL if the pstate is not identical to the top-level query */
1889 else if (strcmp(pstate->p_sourcetext, p) != 0)
1896 * Get hints from the head block comment in client-supplied query string.
1899 get_hints_from_comment(const char *p)
1901 const char *hint_head;
1909 /* extract query head comment. */
1910 hint_head = strstr(p, HINT_START);
1911 if (hint_head == NULL)
1913 for (;p < hint_head; p++)
1916 * Allow these characters precedes hint comment:
1918 * - alphabets which are in ASCII range
1919 * - space, tabs and new-lines
1920 * - underscores, for identifier
1921 * - commas, for SELECT clause, EXPLAIN and PREPARE
1922 * - parentheses, for EXPLAIN and PREPARE
1924 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1925 * avoid behavior which depends on locale setting.
1927 if (!(*p >= '0' && *p <= '9') &&
1928 !(*p >= 'A' && *p <= 'Z') &&
1929 !(*p >= 'a' && *p <= 'z') &&
1933 *p != '(' && *p != ')')
1937 len = strlen(HINT_START);
1942 /* find hint end keyword. */
1943 if ((tail = strstr(p, HINT_END)) == NULL)
1945 hint_ereport(head, ("Unterminated block comment."));
1949 /* We don't support nested block comments. */
1950 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1952 hint_ereport(head, ("Nested block comments are not supported."));
1956 /* Make a copy of hint. */
1958 head = palloc(len + 1);
1959 memcpy(head, p, len);
1967 * Parse hints that got, create hint struct from parse tree and parse hints.
1970 create_hintstate(Query *parse, const char *hints)
1979 /* -1 means that no Parallel hint is specified. */
1980 max_hint_nworkers = -1;
1983 hstate = HintStateCreate();
1984 hstate->hint_str = (char *) hints;
1986 /* parse each hint. */
1987 parse_hints(hstate, parse, p);
1989 /* When nothing specified a hint, we free HintState and returns NULL. */
1990 if (hstate->nall_hints == 0)
1992 HintStateDelete(hstate);
1996 /* Sort hints in order of original position. */
1997 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
2000 /* Count number of hints per hint-type. */
2001 for (i = 0; i < hstate->nall_hints; i++)
2003 Hint *cur_hint = hstate->all_hints[i];
2004 hstate->num_hints[cur_hint->type]++;
2008 * If an object (or a set of objects) has multiple hints of same hint-type,
2009 * only the last hint is valid and others are ignored in planning.
2010 * Hints except the last are marked as 'duplicated' to remember the order.
2012 for (i = 0; i < hstate->nall_hints - 1; i++)
2014 Hint *cur_hint = hstate->all_hints[i];
2015 Hint *next_hint = hstate->all_hints[i + 1];
2018 * Leading hint is marked as 'duplicated' in transform_join_hints.
2020 if (cur_hint->type == HINT_TYPE_LEADING &&
2021 next_hint->type == HINT_TYPE_LEADING)
2025 * Note that we need to pass addresses of hint pointers, because
2026 * HintCmp is designed to sort array of Hint* by qsort.
2028 if (HintCmp(&cur_hint, &next_hint) == 0)
2030 hint_ereport(cur_hint->hint_str,
2031 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
2032 cur_hint->state = HINT_STATE_DUPLICATION;
2037 * Make sure that per-type array pointers point proper position in the
2038 * array which consists of all hints.
2040 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
2041 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
2042 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
2043 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
2044 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
2045 hstate->set_hints = (SetHint **) (hstate->leading_hint +
2046 hstate->num_hints[HINT_TYPE_LEADING]);
2047 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
2048 hstate->num_hints[HINT_TYPE_SET]);
2049 hstate->parallel_hints = (ParallelHint **) (hstate->set_hints +
2050 hstate->num_hints[HINT_TYPE_ROWS]);
2056 * Parse inside of parentheses of scan-method hints.
2059 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
2062 const char *keyword = hint->base.keyword;
2063 HintKeyword hint_keyword = hint->base.hint_keyword;
2064 List *name_list = NIL;
2067 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2070 /* Parse relation name and index name(s) if given hint accepts. */
2071 length = list_length(name_list);
2073 /* at least twp parameters required */
2077 ("%s hint requires a relation.", hint->base.keyword));
2078 hint->base.state = HINT_STATE_ERROR;
2082 hint->relname = linitial(name_list);
2083 hint->indexnames = list_delete_first(name_list);
2085 /* check whether the hint accepts index name(s) */
2086 if (length > 1 && !SCAN_HINT_ACCEPTS_INDEX_NAMES(hint_keyword))
2089 ("%s hint accepts only one relation.",
2090 hint->base.keyword));
2091 hint->base.state = HINT_STATE_ERROR;
2095 /* Set a bit for specified hint. */
2096 switch (hint_keyword)
2098 case HINT_KEYWORD_SEQSCAN:
2099 hint->enforce_mask = ENABLE_SEQSCAN;
2101 case HINT_KEYWORD_INDEXSCAN:
2102 hint->enforce_mask = ENABLE_INDEXSCAN;
2104 case HINT_KEYWORD_INDEXSCANREGEXP:
2105 hint->enforce_mask = ENABLE_INDEXSCAN;
2106 hint->regexp = true;
2108 case HINT_KEYWORD_BITMAPSCAN:
2109 hint->enforce_mask = ENABLE_BITMAPSCAN;
2111 case HINT_KEYWORD_BITMAPSCANREGEXP:
2112 hint->enforce_mask = ENABLE_BITMAPSCAN;
2113 hint->regexp = true;
2115 case HINT_KEYWORD_TIDSCAN:
2116 hint->enforce_mask = ENABLE_TIDSCAN;
2118 case HINT_KEYWORD_NOSEQSCAN:
2119 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
2121 case HINT_KEYWORD_NOINDEXSCAN:
2122 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
2124 case HINT_KEYWORD_NOBITMAPSCAN:
2125 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
2127 case HINT_KEYWORD_NOTIDSCAN:
2128 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
2130 case HINT_KEYWORD_INDEXONLYSCAN:
2131 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2133 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
2134 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2135 hint->regexp = true;
2137 case HINT_KEYWORD_NOINDEXONLYSCAN:
2138 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
2141 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2150 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2153 const char *keyword = hint->base.keyword;
2154 HintKeyword hint_keyword = hint->base.hint_keyword;
2155 List *name_list = NIL;
2157 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2160 hint->nrels = list_length(name_list);
2162 if (hint->nrels > 0)
2168 * Transform relation names from list to array to sort them with qsort
2171 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2172 foreach (l, name_list)
2174 hint->relnames[i] = lfirst(l);
2179 list_free(name_list);
2181 /* A join hint requires at least two relations */
2182 if (hint->nrels < 2)
2185 ("%s hint requires at least two relations.",
2186 hint->base.keyword));
2187 hint->base.state = HINT_STATE_ERROR;
2191 /* Sort hints in alphabetical order of relation names. */
2192 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2194 switch (hint_keyword)
2196 case HINT_KEYWORD_NESTLOOP:
2197 hint->enforce_mask = ENABLE_NESTLOOP;
2199 case HINT_KEYWORD_MERGEJOIN:
2200 hint->enforce_mask = ENABLE_MERGEJOIN;
2202 case HINT_KEYWORD_HASHJOIN:
2203 hint->enforce_mask = ENABLE_HASHJOIN;
2205 case HINT_KEYWORD_NONESTLOOP:
2206 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2208 case HINT_KEYWORD_NOMERGEJOIN:
2209 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2211 case HINT_KEYWORD_NOHASHJOIN:
2212 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2215 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2224 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2227 if (outer_inner->outer_inner_pair == NIL)
2229 if (outer_inner->relation)
2235 if (list_length(outer_inner->outer_inner_pair) == 2)
2237 foreach(l, outer_inner->outer_inner_pair)
2239 if (!OuterInnerPairCheck(lfirst(l)))
2250 OuterInnerList(OuterInnerRels *outer_inner)
2252 List *outer_inner_list = NIL;
2254 OuterInnerRels *outer_inner_rels;
2256 foreach(l, outer_inner->outer_inner_pair)
2258 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2260 if (outer_inner_rels->relation != NULL)
2261 outer_inner_list = lappend(outer_inner_list,
2262 outer_inner_rels->relation);
2264 outer_inner_list = list_concat(outer_inner_list,
2265 OuterInnerList(outer_inner_rels));
2267 return outer_inner_list;
2271 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2274 List *name_list = NIL;
2275 OuterInnerRels *outer_inner = NULL;
2277 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2281 if (outer_inner != NULL)
2282 name_list = OuterInnerList(outer_inner);
2284 hint->relations = name_list;
2285 hint->outer_inner = outer_inner;
2287 /* A Leading hint requires at least two relations */
2288 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2290 hint_ereport(hint->base.hint_str,
2291 ("%s hint requires at least two relations.",
2293 hint->base.state = HINT_STATE_ERROR;
2295 else if (hint->outer_inner != NULL &&
2296 !OuterInnerPairCheck(hint->outer_inner))
2298 hint_ereport(hint->base.hint_str,
2299 ("%s hint requires two sets of relations when parentheses nests.",
2301 hint->base.state = HINT_STATE_ERROR;
2308 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2310 List *name_list = NIL;
2312 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2316 hint->words = name_list;
2318 /* We need both name and value to set GUC parameter. */
2319 if (list_length(name_list) == 2)
2321 hint->name = linitial(name_list);
2322 hint->value = lsecond(name_list);
2326 hint_ereport(hint->base.hint_str,
2327 ("%s hint requires name and value of GUC parameter.",
2329 hint->base.state = HINT_STATE_ERROR;
2336 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2339 HintKeyword hint_keyword = hint->base.hint_keyword;
2340 List *name_list = NIL;
2344 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2347 /* Last element must be rows specification */
2348 hint->nrels = list_length(name_list) - 1;
2350 if (hint->nrels > 0)
2356 * Transform relation names from list to array to sort them with qsort
2359 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2360 foreach (l, name_list)
2362 if (hint->nrels <= i)
2364 hint->relnames[i] = lfirst(l);
2369 /* Retieve rows estimation */
2370 rows_str = list_nth(name_list, hint->nrels);
2371 hint->rows_str = rows_str; /* store as-is for error logging */
2372 if (rows_str[0] == '#')
2374 hint->value_type = RVT_ABSOLUTE;
2377 else if (rows_str[0] == '+')
2379 hint->value_type = RVT_ADD;
2382 else if (rows_str[0] == '-')
2384 hint->value_type = RVT_SUB;
2387 else if (rows_str[0] == '*')
2389 hint->value_type = RVT_MULTI;
2394 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2395 hint->base.state = HINT_STATE_ERROR;
2398 hint->rows = strtod(rows_str, &end_ptr);
2401 hint_ereport(rows_str,
2402 ("%s hint requires valid number as rows estimation.",
2403 hint->base.keyword));
2404 hint->base.state = HINT_STATE_ERROR;
2408 /* A join hint requires at least two relations */
2409 if (hint->nrels < 2)
2412 ("%s hint requires at least two relations.",
2413 hint->base.keyword));
2414 hint->base.state = HINT_STATE_ERROR;
2418 list_free(name_list);
2420 /* Sort relnames in alphabetical order. */
2421 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2427 ParallelHintParse(ParallelHint *hint, HintState *hstate, Query *parse,
2430 HintKeyword hint_keyword = hint->base.hint_keyword;
2431 List *name_list = NIL;
2435 bool force_parallel = false;
2437 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2440 /* Parse relation name and index name(s) if given hint accepts. */
2441 length = list_length(name_list);
2443 if (length < 2 || length > 3)
2446 ("wrong number of arguments (%d): %s",
2447 length, hint->base.keyword));
2448 hint->base.state = HINT_STATE_ERROR;
2452 hint->relname = linitial(name_list);
2454 /* The second parameter is number of workers */
2455 hint->nworkers_str = list_nth(name_list, 1);
2456 nworkers = strtod(hint->nworkers_str, &end_ptr);
2457 if (*end_ptr || nworkers < 0 || nworkers > max_worker_processes)
2460 hint_ereport(hint->nworkers_str,
2461 ("number of workers must be a number: %s",
2462 hint->base.keyword));
2463 else if (nworkers < 0)
2464 hint_ereport(hint->nworkers_str,
2465 ("number of workers must be positive: %s",
2466 hint->base.keyword));
2467 else if (nworkers > max_worker_processes)
2468 hint_ereport(hint->nworkers_str,
2469 ("number of workers = %d is larger than max_worker_processes(%d): %s",
2470 nworkers, max_worker_processes, hint->base.keyword));
2472 hint->base.state = HINT_STATE_ERROR;
2475 hint->nworkers = nworkers;
2477 /* optional third parameter is specified */
2480 const char *modeparam = (const char *)list_nth(name_list, 2);
2481 if (pg_strcasecmp(modeparam, "hard") == 0)
2482 force_parallel = true;
2483 else if (pg_strcasecmp(modeparam, "soft") != 0)
2485 hint_ereport(modeparam,
2486 ("enforcement must be soft or hard: %s",
2487 hint->base.keyword));
2488 hint->base.state = HINT_STATE_ERROR;
2492 hint->force_parallel = force_parallel;
2494 if (hint->base.state != HINT_STATE_ERROR &&
2495 nworkers > max_hint_nworkers)
2496 max_hint_nworkers = nworkers;
2502 * set GUC parameter functions
2506 get_current_scan_mask()
2511 mask |= ENABLE_SEQSCAN;
2512 if (enable_indexscan)
2513 mask |= ENABLE_INDEXSCAN;
2514 if (enable_bitmapscan)
2515 mask |= ENABLE_BITMAPSCAN;
2517 mask |= ENABLE_TIDSCAN;
2518 if (enable_indexonlyscan)
2519 mask |= ENABLE_INDEXONLYSCAN;
2525 get_current_join_mask()
2529 if (enable_nestloop)
2530 mask |= ENABLE_NESTLOOP;
2531 if (enable_mergejoin)
2532 mask |= ENABLE_MERGEJOIN;
2533 if (enable_hashjoin)
2534 mask |= ENABLE_HASHJOIN;
2540 * Sets GUC prameters without throwing exception. Reutrns false if something
2544 set_config_option_noerror(const char *name, const char *value,
2545 GucContext context, GucSource source,
2546 GucAction action, bool changeVal, int elevel)
2549 MemoryContext ccxt = CurrentMemoryContext;
2553 result = set_config_option(name, value, context, source,
2554 action, changeVal, 0, false);
2560 /* Save error info */
2561 MemoryContextSwitchTo(ccxt);
2562 errdata = CopyErrorData();
2566 (errcode(errdata->sqlerrcode),
2567 errmsg("%s", errdata->message),
2568 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2569 errdata->hint ? errhint("%s", errdata->hint) : 0));
2571 FreeErrorData(errdata);
2579 * Sets GUC parameter of int32 type without throwing exceptions. Returns false
2580 * if something wrong.
2583 set_config_int32_option(const char *name, int32 value, GucContext context)
2585 char buf[16]; /* enough for int32 */
2587 if (snprintf(buf, 16, "%d", value) < 0)
2589 ereport(pg_hint_plan_parse_message_level,
2590 (errmsg ("Failed to convert integer to string: %d", value)));
2595 set_config_option_noerror(name, buf, context,
2596 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2597 pg_hint_plan_parse_message_level);
2600 /* setup scan method enforcement according to given options */
2602 setup_guc_enforcement(SetHint **options, int noptions, GucContext context)
2606 for (i = 0; i < noptions; i++)
2608 SetHint *hint = options[i];
2611 if (!hint_state_enabled(hint))
2614 result = set_config_option_noerror(hint->name, hint->value, context,
2615 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2616 pg_hint_plan_parse_message_level);
2618 hint->base.state = HINT_STATE_USED;
2620 hint->base.state = HINT_STATE_ERROR;
2627 * Setup parallel execution environment.
2629 * If hint is not NULL, set up using it, elsewise reset to initial environment.
2632 setup_parallel_plan_enforcement(ParallelHint *hint, HintState *state)
2636 hint->base.state = HINT_STATE_USED;
2637 set_config_int32_option("max_parallel_workers_per_gather",
2638 hint->nworkers, state->context);
2641 set_config_int32_option("max_parallel_workers_per_gather",
2642 state->init_nworkers, state->context);
2644 /* force means that enforce parallel as far as possible */
2645 if (hint && hint->force_parallel && hint->nworkers > 0)
2647 set_config_int32_option("parallel_tuple_cost", 0, state->context);
2648 set_config_int32_option("parallel_setup_cost", 0, state->context);
2649 set_config_int32_option("min_parallel_table_scan_size", 0,
2651 set_config_int32_option("min_parallel_index_scan_size", 0,
2656 set_config_int32_option("parallel_tuple_cost",
2657 state->init_paratup_cost, state->context);
2658 set_config_int32_option("parallel_setup_cost",
2659 state->init_parasetup_cost, state->context);
2660 set_config_int32_option("min_parallel_table_scan_size",
2661 state->init_min_para_tablescan_size,
2663 set_config_int32_option("min_parallel_index_scan_size",
2664 state->init_min_para_indexscan_size,
2669 #define SET_CONFIG_OPTION(name, type_bits) \
2670 set_config_option_noerror((name), \
2671 (mask & (type_bits)) ? "true" : "false", \
2672 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2676 * Setup GUC environment to enforce scan methods. If scanhint is NULL, reset
2677 * GUCs to the saved state in state.
2680 setup_scan_method_enforcement(ScanMethodHint *scanhint, HintState *state)
2682 unsigned char enforce_mask = state->init_scan_mask;
2683 GucContext context = state->context;
2688 enforce_mask = scanhint->enforce_mask;
2689 scanhint->base.state = HINT_STATE_USED;
2692 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2693 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2694 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2696 mask = enforce_mask;
2698 mask = enforce_mask & current_hint_state->init_scan_mask;
2700 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2701 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2702 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2703 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2704 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2708 set_join_config_options(unsigned char enforce_mask, GucContext context)
2712 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2713 enforce_mask == ENABLE_HASHJOIN)
2714 mask = enforce_mask;
2716 mask = enforce_mask & current_hint_state->init_join_mask;
2718 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2719 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2720 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2724 * Push a hint into hint stack which is implemented with List struct. Head of
2725 * list is top of stack.
2728 push_hint(HintState *hstate)
2730 /* Prepend new hint to the list means pushing to stack. */
2731 HintStateStack = lcons(hstate, HintStateStack);
2733 /* Pushed hint is the one which should be used hereafter. */
2734 current_hint_state = hstate;
2737 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2741 /* Hint stack must not be empty. */
2742 if(HintStateStack == NIL)
2743 elog(ERROR, "hint stack is empty");
2746 * Take a hint at the head from the list, and free it. Switch
2747 * current_hint_state to point new head (NULL if the list is empty).
2749 HintStateStack = list_delete_first(HintStateStack);
2750 HintStateDelete(current_hint_state);
2751 if(HintStateStack == NIL)
2752 current_hint_state = NULL;
2754 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
2758 * Retrieve and store a hint string from given query or from the hint table.
2759 * If we are using the hint table, the query string is needed to be normalized.
2760 * However, ParseState, which is not available in planner_hook, is required to
2761 * check if the query tree (Query) is surely corresponding to the target query.
2764 pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query)
2766 const char *query_str;
2767 MemoryContext oldcontext;
2769 if (prev_post_parse_analyze_hook)
2770 prev_post_parse_analyze_hook(pstate, query);
2772 /* do nothing under hint table search */
2773 if (hint_inhibit_level > 0)
2776 if (!pg_hint_plan_enable_hint)
2778 if (current_hint_str)
2780 pfree((void *)current_hint_str);
2781 current_hint_str = NULL;
2786 /* increment the query number */
2788 if (debug_level > 1)
2789 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2792 /* search the hint table for a hint if requested */
2793 if (pg_hint_plan_enable_hint_table)
2796 pgssJumbleState jstate;
2798 char *normalized_query = NULL;
2800 query_str = get_query_string(pstate, query, &jumblequery);
2802 /* If this query is not for hint, just return */
2806 /* clear the previous hint string */
2807 if (current_hint_str)
2809 pfree((void *)current_hint_str);
2810 current_hint_str = NULL;
2816 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2817 * careful to PostgreSQL's version up.
2819 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2820 jstate.jumble_len = 0;
2821 jstate.clocations_buf_size = 32;
2822 jstate.clocations = (pgssLocationLen *)
2823 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2824 jstate.clocations_count = 0;
2826 JumbleQuery(&jstate, jumblequery);
2829 * Normalize the query string by replacing constants with '?'
2832 * Search hint string which is stored keyed by query string
2833 * and application name. The query string is normalized to allow
2836 * Adding 1 byte to query_len ensures that the returned string has
2837 * a terminating NULL.
2839 query_len = strlen(query_str) + 1;
2841 generate_normalized_query(&jstate, query_str,
2842 query->stmt_location,
2844 GetDatabaseEncoding());
2847 * find a hint for the normalized query. the result should be in
2850 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2852 get_hints_from_table(normalized_query, application_name);
2853 MemoryContextSwitchTo(oldcontext);
2855 if (debug_level > 1)
2857 if (current_hint_str)
2858 ereport(pg_hint_plan_debug_message_level,
2859 (errmsg("pg_hint_plan[qno=0x%x]: "
2860 "post_parse_analyze_hook: "
2861 "hints from table: \"%s\": "
2862 "normalized_query=\"%s\", "
2863 "application name =\"%s\"",
2864 qno, current_hint_str,
2865 normalized_query, application_name),
2866 errhidestmt(msgqno != qno),
2867 errhidecontext(msgqno != qno)));
2869 ereport(pg_hint_plan_debug_message_level,
2870 (errmsg("pg_hint_plan[qno=0x%x]: "
2871 "no match found in table: "
2872 "application name = \"%s\", "
2873 "normalized_query=\"%s\"",
2874 qno, application_name,
2876 errhidestmt(msgqno != qno),
2877 errhidecontext(msgqno != qno)));
2883 /* retrun if we have hint here */
2884 if (current_hint_str)
2888 query_str = get_query_string(pstate, query, NULL);
2893 * get hints from the comment. However we may have the same query
2894 * string with the previous call, but just retrieving hints is expected
2895 * to be faster than checking for identicalness before retrieval.
2897 if (current_hint_str)
2898 pfree((void *)current_hint_str);
2900 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2901 current_hint_str = get_hints_from_comment(query_str);
2902 MemoryContextSwitchTo(oldcontext);
2905 if (debug_level > 1)
2907 if (debug_level == 1 &&
2908 (stmt_name || strcmp(query_str, debug_query_string)))
2909 ereport(pg_hint_plan_debug_message_level,
2910 (errmsg("hints in comment=\"%s\"",
2911 current_hint_str ? current_hint_str : "(none)"),
2912 errhidestmt(msgqno != qno),
2913 errhidecontext(msgqno != qno)));
2915 ereport(pg_hint_plan_debug_message_level,
2916 (errmsg("hints in comment=\"%s\", stmt=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2917 current_hint_str ? current_hint_str : "(none)",
2918 stmt_name, query_str, debug_query_string),
2919 errhidestmt(msgqno != qno),
2920 errhidecontext(msgqno != qno)));
2926 * Read and set up hint information
2928 static PlannedStmt *
2929 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2932 PlannedStmt *result;
2936 * Use standard planner if pg_hint_plan is disabled or current nesting
2937 * depth is nesting depth of SPI calls. Other hook functions try to change
2938 * plan with current_hint_state if any, so set it to NULL.
2940 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2942 if (debug_level > 1)
2943 ereport(pg_hint_plan_debug_message_level,
2944 (errmsg ("pg_hint_plan%s: planner: enable_hint=%d,"
2945 " hint_inhibit_level=%d",
2946 qnostr, pg_hint_plan_enable_hint,
2947 hint_inhibit_level),
2948 errhidestmt(msgqno != qno)));
2951 goto standard_planner_proc;
2955 * Support for nested plpgsql functions. This is quite ugly but this is the
2956 * only point I could find where I can get the query string.
2958 if (plpgsql_recurse_level > 0)
2960 MemoryContext oldcontext;
2962 if (current_hint_str)
2963 pfree((void *)current_hint_str);
2965 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2967 get_hints_from_comment((char *)error_context_stack->arg);
2968 MemoryContextSwitchTo(oldcontext);
2971 if (!current_hint_str)
2972 goto standard_planner_proc;
2974 /* parse the hint into hint state struct */
2975 hstate = create_hintstate(parse, pstrdup(current_hint_str));
2977 /* run standard planner if the statement has not valid hint */
2979 goto standard_planner_proc;
2982 * Push new hint struct to the hint stack to disable previous hint context.
2986 /* Set scan enforcement here. */
2987 save_nestlevel = NewGUCNestLevel();
2989 /* Apply Set hints, then save it as the initial state */
2990 setup_guc_enforcement(current_hint_state->set_hints,
2991 current_hint_state->num_hints[HINT_TYPE_SET],
2992 current_hint_state->context);
2994 current_hint_state->init_scan_mask = get_current_scan_mask();
2995 current_hint_state->init_join_mask = get_current_join_mask();
2996 current_hint_state->init_min_para_tablescan_size =
2997 min_parallel_table_scan_size;
2998 current_hint_state->init_min_para_indexscan_size =
2999 min_parallel_index_scan_size;
3000 current_hint_state->init_paratup_cost = parallel_tuple_cost;
3001 current_hint_state->init_parasetup_cost = parallel_setup_cost;
3004 * max_parallel_workers_per_gather should be non-zero here if Workers hint
3007 if (max_hint_nworkers > 0 && max_parallel_workers_per_gather < 1)
3008 set_config_int32_option("max_parallel_workers_per_gather",
3009 1, current_hint_state->context);
3010 current_hint_state->init_nworkers = max_parallel_workers_per_gather;
3012 if (debug_level > 1)
3014 ereport(pg_hint_plan_debug_message_level,
3015 (errhidestmt(msgqno != qno),
3016 errmsg("pg_hint_plan%s: planner", qnostr)));
3021 * Use PG_TRY mechanism to recover GUC parameters and current_hint_state to
3022 * the state when this planner started when error occurred in planner.
3027 result = (*prev_planner) (parse, cursorOptions, boundParams);
3029 result = standard_planner(parse, cursorOptions, boundParams);
3034 * Rollback changes of GUC parameters, and pop current hint context
3035 * from hint stack to rewind the state.
3037 AtEOXact_GUC(true, save_nestlevel);
3043 /* Print hint in debug mode. */
3044 if (debug_level == 1)
3045 HintStateDump(current_hint_state);
3046 else if (debug_level > 1)
3047 HintStateDump2(current_hint_state);
3050 * Rollback changes of GUC parameters, and pop current hint context from
3051 * hint stack to rewind the state.
3053 AtEOXact_GUC(true, save_nestlevel);
3058 standard_planner_proc:
3059 if (debug_level > 1)
3061 ereport(pg_hint_plan_debug_message_level,
3062 (errhidestmt(msgqno != qno),
3063 errmsg("pg_hint_plan%s: planner: no valid hint",
3067 current_hint_state = NULL;
3069 return (*prev_planner) (parse, cursorOptions, boundParams);
3071 return standard_planner(parse, cursorOptions, boundParams);
3075 * Find scan method hint to be applied to the given relation
3078 static ScanMethodHint *
3079 find_scan_hint(PlannerInfo *root, Index relid)
3083 ScanMethodHint *real_name_hint = NULL;
3084 ScanMethodHint *alias_hint = NULL;
3087 /* This should not be a join rel */
3089 rel = root->simple_rel_array[relid];
3092 * This function is called for any RelOptInfo or its inheritance parent if
3093 * any. If we are called from inheritance planner, the RelOptInfo for the
3094 * parent of target child relation is not set in the planner info.
3096 * Otherwise we should check that the reloptinfo is base relation or
3097 * inheritance children.
3100 rel->reloptkind != RELOPT_BASEREL &&
3101 rel->reloptkind != RELOPT_OTHER_MEMBER_REL)
3105 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3107 rte = root->simple_rte_array[relid];
3110 /* We don't hint on other than relation and foreign tables */
3111 if (rte->rtekind != RTE_RELATION ||
3112 rte->relkind == RELKIND_FOREIGN_TABLE)
3115 /* Find scan method hint, which matches given names, from the list. */
3116 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
3118 ScanMethodHint *hint = current_hint_state->scan_hints[i];
3120 /* We ignore disabled hints. */
3121 if (!hint_state_enabled(hint))
3125 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3128 /* check the real name for appendrel children */
3129 if (!real_name_hint &&
3130 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3132 char *realname = get_rel_name(rte->relid);
3134 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3135 real_name_hint = hint;
3138 /* No more match expected, break */
3139 if(alias_hint && real_name_hint)
3143 /* real name match precedes alias match */
3145 return real_name_hint;
3150 static ParallelHint *
3151 find_parallel_hint(PlannerInfo *root, Index relid)
3155 ParallelHint *real_name_hint = NULL;
3156 ParallelHint *alias_hint = NULL;
3159 /* This should not be a join rel */
3161 rel = root->simple_rel_array[relid];
3164 * Parallel planning is appliable only on base relation, which has
3171 * We have set root->glob->parallelModeOK if needed. What we should do here
3172 * is just following the decision of planner.
3174 if (!rel->consider_parallel)
3178 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3180 rte = root->simple_rte_array[relid];
3183 /* Find parallel method hint, which matches given names, from the list. */
3184 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_PARALLEL]; i++)
3186 ParallelHint *hint = current_hint_state->parallel_hints[i];
3188 /* We ignore disabled hints. */
3189 if (!hint_state_enabled(hint))
3193 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3196 /* check the real name for appendrel children */
3197 if (!real_name_hint &&
3198 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3200 char *realname = get_rel_name(rte->relid);
3202 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3203 real_name_hint = hint;
3206 /* No more match expected, break */
3207 if(alias_hint && real_name_hint)
3211 /* real name match precedes alias match */
3213 return real_name_hint;
3221 * Returns TRUE on match, FALSE on no match.
3223 * s1 --- the data to match against
3224 * s2 --- the pattern
3226 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
3229 regexpeq(const char *s1, const char *s2)
3235 strcpy(name.data, s1);
3236 regexp = cstring_to_text(s2);
3238 result = DirectFunctionCall2Coll(nameregexeq,
3239 DEFAULT_COLLATION_OID,
3240 NameGetDatum(&name),
3241 PointerGetDatum(regexp));
3242 return DatumGetBool(result);
3246 /* Remove indexes instructed not to use by hint. */
3248 restrict_indexes(PlannerInfo *root, ScanMethodHint *hint, RelOptInfo *rel,
3249 bool using_parent_hint)
3255 RangeTblEntry *rte = root->simple_rte_array[rel->relid];
3256 Oid relationObjectId = rte->relid;
3259 * We delete all the IndexOptInfo list and prevent you from being usable by
3262 if (hint->enforce_mask == ENABLE_SEQSCAN ||
3263 hint->enforce_mask == ENABLE_TIDSCAN)
3265 list_free_deep(rel->indexlist);
3266 rel->indexlist = NIL;
3267 hint->base.state = HINT_STATE_USED;
3273 * When a list of indexes is not specified, we just use all indexes.
3275 if (hint->indexnames == NIL)
3279 * Leaving only an specified index, we delete it from a IndexOptInfo list
3283 if (debug_level > 0)
3284 initStringInfo(&buf);
3286 for (cell = list_head(rel->indexlist); cell; cell = next)
3288 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
3289 char *indexname = get_rel_name(info->indexoid);
3291 bool use_index = false;
3295 foreach(l, hint->indexnames)
3297 char *hintname = (char *) lfirst(l);
3301 result = regexpeq(indexname, hintname);
3303 result = RelnameCmp(&indexname, &hintname) == 0;
3308 if (debug_level > 0)
3310 appendStringInfoCharMacro(&buf, ' ');
3311 quote_value(&buf, indexname);
3319 * Apply index restriction of parent hint to children. Since index
3320 * inheritance is not explicitly described we should search for an
3321 * children's index with the same definition to that of the parent.
3323 if (using_parent_hint && !use_index)
3325 foreach(l, current_hint_state->parent_index_infos)
3329 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
3332 * we check the 'same' index by comparing uniqueness, access
3333 * method and index key columns.
3335 if (p_info->indisunique != info->unique ||
3336 p_info->method != info->relam ||
3337 list_length(p_info->column_names) != info->ncolumns)
3340 /* Check if index key columns match */
3341 for (i = 0; i < info->ncolumns; i++)
3343 char *c_attname = NULL;
3344 char *p_attname = NULL;
3346 p_attname = list_nth(p_info->column_names, i);
3349 * if both of the key of the same position are expressions,
3350 * ignore them for now and check later.
3352 if (info->indexkeys[i] == 0 && !p_attname)
3355 /* deny if one is expression while another is not */
3356 if (info->indexkeys[i] == 0 || !p_attname)
3359 c_attname = get_attname(relationObjectId,
3360 info->indexkeys[i], false);
3362 /* deny if any of column attributes don't match */
3363 if (strcmp(p_attname, c_attname) != 0 ||
3364 p_info->indcollation[i] != info->indexcollations[i] ||
3365 p_info->opclass[i] != info->opcintype[i]||
3366 ((p_info->indoption[i] & INDOPTION_DESC) != 0)
3367 != info->reverse_sort[i] ||
3368 ((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0)
3369 != info->nulls_first[i])
3373 /* deny this if any difference found */
3374 if (i != info->ncolumns)
3377 /* check on key expressions */
3378 if ((p_info->expression_str && (info->indexprs != NIL)) ||
3379 (p_info->indpred_str && (info->indpred != NIL)))
3381 /* fetch the index of this child */
3382 ht_idx = SearchSysCache1(INDEXRELID,
3383 ObjectIdGetDatum(info->indexoid));
3385 /* check expressions if both expressions are available */
3386 if (p_info->expression_str &&
3387 !heap_attisnull(ht_idx, Anum_pg_index_indexprs, NULL))
3394 * to change the expression's parameter of child's
3397 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3398 Anum_pg_index_indexprs,
3401 result = DirectFunctionCall2(pg_get_expr,
3406 /* deny if expressions don't match */
3407 if (strcmp(p_info->expression_str,
3408 text_to_cstring(DatumGetTextP(result))) != 0)
3411 ReleaseSysCache(ht_idx);
3416 /* compare index predicates */
3417 if (p_info->indpred_str &&
3418 !heap_attisnull(ht_idx, Anum_pg_index_indpred, NULL))
3424 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3425 Anum_pg_index_indpred,
3428 result = DirectFunctionCall2(pg_get_expr,
3433 if (strcmp(p_info->indpred_str,
3434 text_to_cstring(DatumGetTextP(result))) != 0)
3437 ReleaseSysCache(ht_idx);
3443 ReleaseSysCache(ht_idx);
3445 else if (p_info->expression_str || (info->indexprs != NIL))
3447 else if (p_info->indpred_str || (info->indpred != NIL))
3452 /* to log the candidate of index */
3453 if (debug_level > 0)
3455 appendStringInfoCharMacro(&buf, ' ');
3456 quote_value(&buf, indexname);
3464 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
3471 if (debug_level == 1)
3473 StringInfoData rel_buf;
3474 char *disprelname = "";
3477 * If this hint targetted the parent, use the real name of this
3478 * child. Otherwise use hint specification.
3480 if (using_parent_hint)
3481 disprelname = get_rel_name(rte->relid);
3483 disprelname = hint->relname;
3486 initStringInfo(&rel_buf);
3487 quote_value(&rel_buf, disprelname);
3489 ereport(pg_hint_plan_debug_message_level,
3490 (errmsg("available indexes for %s(%s):%s",
3495 pfree(rel_buf.data);
3500 * Return information of index definition.
3502 static ParentIndexInfo *
3503 get_parent_index_info(Oid indexoid, Oid relid)
3505 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3506 Relation indexRelation;
3507 Form_pg_index index;
3511 indexRelation = index_open(indexoid, RowExclusiveLock);
3513 index = indexRelation->rd_index;
3515 p_info->indisunique = index->indisunique;
3516 p_info->method = indexRelation->rd_rel->relam;
3518 p_info->column_names = NIL;
3519 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3520 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3521 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3524 * Collect relation attribute names of index columns for index
3525 * identification, not index attribute names. NULL means expression index
3528 for (i = 0; i < index->indnatts; i++)
3530 attname = get_attname(relid, index->indkey.values[i], true);
3531 p_info->column_names = lappend(p_info->column_names, attname);
3533 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3534 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3535 p_info->indoption[i] = indexRelation->rd_indoption[i];
3539 * to check to match the expression's parameter of index with child indexes
3541 p_info->expression_str = NULL;
3542 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs,
3549 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3550 Anum_pg_index_indexprs, &isnull);
3552 result = DirectFunctionCall2(pg_get_expr,
3554 ObjectIdGetDatum(relid));
3556 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3560 * to check to match the predicate's parameter of index with child indexes
3562 p_info->indpred_str = NULL;
3563 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred,
3570 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3571 Anum_pg_index_indpred, &isnull);
3573 result = DirectFunctionCall2(pg_get_expr,
3575 ObjectIdGetDatum(relid));
3577 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3580 index_close(indexRelation, NoLock);
3586 * cancel hint enforcement
3589 reset_hint_enforcement()
3591 setup_scan_method_enforcement(NULL, current_hint_state);
3592 setup_parallel_plan_enforcement(NULL, current_hint_state);
3596 * Set planner guc parameters according to corresponding scan hints. Returns
3597 * bitmap of HintTypeBitmap. If shint or phint is not NULL, set used hint
3598 * there respectively.
3601 setup_hint_enforcement(PlannerInfo *root, RelOptInfo *rel,
3602 ScanMethodHint **rshint, ParallelHint **rphint)
3604 Index new_parent_relid = 0;
3606 ScanMethodHint *shint = NULL;
3607 ParallelHint *phint = NULL;
3608 bool inhparent = root->simple_rte_array[rel->relid]->inh;
3609 Oid relationObjectId = root->simple_rte_array[rel->relid]->relid;
3612 /* reset returns if requested */
3613 if (rshint != NULL) *rshint = NULL;
3614 if (rphint != NULL) *rphint = NULL;
3617 * We could register the parent relation of the following children here
3618 * when inhparent == true but inheritnce planner doesn't call this function
3619 * for parents. Since we cannot distinguish who called this function we
3620 * cannot do other than always seeking the parent regardless of who called
3625 /* set up only parallel hints for parent relation */
3626 phint = find_parallel_hint(root, rel->relid);
3629 setup_parallel_plan_enforcement(phint, current_hint_state);
3630 if (rphint) *rphint = phint;
3631 ret |= HINT_BM_PARALLEL;
3635 if (debug_level > 1)
3636 ereport(pg_hint_plan_debug_message_level,
3638 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3639 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3640 " current_hint_state=%p, hint_inhibit_level=%d",
3641 qnostr, relationObjectId,
3642 get_rel_name(relationObjectId),
3643 inhparent, current_hint_state, hint_inhibit_level)));
3647 /* Forget about the parent of another subquery */
3648 if (root != current_hint_state->current_root)
3649 current_hint_state->parent_relid = 0;
3651 /* Find the parent for this relation other than the registered parent */
3652 foreach (l, root->append_rel_list)
3654 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3656 if (appinfo->child_relid == rel->relid)
3658 if (current_hint_state->parent_relid != appinfo->parent_relid)
3660 new_parent_relid = appinfo->parent_relid;
3661 current_hint_state->current_root = root;
3669 /* This relation doesn't have a parent. Cancel current_hint_state. */
3670 current_hint_state->parent_relid = 0;
3671 current_hint_state->parent_scan_hint = NULL;
3672 current_hint_state->parent_parallel_hint = NULL;
3675 if (new_parent_relid > 0)
3678 * Here we found a new parent for the current relation. Scan continues
3679 * hint to other childrens of this parent so remember it to avoid
3680 * redundant setup cost.
3682 current_hint_state->parent_relid = new_parent_relid;
3684 /* Find hints for the parent */
3685 current_hint_state->parent_scan_hint =
3686 find_scan_hint(root, current_hint_state->parent_relid);
3688 current_hint_state->parent_parallel_hint =
3689 find_parallel_hint(root, current_hint_state->parent_relid);
3692 * If hint is found for the parent, apply it for this child instead
3695 if (current_hint_state->parent_scan_hint)
3697 ScanMethodHint * pshint = current_hint_state->parent_scan_hint;
3699 pshint->base.state = HINT_STATE_USED;
3701 /* Apply index mask in the same manner to the parent. */
3702 if (pshint->indexnames)
3705 Relation parent_rel;
3708 root->simple_rte_array[current_hint_state->parent_relid]->relid;
3709 parent_rel = heap_open(parentrel_oid, NoLock);
3711 /* Search the parent relation for indexes match the hint spec */
3712 foreach(l, RelationGetIndexList(parent_rel))
3714 Oid indexoid = lfirst_oid(l);
3715 char *indexname = get_rel_name(indexoid);
3717 ParentIndexInfo *parent_index_info;
3719 foreach(lc, pshint->indexnames)
3721 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3728 get_parent_index_info(indexoid, parentrel_oid);
3729 current_hint_state->parent_index_infos =
3730 lappend(current_hint_state->parent_index_infos,
3733 heap_close(parent_rel, NoLock);
3738 shint = find_scan_hint(root, rel->relid);
3740 shint = current_hint_state->parent_scan_hint;
3744 bool using_parent_hint =
3745 (shint == current_hint_state->parent_scan_hint);
3747 ret |= HINT_BM_SCAN_METHOD;
3749 /* Setup scan enforcement environment */
3750 setup_scan_method_enforcement(shint, current_hint_state);
3752 /* restrict unwanted inexes */
3753 restrict_indexes(root, shint, rel, using_parent_hint);
3755 if (debug_level > 1)
3757 char *additional_message = "";
3759 if (shint == current_hint_state->parent_scan_hint)
3760 additional_message = " by parent hint";
3762 ereport(pg_hint_plan_debug_message_level,
3764 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3765 " index deletion%s:"
3766 " relation=%u(%s), inhparent=%d, "
3767 "current_hint_state=%p,"
3768 " hint_inhibit_level=%d, scanmask=0x%x",
3769 qnostr, additional_message,
3771 get_rel_name(relationObjectId),
3772 inhparent, current_hint_state,
3774 shint->enforce_mask)));
3778 /* Do the same for parallel plan enforcement */
3779 phint = find_parallel_hint(root, rel->relid);
3781 phint = current_hint_state->parent_parallel_hint;
3783 setup_parallel_plan_enforcement(phint, current_hint_state);
3786 ret |= HINT_BM_PARALLEL;
3788 /* Nothing to apply. Reset the scan mask to intial state */
3789 if (!shint && ! phint)
3791 if (debug_level > 1)
3792 ereport(pg_hint_plan_debug_message_level,
3793 (errhidestmt (true),
3794 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3796 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3797 " hint_inhibit_level=%d, scanmask=0x%x",
3798 qnostr, relationObjectId,
3799 get_rel_name(relationObjectId),
3800 inhparent, current_hint_state, hint_inhibit_level,
3801 current_hint_state->init_scan_mask)));
3803 setup_scan_method_enforcement(NULL, current_hint_state);
3808 if (rshint != NULL) *rshint = shint;
3809 if (rphint != NULL) *rphint = phint;
3815 * Return index of relation which matches given aliasname, or 0 if not found.
3816 * If same aliasname was used multiple times in a query, return -1.
3819 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3825 for (i = 1; i < root->simple_rel_array_size; i++)
3829 if (root->simple_rel_array[i] == NULL)
3832 Assert(i == root->simple_rel_array[i]->relid);
3834 if (RelnameCmp(&aliasname,
3835 &root->simple_rte_array[i]->eref->aliasname) != 0)
3838 foreach(l, initial_rels)
3840 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3842 if (rel->reloptkind == RELOPT_BASEREL)
3844 if (rel->relid != i)
3849 Assert(rel->reloptkind == RELOPT_JOINREL);
3851 if (!bms_is_member(i, rel->relids))
3858 ("Relation name \"%s\" is ambiguous.",
3873 * Return join hint which matches given joinrelids.
3875 static JoinMethodHint *
3876 find_join_hint(Relids joinrelids)
3881 join_hint = current_hint_state->join_hint_level[bms_num_members(joinrelids)];
3883 foreach(l, join_hint)
3885 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3887 if (bms_equal(joinrelids, hint->joinrelids))
3895 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3896 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3898 OuterInnerRels *outer_rels;
3899 OuterInnerRels *inner_rels;
3900 Relids outer_relids;
3901 Relids inner_relids;
3903 JoinMethodHint *hint;
3905 if (outer_inner->relation != NULL)
3907 return bms_make_singleton(
3908 find_relid_aliasname(root, outer_inner->relation,
3910 leading_hint->base.hint_str));
3913 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3914 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3916 outer_relids = OuterInnerJoinCreate(outer_rels,
3922 inner_relids = OuterInnerJoinCreate(inner_rels,
3929 join_relids = bms_add_members(outer_relids, inner_relids);
3931 if (bms_num_members(join_relids) > nbaserel)
3935 * If we don't have join method hint, create new one for the
3936 * join combination with all join methods are enabled.
3938 hint = find_join_hint(join_relids);
3942 * Here relnames is not set, since Relids bitmap is sufficient to
3943 * control paths of this query afterward.
3945 hint = (JoinMethodHint *) JoinMethodHintCreate(
3946 leading_hint->base.hint_str,
3948 HINT_KEYWORD_LEADING);
3949 hint->base.state = HINT_STATE_USED;
3950 hint->nrels = bms_num_members(join_relids);
3951 hint->enforce_mask = ENABLE_ALL_JOIN;
3952 hint->joinrelids = bms_copy(join_relids);
3953 hint->inner_nrels = bms_num_members(inner_relids);
3954 hint->inner_joinrelids = bms_copy(inner_relids);
3956 hstate->join_hint_level[hint->nrels] =
3957 lappend(hstate->join_hint_level[hint->nrels], hint);
3961 hint->inner_nrels = bms_num_members(inner_relids);
3962 hint->inner_joinrelids = bms_copy(inner_relids);
3969 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3970 int nrels, char **relnames)
3973 Relids relids = NULL;
3977 for (j = 0; j < nrels; j++)
3979 relname = relnames[j];
3981 relid = find_relid_aliasname(root, relname, initial_rels,
3985 base->state = HINT_STATE_ERROR;
3988 * the aliasname is not found(relid == 0) or same aliasname was used
3989 * multiple times in a query(relid == -1)
3996 if (bms_is_member(relid, relids))
3998 hint_ereport(base->hint_str,
3999 ("Relation name \"%s\" is duplicated.", relname));
4000 base->state = HINT_STATE_ERROR;
4004 relids = bms_add_member(relids, relid);
4009 * Transform join method hint into handy form.
4011 * - create bitmap of relids from alias names, to make it easier to check
4012 * whether a join path matches a join method hint.
4013 * - add join method hints which are necessary to enforce join order
4014 * specified by Leading hint
4017 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
4018 List *initial_rels, JoinMethodHint **join_method_hints)
4026 LeadingHint *lhint = NULL;
4029 * Create bitmap of relids from alias names for each join method hint.
4030 * Bitmaps are more handy than strings in join searching.
4032 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
4034 JoinMethodHint *hint = hstate->join_hints[i];
4036 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4039 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4040 initial_rels, hint->nrels, hint->relnames);
4042 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
4045 hstate->join_hint_level[hint->nrels] =
4046 lappend(hstate->join_hint_level[hint->nrels], hint);
4050 * Create bitmap of relids from alias names for each rows hint.
4051 * Bitmaps are more handy than strings in join searching.
4053 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
4055 RowsHint *hint = hstate->rows_hints[i];
4057 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4060 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4061 initial_rels, hint->nrels, hint->relnames);
4064 /* Do nothing if no Leading hint was supplied. */
4065 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
4069 * Decide whether to use Leading hint
4071 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
4073 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
4076 if (leading_hint->base.state == HINT_STATE_ERROR)
4082 foreach(l, leading_hint->relations)
4084 relname = (char *)lfirst(l);;
4086 relid = find_relid_aliasname(root, relname, initial_rels,
4087 leading_hint->base.hint_str);
4089 leading_hint->base.state = HINT_STATE_ERROR;
4094 if (bms_is_member(relid, relids))
4096 hint_ereport(leading_hint->base.hint_str,
4097 ("Relation name \"%s\" is duplicated.", relname));
4098 leading_hint->base.state = HINT_STATE_ERROR;
4102 relids = bms_add_member(relids, relid);
4105 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
4110 hint_ereport(lhint->base.hint_str,
4111 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
4112 lhint->base.state = HINT_STATE_DUPLICATION;
4114 leading_hint->base.state = HINT_STATE_USED;
4115 lhint = leading_hint;
4118 /* check to exist Leading hint marked with 'used'. */
4123 * We need join method hints which fit specified join order in every join
4124 * level. For example, Leading(A B C) virtually requires following join
4125 * method hints, if no join method hint supplied:
4127 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
4128 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
4130 * If we already have join method hint which fits specified join order in
4131 * that join level, we leave it as-is and don't add new hints.
4135 if (lhint->outer_inner == NULL)
4137 foreach(l, lhint->relations)
4139 JoinMethodHint *hint;
4141 relname = (char *)lfirst(l);
4144 * Find relid of the relation which has given name. If we have the
4145 * name given in Leading hint multiple times in the join, nothing to
4148 relid = find_relid_aliasname(root, relname, initial_rels,
4151 /* Create bitmap of relids for current join level. */
4152 joinrelids = bms_add_member(joinrelids, relid);
4155 /* We never have join method hint for single relation. */
4160 * If we don't have join method hint, create new one for the
4161 * join combination with all join methods are enabled.
4163 hint = find_join_hint(joinrelids);
4167 * Here relnames is not set, since Relids bitmap is sufficient
4168 * to control paths of this query afterward.
4170 hint = (JoinMethodHint *) JoinMethodHintCreate(
4171 lhint->base.hint_str,
4173 HINT_KEYWORD_LEADING);
4174 hint->base.state = HINT_STATE_USED;
4175 hint->nrels = njoinrels;
4176 hint->enforce_mask = ENABLE_ALL_JOIN;
4177 hint->joinrelids = bms_copy(joinrelids);
4180 join_method_hints[njoinrels] = hint;
4182 if (njoinrels >= nbaserel)
4185 bms_free(joinrelids);
4191 * Delete all join hints which have different combination from Leading
4194 for (i = 2; i <= njoinrels; i++)
4196 list_free(hstate->join_hint_level[i]);
4198 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
4203 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
4210 njoinrels = bms_num_members(joinrelids);
4211 Assert(njoinrels >= 2);
4214 * Delete all join hints which have different combination from Leading
4217 for (i = 2;i <= njoinrels; i++)
4219 if (hstate->join_hint_level[i] != NIL)
4221 ListCell *prev = NULL;
4222 ListCell *next = NULL;
4223 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
4226 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
4230 if (hint->inner_nrels == 0 &&
4231 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
4232 bms_equal(bms_union(hint->joinrelids, joinrelids),
4235 hstate->join_hint_level[i] =
4236 list_delete_cell(hstate->join_hint_level[i], l,
4245 bms_free(joinrelids);
4248 if (hint_state_enabled(lhint))
4250 set_join_config_options(DISABLE_ALL_JOIN, current_hint_state->context);
4257 * wrapper of make_join_rel()
4259 * call make_join_rel() after changing enable_* parameters according to given
4263 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
4266 JoinMethodHint *hint;
4270 joinrelids = bms_union(rel1->relids, rel2->relids);
4271 hint = find_join_hint(joinrelids);
4272 bms_free(joinrelids);
4275 return pg_hint_plan_make_join_rel(root, rel1, rel2);
4277 if (hint->inner_nrels == 0)
4279 save_nestlevel = NewGUCNestLevel();
4281 set_join_config_options(hint->enforce_mask,
4282 current_hint_state->context);
4284 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4285 hint->base.state = HINT_STATE_USED;
4288 * Restore the GUC variables we set above.
4290 AtEOXact_GUC(true, save_nestlevel);
4293 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4302 add_paths_to_joinrel_wrapper(PlannerInfo *root,
4303 RelOptInfo *joinrel,
4304 RelOptInfo *outerrel,
4305 RelOptInfo *innerrel,
4307 SpecialJoinInfo *sjinfo,
4311 JoinMethodHint *join_hint;
4314 joinrelids = bms_union(outerrel->relids, innerrel->relids);
4315 join_hint = find_join_hint(joinrelids);
4316 bms_free(joinrelids);
4318 if (join_hint && join_hint->inner_nrels != 0)
4320 save_nestlevel = NewGUCNestLevel();
4322 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
4325 set_join_config_options(join_hint->enforce_mask,
4326 current_hint_state->context);
4328 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4329 sjinfo, restrictlist);
4330 join_hint->base.state = HINT_STATE_USED;
4334 set_join_config_options(DISABLE_ALL_JOIN,
4335 current_hint_state->context);
4336 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4337 sjinfo, restrictlist);
4341 * Restore the GUC variables we set above.
4343 AtEOXact_GUC(true, save_nestlevel);
4346 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4347 sjinfo, restrictlist);
4351 get_num_baserels(List *initial_rels)
4356 foreach(l, initial_rels)
4358 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
4360 if (rel->reloptkind == RELOPT_BASEREL)
4362 else if (rel->reloptkind ==RELOPT_JOINREL)
4363 nbaserel+= bms_num_members(rel->relids);
4366 /* other values not expected here */
4367 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
4375 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
4378 JoinMethodHint **join_method_hints;
4382 bool leading_hint_enable;
4385 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
4386 * valid hint is supplied or current nesting depth is nesting depth of SPI
4389 if (!current_hint_state || hint_inhibit_level > 0)
4391 if (prev_join_search)
4392 return (*prev_join_search) (root, levels_needed, initial_rels);
4393 else if (enable_geqo && levels_needed >= geqo_threshold)
4394 return geqo(root, levels_needed, initial_rels);
4396 return standard_join_search(root, levels_needed, initial_rels);
4400 * In the case using GEQO, only scan method hints and Set hints have
4401 * effect. Join method and join order is not controllable by hints.
4403 if (enable_geqo && levels_needed >= geqo_threshold)
4404 return geqo(root, levels_needed, initial_rels);
4406 nbaserel = get_num_baserels(initial_rels);
4407 current_hint_state->join_hint_level =
4408 palloc0(sizeof(List *) * (nbaserel + 1));
4409 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4411 leading_hint_enable = transform_join_hints(current_hint_state,
4413 initial_rels, join_method_hints);
4415 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4418 * Adjust number of parallel workers of the result rel to the largest
4419 * number of the component paths.
4421 if (current_hint_state->num_hints[HINT_TYPE_PARALLEL] > 0)
4426 foreach (lc, initial_rels)
4429 RelOptInfo *rel = (RelOptInfo *) lfirst(lc);
4431 foreach (lcp, rel->partial_pathlist)
4433 Path *path = (Path *) lfirst(lcp);
4435 if (nworkers < path-> parallel_workers)
4436 nworkers = path-> parallel_workers;
4440 foreach (lc, rel->partial_pathlist)
4442 Path *path = (Path *) lfirst(lc);
4444 if (path->parallel_safe && path->parallel_workers < nworkers)
4445 path->parallel_workers = nworkers;
4449 for (i = 2; i <= nbaserel; i++)
4451 list_free(current_hint_state->join_hint_level[i]);
4453 /* free Leading hint only */
4454 if (join_method_hints[i] != NULL &&
4455 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4456 JoinMethodHintDelete(join_method_hints[i]);
4458 pfree(current_hint_state->join_hint_level);
4459 pfree(join_method_hints);
4461 if (leading_hint_enable)
4462 set_join_config_options(current_hint_state->init_join_mask,
4463 current_hint_state->context);
4469 * Force number of wokers if instructed by hint
4472 pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
4473 Index rti, RangeTblEntry *rte)
4475 ParallelHint *phint;
4479 /* call the previous hook */
4480 if (prev_set_rel_pathlist)
4481 prev_set_rel_pathlist(root, rel, rti, rte);
4483 /* Nothing to do if no hint available */
4484 if (current_hint_state == NULL)
4487 /* Don't touch dummy rels. */
4488 if (IS_DUMMY_REL(rel))
4492 * We can accept only plain relations, foreign tables and table saples are
4493 * also unacceptable. See set_rel_pathlist.
4495 if ((rel->rtekind != RTE_RELATION &&
4496 rel->rtekind != RTE_SUBQUERY)||
4497 rte->relkind == RELKIND_FOREIGN_TABLE ||
4498 rte->tablesample != NULL)
4502 * Even though UNION ALL node doesn't have particular name so usually it is
4503 * unhintable, turn on parallel when it contains parallel nodes.
4505 if (rel->rtekind == RTE_SUBQUERY)
4508 bool inhibit_nonparallel = false;
4510 if (rel->partial_pathlist == NIL)
4513 foreach(lc, rel->partial_pathlist)
4516 AppendPath *apath = (AppendPath *) lfirst(lc);
4517 int parallel_workers = 0;
4519 if (!IsA(apath, AppendPath))
4522 foreach (lcp, apath->subpaths)
4524 Path *spath = (Path *) lfirst(lcp);
4526 if (spath->parallel_aware &&
4527 parallel_workers < spath->parallel_workers)
4528 parallel_workers = spath->parallel_workers;
4531 apath->path.parallel_workers = parallel_workers;
4532 inhibit_nonparallel = true;
4535 if (inhibit_nonparallel)
4539 foreach(lc, rel->pathlist)
4541 Path *path = (Path *) lfirst(lc);
4543 if (path->startup_cost < disable_cost)
4545 path->startup_cost += disable_cost;
4546 path->total_cost += disable_cost;
4554 /* We cannot handle if this requires an outer */
4555 if (rel->lateral_relids)
4558 /* Return if this relation gets no enfocement */
4559 if ((found_hints = setup_hint_enforcement(root, rel, NULL, &phint)) == 0)
4562 /* Here, we regenerate paths with the current hint restriction */
4563 if (found_hints & HINT_BM_SCAN_METHOD || found_hints & HINT_BM_PARALLEL)
4566 * When hint is specified on non-parent relations, discard existing
4567 * paths and regenerate based on the hint considered. Otherwise we
4568 * already have hinted childx paths then just adjust the number of
4569 * planned number of workers.
4571 if (root->simple_rte_array[rel->relid]->inh)
4573 /* enforce number of workers if requested */
4574 if (phint && phint->force_parallel)
4576 if (phint->nworkers == 0)
4578 list_free_deep(rel->partial_pathlist);
4579 rel->partial_pathlist = NIL;
4583 /* prioritize partial paths */
4584 foreach (l, rel->partial_pathlist)
4586 Path *ppath = (Path *) lfirst(l);
4588 if (ppath->parallel_safe)
4590 ppath->parallel_workers = phint->nworkers;
4591 ppath->startup_cost = 0;
4592 ppath->total_cost = 0;
4596 /* disable non-partial paths */
4597 foreach (l, rel->pathlist)
4599 Path *ppath = (Path *) lfirst(l);
4601 if (ppath->startup_cost < disable_cost)
4603 ppath->startup_cost += disable_cost;
4604 ppath->total_cost += disable_cost;
4612 /* Just discard all the paths considered so far */
4613 list_free_deep(rel->pathlist);
4614 rel->pathlist = NIL;
4615 list_free_deep(rel->partial_pathlist);
4616 rel->partial_pathlist = NIL;
4618 /* Regenerate paths with the current enforcement */
4619 set_plain_rel_pathlist(root, rel, rte);
4621 /* Additional work to enforce parallel query execution */
4622 if (phint && phint->nworkers > 0)
4625 * For Parallel Append to be planned properly, we shouldn't set
4626 * the costs of non-partial paths to disable-value. Lower the
4627 * priority of non-parallel paths by setting partial path costs
4630 foreach (l, rel->partial_pathlist)
4632 Path *path = (Path *) lfirst(l);
4634 path->startup_cost = 0;
4635 path->total_cost = 0;
4638 /* enforce number of workers if requested */
4639 if (phint->force_parallel)
4641 foreach (l, rel->partial_pathlist)
4643 Path *ppath = (Path *) lfirst(l);
4645 if (ppath->parallel_safe)
4646 ppath->parallel_workers = phint->nworkers;
4650 /* Generate gather paths */
4651 if (rel->reloptkind == RELOPT_BASEREL)
4652 generate_gather_paths(root, rel, false);
4657 reset_hint_enforcement();
4662 * Build access paths for a base relation
4664 * This function was copied and edited from set_rel_pathlist() in
4665 * src/backend/optimizer/path/allpaths.c in order not to copy other static
4666 * functions not required here.
4669 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4670 Index rti, RangeTblEntry *rte)
4672 if (IS_DUMMY_REL(rel))
4674 /* We already proved the relation empty, so nothing more to do */
4678 /* It's an "append relation", process accordingly */
4679 set_append_rel_pathlist(root, rel, rti, rte);
4683 if (rel->rtekind == RTE_RELATION)
4685 if (rte->relkind == RELKIND_RELATION)
4687 if(rte->tablesample != NULL)
4688 elog(ERROR, "sampled relation is not supported");
4690 /* Plain relation */
4691 set_plain_rel_pathlist(root, rel, rte);
4694 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4697 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4701 * Allow a plugin to editorialize on the set of Paths for this base
4702 * relation. It could add new paths (such as CustomPaths) by calling
4703 * add_path(), or delete or modify paths added by the core code.
4705 if (set_rel_pathlist_hook)
4706 (*set_rel_pathlist_hook) (root, rel, rti, rte);
4708 /* Now find the cheapest of the paths for this rel */
4713 * stmt_beg callback is called when each query in PL/pgSQL function is about
4714 * to be executed. At that timing, we save query string in the global variable
4715 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4716 * variable for the purpose, because its content is only necessary until
4717 * planner hook is called for the query, so recursive PL/pgSQL function calls
4718 * don't harm this mechanism.
4721 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4723 plpgsql_recurse_level++;
4727 * stmt_end callback is called then each query in PL/pgSQL function has
4728 * finished. At that timing, we clear plpgsql_query_string to tell planner
4729 * hook that next call is not for a query written in PL/pgSQL block.
4732 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4734 plpgsql_recurse_level--;
4737 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4742 if (!isTopLevel || phase != RESOURCE_RELEASE_AFTER_LOCKS)
4744 /* Cancel plpgsql nest level*/
4745 plpgsql_recurse_level = 0;
4748 #define standard_join_search pg_hint_plan_standard_join_search
4749 #define join_search_one_level pg_hint_plan_join_search_one_level
4750 #define make_join_rel make_join_rel_wrapper
4753 #undef make_join_rel
4754 #define make_join_rel pg_hint_plan_make_join_rel
4755 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4756 #include "make_join_rel.c"
4758 #include "pg_stat_statements.c"