1 /*-------------------------------------------------------------------------
4 * hinting on how to execute a query for PostgreSQL
6 * Copyright (c) 2012-2019, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
8 *-------------------------------------------------------------------------
13 #include "catalog/pg_collation.h"
14 #include "catalog/pg_index.h"
15 #include "commands/prepare.h"
16 #include "mb/pg_wchar.h"
17 #include "miscadmin.h"
18 #include "nodes/nodeFuncs.h"
19 #include "nodes/params.h"
20 #include "nodes/relation.h"
21 #include "optimizer/clauses.h"
22 #include "optimizer/cost.h"
23 #include "optimizer/geqo.h"
24 #include "optimizer/joininfo.h"
25 #include "optimizer/pathnode.h"
26 #include "optimizer/paths.h"
27 #include "optimizer/plancat.h"
28 #include "optimizer/planner.h"
29 #include "optimizer/prep.h"
30 #include "optimizer/restrictinfo.h"
31 #include "parser/analyze.h"
32 #include "parser/parsetree.h"
33 #include "parser/scansup.h"
34 #include "tcop/utility.h"
35 #include "utils/builtins.h"
36 #include "utils/lsyscache.h"
37 #include "utils/memutils.h"
38 #include "utils/rel.h"
39 #include "utils/snapmgr.h"
40 #include "utils/syscache.h"
41 #include "utils/resowner.h"
43 #include "catalog/pg_class.h"
45 #include "executor/spi.h"
46 #include "catalog/pg_type.h"
50 /* partially copied from pg_stat_statements */
51 #include "normalize_query.h"
54 #include "access/htup_details.h"
56 #ifdef PG_MODULE_MAGIC
60 #define BLOCK_COMMENT_START "/*"
61 #define BLOCK_COMMENT_END "*/"
62 #define HINT_COMMENT_KEYWORD "+"
63 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
64 #define HINT_END BLOCK_COMMENT_END
67 #define HINT_SEQSCAN "SeqScan"
68 #define HINT_INDEXSCAN "IndexScan"
69 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
70 #define HINT_BITMAPSCAN "BitmapScan"
71 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
72 #define HINT_TIDSCAN "TidScan"
73 #define HINT_NOSEQSCAN "NoSeqScan"
74 #define HINT_NOINDEXSCAN "NoIndexScan"
75 #define HINT_NOBITMAPSCAN "NoBitmapScan"
76 #define HINT_NOTIDSCAN "NoTidScan"
77 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
78 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
79 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
80 #define HINT_PARALLEL "Parallel"
82 #define HINT_NESTLOOP "NestLoop"
83 #define HINT_MERGEJOIN "MergeJoin"
84 #define HINT_HASHJOIN "HashJoin"
85 #define HINT_NONESTLOOP "NoNestLoop"
86 #define HINT_NOMERGEJOIN "NoMergeJoin"
87 #define HINT_NOHASHJOIN "NoHashJoin"
88 #define HINT_LEADING "Leading"
89 #define HINT_SET "Set"
90 #define HINT_ROWS "Rows"
92 #define HINT_ARRAY_DEFAULT_INITSIZE 8
94 #define hint_ereport(str, detail) hint_parse_ereport(str, detail)
95 #define hint_parse_ereport(str, detail) \
97 ereport(pg_hint_plan_parse_message_level, \
98 (errmsg("pg_hint_plan: hint syntax error at or near \"%s\"", (str)), \
102 #define skip_space(str) \
103 while (isspace(*str)) \
108 ENABLE_SEQSCAN = 0x01,
109 ENABLE_INDEXSCAN = 0x02,
110 ENABLE_BITMAPSCAN = 0x04,
111 ENABLE_TIDSCAN = 0x08,
112 ENABLE_INDEXONLYSCAN = 0x10
117 ENABLE_NESTLOOP = 0x01,
118 ENABLE_MERGEJOIN = 0x02,
119 ENABLE_HASHJOIN = 0x04
122 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
123 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
124 ENABLE_INDEXONLYSCAN)
125 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
126 #define DISABLE_ALL_SCAN 0
127 #define DISABLE_ALL_JOIN 0
129 /* hint keyword of enum type*/
130 typedef enum HintKeyword
132 HINT_KEYWORD_SEQSCAN,
133 HINT_KEYWORD_INDEXSCAN,
134 HINT_KEYWORD_INDEXSCANREGEXP,
135 HINT_KEYWORD_BITMAPSCAN,
136 HINT_KEYWORD_BITMAPSCANREGEXP,
137 HINT_KEYWORD_TIDSCAN,
138 HINT_KEYWORD_NOSEQSCAN,
139 HINT_KEYWORD_NOINDEXSCAN,
140 HINT_KEYWORD_NOBITMAPSCAN,
141 HINT_KEYWORD_NOTIDSCAN,
142 HINT_KEYWORD_INDEXONLYSCAN,
143 HINT_KEYWORD_INDEXONLYSCANREGEXP,
144 HINT_KEYWORD_NOINDEXONLYSCAN,
146 HINT_KEYWORD_NESTLOOP,
147 HINT_KEYWORD_MERGEJOIN,
148 HINT_KEYWORD_HASHJOIN,
149 HINT_KEYWORD_NONESTLOOP,
150 HINT_KEYWORD_NOMERGEJOIN,
151 HINT_KEYWORD_NOHASHJOIN,
153 HINT_KEYWORD_LEADING,
156 HINT_KEYWORD_PARALLEL,
158 HINT_KEYWORD_UNRECOGNIZED
161 #define SCAN_HINT_ACCEPTS_INDEX_NAMES(kw) \
162 (kw == HINT_KEYWORD_INDEXSCAN || \
163 kw == HINT_KEYWORD_INDEXSCANREGEXP || \
164 kw == HINT_KEYWORD_INDEXONLYSCAN || \
165 kw == HINT_KEYWORD_INDEXONLYSCANREGEXP || \
166 kw == HINT_KEYWORD_BITMAPSCAN || \
167 kw == HINT_KEYWORD_BITMAPSCANREGEXP)
170 typedef struct Hint Hint;
171 typedef struct HintState HintState;
173 typedef Hint *(*HintCreateFunction) (const char *hint_str,
175 HintKeyword hint_keyword);
176 typedef void (*HintDeleteFunction) (Hint *hint);
177 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf, bool nolf);
178 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
179 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
180 Query *parse, const char *str);
183 #define NUM_HINT_TYPE 6
184 typedef enum HintType
186 HINT_TYPE_SCAN_METHOD,
187 HINT_TYPE_JOIN_METHOD,
194 typedef enum HintTypeBitmap
196 HINT_BM_SCAN_METHOD = 1,
200 static const char *HintTypeName[] = {
210 typedef enum HintStatus
212 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
213 HINT_STATE_USED, /* hint is used */
214 HINT_STATE_DUPLICATION, /* specified hint duplication */
215 HINT_STATE_ERROR /* execute error (parse error does not include
219 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
220 (hint)->base.state == HINT_STATE_USED)
222 static unsigned int qno = 0;
223 static unsigned int msgqno = 0;
224 static char qnostr[32];
225 static const char *current_hint_str = NULL;
228 * However we usually take a hint stirng in post_parse_analyze_hook, we still
229 * need to do so in planner_hook when client starts query execution from the
230 * bind message on a prepared query. This variable prevent duplicate and
231 * sometimes harmful hint string retrieval.
233 static bool current_hint_retrieved = false;
235 /* common data for all hints. */
238 const char *hint_str; /* must not do pfree */
239 const char *keyword; /* must not do pfree */
240 HintKeyword hint_keyword;
243 HintDeleteFunction delete_func;
244 HintDescFunction desc_func;
245 HintCmpFunction cmp_func;
246 HintParseFunction parse_func;
249 /* scan method hints */
250 typedef struct ScanMethodHint
256 unsigned char enforce_mask;
259 typedef struct ParentIndexInfo
264 char *expression_str;
271 /* join method hints */
272 typedef struct JoinMethodHint
278 unsigned char enforce_mask;
280 Relids inner_joinrelids;
283 /* join order hints */
284 typedef struct OuterInnerRels
287 List *outer_inner_pair;
290 typedef struct LeadingHint
293 List *relations; /* relation names specified in Leading hint */
294 OuterInnerRels *outer_inner;
297 /* change a run-time parameter hints */
298 typedef struct SetHint
301 char *name; /* name of variable */
307 typedef enum RowsValueType {
308 RVT_ABSOLUTE, /* Rows(... #1000) */
309 RVT_ADD, /* Rows(... +1000) */
310 RVT_SUB, /* Rows(... -1000) */
311 RVT_MULTI, /* Rows(... *1.2) */
313 typedef struct RowsHint
320 Relids inner_joinrelids;
322 RowsValueType value_type;
327 typedef struct ParallelHint
331 char *nworkers_str; /* original string of nworkers */
332 int nworkers; /* num of workers specified by Worker */
333 bool force_parallel; /* force parallel scan */
337 * Describes a context of hint processing.
341 char *hint_str; /* original hint string */
344 int nall_hints; /* # of valid all hints */
345 int max_all_hints; /* # of slots for all hints */
346 Hint **all_hints; /* parsed all hints */
348 /* # of each hints */
349 int num_hints[NUM_HINT_TYPE];
351 /* for scan method hints */
352 ScanMethodHint **scan_hints; /* parsed scan hints */
354 /* Initial values of parameters */
355 int init_scan_mask; /* enable_* mask */
356 int init_nworkers; /* max_parallel_workers_per_gather */
357 /* min_parallel_table_scan_size*/
358 int init_min_para_tablescan_size;
359 /* min_parallel_index_scan_size*/
360 int init_min_para_indexscan_size;
361 int init_paratup_cost; /* parallel_tuple_cost */
362 int init_parasetup_cost;/* parallel_setup_cost */
364 PlannerInfo *current_root; /* PlannerInfo for the followings */
365 Index parent_relid; /* inherit parent of table relid */
366 ScanMethodHint *parent_scan_hint; /* scan hint for the parent */
367 ParallelHint *parent_parallel_hint; /* parallel hint for the parent */
368 List *parent_index_infos; /* list of parent table's index */
370 JoinMethodHint **join_hints; /* parsed join hints */
371 int init_join_mask; /* initial value join parameter */
372 List **join_hint_level;
373 LeadingHint **leading_hint; /* parsed Leading hints */
374 SetHint **set_hints; /* parsed Set hints */
375 GucContext context; /* which GUC parameters can we set? */
376 RowsHint **rows_hints; /* parsed Rows hints */
377 ParallelHint **parallel_hints; /* parsed Parallel hints */
381 * Describes a hint parser module which is bound with particular hint keyword.
383 typedef struct HintParser
386 HintCreateFunction create_func;
387 HintKeyword hint_keyword;
390 /* Module callbacks */
394 static void push_hint(HintState *hstate);
395 static void pop_hint(void);
397 static void pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query);
398 static void pg_hint_plan_ProcessUtility(PlannedStmt *pstmt,
399 const char *queryString,
400 ProcessUtilityContext context,
401 ParamListInfo params, QueryEnvironment *queryEnv,
402 DestReceiver *dest, char *completionTag);
403 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
404 ParamListInfo boundParams);
405 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
409 /* Scan method hint callbacks */
410 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
411 HintKeyword hint_keyword);
412 static void ScanMethodHintDelete(ScanMethodHint *hint);
413 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
414 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
415 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
416 Query *parse, const char *str);
418 /* Join method hint callbacks */
419 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
420 HintKeyword hint_keyword);
421 static void JoinMethodHintDelete(JoinMethodHint *hint);
422 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
423 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
424 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
425 Query *parse, const char *str);
427 /* Leading hint callbacks */
428 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
429 HintKeyword hint_keyword);
430 static void LeadingHintDelete(LeadingHint *hint);
431 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
432 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
433 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
434 Query *parse, const char *str);
436 /* Set hint callbacks */
437 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
438 HintKeyword hint_keyword);
439 static void SetHintDelete(SetHint *hint);
440 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
441 static int SetHintCmp(const SetHint *a, const SetHint *b);
442 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
445 /* Rows hint callbacks */
446 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
447 HintKeyword hint_keyword);
448 static void RowsHintDelete(RowsHint *hint);
449 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
450 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
451 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
452 Query *parse, const char *str);
454 /* Parallel hint callbacks */
455 static Hint *ParallelHintCreate(const char *hint_str, const char *keyword,
456 HintKeyword hint_keyword);
457 static void ParallelHintDelete(ParallelHint *hint);
458 static void ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf);
459 static int ParallelHintCmp(const ParallelHint *a, const ParallelHint *b);
460 static const char *ParallelHintParse(ParallelHint *hint, HintState *hstate,
461 Query *parse, const char *str);
463 static void quote_value(StringInfo buf, const char *value);
465 static const char *parse_quoted_value(const char *str, char **word,
468 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
471 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
472 void pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
473 Index rti, RangeTblEntry *rte);
474 static void create_plain_partial_paths(PlannerInfo *root,
476 static void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel,
477 List *live_childrels);
478 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
479 ListCell *other_rels);
480 static void make_rels_by_clauseless_joins(PlannerInfo *root,
482 ListCell *other_rels);
483 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
484 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
486 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
487 Index rti, RangeTblEntry *rte);
488 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
489 List *live_childrels,
490 List *all_child_pathkeys,
491 List *partitioned_rels);
492 static Path *get_cheapest_parameterized_child_path(PlannerInfo *root,
494 Relids required_outer);
495 static List *accumulate_append_subpath(List *subpaths, Path *path);
496 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
499 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
501 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
503 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
507 static int set_config_option_noerror(const char *name, const char *value,
508 GucContext context, GucSource source,
509 GucAction action, bool changeVal, int elevel);
510 static void setup_scan_method_enforcement(ScanMethodHint *scanhint,
512 static int set_config_int32_option(const char *name, int32 value,
516 static bool pg_hint_plan_enable_hint = true;
517 static int debug_level = 0;
518 static int pg_hint_plan_parse_message_level = INFO;
519 static int pg_hint_plan_debug_message_level = LOG;
520 /* Default is off, to keep backward compatibility. */
521 static bool pg_hint_plan_enable_hint_table = false;
523 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
524 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
525 /* (This could not be above 1) */
526 static int max_hint_nworkers = -1; /* Maximum nworkers of Workers hints */
528 static const struct config_enum_entry parse_messages_level_options[] = {
529 {"debug", DEBUG2, true},
530 {"debug5", DEBUG5, false},
531 {"debug4", DEBUG4, false},
532 {"debug3", DEBUG3, false},
533 {"debug2", DEBUG2, false},
534 {"debug1", DEBUG1, false},
536 {"info", INFO, false},
537 {"notice", NOTICE, false},
538 {"warning", WARNING, false},
539 {"error", ERROR, false},
541 * {"fatal", FATAL, true},
542 * {"panic", PANIC, true},
547 static const struct config_enum_entry parse_debug_level_options[] = {
550 {"detailed", 2, false},
551 {"verbose", 3, false},
563 /* Saved hook values in case of unload */
564 static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
565 static planner_hook_type prev_planner = NULL;
566 static join_search_hook_type prev_join_search = NULL;
567 static set_rel_pathlist_hook_type prev_set_rel_pathlist = NULL;
568 static ProcessUtility_hook_type prev_ProcessUtility_hook = NULL;
570 /* Hold reference to currently active hint */
571 static HintState *current_hint_state = NULL;
574 * List of hint contexts. We treat the head of the list as the Top of the
575 * context stack, so current_hint_state always points the first element of this
578 static List *HintStateStack = NIL;
580 static const HintParser parsers[] = {
581 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
582 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
583 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
584 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
585 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
586 HINT_KEYWORD_BITMAPSCANREGEXP},
587 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
588 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
589 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
590 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
591 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
592 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
593 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
594 HINT_KEYWORD_INDEXONLYSCANREGEXP},
595 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
597 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
598 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
599 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
600 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
601 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
602 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
604 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
605 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
606 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
607 {HINT_PARALLEL, ParallelHintCreate, HINT_KEYWORD_PARALLEL},
609 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
612 PLpgSQL_plugin plugin_funcs = {
616 pg_hint_plan_plpgsql_stmt_beg,
617 pg_hint_plan_plpgsql_stmt_end,
623 * Module load callbacks
628 PLpgSQL_plugin **var_ptr;
630 /* Define custom GUC variables. */
631 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
632 "Force planner to use plans specified in the hint comment preceding to the query.",
634 &pg_hint_plan_enable_hint,
642 DefineCustomEnumVariable("pg_hint_plan.debug_print",
643 "Logs results of hint parsing.",
647 parse_debug_level_options,
654 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
655 "Message level of parse errors.",
657 &pg_hint_plan_parse_message_level,
659 parse_messages_level_options,
666 DefineCustomEnumVariable("pg_hint_plan.message_level",
667 "Message level of debug messages.",
669 &pg_hint_plan_debug_message_level,
671 parse_messages_level_options,
678 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
679 "Let pg_hint_plan look up the hint table.",
681 &pg_hint_plan_enable_hint_table,
690 prev_post_parse_analyze_hook = post_parse_analyze_hook;
691 post_parse_analyze_hook = pg_hint_plan_post_parse_analyze;
692 prev_planner = planner_hook;
693 planner_hook = pg_hint_plan_planner;
694 prev_join_search = join_search_hook;
695 join_search_hook = pg_hint_plan_join_search;
696 prev_set_rel_pathlist = set_rel_pathlist_hook;
697 set_rel_pathlist_hook = pg_hint_plan_set_rel_pathlist;
698 prev_ProcessUtility_hook = ProcessUtility_hook;
699 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
701 /* setup PL/pgSQL plugin hook */
702 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
703 *var_ptr = &plugin_funcs;
705 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
709 * Module unload callback
715 PLpgSQL_plugin **var_ptr;
717 /* Uninstall hooks. */
718 post_parse_analyze_hook = prev_post_parse_analyze_hook;
719 planner_hook = prev_planner;
720 join_search_hook = prev_join_search;
721 set_rel_pathlist_hook = prev_set_rel_pathlist;
722 ProcessUtility_hook = prev_ProcessUtility_hook;
724 /* uninstall PL/pgSQL plugin hook */
725 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
730 * create and delete functions the hint object
734 ScanMethodHintCreate(const char *hint_str, const char *keyword,
735 HintKeyword hint_keyword)
737 ScanMethodHint *hint;
739 hint = palloc(sizeof(ScanMethodHint));
740 hint->base.hint_str = hint_str;
741 hint->base.keyword = keyword;
742 hint->base.hint_keyword = hint_keyword;
743 hint->base.type = HINT_TYPE_SCAN_METHOD;
744 hint->base.state = HINT_STATE_NOTUSED;
745 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
746 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
747 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
748 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
749 hint->relname = NULL;
750 hint->indexnames = NIL;
751 hint->regexp = false;
752 hint->enforce_mask = 0;
754 return (Hint *) hint;
758 ScanMethodHintDelete(ScanMethodHint *hint)
764 pfree(hint->relname);
765 list_free_deep(hint->indexnames);
770 JoinMethodHintCreate(const char *hint_str, const char *keyword,
771 HintKeyword hint_keyword)
773 JoinMethodHint *hint;
775 hint = palloc(sizeof(JoinMethodHint));
776 hint->base.hint_str = hint_str;
777 hint->base.keyword = keyword;
778 hint->base.hint_keyword = hint_keyword;
779 hint->base.type = HINT_TYPE_JOIN_METHOD;
780 hint->base.state = HINT_STATE_NOTUSED;
781 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
782 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
783 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
784 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
786 hint->inner_nrels = 0;
787 hint->relnames = NULL;
788 hint->enforce_mask = 0;
789 hint->joinrelids = NULL;
790 hint->inner_joinrelids = NULL;
792 return (Hint *) hint;
796 JoinMethodHintDelete(JoinMethodHint *hint)
805 for (i = 0; i < hint->nrels; i++)
806 pfree(hint->relnames[i]);
807 pfree(hint->relnames);
810 bms_free(hint->joinrelids);
811 bms_free(hint->inner_joinrelids);
816 LeadingHintCreate(const char *hint_str, const char *keyword,
817 HintKeyword hint_keyword)
821 hint = palloc(sizeof(LeadingHint));
822 hint->base.hint_str = hint_str;
823 hint->base.keyword = keyword;
824 hint->base.hint_keyword = hint_keyword;
825 hint->base.type = HINT_TYPE_LEADING;
826 hint->base.state = HINT_STATE_NOTUSED;
827 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
828 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
829 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
830 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
831 hint->relations = NIL;
832 hint->outer_inner = NULL;
834 return (Hint *) hint;
838 LeadingHintDelete(LeadingHint *hint)
843 list_free_deep(hint->relations);
844 if (hint->outer_inner)
845 pfree(hint->outer_inner);
850 SetHintCreate(const char *hint_str, const char *keyword,
851 HintKeyword hint_keyword)
855 hint = palloc(sizeof(SetHint));
856 hint->base.hint_str = hint_str;
857 hint->base.keyword = keyword;
858 hint->base.hint_keyword = hint_keyword;
859 hint->base.type = HINT_TYPE_SET;
860 hint->base.state = HINT_STATE_NOTUSED;
861 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
862 hint->base.desc_func = (HintDescFunction) SetHintDesc;
863 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
864 hint->base.parse_func = (HintParseFunction) SetHintParse;
869 return (Hint *) hint;
873 SetHintDelete(SetHint *hint)
883 list_free(hint->words);
888 RowsHintCreate(const char *hint_str, const char *keyword,
889 HintKeyword hint_keyword)
893 hint = palloc(sizeof(RowsHint));
894 hint->base.hint_str = hint_str;
895 hint->base.keyword = keyword;
896 hint->base.hint_keyword = hint_keyword;
897 hint->base.type = HINT_TYPE_ROWS;
898 hint->base.state = HINT_STATE_NOTUSED;
899 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
900 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
901 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
902 hint->base.parse_func = (HintParseFunction) RowsHintParse;
904 hint->inner_nrels = 0;
905 hint->relnames = NULL;
906 hint->joinrelids = NULL;
907 hint->inner_joinrelids = NULL;
908 hint->rows_str = NULL;
909 hint->value_type = RVT_ABSOLUTE;
912 return (Hint *) hint;
916 RowsHintDelete(RowsHint *hint)
925 for (i = 0; i < hint->nrels; i++)
926 pfree(hint->relnames[i]);
927 pfree(hint->relnames);
930 bms_free(hint->joinrelids);
931 bms_free(hint->inner_joinrelids);
936 ParallelHintCreate(const char *hint_str, const char *keyword,
937 HintKeyword hint_keyword)
941 hint = palloc(sizeof(ScanMethodHint));
942 hint->base.hint_str = hint_str;
943 hint->base.keyword = keyword;
944 hint->base.hint_keyword = hint_keyword;
945 hint->base.type = HINT_TYPE_PARALLEL;
946 hint->base.state = HINT_STATE_NOTUSED;
947 hint->base.delete_func = (HintDeleteFunction) ParallelHintDelete;
948 hint->base.desc_func = (HintDescFunction) ParallelHintDesc;
949 hint->base.cmp_func = (HintCmpFunction) ParallelHintCmp;
950 hint->base.parse_func = (HintParseFunction) ParallelHintParse;
951 hint->relname = NULL;
953 hint->nworkers_str = "0";
955 return (Hint *) hint;
959 ParallelHintDelete(ParallelHint *hint)
965 pfree(hint->relname);
971 HintStateCreate(void)
975 hstate = palloc(sizeof(HintState));
976 hstate->hint_str = NULL;
977 hstate->nall_hints = 0;
978 hstate->max_all_hints = 0;
979 hstate->all_hints = NULL;
980 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
981 hstate->scan_hints = NULL;
982 hstate->init_scan_mask = 0;
983 hstate->init_nworkers = 0;
984 hstate->init_min_para_tablescan_size = 0;
985 hstate->init_min_para_indexscan_size = 0;
986 hstate->init_paratup_cost = 0;
987 hstate->init_parasetup_cost = 0;
988 hstate->current_root = NULL;
989 hstate->parent_relid = 0;
990 hstate->parent_scan_hint = NULL;
991 hstate->parent_parallel_hint = NULL;
992 hstate->parent_index_infos = NIL;
993 hstate->join_hints = NULL;
994 hstate->init_join_mask = 0;
995 hstate->join_hint_level = NULL;
996 hstate->leading_hint = NULL;
997 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
998 hstate->set_hints = NULL;
999 hstate->rows_hints = NULL;
1000 hstate->parallel_hints = NULL;
1006 HintStateDelete(HintState *hstate)
1013 if (hstate->hint_str)
1014 pfree(hstate->hint_str);
1016 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1017 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
1018 if (hstate->all_hints)
1019 pfree(hstate->all_hints);
1020 if (hstate->parent_index_infos)
1021 list_free(hstate->parent_index_infos);
1025 * Copy given value into buf, with quoting with '"' if necessary.
1028 quote_value(StringInfo buf, const char *value)
1030 bool need_quote = false;
1033 for (str = value; *str != '\0'; str++)
1035 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
1038 appendStringInfoCharMacro(buf, '"');
1043 for (str = value; *str != '\0'; str++)
1046 appendStringInfoCharMacro(buf, '"');
1048 appendStringInfoCharMacro(buf, *str);
1052 appendStringInfoCharMacro(buf, '"');
1056 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
1060 appendStringInfo(buf, "%s(", hint->base.keyword);
1061 if (hint->relname != NULL)
1063 quote_value(buf, hint->relname);
1064 foreach(l, hint->indexnames)
1066 appendStringInfoCharMacro(buf, ' ');
1067 quote_value(buf, (char *) lfirst(l));
1070 appendStringInfoString(buf, ")");
1072 appendStringInfoChar(buf, '\n');
1076 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
1080 appendStringInfo(buf, "%s(", hint->base.keyword);
1081 if (hint->relnames != NULL)
1083 quote_value(buf, hint->relnames[0]);
1084 for (i = 1; i < hint->nrels; i++)
1086 appendStringInfoCharMacro(buf, ' ');
1087 quote_value(buf, hint->relnames[i]);
1090 appendStringInfoString(buf, ")");
1092 appendStringInfoChar(buf, '\n');
1096 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
1098 if (outer_inner->relation == NULL)
1105 appendStringInfoCharMacro(buf, '(');
1106 foreach(l, outer_inner->outer_inner_pair)
1111 appendStringInfoCharMacro(buf, ' ');
1113 OuterInnerDesc(lfirst(l), buf);
1116 appendStringInfoCharMacro(buf, ')');
1119 quote_value(buf, outer_inner->relation);
1123 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
1125 appendStringInfo(buf, "%s(", HINT_LEADING);
1126 if (hint->outer_inner == NULL)
1133 foreach(l, hint->relations)
1138 appendStringInfoCharMacro(buf, ' ');
1140 quote_value(buf, (char *) lfirst(l));
1144 OuterInnerDesc(hint->outer_inner, buf);
1146 appendStringInfoString(buf, ")");
1148 appendStringInfoChar(buf, '\n');
1152 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1154 bool is_first = true;
1157 appendStringInfo(buf, "%s(", HINT_SET);
1158 foreach(l, hint->words)
1163 appendStringInfoCharMacro(buf, ' ');
1165 quote_value(buf, (char *) lfirst(l));
1167 appendStringInfo(buf, ")");
1169 appendStringInfoChar(buf, '\n');
1173 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1177 appendStringInfo(buf, "%s(", hint->base.keyword);
1178 if (hint->relnames != NULL)
1180 quote_value(buf, hint->relnames[0]);
1181 for (i = 1; i < hint->nrels; i++)
1183 appendStringInfoCharMacro(buf, ' ');
1184 quote_value(buf, hint->relnames[i]);
1187 appendStringInfo(buf, " %s", hint->rows_str);
1188 appendStringInfoString(buf, ")");
1190 appendStringInfoChar(buf, '\n');
1194 ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf)
1196 appendStringInfo(buf, "%s(", hint->base.keyword);
1197 if (hint->relname != NULL)
1199 quote_value(buf, hint->relname);
1201 /* number of workers */
1202 appendStringInfoCharMacro(buf, ' ');
1203 quote_value(buf, hint->nworkers_str);
1204 /* application mode of num of workers */
1205 appendStringInfoCharMacro(buf, ' ');
1206 appendStringInfoString(buf,
1207 (hint->force_parallel ? "hard" : "soft"));
1209 appendStringInfoString(buf, ")");
1211 appendStringInfoChar(buf, '\n');
1215 * Append string which represents all hints in a given state to buf, with
1216 * preceding title with them.
1219 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1220 HintStatus state, bool nolf)
1224 appendStringInfo(buf, "%s:", title);
1226 appendStringInfoChar(buf, '\n');
1229 for (i = 0; i < hstate->nall_hints; i++)
1231 if (hstate->all_hints[i]->state != state)
1234 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1238 if (nolf && nshown == 0)
1239 appendStringInfoString(buf, "(none)");
1243 * Dump contents of given hstate to server log with log level LOG.
1246 HintStateDump(HintState *hstate)
1252 elog(pg_hint_plan_debug_message_level, "pg_hint_plan:\nno hint");
1256 initStringInfo(&buf);
1258 appendStringInfoString(&buf, "pg_hint_plan:\n");
1259 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1260 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1261 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1262 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1264 ereport(pg_hint_plan_debug_message_level,
1265 (errmsg ("%s", buf.data)));
1271 HintStateDump2(HintState *hstate)
1277 elog(pg_hint_plan_debug_message_level,
1278 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1282 initStringInfo(&buf);
1283 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1284 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1285 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1286 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1287 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1288 appendStringInfoChar(&buf, '}');
1290 ereport(pg_hint_plan_debug_message_level,
1291 (errmsg("%s", buf.data),
1293 errhidecontext(true)));
1303 RelnameCmp(const void *a, const void *b)
1305 const char *relnamea = *((const char **) a);
1306 const char *relnameb = *((const char **) b);
1308 return strcmp(relnamea, relnameb);
1312 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1314 return RelnameCmp(&a->relname, &b->relname);
1318 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1322 if (a->nrels != b->nrels)
1323 return a->nrels - b->nrels;
1325 for (i = 0; i < a->nrels; i++)
1328 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1336 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1342 SetHintCmp(const SetHint *a, const SetHint *b)
1344 return strcmp(a->name, b->name);
1348 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1352 if (a->nrels != b->nrels)
1353 return a->nrels - b->nrels;
1355 for (i = 0; i < a->nrels; i++)
1358 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1366 ParallelHintCmp(const ParallelHint *a, const ParallelHint *b)
1368 return RelnameCmp(&a->relname, &b->relname);
1372 HintCmp(const void *a, const void *b)
1374 const Hint *hinta = *((const Hint **) a);
1375 const Hint *hintb = *((const Hint **) b);
1377 if (hinta->type != hintb->type)
1378 return hinta->type - hintb->type;
1379 if (hinta->state == HINT_STATE_ERROR)
1381 if (hintb->state == HINT_STATE_ERROR)
1383 return hinta->cmp_func(hinta, hintb);
1387 * Returns byte offset of hint b from hint a. If hint a was specified before
1388 * b, positive value is returned.
1391 HintCmpWithPos(const void *a, const void *b)
1393 const Hint *hinta = *((const Hint **) a);
1394 const Hint *hintb = *((const Hint **) b);
1397 result = HintCmp(a, b);
1399 result = hinta->hint_str - hintb->hint_str;
1408 parse_keyword(const char *str, StringInfo buf)
1412 while (!isspace(*str) && *str != '(' && *str != '\0')
1413 appendStringInfoCharMacro(buf, *str++);
1419 skip_parenthesis(const char *str, char parenthesis)
1423 if (*str != parenthesis)
1425 if (parenthesis == '(')
1426 hint_ereport(str, ("Opening parenthesis is necessary."));
1427 else if (parenthesis == ')')
1428 hint_ereport(str, ("Closing parenthesis is necessary."));
1439 * Parse a token from str, and store malloc'd copy into word. A token can be
1440 * quoted with '"'. Return value is pointer to unparsed portion of original
1441 * string, or NULL if an error occurred.
1443 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1446 parse_quoted_value(const char *str, char **word, bool truncate)
1451 /* Skip leading spaces. */
1454 initStringInfo(&buf);
1467 /* Double quotation must be closed. */
1471 hint_ereport(str, ("Unterminated quoted string."));
1476 * Skip escaped double quotation.
1478 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1479 * block comments) to be an object name, so users must specify
1480 * alias for such object names.
1482 * Those special names can be allowed if we care escaped slashes
1483 * and asterisks, but we don't.
1492 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1496 appendStringInfoCharMacro(&buf, *str++);
1501 hint_ereport(str, ("Zero-length delimited string."));
1508 /* Truncate name if it's too long */
1510 truncate_identifier(buf.data, strlen(buf.data), true);
1517 static OuterInnerRels *
1518 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1520 OuterInnerRels *outer_inner;
1522 outer_inner = palloc(sizeof(OuterInnerRels));
1523 outer_inner->relation = name;
1524 outer_inner->outer_inner_pair = outer_inner_list;
1530 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1532 List *outer_inner_pair = NIL;
1534 if ((str = skip_parenthesis(str, '(')) == NULL)
1539 /* Store words in parentheses into outer_inner_list. */
1540 while(*str != ')' && *str != '\0')
1542 OuterInnerRels *outer_inner_rels;
1546 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1554 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1557 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1560 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1565 (str = skip_parenthesis(str, ')')) == NULL)
1567 list_free(outer_inner_pair);
1571 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1577 parse_parentheses_Leading(const char *str, List **name_list,
1578 OuterInnerRels **outer_inner)
1581 bool truncate = true;
1583 if ((str = skip_parenthesis(str, '(')) == NULL)
1589 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1594 /* Store words in parentheses into name_list. */
1595 while(*str != ')' && *str != '\0')
1597 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1599 list_free(*name_list);
1603 *name_list = lappend(*name_list, name);
1608 if ((str = skip_parenthesis(str, ')')) == NULL)
1614 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1617 bool truncate = true;
1619 if ((str = skip_parenthesis(str, '(')) == NULL)
1624 /* Store words in parentheses into name_list. */
1625 while(*str != ')' && *str != '\0')
1627 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1629 list_free(*name_list);
1633 *name_list = lappend(*name_list, name);
1636 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1637 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1638 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1639 keyword == HINT_KEYWORD_SET)
1645 if ((str = skip_parenthesis(str, ')')) == NULL)
1651 parse_hints(HintState *hstate, Query *parse, const char *str)
1656 initStringInfo(&buf);
1657 while (*str != '\0')
1659 const HintParser *parser;
1661 /* in error message, we output the comment including the keyword. */
1662 head = (char *) str;
1664 /* parse only the keyword of the hint. */
1665 resetStringInfo(&buf);
1666 str = parse_keyword(str, &buf);
1668 for (parser = parsers; parser->keyword != NULL; parser++)
1670 char *keyword = parser->keyword;
1673 if (pg_strcasecmp(buf.data, keyword) != 0)
1676 hint = parser->create_func(head, keyword, parser->hint_keyword);
1678 /* parser of each hint does parse in a parenthesis. */
1679 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1681 hint->delete_func(hint);
1687 * Add hint information into all_hints array. If we don't have
1688 * enough space, double the array.
1690 if (hstate->nall_hints == 0)
1692 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1693 hstate->all_hints = (Hint **)
1694 palloc(sizeof(Hint *) * hstate->max_all_hints);
1696 else if (hstate->nall_hints == hstate->max_all_hints)
1698 hstate->max_all_hints *= 2;
1699 hstate->all_hints = (Hint **)
1700 repalloc(hstate->all_hints,
1701 sizeof(Hint *) * hstate->max_all_hints);
1704 hstate->all_hints[hstate->nall_hints] = hint;
1705 hstate->nall_hints++;
1712 if (parser->keyword == NULL)
1715 ("Unrecognized hint keyword \"%s\".", buf.data));
1726 * Get hints from table by client-supplied query string and application name.
1729 get_hints_from_table(const char *client_query, const char *client_application)
1731 const char *search_query =
1733 " FROM hint_plan.hints "
1734 " WHERE norm_query_string = $1 "
1735 " AND ( application_name = $2 "
1736 " OR application_name = '' ) "
1737 " ORDER BY application_name DESC";
1738 static SPIPlanPtr plan = NULL;
1740 Oid argtypes[2] = { TEXTOID, TEXTOID };
1742 bool nulls[2] = { false, false };
1748 bool snapshot_set = false;
1750 hint_inhibit_level++;
1752 if (!ActiveSnapshotSet())
1754 PushActiveSnapshot(GetTransactionSnapshot());
1755 snapshot_set = true;
1763 p = SPI_prepare(search_query, 2, argtypes);
1764 plan = SPI_saveplan(p);
1768 qry = cstring_to_text(client_query);
1769 app = cstring_to_text(client_application);
1770 values[0] = PointerGetDatum(qry);
1771 values[1] = PointerGetDatum(app);
1773 SPI_execute_plan(plan, values, nulls, true, 1);
1775 if (SPI_processed > 0)
1779 hints = SPI_getvalue(SPI_tuptable->vals[0],
1780 SPI_tuptable->tupdesc, 1);
1782 * Here we use SPI_palloc to ensure that hints string is valid even
1783 * after SPI_finish call. We can't use simple palloc because it
1784 * allocates memory in SPI's context and that context is deleted in
1787 buf = SPI_palloc(strlen(hints) + 1);
1795 PopActiveSnapshot();
1797 hint_inhibit_level--;
1801 hint_inhibit_level--;
1810 * Get client-supplied query string. Addtion to that the jumbled query is
1811 * supplied if the caller requested. From the restriction of JumbleQuery, some
1812 * kind of query needs special amendments. Reutrns NULL if this query doesn't
1813 * change the current hint. This function returns NULL also when something
1814 * wrong has happend and let the caller continue using the current hints.
1817 get_query_string(ParseState *pstate, Query *query, Query **jumblequery)
1819 const char *p = debug_query_string;
1822 * If debug_query_string is set, it is the top level statement. But in some
1823 * cases we reach here with debug_query_string set NULL for example in the
1824 * case of DESCRIBE message handling or EXECUTE command. We may still see a
1825 * candidate top-level query in pstate in the case.
1828 p = pstate->p_sourcetext;
1830 /* We don't see a query string, return NULL */
1834 if (jumblequery != NULL)
1835 *jumblequery = query;
1837 if (query->commandType == CMD_UTILITY)
1839 Query *target_query = (Query *)query->utilityStmt;
1842 * Some CMD_UTILITY statements have a subquery that we can hint on.
1843 * Since EXPLAIN can be placed before other kind of utility statements
1844 * and EXECUTE can be contained other kind of utility statements, these
1845 * conditions are not mutually exclusive and should be considered in
1848 if (IsA(target_query, ExplainStmt))
1850 ExplainStmt *stmt = (ExplainStmt *)target_query;
1852 Assert(IsA(stmt->query, Query));
1853 target_query = (Query *)stmt->query;
1855 /* strip out the top-level query for further processing */
1856 if (target_query->commandType == CMD_UTILITY &&
1857 target_query->utilityStmt != NULL)
1858 target_query = (Query *)target_query->utilityStmt;
1861 if (IsA(target_query, DeclareCursorStmt))
1863 DeclareCursorStmt *stmt = (DeclareCursorStmt *)target_query;
1864 Query *query = (Query *)stmt->query;
1866 /* the target must be CMD_SELECT in this case */
1867 Assert(IsA(query, Query) && query->commandType == CMD_SELECT);
1868 target_query = query;
1871 if (IsA(target_query, CreateTableAsStmt))
1873 CreateTableAsStmt *stmt = (CreateTableAsStmt *) target_query;
1875 Assert(IsA(stmt->query, Query));
1876 target_query = (Query *) stmt->query;
1878 /* strip out the top-level query for further processing */
1879 if (target_query->commandType == CMD_UTILITY &&
1880 target_query->utilityStmt != NULL)
1881 target_query = (Query *)target_query->utilityStmt;
1884 if (IsA(target_query, ExecuteStmt))
1887 * Use the prepared query for EXECUTE. The Query for jumble
1888 * also replaced with the corresponding one.
1890 ExecuteStmt *stmt = (ExecuteStmt *)target_query;
1891 PreparedStatement *entry;
1893 entry = FetchPreparedStatement(stmt->name, true);
1894 p = entry->plansource->query_string;
1895 target_query = (Query *) linitial (entry->plansource->query_list);
1898 /* JumbleQuery accespts only a non-utility Query */
1899 if (!IsA(target_query, Query) ||
1900 target_query->utilityStmt != NULL)
1901 target_query = NULL;
1904 *jumblequery = target_query;
1907 * Return NULL if pstate is not of top-level query. We don't need this
1908 * when jumble info is not requested or cannot do this when pstate is NULL.
1910 else if (!jumblequery && pstate && pstate->p_sourcetext != p &&
1911 strcmp(pstate->p_sourcetext, p) != 0)
1918 * Get hints from the head block comment in client-supplied query string.
1921 get_hints_from_comment(const char *p)
1923 const char *hint_head;
1931 /* extract query head comment. */
1932 hint_head = strstr(p, HINT_START);
1933 if (hint_head == NULL)
1935 for (;p < hint_head; p++)
1938 * Allow these characters precedes hint comment:
1940 * - alphabets which are in ASCII range
1941 * - space, tabs and new-lines
1942 * - underscores, for identifier
1943 * - commas, for SELECT clause, EXPLAIN and PREPARE
1944 * - parentheses, for EXPLAIN and PREPARE
1946 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1947 * avoid behavior which depends on locale setting.
1949 if (!(*p >= '0' && *p <= '9') &&
1950 !(*p >= 'A' && *p <= 'Z') &&
1951 !(*p >= 'a' && *p <= 'z') &&
1955 *p != '(' && *p != ')')
1959 len = strlen(HINT_START);
1964 /* find hint end keyword. */
1965 if ((tail = strstr(p, HINT_END)) == NULL)
1967 hint_ereport(head, ("Unterminated block comment."));
1971 /* We don't support nested block comments. */
1972 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1974 hint_ereport(head, ("Nested block comments are not supported."));
1978 /* Make a copy of hint. */
1980 head = palloc(len + 1);
1981 memcpy(head, p, len);
1989 * Parse hints that got, create hint struct from parse tree and parse hints.
1992 create_hintstate(Query *parse, const char *hints)
2001 /* -1 means that no Parallel hint is specified. */
2002 max_hint_nworkers = -1;
2005 hstate = HintStateCreate();
2006 hstate->hint_str = (char *) hints;
2008 /* parse each hint. */
2009 parse_hints(hstate, parse, p);
2011 /* When nothing specified a hint, we free HintState and returns NULL. */
2012 if (hstate->nall_hints == 0)
2014 HintStateDelete(hstate);
2018 /* Sort hints in order of original position. */
2019 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
2022 /* Count number of hints per hint-type. */
2023 for (i = 0; i < hstate->nall_hints; i++)
2025 Hint *cur_hint = hstate->all_hints[i];
2026 hstate->num_hints[cur_hint->type]++;
2030 * If an object (or a set of objects) has multiple hints of same hint-type,
2031 * only the last hint is valid and others are ignored in planning.
2032 * Hints except the last are marked as 'duplicated' to remember the order.
2034 for (i = 0; i < hstate->nall_hints - 1; i++)
2036 Hint *cur_hint = hstate->all_hints[i];
2037 Hint *next_hint = hstate->all_hints[i + 1];
2040 * Leading hint is marked as 'duplicated' in transform_join_hints.
2042 if (cur_hint->type == HINT_TYPE_LEADING &&
2043 next_hint->type == HINT_TYPE_LEADING)
2047 * Note that we need to pass addresses of hint pointers, because
2048 * HintCmp is designed to sort array of Hint* by qsort.
2050 if (HintCmp(&cur_hint, &next_hint) == 0)
2052 hint_ereport(cur_hint->hint_str,
2053 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
2054 cur_hint->state = HINT_STATE_DUPLICATION;
2059 * Make sure that per-type array pointers point proper position in the
2060 * array which consists of all hints.
2062 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
2063 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
2064 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
2065 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
2066 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
2067 hstate->set_hints = (SetHint **) (hstate->leading_hint +
2068 hstate->num_hints[HINT_TYPE_LEADING]);
2069 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
2070 hstate->num_hints[HINT_TYPE_SET]);
2071 hstate->parallel_hints = (ParallelHint **) (hstate->set_hints +
2072 hstate->num_hints[HINT_TYPE_ROWS]);
2078 * Parse inside of parentheses of scan-method hints.
2081 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
2084 const char *keyword = hint->base.keyword;
2085 HintKeyword hint_keyword = hint->base.hint_keyword;
2086 List *name_list = NIL;
2089 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2092 /* Parse relation name and index name(s) if given hint accepts. */
2093 length = list_length(name_list);
2095 /* at least twp parameters required */
2099 ("%s hint requires a relation.", hint->base.keyword));
2100 hint->base.state = HINT_STATE_ERROR;
2104 hint->relname = linitial(name_list);
2105 hint->indexnames = list_delete_first(name_list);
2107 /* check whether the hint accepts index name(s) */
2108 if (length > 1 && !SCAN_HINT_ACCEPTS_INDEX_NAMES(hint_keyword))
2111 ("%s hint accepts only one relation.",
2112 hint->base.keyword));
2113 hint->base.state = HINT_STATE_ERROR;
2117 /* Set a bit for specified hint. */
2118 switch (hint_keyword)
2120 case HINT_KEYWORD_SEQSCAN:
2121 hint->enforce_mask = ENABLE_SEQSCAN;
2123 case HINT_KEYWORD_INDEXSCAN:
2124 hint->enforce_mask = ENABLE_INDEXSCAN;
2126 case HINT_KEYWORD_INDEXSCANREGEXP:
2127 hint->enforce_mask = ENABLE_INDEXSCAN;
2128 hint->regexp = true;
2130 case HINT_KEYWORD_BITMAPSCAN:
2131 hint->enforce_mask = ENABLE_BITMAPSCAN;
2133 case HINT_KEYWORD_BITMAPSCANREGEXP:
2134 hint->enforce_mask = ENABLE_BITMAPSCAN;
2135 hint->regexp = true;
2137 case HINT_KEYWORD_TIDSCAN:
2138 hint->enforce_mask = ENABLE_TIDSCAN;
2140 case HINT_KEYWORD_NOSEQSCAN:
2141 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
2143 case HINT_KEYWORD_NOINDEXSCAN:
2144 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
2146 case HINT_KEYWORD_NOBITMAPSCAN:
2147 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
2149 case HINT_KEYWORD_NOTIDSCAN:
2150 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
2152 case HINT_KEYWORD_INDEXONLYSCAN:
2153 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2155 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
2156 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2157 hint->regexp = true;
2159 case HINT_KEYWORD_NOINDEXONLYSCAN:
2160 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
2163 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2172 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2175 const char *keyword = hint->base.keyword;
2176 HintKeyword hint_keyword = hint->base.hint_keyword;
2177 List *name_list = NIL;
2179 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2182 hint->nrels = list_length(name_list);
2184 if (hint->nrels > 0)
2190 * Transform relation names from list to array to sort them with qsort
2193 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2194 foreach (l, name_list)
2196 hint->relnames[i] = lfirst(l);
2201 list_free(name_list);
2203 /* A join hint requires at least two relations */
2204 if (hint->nrels < 2)
2207 ("%s hint requires at least two relations.",
2208 hint->base.keyword));
2209 hint->base.state = HINT_STATE_ERROR;
2213 /* Sort hints in alphabetical order of relation names. */
2214 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2216 switch (hint_keyword)
2218 case HINT_KEYWORD_NESTLOOP:
2219 hint->enforce_mask = ENABLE_NESTLOOP;
2221 case HINT_KEYWORD_MERGEJOIN:
2222 hint->enforce_mask = ENABLE_MERGEJOIN;
2224 case HINT_KEYWORD_HASHJOIN:
2225 hint->enforce_mask = ENABLE_HASHJOIN;
2227 case HINT_KEYWORD_NONESTLOOP:
2228 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2230 case HINT_KEYWORD_NOMERGEJOIN:
2231 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2233 case HINT_KEYWORD_NOHASHJOIN:
2234 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2237 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2246 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2249 if (outer_inner->outer_inner_pair == NIL)
2251 if (outer_inner->relation)
2257 if (list_length(outer_inner->outer_inner_pair) == 2)
2259 foreach(l, outer_inner->outer_inner_pair)
2261 if (!OuterInnerPairCheck(lfirst(l)))
2272 OuterInnerList(OuterInnerRels *outer_inner)
2274 List *outer_inner_list = NIL;
2276 OuterInnerRels *outer_inner_rels;
2278 foreach(l, outer_inner->outer_inner_pair)
2280 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2282 if (outer_inner_rels->relation != NULL)
2283 outer_inner_list = lappend(outer_inner_list,
2284 outer_inner_rels->relation);
2286 outer_inner_list = list_concat(outer_inner_list,
2287 OuterInnerList(outer_inner_rels));
2289 return outer_inner_list;
2293 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2296 List *name_list = NIL;
2297 OuterInnerRels *outer_inner = NULL;
2299 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2303 if (outer_inner != NULL)
2304 name_list = OuterInnerList(outer_inner);
2306 hint->relations = name_list;
2307 hint->outer_inner = outer_inner;
2309 /* A Leading hint requires at least two relations */
2310 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2312 hint_ereport(hint->base.hint_str,
2313 ("%s hint requires at least two relations.",
2315 hint->base.state = HINT_STATE_ERROR;
2317 else if (hint->outer_inner != NULL &&
2318 !OuterInnerPairCheck(hint->outer_inner))
2320 hint_ereport(hint->base.hint_str,
2321 ("%s hint requires two sets of relations when parentheses nests.",
2323 hint->base.state = HINT_STATE_ERROR;
2330 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2332 List *name_list = NIL;
2334 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2338 hint->words = name_list;
2340 /* We need both name and value to set GUC parameter. */
2341 if (list_length(name_list) == 2)
2343 hint->name = linitial(name_list);
2344 hint->value = lsecond(name_list);
2348 hint_ereport(hint->base.hint_str,
2349 ("%s hint requires name and value of GUC parameter.",
2351 hint->base.state = HINT_STATE_ERROR;
2358 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2361 HintKeyword hint_keyword = hint->base.hint_keyword;
2362 List *name_list = NIL;
2366 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2369 /* Last element must be rows specification */
2370 hint->nrels = list_length(name_list) - 1;
2372 if (hint->nrels > 0)
2378 * Transform relation names from list to array to sort them with qsort
2381 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2382 foreach (l, name_list)
2384 if (hint->nrels <= i)
2386 hint->relnames[i] = lfirst(l);
2391 /* Retieve rows estimation */
2392 rows_str = list_nth(name_list, hint->nrels);
2393 hint->rows_str = rows_str; /* store as-is for error logging */
2394 if (rows_str[0] == '#')
2396 hint->value_type = RVT_ABSOLUTE;
2399 else if (rows_str[0] == '+')
2401 hint->value_type = RVT_ADD;
2404 else if (rows_str[0] == '-')
2406 hint->value_type = RVT_SUB;
2409 else if (rows_str[0] == '*')
2411 hint->value_type = RVT_MULTI;
2416 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2417 hint->base.state = HINT_STATE_ERROR;
2420 hint->rows = strtod(rows_str, &end_ptr);
2423 hint_ereport(rows_str,
2424 ("%s hint requires valid number as rows estimation.",
2425 hint->base.keyword));
2426 hint->base.state = HINT_STATE_ERROR;
2430 /* A join hint requires at least two relations */
2431 if (hint->nrels < 2)
2434 ("%s hint requires at least two relations.",
2435 hint->base.keyword));
2436 hint->base.state = HINT_STATE_ERROR;
2440 list_free(name_list);
2442 /* Sort relnames in alphabetical order. */
2443 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2449 ParallelHintParse(ParallelHint *hint, HintState *hstate, Query *parse,
2452 HintKeyword hint_keyword = hint->base.hint_keyword;
2453 List *name_list = NIL;
2457 bool force_parallel = false;
2459 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2462 /* Parse relation name and index name(s) if given hint accepts. */
2463 length = list_length(name_list);
2465 if (length < 2 || length > 3)
2468 ("wrong number of arguments (%d): %s",
2469 length, hint->base.keyword));
2470 hint->base.state = HINT_STATE_ERROR;
2474 hint->relname = linitial(name_list);
2476 /* The second parameter is number of workers */
2477 hint->nworkers_str = list_nth(name_list, 1);
2478 nworkers = strtod(hint->nworkers_str, &end_ptr);
2479 if (*end_ptr || nworkers < 0 || nworkers > max_worker_processes)
2482 hint_ereport(hint->nworkers_str,
2483 ("number of workers must be a number: %s",
2484 hint->base.keyword));
2485 else if (nworkers < 0)
2486 hint_ereport(hint->nworkers_str,
2487 ("number of workers must be positive: %s",
2488 hint->base.keyword));
2489 else if (nworkers > max_worker_processes)
2490 hint_ereport(hint->nworkers_str,
2491 ("number of workers = %d is larger than max_worker_processes(%d): %s",
2492 nworkers, max_worker_processes, hint->base.keyword));
2494 hint->base.state = HINT_STATE_ERROR;
2497 hint->nworkers = nworkers;
2499 /* optional third parameter is specified */
2502 const char *modeparam = (const char *)list_nth(name_list, 2);
2503 if (pg_strcasecmp(modeparam, "hard") == 0)
2504 force_parallel = true;
2505 else if (pg_strcasecmp(modeparam, "soft") != 0)
2507 hint_ereport(modeparam,
2508 ("enforcement must be soft or hard: %s",
2509 hint->base.keyword));
2510 hint->base.state = HINT_STATE_ERROR;
2514 hint->force_parallel = force_parallel;
2516 if (hint->base.state != HINT_STATE_ERROR &&
2517 nworkers > max_hint_nworkers)
2518 max_hint_nworkers = nworkers;
2524 * set GUC parameter functions
2528 get_current_scan_mask()
2533 mask |= ENABLE_SEQSCAN;
2534 if (enable_indexscan)
2535 mask |= ENABLE_INDEXSCAN;
2536 if (enable_bitmapscan)
2537 mask |= ENABLE_BITMAPSCAN;
2539 mask |= ENABLE_TIDSCAN;
2540 if (enable_indexonlyscan)
2541 mask |= ENABLE_INDEXONLYSCAN;
2547 get_current_join_mask()
2551 if (enable_nestloop)
2552 mask |= ENABLE_NESTLOOP;
2553 if (enable_mergejoin)
2554 mask |= ENABLE_MERGEJOIN;
2555 if (enable_hashjoin)
2556 mask |= ENABLE_HASHJOIN;
2562 * Sets GUC prameters without throwing exception. Reutrns false if something
2566 set_config_option_noerror(const char *name, const char *value,
2567 GucContext context, GucSource source,
2568 GucAction action, bool changeVal, int elevel)
2571 MemoryContext ccxt = CurrentMemoryContext;
2575 result = set_config_option(name, value, context, source,
2576 action, changeVal, 0, false);
2582 /* Save error info */
2583 MemoryContextSwitchTo(ccxt);
2584 errdata = CopyErrorData();
2588 (errcode(errdata->sqlerrcode),
2589 errmsg("%s", errdata->message),
2590 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2591 errdata->hint ? errhint("%s", errdata->hint) : 0));
2593 FreeErrorData(errdata);
2601 * Sets GUC parameter of int32 type without throwing exceptions. Returns false
2602 * if something wrong.
2605 set_config_int32_option(const char *name, int32 value, GucContext context)
2607 char buf[16]; /* enough for int32 */
2609 if (snprintf(buf, 16, "%d", value) < 0)
2611 ereport(pg_hint_plan_parse_message_level,
2612 (errmsg ("Failed to convert integer to string: %d", value)));
2617 set_config_option_noerror(name, buf, context,
2618 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2619 pg_hint_plan_parse_message_level);
2622 /* setup scan method enforcement according to given options */
2624 setup_guc_enforcement(SetHint **options, int noptions, GucContext context)
2628 for (i = 0; i < noptions; i++)
2630 SetHint *hint = options[i];
2633 if (!hint_state_enabled(hint))
2636 result = set_config_option_noerror(hint->name, hint->value, context,
2637 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2638 pg_hint_plan_parse_message_level);
2640 hint->base.state = HINT_STATE_USED;
2642 hint->base.state = HINT_STATE_ERROR;
2649 * Setup parallel execution environment.
2651 * If hint is not NULL, set up using it, elsewise reset to initial environment.
2654 setup_parallel_plan_enforcement(ParallelHint *hint, HintState *state)
2658 hint->base.state = HINT_STATE_USED;
2659 set_config_int32_option("max_parallel_workers_per_gather",
2660 hint->nworkers, state->context);
2663 set_config_int32_option("max_parallel_workers_per_gather",
2664 state->init_nworkers, state->context);
2666 /* force means that enforce parallel as far as possible */
2667 if (hint && hint->force_parallel)
2669 set_config_int32_option("parallel_tuple_cost", 0, state->context);
2670 set_config_int32_option("parallel_setup_cost", 0, state->context);
2671 set_config_int32_option("min_parallel_table_scan_size", 0,
2673 set_config_int32_option("min_parallel_index_scan_size", 0,
2678 set_config_int32_option("parallel_tuple_cost",
2679 state->init_paratup_cost, state->context);
2680 set_config_int32_option("parallel_setup_cost",
2681 state->init_parasetup_cost, state->context);
2682 set_config_int32_option("min_parallel_table_scan_size",
2683 state->init_min_para_tablescan_size,
2685 set_config_int32_option("min_parallel_index_scan_size",
2686 state->init_min_para_indexscan_size,
2691 #define SET_CONFIG_OPTION(name, type_bits) \
2692 set_config_option_noerror((name), \
2693 (mask & (type_bits)) ? "true" : "false", \
2694 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2698 * Setup GUC environment to enforce scan methods. If scanhint is NULL, reset
2699 * GUCs to the saved state in state.
2702 setup_scan_method_enforcement(ScanMethodHint *scanhint, HintState *state)
2704 unsigned char enforce_mask = state->init_scan_mask;
2705 GucContext context = state->context;
2710 enforce_mask = scanhint->enforce_mask;
2711 scanhint->base.state = HINT_STATE_USED;
2714 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2715 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2716 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2718 mask = enforce_mask;
2720 mask = enforce_mask & current_hint_state->init_scan_mask;
2722 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2723 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2724 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2725 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2726 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2730 set_join_config_options(unsigned char enforce_mask, GucContext context)
2734 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2735 enforce_mask == ENABLE_HASHJOIN)
2736 mask = enforce_mask;
2738 mask = enforce_mask & current_hint_state->init_join_mask;
2740 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2741 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2742 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2746 * Push a hint into hint stack which is implemented with List struct. Head of
2747 * list is top of stack.
2750 push_hint(HintState *hstate)
2752 /* Prepend new hint to the list means pushing to stack. */
2753 HintStateStack = lcons(hstate, HintStateStack);
2755 /* Pushed hint is the one which should be used hereafter. */
2756 current_hint_state = hstate;
2759 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2763 /* Hint stack must not be empty. */
2764 if(HintStateStack == NIL)
2765 elog(ERROR, "hint stack is empty");
2768 * Take a hint at the head from the list, and free it. Switch
2769 * current_hint_state to point new head (NULL if the list is empty).
2771 HintStateStack = list_delete_first(HintStateStack);
2772 HintStateDelete(current_hint_state);
2773 if(HintStateStack == NIL)
2774 current_hint_state = NULL;
2776 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
2780 * Retrieve and store hint string from given query or from the hint table.
2783 get_current_hint_string(ParseState *pstate, Query *query)
2785 const char *query_str;
2786 MemoryContext oldcontext;
2788 /* do nothing under hint table search */
2789 if (hint_inhibit_level > 0)
2792 /* We alredy have one, don't parse it again. */
2793 if (current_hint_retrieved)
2796 /* Don't parse the current query hereafter */
2797 current_hint_retrieved = true;
2799 if (!pg_hint_plan_enable_hint)
2801 if (current_hint_str)
2803 pfree((void *)current_hint_str);
2804 current_hint_str = NULL;
2809 /* increment the query number */
2811 if (debug_level > 1)
2812 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2815 /* search the hint table for a hint if requested */
2816 if (pg_hint_plan_enable_hint_table)
2819 pgssJumbleState jstate;
2821 char *normalized_query = NULL;
2823 query_str = get_query_string(pstate, query, &jumblequery);
2825 /* If this query is not for hint, just return */
2829 /* clear the previous hint string */
2830 if (current_hint_str)
2832 pfree((void *)current_hint_str);
2833 current_hint_str = NULL;
2839 * XXX: normalization code is copied from pg_stat_statements.c.
2840 * Make sure to keep up-to-date with it.
2842 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2843 jstate.jumble_len = 0;
2844 jstate.clocations_buf_size = 32;
2845 jstate.clocations = (pgssLocationLen *)
2846 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2847 jstate.clocations_count = 0;
2849 JumbleQuery(&jstate, jumblequery);
2852 * Normalize the query string by replacing constants with '?'
2855 * Search hint string which is stored keyed by query string
2856 * and application name. The query string is normalized to allow
2859 * Adding 1 byte to query_len ensures that the returned string has
2860 * a terminating NULL.
2862 query_len = strlen(query_str) + 1;
2864 generate_normalized_query(&jstate, query_str,
2865 query->stmt_location,
2867 GetDatabaseEncoding());
2870 * find a hint for the normalized query. the result should be in
2873 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2875 get_hints_from_table(normalized_query, application_name);
2876 MemoryContextSwitchTo(oldcontext);
2878 if (debug_level > 1)
2880 if (current_hint_str)
2881 ereport(pg_hint_plan_debug_message_level,
2882 (errmsg("pg_hint_plan[qno=0x%x]: "
2883 "post_parse_analyze_hook: "
2884 "hints from table: \"%s\": "
2885 "normalized_query=\"%s\", "
2886 "application name =\"%s\"",
2887 qno, current_hint_str,
2888 normalized_query, application_name),
2889 errhidestmt(msgqno != qno),
2890 errhidecontext(msgqno != qno)));
2892 ereport(pg_hint_plan_debug_message_level,
2893 (errmsg("pg_hint_plan[qno=0x%x]: "
2894 "no match found in table: "
2895 "application name = \"%s\", "
2896 "normalized_query=\"%s\"",
2897 qno, application_name,
2899 errhidestmt(msgqno != qno),
2900 errhidecontext(msgqno != qno)));
2906 /* retrun if we have hint here */
2907 if (current_hint_str)
2911 query_str = get_query_string(pstate, query, NULL);
2916 * get hints from the comment. However we may have the same query
2917 * string with the previous call, but the extra comparison seems no
2920 if (current_hint_str)
2921 pfree((void *)current_hint_str);
2923 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2924 current_hint_str = get_hints_from_comment(query_str);
2925 MemoryContextSwitchTo(oldcontext);
2928 if (debug_level > 1)
2930 if (debug_level == 1 && query_str && debug_query_string &&
2931 strcmp(query_str, debug_query_string))
2932 ereport(pg_hint_plan_debug_message_level,
2933 (errmsg("hints in comment=\"%s\"",
2934 current_hint_str ? current_hint_str : "(none)"),
2935 errhidestmt(msgqno != qno),
2936 errhidecontext(msgqno != qno)));
2938 ereport(pg_hint_plan_debug_message_level,
2939 (errmsg("hints in comment=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2940 current_hint_str ? current_hint_str : "(none)",
2941 query_str ? query_str : "(none)",
2942 debug_query_string ? debug_query_string : "(none)"),
2943 errhidestmt(msgqno != qno),
2944 errhidecontext(msgqno != qno)));
2950 * Retrieve hint string from the current query.
2953 pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query)
2955 if (prev_post_parse_analyze_hook)
2956 prev_post_parse_analyze_hook(pstate, query);
2958 /* always retrieve hint from the top-level query string */
2959 if (plpgsql_recurse_level == 0)
2960 current_hint_retrieved = false;
2962 get_current_hint_string(pstate, query);
2966 * We need to reset current_hint_retrieved flag always when a command execution
2967 * is finished. This is true even for a pure utility command that doesn't
2968 * involve planning phase.
2971 pg_hint_plan_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
2972 ProcessUtilityContext context,
2973 ParamListInfo params, QueryEnvironment *queryEnv,
2974 DestReceiver *dest, char *completionTag)
2976 if (prev_ProcessUtility_hook)
2977 prev_ProcessUtility_hook(pstmt, queryString, context, params, queryEnv,
2978 dest, completionTag);
2980 standard_ProcessUtility(pstmt, queryString, context, params, queryEnv,
2981 dest, completionTag);
2983 if (plpgsql_recurse_level == 0)
2984 current_hint_retrieved = false;
2988 * Read and set up hint information
2990 static PlannedStmt *
2991 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2994 PlannedStmt *result;
2998 * Use standard planner if pg_hint_plan is disabled or current nesting
2999 * depth is nesting depth of SPI calls. Other hook functions try to change
3000 * plan with current_hint_state if any, so set it to NULL.
3002 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
3004 if (debug_level > 1)
3005 ereport(pg_hint_plan_debug_message_level,
3006 (errmsg ("pg_hint_plan%s: planner: enable_hint=%d,"
3007 " hint_inhibit_level=%d",
3008 qnostr, pg_hint_plan_enable_hint,
3009 hint_inhibit_level),
3010 errhidestmt(msgqno != qno)));
3013 goto standard_planner_proc;
3017 * Support for nested plpgsql functions. This is quite ugly but this is the
3018 * only point I could find where I can get the query string.
3020 if (plpgsql_recurse_level > 0)
3022 MemoryContext oldcontext;
3024 if (current_hint_str)
3025 pfree((void *)current_hint_str);
3027 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
3029 get_hints_from_comment((char *)error_context_stack->arg);
3030 MemoryContextSwitchTo(oldcontext);
3034 * Query execution in extended protocol can be started without the analyze
3035 * phase. In the case retrieve hint string here.
3037 if (!current_hint_str)
3038 get_current_hint_string(NULL, parse);
3040 /* No hint, go the normal way */
3041 if (!current_hint_str)
3042 goto standard_planner_proc;
3044 /* parse the hint into hint state struct */
3045 hstate = create_hintstate(parse, pstrdup(current_hint_str));
3047 /* run standard planner if the statement has not valid hint */
3049 goto standard_planner_proc;
3052 * Push new hint struct to the hint stack to disable previous hint context.
3056 /* Set scan enforcement here. */
3057 save_nestlevel = NewGUCNestLevel();
3059 /* Apply Set hints, then save it as the initial state */
3060 setup_guc_enforcement(current_hint_state->set_hints,
3061 current_hint_state->num_hints[HINT_TYPE_SET],
3062 current_hint_state->context);
3064 current_hint_state->init_scan_mask = get_current_scan_mask();
3065 current_hint_state->init_join_mask = get_current_join_mask();
3066 current_hint_state->init_min_para_tablescan_size =
3067 min_parallel_table_scan_size;
3068 current_hint_state->init_min_para_indexscan_size =
3069 min_parallel_index_scan_size;
3070 current_hint_state->init_paratup_cost = parallel_tuple_cost;
3071 current_hint_state->init_parasetup_cost = parallel_setup_cost;
3074 * max_parallel_workers_per_gather should be non-zero here if Workers hint
3077 if (max_hint_nworkers > 0 && max_parallel_workers_per_gather < 1)
3078 set_config_int32_option("max_parallel_workers_per_gather",
3079 1, current_hint_state->context);
3080 current_hint_state->init_nworkers = max_parallel_workers_per_gather;
3082 if (debug_level > 1)
3084 ereport(pg_hint_plan_debug_message_level,
3085 (errhidestmt(msgqno != qno),
3086 errmsg("pg_hint_plan%s: planner", qnostr)));
3091 * Use PG_TRY mechanism to recover GUC parameters and current_hint_state to
3092 * the state when this planner started when error occurred in planner.
3097 result = (*prev_planner) (parse, cursorOptions, boundParams);
3099 result = standard_planner(parse, cursorOptions, boundParams);
3104 * Rollback changes of GUC parameters, and pop current hint context
3105 * from hint stack to rewind the state.
3107 AtEOXact_GUC(true, save_nestlevel);
3115 * current_hint_str is useless after planning of the top-level query.
3117 if (plpgsql_recurse_level < 1 && current_hint_str)
3119 pfree((void *)current_hint_str);
3120 current_hint_str = NULL;
3121 current_hint_retrieved = false;
3124 /* Print hint in debug mode. */
3125 if (debug_level == 1)
3126 HintStateDump(current_hint_state);
3127 else if (debug_level > 1)
3128 HintStateDump2(current_hint_state);
3131 * Rollback changes of GUC parameters, and pop current hint context from
3132 * hint stack to rewind the state.
3134 AtEOXact_GUC(true, save_nestlevel);
3139 standard_planner_proc:
3140 if (debug_level > 1)
3142 ereport(pg_hint_plan_debug_message_level,
3143 (errhidestmt(msgqno != qno),
3144 errmsg("pg_hint_plan%s: planner: no valid hint",
3148 current_hint_state = NULL;
3150 return (*prev_planner) (parse, cursorOptions, boundParams);
3152 return standard_planner(parse, cursorOptions, boundParams);
3156 * Find scan method hint to be applied to the given relation
3159 static ScanMethodHint *
3160 find_scan_hint(PlannerInfo *root, Index relid)
3164 ScanMethodHint *real_name_hint = NULL;
3165 ScanMethodHint *alias_hint = NULL;
3168 /* This should not be a join rel */
3170 rel = root->simple_rel_array[relid];
3173 * This function is called for any RelOptInfo or its inheritance parent if
3174 * any. If we are called from inheritance planner, the RelOptInfo for the
3175 * parent of target child relation is not set in the planner info.
3177 * Otherwise we should check that the reloptinfo is base relation or
3178 * inheritance children.
3181 rel->reloptkind != RELOPT_BASEREL &&
3182 rel->reloptkind != RELOPT_OTHER_MEMBER_REL)
3186 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3188 rte = root->simple_rte_array[relid];
3191 /* We don't hint on other than relation and foreign tables */
3192 if (rte->rtekind != RTE_RELATION ||
3193 rte->relkind == RELKIND_FOREIGN_TABLE)
3196 /* Find scan method hint, which matches given names, from the list. */
3197 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
3199 ScanMethodHint *hint = current_hint_state->scan_hints[i];
3201 /* We ignore disabled hints. */
3202 if (!hint_state_enabled(hint))
3206 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3209 /* check the real name for appendrel children */
3210 if (!real_name_hint &&
3211 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3213 char *realname = get_rel_name(rte->relid);
3215 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3216 real_name_hint = hint;
3219 /* No more match expected, break */
3220 if(alias_hint && real_name_hint)
3224 /* real name match precedes alias match */
3226 return real_name_hint;
3231 static ParallelHint *
3232 find_parallel_hint(PlannerInfo *root, Index relid)
3236 ParallelHint *real_name_hint = NULL;
3237 ParallelHint *alias_hint = NULL;
3240 /* This should not be a join rel */
3242 rel = root->simple_rel_array[relid];
3245 * Parallel planning is appliable only on base relation, which has
3252 * We have set root->glob->parallelModeOK if needed. What we should do here
3253 * is just following the decision of planner.
3255 if (!rel->consider_parallel)
3259 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3261 rte = root->simple_rte_array[relid];
3264 /* Find parallel method hint, which matches given names, from the list. */
3265 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_PARALLEL]; i++)
3267 ParallelHint *hint = current_hint_state->parallel_hints[i];
3269 /* We ignore disabled hints. */
3270 if (!hint_state_enabled(hint))
3274 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3277 /* check the real name for appendrel children */
3278 if (!real_name_hint &&
3279 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3281 char *realname = get_rel_name(rte->relid);
3283 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3284 real_name_hint = hint;
3287 /* No more match expected, break */
3288 if(alias_hint && real_name_hint)
3292 /* real name match precedes alias match */
3294 return real_name_hint;
3302 * Returns TRUE on match, FALSE on no match.
3304 * s1 --- the data to match against
3305 * s2 --- the pattern
3307 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
3310 regexpeq(const char *s1, const char *s2)
3316 strcpy(name.data, s1);
3317 regexp = cstring_to_text(s2);
3319 result = DirectFunctionCall2Coll(nameregexeq,
3320 DEFAULT_COLLATION_OID,
3321 NameGetDatum(&name),
3322 PointerGetDatum(regexp));
3323 return DatumGetBool(result);
3327 /* Remove indexes instructed not to use by hint. */
3329 restrict_indexes(PlannerInfo *root, ScanMethodHint *hint, RelOptInfo *rel,
3330 bool using_parent_hint)
3336 RangeTblEntry *rte = root->simple_rte_array[rel->relid];
3337 Oid relationObjectId = rte->relid;
3340 * We delete all the IndexOptInfo list and prevent you from being usable by
3343 if (hint->enforce_mask == ENABLE_SEQSCAN ||
3344 hint->enforce_mask == ENABLE_TIDSCAN)
3346 list_free_deep(rel->indexlist);
3347 rel->indexlist = NIL;
3348 hint->base.state = HINT_STATE_USED;
3354 * When a list of indexes is not specified, we just use all indexes.
3356 if (hint->indexnames == NIL)
3360 * Leaving only an specified index, we delete it from a IndexOptInfo list
3364 if (debug_level > 0)
3365 initStringInfo(&buf);
3367 for (cell = list_head(rel->indexlist); cell; cell = next)
3369 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
3370 char *indexname = get_rel_name(info->indexoid);
3372 bool use_index = false;
3376 foreach(l, hint->indexnames)
3378 char *hintname = (char *) lfirst(l);
3382 result = regexpeq(indexname, hintname);
3384 result = RelnameCmp(&indexname, &hintname) == 0;
3389 if (debug_level > 0)
3391 appendStringInfoCharMacro(&buf, ' ');
3392 quote_value(&buf, indexname);
3400 * Apply index restriction of parent hint to children. Since index
3401 * inheritance is not explicitly described we should search for an
3402 * children's index with the same definition to that of the parent.
3404 if (using_parent_hint && !use_index)
3406 foreach(l, current_hint_state->parent_index_infos)
3410 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
3413 * we check the 'same' index by comparing uniqueness, access
3414 * method and index key columns.
3416 if (p_info->indisunique != info->unique ||
3417 p_info->method != info->relam ||
3418 list_length(p_info->column_names) != info->ncolumns)
3421 /* Check if index key columns match */
3422 for (i = 0; i < info->ncolumns; i++)
3424 char *c_attname = NULL;
3425 char *p_attname = NULL;
3427 p_attname = list_nth(p_info->column_names, i);
3430 * if both of the key of the same position are expressions,
3431 * ignore them for now and check later.
3433 if (info->indexkeys[i] == 0 && !p_attname)
3436 /* deny if one is expression while another is not */
3437 if (info->indexkeys[i] == 0 || !p_attname)
3440 c_attname = get_attname(relationObjectId,
3441 info->indexkeys[i]);
3443 /* deny if any of column attributes don't match */
3444 if (strcmp(p_attname, c_attname) != 0 ||
3445 p_info->indcollation[i] != info->indexcollations[i] ||
3446 p_info->opclass[i] != info->opcintype[i]||
3447 ((p_info->indoption[i] & INDOPTION_DESC) != 0)
3448 != info->reverse_sort[i] ||
3449 ((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0)
3450 != info->nulls_first[i])
3454 /* deny this if any difference found */
3455 if (i != info->ncolumns)
3458 /* check on key expressions */
3459 if ((p_info->expression_str && (info->indexprs != NIL)) ||
3460 (p_info->indpred_str && (info->indpred != NIL)))
3462 /* fetch the index of this child */
3463 ht_idx = SearchSysCache1(INDEXRELID,
3464 ObjectIdGetDatum(info->indexoid));
3466 /* check expressions if both expressions are available */
3467 if (p_info->expression_str &&
3468 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
3475 * to change the expression's parameter of child's
3478 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3479 Anum_pg_index_indexprs,
3482 result = DirectFunctionCall2(pg_get_expr,
3487 /* deny if expressions don't match */
3488 if (strcmp(p_info->expression_str,
3489 text_to_cstring(DatumGetTextP(result))) != 0)
3492 ReleaseSysCache(ht_idx);
3497 /* compare index predicates */
3498 if (p_info->indpred_str &&
3499 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
3505 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3506 Anum_pg_index_indpred,
3509 result = DirectFunctionCall2(pg_get_expr,
3514 if (strcmp(p_info->indpred_str,
3515 text_to_cstring(DatumGetTextP(result))) != 0)
3518 ReleaseSysCache(ht_idx);
3524 ReleaseSysCache(ht_idx);
3526 else if (p_info->expression_str || (info->indexprs != NIL))
3528 else if (p_info->indpred_str || (info->indpred != NIL))
3533 /* to log the candidate of index */
3534 if (debug_level > 0)
3536 appendStringInfoCharMacro(&buf, ' ');
3537 quote_value(&buf, indexname);
3545 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
3552 if (debug_level == 1)
3554 StringInfoData rel_buf;
3555 char *disprelname = "";
3558 * If this hint targetted the parent, use the real name of this
3559 * child. Otherwise use hint specification.
3561 if (using_parent_hint)
3562 disprelname = get_rel_name(rte->relid);
3564 disprelname = hint->relname;
3567 initStringInfo(&rel_buf);
3568 quote_value(&rel_buf, disprelname);
3570 ereport(pg_hint_plan_debug_message_level,
3571 (errmsg("available indexes for %s(%s):%s",
3576 pfree(rel_buf.data);
3581 * Return information of index definition.
3583 static ParentIndexInfo *
3584 get_parent_index_info(Oid indexoid, Oid relid)
3586 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3587 Relation indexRelation;
3588 Form_pg_index index;
3592 indexRelation = index_open(indexoid, RowExclusiveLock);
3594 index = indexRelation->rd_index;
3596 p_info->indisunique = index->indisunique;
3597 p_info->method = indexRelation->rd_rel->relam;
3599 p_info->column_names = NIL;
3600 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3601 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3602 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3604 for (i = 0; i < index->indnatts; i++)
3606 attname = get_attname(relid, index->indkey.values[i]);
3607 p_info->column_names = lappend(p_info->column_names, attname);
3609 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3610 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3611 p_info->indoption[i] = indexRelation->rd_indoption[i];
3615 * to check to match the expression's parameter of index with child indexes
3617 p_info->expression_str = NULL;
3618 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
3624 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3625 Anum_pg_index_indexprs, &isnull);
3627 result = DirectFunctionCall2(pg_get_expr,
3629 ObjectIdGetDatum(relid));
3631 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3635 * to check to match the predicate's parameter of index with child indexes
3637 p_info->indpred_str = NULL;
3638 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
3644 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3645 Anum_pg_index_indpred, &isnull);
3647 result = DirectFunctionCall2(pg_get_expr,
3649 ObjectIdGetDatum(relid));
3651 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3654 index_close(indexRelation, NoLock);
3660 * cancel hint enforcement
3663 reset_hint_enforcement()
3665 setup_scan_method_enforcement(NULL, current_hint_state);
3666 setup_parallel_plan_enforcement(NULL, current_hint_state);
3670 * Set planner guc parameters according to corresponding scan hints. Returns
3671 * bitmap of HintTypeBitmap. If shint or phint is not NULL, set used hint
3672 * there respectively.
3675 setup_hint_enforcement(PlannerInfo *root, RelOptInfo *rel,
3676 ScanMethodHint **rshint, ParallelHint **rphint)
3678 Index new_parent_relid = 0;
3680 ScanMethodHint *shint = NULL;
3681 ParallelHint *phint = NULL;
3682 bool inhparent = root->simple_rte_array[rel->relid]->inh;
3683 Oid relationObjectId = root->simple_rte_array[rel->relid]->relid;
3686 /* reset returns if requested */
3687 if (rshint != NULL) *rshint = NULL;
3688 if (rphint != NULL) *rphint = NULL;
3691 * We could register the parent relation of the following children here
3692 * when inhparent == true but inheritnce planner doesn't call this function
3693 * for parents. Since we cannot distinguish who called this function we
3694 * cannot do other than always seeking the parent regardless of who called
3699 if (debug_level > 1)
3700 ereport(pg_hint_plan_debug_message_level,
3702 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3703 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3704 " current_hint_state=%p, hint_inhibit_level=%d",
3705 qnostr, relationObjectId,
3706 get_rel_name(relationObjectId),
3707 inhparent, current_hint_state, hint_inhibit_level)));
3711 /* Forget about the parent of another subquery */
3712 if (root != current_hint_state->current_root)
3713 current_hint_state->parent_relid = 0;
3715 /* Find the parent for this relation other than the registered parent */
3716 foreach (l, root->append_rel_list)
3718 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3720 if (appinfo->child_relid == rel->relid)
3722 if (current_hint_state->parent_relid != appinfo->parent_relid)
3724 new_parent_relid = appinfo->parent_relid;
3725 current_hint_state->current_root = root;
3733 /* This relation doesn't have a parent. Cancel current_hint_state. */
3734 current_hint_state->parent_relid = 0;
3735 current_hint_state->parent_scan_hint = NULL;
3736 current_hint_state->parent_parallel_hint = NULL;
3739 if (new_parent_relid > 0)
3742 * Here we found a new parent for the current relation. Scan continues
3743 * hint to other childrens of this parent so remember it * to avoid
3744 * hinthintredundant setup cost.
3746 current_hint_state->parent_relid = new_parent_relid;
3748 /* Find hints for the parent */
3749 current_hint_state->parent_scan_hint =
3750 find_scan_hint(root, current_hint_state->parent_relid);
3752 current_hint_state->parent_parallel_hint =
3753 find_parallel_hint(root, current_hint_state->parent_relid);
3756 * If hint is found for the parent, apply it for this child instead
3759 if (current_hint_state->parent_scan_hint)
3761 ScanMethodHint * pshint = current_hint_state->parent_scan_hint;
3763 pshint->base.state = HINT_STATE_USED;
3765 /* Apply index mask in the same manner to the parent. */
3766 if (pshint->indexnames)
3769 Relation parent_rel;
3772 root->simple_rte_array[current_hint_state->parent_relid]->relid;
3773 parent_rel = heap_open(parentrel_oid, NoLock);
3775 /* Search the parent relation for indexes match the hint spec */
3776 foreach(l, RelationGetIndexList(parent_rel))
3778 Oid indexoid = lfirst_oid(l);
3779 char *indexname = get_rel_name(indexoid);
3781 ParentIndexInfo *parent_index_info;
3783 foreach(lc, pshint->indexnames)
3785 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3792 get_parent_index_info(indexoid, parentrel_oid);
3793 current_hint_state->parent_index_infos =
3794 lappend(current_hint_state->parent_index_infos,
3797 heap_close(parent_rel, NoLock);
3802 shint = find_scan_hint(root, rel->relid);
3804 shint = current_hint_state->parent_scan_hint;
3808 bool using_parent_hint =
3809 (shint == current_hint_state->parent_scan_hint);
3811 ret |= HINT_BM_SCAN_METHOD;
3813 /* Setup scan enforcement environment */
3814 setup_scan_method_enforcement(shint, current_hint_state);
3816 /* restrict unwanted inexes */
3817 restrict_indexes(root, shint, rel, using_parent_hint);
3819 if (debug_level > 1)
3821 char *additional_message = "";
3823 if (shint == current_hint_state->parent_scan_hint)
3824 additional_message = " by parent hint";
3826 ereport(pg_hint_plan_debug_message_level,
3828 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3829 " index deletion%s:"
3830 " relation=%u(%s), inhparent=%d, "
3831 "current_hint_state=%p,"
3832 " hint_inhibit_level=%d, scanmask=0x%x",
3833 qnostr, additional_message,
3835 get_rel_name(relationObjectId),
3836 inhparent, current_hint_state,
3838 shint->enforce_mask)));
3842 /* Do the same for parallel plan enforcement */
3843 phint = find_parallel_hint(root, rel->relid);
3845 phint = current_hint_state->parent_parallel_hint;
3847 setup_parallel_plan_enforcement(phint, current_hint_state);
3850 ret |= HINT_BM_PARALLEL;
3852 /* Nothing to apply. Reset the scan mask to intial state */
3853 if (!shint && ! phint)
3855 if (debug_level > 1)
3856 ereport(pg_hint_plan_debug_message_level,
3857 (errhidestmt (true),
3858 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3860 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3861 " hint_inhibit_level=%d, scanmask=0x%x",
3862 qnostr, relationObjectId,
3863 get_rel_name(relationObjectId),
3864 inhparent, current_hint_state, hint_inhibit_level,
3865 current_hint_state->init_scan_mask)));
3867 setup_scan_method_enforcement(NULL, current_hint_state);
3872 if (rshint != NULL) *rshint = shint;
3873 if (rphint != NULL) *rphint = phint;
3879 * Return index of relation which matches given aliasname, or 0 if not found.
3880 * If same aliasname was used multiple times in a query, return -1.
3883 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3889 for (i = 1; i < root->simple_rel_array_size; i++)
3893 if (root->simple_rel_array[i] == NULL)
3896 Assert(i == root->simple_rel_array[i]->relid);
3898 if (RelnameCmp(&aliasname,
3899 &root->simple_rte_array[i]->eref->aliasname) != 0)
3902 foreach(l, initial_rels)
3904 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3906 if (rel->reloptkind == RELOPT_BASEREL)
3908 if (rel->relid != i)
3913 Assert(rel->reloptkind == RELOPT_JOINREL);
3915 if (!bms_is_member(i, rel->relids))
3922 ("Relation name \"%s\" is ambiguous.",
3937 * Return join hint which matches given joinrelids.
3939 static JoinMethodHint *
3940 find_join_hint(Relids joinrelids)
3945 join_hint = current_hint_state->join_hint_level[bms_num_members(joinrelids)];
3947 foreach(l, join_hint)
3949 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3951 if (bms_equal(joinrelids, hint->joinrelids))
3959 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3960 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3962 OuterInnerRels *outer_rels;
3963 OuterInnerRels *inner_rels;
3964 Relids outer_relids;
3965 Relids inner_relids;
3967 JoinMethodHint *hint;
3969 if (outer_inner->relation != NULL)
3971 return bms_make_singleton(
3972 find_relid_aliasname(root, outer_inner->relation,
3974 leading_hint->base.hint_str));
3977 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3978 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3980 outer_relids = OuterInnerJoinCreate(outer_rels,
3986 inner_relids = OuterInnerJoinCreate(inner_rels,
3993 join_relids = bms_add_members(outer_relids, inner_relids);
3995 if (bms_num_members(join_relids) > nbaserel)
3999 * If we don't have join method hint, create new one for the
4000 * join combination with all join methods are enabled.
4002 hint = find_join_hint(join_relids);
4006 * Here relnames is not set, since Relids bitmap is sufficient to
4007 * control paths of this query afterward.
4009 hint = (JoinMethodHint *) JoinMethodHintCreate(
4010 leading_hint->base.hint_str,
4012 HINT_KEYWORD_LEADING);
4013 hint->base.state = HINT_STATE_USED;
4014 hint->nrels = bms_num_members(join_relids);
4015 hint->enforce_mask = ENABLE_ALL_JOIN;
4016 hint->joinrelids = bms_copy(join_relids);
4017 hint->inner_nrels = bms_num_members(inner_relids);
4018 hint->inner_joinrelids = bms_copy(inner_relids);
4020 hstate->join_hint_level[hint->nrels] =
4021 lappend(hstate->join_hint_level[hint->nrels], hint);
4025 hint->inner_nrels = bms_num_members(inner_relids);
4026 hint->inner_joinrelids = bms_copy(inner_relids);
4033 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
4034 int nrels, char **relnames)
4037 Relids relids = NULL;
4041 for (j = 0; j < nrels; j++)
4043 relname = relnames[j];
4045 relid = find_relid_aliasname(root, relname, initial_rels,
4049 base->state = HINT_STATE_ERROR;
4052 * the aliasname is not found(relid == 0) or same aliasname was used
4053 * multiple times in a query(relid == -1)
4060 if (bms_is_member(relid, relids))
4062 hint_ereport(base->hint_str,
4063 ("Relation name \"%s\" is duplicated.", relname));
4064 base->state = HINT_STATE_ERROR;
4068 relids = bms_add_member(relids, relid);
4073 * Transform join method hint into handy form.
4075 * - create bitmap of relids from alias names, to make it easier to check
4076 * whether a join path matches a join method hint.
4077 * - add join method hints which are necessary to enforce join order
4078 * specified by Leading hint
4081 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
4082 List *initial_rels, JoinMethodHint **join_method_hints)
4090 LeadingHint *lhint = NULL;
4093 * Create bitmap of relids from alias names for each join method hint.
4094 * Bitmaps are more handy than strings in join searching.
4096 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
4098 JoinMethodHint *hint = hstate->join_hints[i];
4100 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4103 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4104 initial_rels, hint->nrels, hint->relnames);
4106 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
4109 hstate->join_hint_level[hint->nrels] =
4110 lappend(hstate->join_hint_level[hint->nrels], hint);
4114 * Create bitmap of relids from alias names for each rows hint.
4115 * Bitmaps are more handy than strings in join searching.
4117 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
4119 RowsHint *hint = hstate->rows_hints[i];
4121 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4124 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4125 initial_rels, hint->nrels, hint->relnames);
4128 /* Do nothing if no Leading hint was supplied. */
4129 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
4133 * Decide whether to use Leading hint
4135 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
4137 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
4140 if (leading_hint->base.state == HINT_STATE_ERROR)
4146 foreach(l, leading_hint->relations)
4148 relname = (char *)lfirst(l);;
4150 relid = find_relid_aliasname(root, relname, initial_rels,
4151 leading_hint->base.hint_str);
4153 leading_hint->base.state = HINT_STATE_ERROR;
4158 if (bms_is_member(relid, relids))
4160 hint_ereport(leading_hint->base.hint_str,
4161 ("Relation name \"%s\" is duplicated.", relname));
4162 leading_hint->base.state = HINT_STATE_ERROR;
4166 relids = bms_add_member(relids, relid);
4169 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
4174 hint_ereport(lhint->base.hint_str,
4175 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
4176 lhint->base.state = HINT_STATE_DUPLICATION;
4178 leading_hint->base.state = HINT_STATE_USED;
4179 lhint = leading_hint;
4182 /* check to exist Leading hint marked with 'used'. */
4187 * We need join method hints which fit specified join order in every join
4188 * level. For example, Leading(A B C) virtually requires following join
4189 * method hints, if no join method hint supplied:
4191 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
4192 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
4194 * If we already have join method hint which fits specified join order in
4195 * that join level, we leave it as-is and don't add new hints.
4199 if (lhint->outer_inner == NULL)
4201 foreach(l, lhint->relations)
4203 JoinMethodHint *hint;
4205 relname = (char *)lfirst(l);
4208 * Find relid of the relation which has given name. If we have the
4209 * name given in Leading hint multiple times in the join, nothing to
4212 relid = find_relid_aliasname(root, relname, initial_rels,
4215 /* Create bitmap of relids for current join level. */
4216 joinrelids = bms_add_member(joinrelids, relid);
4219 /* We never have join method hint for single relation. */
4224 * If we don't have join method hint, create new one for the
4225 * join combination with all join methods are enabled.
4227 hint = find_join_hint(joinrelids);
4231 * Here relnames is not set, since Relids bitmap is sufficient
4232 * to control paths of this query afterward.
4234 hint = (JoinMethodHint *) JoinMethodHintCreate(
4235 lhint->base.hint_str,
4237 HINT_KEYWORD_LEADING);
4238 hint->base.state = HINT_STATE_USED;
4239 hint->nrels = njoinrels;
4240 hint->enforce_mask = ENABLE_ALL_JOIN;
4241 hint->joinrelids = bms_copy(joinrelids);
4244 join_method_hints[njoinrels] = hint;
4246 if (njoinrels >= nbaserel)
4249 bms_free(joinrelids);
4255 * Delete all join hints which have different combination from Leading
4258 for (i = 2; i <= njoinrels; i++)
4260 list_free(hstate->join_hint_level[i]);
4262 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
4267 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
4274 njoinrels = bms_num_members(joinrelids);
4275 Assert(njoinrels >= 2);
4278 * Delete all join hints which have different combination from Leading
4281 for (i = 2;i <= njoinrels; i++)
4283 if (hstate->join_hint_level[i] != NIL)
4285 ListCell *prev = NULL;
4286 ListCell *next = NULL;
4287 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
4290 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
4294 if (hint->inner_nrels == 0 &&
4295 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
4296 bms_equal(bms_union(hint->joinrelids, joinrelids),
4299 hstate->join_hint_level[i] =
4300 list_delete_cell(hstate->join_hint_level[i], l,
4309 bms_free(joinrelids);
4312 if (hint_state_enabled(lhint))
4314 set_join_config_options(DISABLE_ALL_JOIN, current_hint_state->context);
4321 * wrapper of make_join_rel()
4323 * call make_join_rel() after changing enable_* parameters according to given
4327 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
4330 JoinMethodHint *hint;
4334 joinrelids = bms_union(rel1->relids, rel2->relids);
4335 hint = find_join_hint(joinrelids);
4336 bms_free(joinrelids);
4339 return pg_hint_plan_make_join_rel(root, rel1, rel2);
4341 if (hint->inner_nrels == 0)
4343 save_nestlevel = NewGUCNestLevel();
4345 set_join_config_options(hint->enforce_mask,
4346 current_hint_state->context);
4348 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4349 hint->base.state = HINT_STATE_USED;
4352 * Restore the GUC variables we set above.
4354 AtEOXact_GUC(true, save_nestlevel);
4357 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4366 add_paths_to_joinrel_wrapper(PlannerInfo *root,
4367 RelOptInfo *joinrel,
4368 RelOptInfo *outerrel,
4369 RelOptInfo *innerrel,
4371 SpecialJoinInfo *sjinfo,
4375 JoinMethodHint *join_hint;
4378 joinrelids = bms_union(outerrel->relids, innerrel->relids);
4379 join_hint = find_join_hint(joinrelids);
4380 bms_free(joinrelids);
4382 if (join_hint && join_hint->inner_nrels != 0)
4384 save_nestlevel = NewGUCNestLevel();
4386 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
4389 set_join_config_options(join_hint->enforce_mask,
4390 current_hint_state->context);
4392 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4393 sjinfo, restrictlist);
4394 join_hint->base.state = HINT_STATE_USED;
4398 set_join_config_options(DISABLE_ALL_JOIN,
4399 current_hint_state->context);
4400 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4401 sjinfo, restrictlist);
4405 * Restore the GUC variables we set above.
4407 AtEOXact_GUC(true, save_nestlevel);
4410 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4411 sjinfo, restrictlist);
4415 get_num_baserels(List *initial_rels)
4420 foreach(l, initial_rels)
4422 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
4424 if (rel->reloptkind == RELOPT_BASEREL)
4426 else if (rel->reloptkind ==RELOPT_JOINREL)
4427 nbaserel+= bms_num_members(rel->relids);
4430 /* other values not expected here */
4431 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
4439 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
4442 JoinMethodHint **join_method_hints;
4446 bool leading_hint_enable;
4449 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
4450 * valid hint is supplied or current nesting depth is nesting depth of SPI
4453 if (!current_hint_state || hint_inhibit_level > 0)
4455 if (prev_join_search)
4456 return (*prev_join_search) (root, levels_needed, initial_rels);
4457 else if (enable_geqo && levels_needed >= geqo_threshold)
4458 return geqo(root, levels_needed, initial_rels);
4460 return standard_join_search(root, levels_needed, initial_rels);
4464 * In the case using GEQO, only scan method hints and Set hints have
4465 * effect. Join method and join order is not controllable by hints.
4467 if (enable_geqo && levels_needed >= geqo_threshold)
4468 return geqo(root, levels_needed, initial_rels);
4470 nbaserel = get_num_baserels(initial_rels);
4471 current_hint_state->join_hint_level =
4472 palloc0(sizeof(List *) * (nbaserel + 1));
4473 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4475 leading_hint_enable = transform_join_hints(current_hint_state,
4477 initial_rels, join_method_hints);
4479 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4481 for (i = 2; i <= nbaserel; i++)
4483 list_free(current_hint_state->join_hint_level[i]);
4485 /* free Leading hint only */
4486 if (join_method_hints[i] != NULL &&
4487 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4488 JoinMethodHintDelete(join_method_hints[i]);
4490 pfree(current_hint_state->join_hint_level);
4491 pfree(join_method_hints);
4493 if (leading_hint_enable)
4494 set_join_config_options(current_hint_state->init_join_mask,
4495 current_hint_state->context);
4501 * Force number of wokers if instructed by hint
4504 pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
4505 Index rti, RangeTblEntry *rte)
4507 ParallelHint *phint;
4511 /* call the previous hook */
4512 if (prev_set_rel_pathlist)
4513 prev_set_rel_pathlist(root, rel, rti, rte);
4515 /* Nothing to do if no hint available */
4516 if (current_hint_state == NULL)
4519 /* Don't touch dummy rels. */
4520 if (IS_DUMMY_REL(rel))
4524 * We can accept only plain relations, foreign tables and table saples are
4525 * also unacceptable. See set_rel_pathlist.
4527 if (rel->rtekind != RTE_RELATION ||
4528 rte->relkind == RELKIND_FOREIGN_TABLE ||
4529 rte->tablesample != NULL)
4532 /* We cannot handle if this requires an outer */
4533 if (rel->lateral_relids)
4536 /* Return if this relation gets no enfocement */
4537 if ((found_hints = setup_hint_enforcement(root, rel, NULL, &phint)) == 0)
4540 /* Here, we regenerate paths with the current hint restriction */
4541 if (found_hints & HINT_BM_SCAN_METHOD || found_hints & HINT_BM_PARALLEL)
4543 /* Just discard all the paths considered so far */
4544 list_free_deep(rel->pathlist);
4545 rel->pathlist = NIL;
4547 /* Remove all the partial paths if Parallel hint is specfied */
4548 if ((found_hints & HINT_BM_PARALLEL) && rel->partial_pathlist)
4550 list_free_deep(rel->partial_pathlist);
4551 rel->partial_pathlist = NIL;
4554 /* Regenerate paths with the current enforcement */
4555 set_plain_rel_pathlist(root, rel, rte);
4557 /* Additional work to enforce parallel query execution */
4558 if (phint && phint->nworkers > 0)
4560 /* Lower the priorities of non-parallel paths */
4561 foreach (l, rel->pathlist)
4563 Path *path = (Path *) lfirst(l);
4565 if (path->startup_cost < disable_cost)
4567 path->startup_cost += disable_cost;
4568 path->total_cost += disable_cost;
4572 /* enforce number of workers if requested */
4573 if (phint->force_parallel)
4575 foreach (l, rel->partial_pathlist)
4577 Path *ppath = (Path *) lfirst(l);
4579 ppath->parallel_workers = phint->nworkers;
4583 /* Generate gather paths for base rels */
4584 if (rel->reloptkind == RELOPT_BASEREL)
4585 generate_gather_paths(root, rel);
4589 reset_hint_enforcement();
4594 * Build access paths for a base relation
4596 * This function was copied and edited from set_rel_pathlist() in
4597 * src/backend/optimizer/path/allpaths.c in order not to copy other static
4598 * functions not required here.
4601 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4602 Index rti, RangeTblEntry *rte)
4604 if (IS_DUMMY_REL(rel))
4606 /* We already proved the relation empty, so nothing more to do */
4610 /* It's an "append relation", process accordingly */
4611 set_append_rel_pathlist(root, rel, rti, rte);
4615 if (rel->rtekind == RTE_RELATION)
4617 if (rte->relkind == RELKIND_RELATION)
4619 if(rte->tablesample != NULL)
4620 elog(ERROR, "sampled relation is not supported");
4622 /* Plain relation */
4623 set_plain_rel_pathlist(root, rel, rte);
4626 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4629 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4633 * Allow a plugin to editorialize on the set of Paths for this base
4634 * relation. It could add new paths (such as CustomPaths) by calling
4635 * add_path(), or delete or modify paths added by the core code.
4637 if (set_rel_pathlist_hook)
4638 (*set_rel_pathlist_hook) (root, rel, rti, rte);
4640 /* Now find the cheapest of the paths for this rel */
4645 * stmt_beg callback is called when each query in PL/pgSQL function is about
4646 * to be executed. At that timing, we save query string in the global variable
4647 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4648 * variable for the purpose, because its content is only necessary until
4649 * planner hook is called for the query, so recursive PL/pgSQL function calls
4650 * don't harm this mechanism.
4653 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4655 plpgsql_recurse_level++;
4659 * stmt_end callback is called then each query in PL/pgSQL function has
4660 * finished. At that timing, we clear plpgsql_query_string to tell planner
4661 * hook that next call is not for a query written in PL/pgSQL block.
4664 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4666 plpgsql_recurse_level--;
4669 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4674 if (!isTopLevel || phase != RESOURCE_RELEASE_AFTER_LOCKS)
4676 /* Cancel plpgsql nest level*/
4677 plpgsql_recurse_level = 0;
4680 #define standard_join_search pg_hint_plan_standard_join_search
4681 #define join_search_one_level pg_hint_plan_join_search_one_level
4682 #define make_join_rel make_join_rel_wrapper
4685 #undef make_join_rel
4686 #define make_join_rel pg_hint_plan_make_join_rel
4687 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4688 #include "make_join_rel.c"
4690 #include "pg_stat_statements.c"